forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.8 MiB1f91eddTahinli2 months ago3507 commits

decode.rs24469 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 if rect {
4433 target.reconstruct_rect(
4434 x,
4435 oy,
4436 bw,
4437 bh,
4438 mode,
4439 angle_delta,
4440 reach,
4441 residual,
4442 cfl,
4443 filter_intra,
4444 smooth_neighbor,
4445 pred,
4446 fctx,
4447 );
4448 } else {
4449 target.reconstruct(
4450 x,
4451 oy,
4452 bw,
4453 mode,
4454 angle_delta,
4455 reach,
4456 residual,
4457 cfl,
4458 filter_intra,
4459 smooth_neighbor,
4460 pred,
4461 fctx,
4462 );
4463 }
4464}
4465
4466/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
4467#[allow(clippy::too_many_arguments)]
4468fn exec_mc(
4469 y: &mut PlaneBuf<'static>,
4470 u: &mut PlaneBuf<'static>,
4471 v: &mut PlaneBuf<'static>,
4472 plane: usize,
4473 x: usize,
4474 oy: usize,
4475 stride: usize,
4476 w: usize,
4477 h: usize,
4478 prediction: &[u16],
4479 residual: &[i32],
4480 fctx: &crate::decode::FrameCtx,
4481) {
4482 let target: &mut PlaneBuf<'static> = match plane {
4483 0 => &mut *y,
4484 1 => &mut *u,
4485 _ => &mut *v,
4486 };
4487 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
4488}
4489
4490thread_local! {
4491 /// The current frame's `mi` grid, kept only while a frame header set
4492 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
4493 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
4494 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
4495 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
4496 /// does not allow intrabc (so nothing is paid for it).
4497 ///
4498 /// corner-cut: only [`decode_block`] (the square path) records into it,
4499 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
4500 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
4501 /// be wrong there; upgrade = record from the rect/leaf paths too.
4502 /// The block vector [`read_intra_mode`] just decoded, handed to
4503 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
4504 /// which the alternative -- a tenth tuple member through every caller --
4505 /// already avoids). Always `.take()`n by the block that reads it.
4506 /// How many blocks read `use_intrabc == 1` and took the DV path -- the
4507 /// gate's hit counter. Bumped on the READ, before the rect-strip refusal
4508 /// returns too, so it counts reads, not reconstructions (a refused block
4509 /// is never reconstructed).
4510 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4511}
4512// The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
4513// an intrabc block's chroma reads can inherit it (see
4514// [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
4515// through that one arming site.
4516// libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
4517// branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
4518// satisfies (`blockd.h:373`) -- and takes the *colocated luma
4519// transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
4520// `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
4521// intrabc block's two chroma [`read_plane`] calls; the type decides the
4522// `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
4523// -- getting it wrong desyncs the chroma coefficients, it is not a
4524// reconstruction-only detail.
4525
4526/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
4527/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
4528/// needs no separate plumbing to reach the rect-strip mode reader.
4529fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
4530 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
4531}
4532
4533thread_local! {
4534 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
4535 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
4536 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
4537 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4538}
4539
4540/// Current value of [`RECT_INTRABC_READS`].
4541pub(crate) fn rect_intrabc_reads() -> usize {
4542 RECT_INTRABC_READS.with(|c| c.get())
4543}
4544
4545/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
4546#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4547pub(crate) fn reset_rect_intrabc_reads() {
4548 RECT_INTRABC_READS.with(|c| c.set(0));
4549}
4550
4551thread_local! {
4552 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
4553 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
4554 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4555}
4556
4557thread_local! {
4558 /// Chroma reads of an intrabc TX4-split leaf that consulted an ARMED
4559 /// [`INTRABC_CHROMA_TX`] slot -- proof that the arm's frame-copy +
4560 /// inherited-type route actually ran (lane-av1intrapred r2's non-vacuity
4561 /// counter: zero means the gate's fixture no longer reaches the route).
4562 static INTRABC_TX4_CHROMA_COPY_HITS: std::cell::Cell<usize> =
4563 const { std::cell::Cell::new(0) };
4564}
4565
4566/// Current value of [`INTRABC_TX4_CHROMA_COPY_HITS`].
4567#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4568pub(crate) fn intrabc_tx4_chroma_copy_hits() -> usize {
4569 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.get())
4570}
4571
4572/// Zeroes [`INTRABC_TX4_CHROMA_COPY_HITS`] (gate tests call this before a decode).
4573#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4574pub(crate) fn reset_intrabc_tx4_chroma_copy_hits() {
4575 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.set(0));
4576}
4577
4578/// Current value of [`LEAF8_INTRABC_HITS`].
4579pub(crate) fn leaf8_intrabc_hits() -> usize {
4580 LEAF8_INTRABC_HITS.with(|c| c.get())
4581}
4582
4583/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
4584#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4585pub(crate) fn reset_leaf8_intrabc_hits() {
4586 LEAF8_INTRABC_HITS.with(|c| c.set(0));
4587}
4588
4589/// Current value of [`INTRABC_HITS`].
4590#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4591pub(crate) fn intrabc_hits() -> usize {
4592 INTRABC_HITS.with(|c| c.get())
4593}
4594
4595thread_local! {
4596 /// An intrabc block that IS a sub-8x8 group's CHROMA REFERENCE and is
4597 /// SKIPPED: the route that arms [`INTRABC_CHROMA_TX`] and then reads no
4598 /// chroma coefficient at all, so the slot used to stay armed into the NEXT
4599 /// block's chroma read. Both group shapes (4x4 split, 4x8/8x4 rect) count
4600 /// here. A non-zero value is what makes the disarm below load-bearing.
4601 static SKIPPED_INTRABC_CHROMA_ARM_HITS: std::cell::Cell<usize> =
4602 const { std::cell::Cell::new(0) };
4603}
4604
4605/// Current value of [`SKIPPED_INTRABC_CHROMA_ARM_HITS`].
4606#[allow(dead_code)] // read only from the `#[cfg(test)]` gates and the probe
4607pub(crate) fn skipped_intrabc_chroma_arm_hits() -> usize {
4608 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.get())
4609}
4610
4611/// Zeroes [`SKIPPED_INTRABC_CHROMA_ARM_HITS`] (gate tests call this before a
4612/// decode).
4613#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4614pub(crate) fn reset_skipped_intrabc_chroma_arm_hits() {
4615 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.set(0));
4616}
4617
4618thread_local! {
4619 /// lane-av1-ibcskip2: a sub-8x8 4:4:4 leaf that is BOTH intrabc AND
4620 /// `skip` -- the arm whose chroma is the bare frame copy at the DV
4621 /// (libaom `av1_build_inter_predictors_sb` runs regardless of `skip`).
4622 /// Before the fix this route predicted intra-DC and every one of this
4623 /// fixture's 150 such cells differed from the oracle on both chroma
4624 /// planes.
4625 static SKIPPED_INTRABC_DV_COPY_HITS: std::cell::Cell<usize> =
4626 const { std::cell::Cell::new(0) };
4627}
4628
4629/// Current value of [`SKIPPED_INTRABC_DV_COPY_HITS`].
4630#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4631pub(crate) fn skipped_intrabc_dv_copy_hits() -> usize {
4632 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.get())
4633}
4634
4635/// Zeroes [`SKIPPED_INTRABC_DV_COPY_HITS`] (gate tests call this before a
4636/// decode).
4637#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4638pub(crate) fn reset_skipped_intrabc_dv_copy_hits() {
4639 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.set(0));
4640}
4641
4642/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
4643#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4644pub(crate) fn reset_intrabc_hits() {
4645 INTRABC_HITS.with(|c| c.set(0));
4646}
4647
4648thread_local! {
4649 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
4650 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
4651 /// that replaced the refusal "an intrabc block under TxMode::Select".
4652 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4653 /// lane-av1-ibcvtx: intrabc var-tx trees that resolved to MIXED leaf
4654 /// sizes (not one square size across every leaf) -- the engagement
4655 /// counter proving a witness actually exercises the per-leaf reconstruct.
4656 static INTRABC_VARTX_MIXED_LEAVES_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4657 /// lane-av1txr: as above for a `BLOCK_4X8`/`BLOCK_8X4` intrabc leaf --
4658 /// libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`, so these leaves
4659 /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no
4660 /// symbol here desynced `warped.obu` at the very next block.
4661 static RECT_INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4662 /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction
4663 /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip
4664 /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never
4665 /// this one).
4666 static INTRABC_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4667 /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT).
4668 static INTRABC_RECT_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4669 /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction
4670 /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read),
4671 /// split by the strip's orientation -- `bw > bh` is a HORZ strip,
4672 /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED
4673 /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS`
4674 /// counts neither orientation nor the skip flag, so an arm that flipped
4675 /// to an all-skip stream (no residual reader at all) would stay green.
4676 static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> =
4677 const { std::cell::Cell::new([0, 0]) };
4678 /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`]
4679 /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split
4680 /// by orientation. The r5 panic (residual stride `bw * bh` underrunning
4681 /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was
4682 /// invisible to every gate because they only counted CODED strips.
4683 static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> =
4684 const { std::cell::Cell::new([0, 0]) };
4685 /// lane-whtshape: LOSSLESS rect intrabc blocks whose chroma plane block
4686 /// [`decode_intrabc_rect`] walked as a `(cw/4) * (ch/4)` PLANE-MAJOR
4687 /// raster of TX_4X4 units -- the shape libaom's lossless geometry codes
4688 /// (`read_tx_size` returns `TX_4X4` for EVERY plane of a lossless block,
4689 /// `get_vartx_max_txsize` likewise, and `read_tx_mode` forced the frame's
4690 /// `ONLY_4X4`) -- instead of the single rect unit, which is what put a
4691 /// non-4x4 unit on the lossless Walsh-Hadamard path. EXCLUSIVE to this arm:
4692 /// no other caller walks a rect intrabc block's chroma, so `>= 1` cannot
4693 /// be satisfied by any older route.
4694 static INTRABC_RECT_LOSSLESS_CHROMA4_HITS: std::cell::Cell<usize> =
4695 const { std::cell::Cell::new(0) };
4696}
4697
4698/// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed,
4699/// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`].
4700#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4701pub fn intrabc_rect_coded_hits() -> [usize; 2] {
4702 INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get)
4703}
4704
4705/// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks
4706/// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`].
4707#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4708pub fn intrabc_rect_skipped_hits() -> [usize; 2] {
4709 INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get)
4710}
4711
4712/// Current value of [`INTRABC_RECT_HITS`].
4713#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4714pub fn intrabc_rect_hits() -> usize {
4715 INTRABC_RECT_HITS.with(|c| c.get())
4716}
4717
4718/// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`].
4719#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4720pub(crate) fn reset_intrabc_rect_hits() {
4721 INTRABC_RECT_HITS.with(|c| c.set(0));
4722 INTRABC_RECT_VARTX_HITS.with(|c| c.set(0));
4723 INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0]));
4724 INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0]));
4725}
4726
4727/// lane-whtshape: [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
4728#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4729pub fn intrabc_rect_lossless_chroma4_hits() -> usize {
4730 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.get())
4731}
4732
4733/// lane-whtshape: zeroes [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
4734#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4735pub(crate) fn reset_intrabc_rect_lossless_chroma4_hits() {
4736 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.set(0));
4737}
4738
4739/// Current value of [`INTRABC_RECT_VARTX_HITS`].
4740#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4741pub fn intrabc_rect_vartx_hits() -> usize {
4742 INTRABC_RECT_VARTX_HITS.with(|c| c.get())
4743}
4744
4745thread_local! {
4746 /// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip
4747 /// (BLOCK_128X64 / BLOCK_64X128) whose reconstruction
4748 /// [`decode_intrabc_128rect`] ran -- the shape the named refusal used to
4749 /// guard (`decode_block_128rect`). A refused block bumps
4750 /// [`INTRABC_HITS`] but never this one.
4751 static INTRABC_128RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4752 /// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc
4753 /// strip's mu-chunk walk read, one per `read_inter_plane` chroma call.
4754 /// At 4:2:0 a 64x64 mu chunk's chroma plane block is 32x32, so one
4755 /// TX_32X32 per plane per chunk; at 4:2:2 it is 32x64 and holds TWO
4756 /// STACKED units per plane. The square-cut `chunk_chroma = cside * 64 /
4757 /// side` model walked the 4:2:0 count on every axis, so this counter is
4758 /// the reach/arm witness for the per-axis walk.
4759 static INTRABC_128RECT_CHROMA_CHUNK_HITS: std::cell::Cell<usize> =
4760 const { std::cell::Cell::new(0) };
4761 /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as
4762 /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the
4763 /// per-axis walk used. A 4:2:2 run and a 4:2:0 run of the same block
4764 /// differ here (32|64 vs 32|32), which is what the de-square-cut fixes.
4765 static INTRABC_128RECT_CHUNK_SHAPE: std::cell::Cell<usize> =
4766 const { std::cell::Cell::new(0) };
4767}
4768
4769/// Current value of [`INTRABC_128RECT_HITS`].
4770#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4771pub fn intrabc_128rect_hits() -> usize {
4772 INTRABC_128RECT_HITS.with(|c| c.get())
4773}
4774
4775/// Zeroes [`INTRABC_128RECT_HITS`].
4776#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4777pub(crate) fn reset_intrabc_128rect_hits() {
4778 INTRABC_128RECT_HITS.with(|c| c.set(0));
4779}
4780
4781/// Current value of [`INTRABC_128RECT_CHROMA_CHUNK_HITS`].
4782#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4783pub fn intrabc_128rect_chroma_chunk_hits() -> usize {
4784 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.get())
4785}
4786
4787/// Current value of [`INTRABC_128RECT_CHUNK_SHAPE`].
4788#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4789pub fn intrabc_128rect_chunk_shape() -> usize {
4790 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.get())
4791}
4792
4793/// Zeroes [`INTRABC_128RECT_CHROMA_CHUNK_HITS`] and
4794/// [`INTRABC_128RECT_CHUNK_SHAPE`].
4795#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4796pub(crate) fn reset_intrabc_128rect_chroma_chunk_hits() {
4797 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(0));
4798 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.set(0));
4799}
4800
4801/// Current value of [`INTRABC_VARTX_HITS`].
4802pub fn intrabc_vartx_hits() -> usize {
4803 INTRABC_VARTX_HITS.with(|c| c.get())
4804}
4805
4806/// Current value of [`INTRABC_VARTX_MIXED_LEAVES_HITS`].
4807pub fn intrabc_vartx_mixed_leaves_hits() -> usize {
4808 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.get())
4809}
4810
4811/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
4812#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4813pub(crate) fn reset_intrabc_vartx_hits() {
4814 INTRABC_VARTX_HITS.with(|c| c.set(0));
4815}
4816
4817/// Zeroes [`INTRABC_VARTX_MIXED_LEAVES_HITS`] (gate tests call this before a
4818/// decode).
4819#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4820pub(crate) fn reset_intrabc_vartx_mixed_leaves_hits() {
4821 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.set(0));
4822}
4823
4824/// Current value of [`RECT_INTRABC_VARTX_HITS`].
4825#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4826pub fn rect_intrabc_vartx_hits() -> usize {
4827 RECT_INTRABC_VARTX_HITS.with(|c| c.get())
4828}
4829
4830/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
4831/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
4832/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
4833/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
4834fn record_intrabc_mi(
4835 mi_r: usize,
4836 mi_c: usize,
4837 n4: usize,
4838 dv: Option<(i32, i32)>,
4839 n: &mut Neighbours,
4840 fctx: &crate::decode::FrameCtx,
4841) {
4842 record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx);
4843}
4844
4845/// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs`
4846/// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4`
4847/// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr).
4848///
4849/// Also stamps libaom's `is_inter_block` verdict for this block into the
4850/// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override
4851/// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] >
4852/// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and
4853/// `get_tx_size_context` reads its BLOCK size rather than its transform band.
4854/// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which
4855/// every block runs; this runs after it (class leaked-band otherwise).
4856fn record_intrabc_mi_rect(
4857 mi_r: usize,
4858 mi_c: usize,
4859 n4_w: usize,
4860 n4_h: usize,
4861 dv: Option<(i32, i32)>,
4862 n: &mut Neighbours,
4863 fctx: &crate::decode::FrameCtx,
4864) {
4865 if dv.is_some() {
4866 for i in 0..n4_w {
4867 if let Some(cell) = n.above_inter.get_mut(mi_c + i) {
4868 *cell = true;
4869 }
4870 }
4871 for i in 0..n4_h {
4872 if let Some(cell) = n.left_inter.get_mut(mi_r + i) {
4873 *cell = true;
4874 }
4875 }
4876 }
4877 fctx.intrabc_mi_grid.with(|g| {
4878 let mut g = g.borrow_mut();
4879 let Some((grid, _, _)) = g.as_mut() else {
4880 return;
4881 };
4882 let info = crate::mvstack::MiInfo {
4883 is_inter: dv.is_some(),
4884 ref_frame: 0,
4885 ref_frame1: NO_REF1,
4886 mv: mv16(dv.unwrap_or((0, 0))),
4887 mv1: (0, 0),
4888 is_new_mv: dv.is_some(),
4889 is_global_mv0: false,
4890 is_global_mv1: false,
4891 size: n4_w as u8,
4892 size_h: n4_h as u8,
4893 };
4894 for r in mi_r..mi_r + n4_h {
4895 for c in mi_c..mi_c + n4_w {
4896 grid.set(r, c, info);
4897 }
4898 }
4899 });
4900}
4901
4902// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
4903// proves a real `skip_mode_present` stream actually reached a block that
4904// picked it, not just that the frame header bit was set.
4905thread_local! {
4906 static SKIP_MODE_HITS: std::cell::Cell<usize> =
4907 const { std::cell::Cell::new(0) };
4908}
4909
4910/// Current value of [`SKIP_MODE_HITS`].
4911#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4912pub(crate) fn skip_mode_hits() -> usize {
4913 SKIP_MODE_HITS.with(|c| c.get())
4914}
4915
4916// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
4917// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
4918// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
4919// reached [`obmc_blend`], not just the header bit.
4920thread_local! {
4921 static OBMC_HITS: std::cell::Cell<usize> =
4922 const { std::cell::Cell::new(0) };
4923}
4924
4925// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
4926// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
4927// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
4928// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
4929// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
4930// decoder used to read with the wrong alphabet, so a gate that asserts this
4931// counter advanced proves the fixed path fired (class
4932// `gate-blind-to-feature`).
4933thread_local! {
4934 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4935}
4936
4937/// Current value of [`FIMV_ALPHABET_HITS`].
4938pub fn fimv_alphabet_hits() -> usize {
4939 FIMV_ALPHABET_HITS.with(|c| c.get())
4940}
4941
4942// lane-fimv r1: how many frame headers this decoder has decoded with
4943// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
4944// prove the encoder really produced the header state under test rather than
4945// assume it.
4946thread_local! {
4947 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4948}
4949
4950/// Current value of [`FIMV_FRAME_HITS`].
4951pub fn fimv_frame_hits() -> usize {
4952 FIMV_FRAME_HITS.with(|c| c.get())
4953}
4954
4955/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
4956/// `force_integer_mv` bit is set.
4957pub fn note_force_integer_mv_frame() {
4958 hit!(FIMV_FRAME_HITS);
4959}
4960
4961/// Current value of [`OBMC_HITS`].
4962#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4963pub(crate) fn obmc_hits() -> usize {
4964 OBMC_HITS.with(|c| c.get())
4965}
4966
4967// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
4968// off the neighbour band -- the positive half of the proof for "an OBMC
4969// neighbour whose switchable interp filter was never recorded". A
4970// fixed-filter frame returns before this point (its neighbours legitimately
4971// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
4972// `interp_filter` symbols were published by `record_inter_rect_mi`.
4973thread_local! {
4974 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4975}
4976
4977/// Current value of [`OBMC_FILTER_BAND_READS`].
4978#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4979pub(crate) fn obmc_filter_band_reads() -> usize {
4980 OBMC_FILTER_BAND_READS.with(|c| c.get())
4981}
4982
4983// lane-scaledref r1: per-case firing counts for the scaled-reference gate
4984// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
4985// reference would pass just as well and prove nothing, so the gate
4986// hard-asserts each combination this round lifts actually occurred:
4987// a compound block with a scaled tap, a warp block whose warp libaom
4988// suppresses because the reference is scaled, an OBMC block, an interintra
4989// block, and an 8x8 leaf.
4990thread_local! {
4991 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4992 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4993 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4994 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4995 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4996 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4997 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4998}
4999
5000/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
5001/// scaled and one unscaled tap.
5002#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5003pub(crate) fn mixed_scale_compound_hits() -> usize {
5004 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
5005}
5006
5007/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
5008/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
5009/// instead because their reference is scaled (libaom `motion_mode_allowed`,
5010/// `blockd.h:1484`).
5011#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5012pub(crate) fn scaled_warp_suppressed_hits() -> usize {
5013 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
5014}
5015
5016/// Current value of [`SCALED_COMPOUND_HITS`].
5017#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5018pub(crate) fn scaled_compound_hits() -> usize {
5019 SCALED_COMPOUND_HITS.with(|c| c.get())
5020}
5021
5022/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
5023pub fn scaled_warp_fallback_hits() -> usize {
5024 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
5025}
5026
5027/// Current value of [`SCALED_OBMC_HITS`].
5028#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5029pub(crate) fn scaled_obmc_hits() -> usize {
5030 SCALED_OBMC_HITS.with(|c| c.get())
5031}
5032
5033/// Current value of [`SCALED_INTERINTRA_HITS`].
5034#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5035pub(crate) fn scaled_interintra_hits() -> usize {
5036 SCALED_INTERINTRA_HITS.with(|c| c.get())
5037}
5038
5039/// Current value of [`SCALED_BLOCK8_HITS`].
5040#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5041pub(crate) fn scaled_block8_hits() -> usize {
5042 SCALED_BLOCK8_HITS.with(|c| c.get())
5043}
5044
5045// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
5046// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
5047// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
5048// 8x8-leaf OBMC block apart from a 16x16+ one.
5049thread_local! {
5050 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5051}
5052
5053// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
5054// pair whose two directions differ (`enable_dual_filter` only -- with dual
5055// filter off both directions take the single symbol, so this can never fire).
5056// A gate asserting it proves the stream really carries dual-filter blocks.
5057thread_local! {
5058 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5059}
5060
5061// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
5062// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
5063// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
5064// no-filter sentinel that made a neighbouring OBMC block panic).
5065thread_local! {
5066 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5067}
5068
5069/// Current value of [`DUAL_FILTER_DIFF_HITS`].
5070#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5071pub(crate) fn dual_filter_diff_hits() -> usize {
5072 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
5073}
5074
5075/// Current value of [`COMPOUND8_FILTER_HITS`].
5076#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5077pub(crate) fn compound8_filter_hits() -> usize {
5078 COMPOUND8_FILTER_HITS.with(|c| c.get())
5079}
5080
5081// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
5082// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
5083// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
5084// -- the gate's proof that a fixture really exercises the alphabet this
5085// round changed, even though the block itself still refuses (warp
5086// estimation/filter not ported).
5087thread_local! {
5088 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
5089 const { std::cell::Cell::new(0) };
5090}
5091
5092/// Current value of [`WARP_SELECTED_HITS`].
5093#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5094pub(crate) fn warp_selected_hits() -> usize {
5095 WARP_SELECTED_HITS.with(|c| c.get())
5096}
5097
5098// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
5099// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
5100// into the compound intermediate) rather than translationally -- the
5101// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
5102// really reached [`crate::warp::warp_affine_compound`].
5103// lane-av1422warp: the 4:2:2 coverage witness has to show compound and warped
5104// motion firing ABOVE the vertical midpoint, and every pre-existing warp
5105// counter is frame-global. These two are the same arms restricted to blocks
5106// whose top mode-info row is in the frame's upper half, which is the half
5107// this lane's evidence covers.
5108thread_local! {
5109 static TOP_HALF_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5110 static TOP_HALF_WARP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5111}
5112
5113/// How many `GLOBAL_GLOBALMV` (compound) inter blocks decoded in the frame's
5114/// upper half -- the block's top mode-info row is under `mi_rows / 2`.
5115///
5116/// NO COMMITTED TEST READS THIS, and none can while the 4:2:2 header refusal
5117/// stands: the pinned 4:2:2 coverage gate asserts the byte pin and the
5118/// refusal by name, so nothing in the suite ever decodes a 4:2:2 stream.
5119/// The figure quoted for that fixture comes from a patch-run-restore build
5120/// with the `EC_AV1_ALLOW_422_PROBE` bypass applied and then reverted, which
5121/// is the same discipline every 4:2:2 lane in this family uses.
5122#[allow(dead_code)]
5123pub(crate) fn top_half_compound_hits() -> usize {
5124 TOP_HALF_COMPOUND_HITS.with(std::cell::Cell::get)
5125}
5126
5127/// How many inter blocks in the frame's upper half satisfy libaom's
5128/// `is_global_mv_block` on at least one reference slot -- mode
5129/// `GLOBAL_GLOBALMV` AND block >= 8x8 AND that slot's own global-motion
5130/// model > `TRANSLATION`. This is the block set whose prediction goes
5131/// through `crate::warp`, and it is exactly `is_global_mv0 || is_global_mv1`
5132/// as computed at the increment site; it is NOT merely "some slot has a
5133/// non-TRANSLATION model", which also counts blocks that are not global-mv
5134/// blocks.
5135///
5136/// Like [`top_half_compound_hits`], no committed test reads it: with the
5137/// 4:2:2 header refusal in force nothing in the suite decodes the stream
5138/// these numbers describe.
5139#[allow(dead_code)]
5140pub(crate) fn top_half_warp_hits() -> usize {
5141 TOP_HALF_WARP_HITS.with(std::cell::Cell::get)
5142}
5143
5144thread_local! {
5145 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
5146 const { std::cell::Cell::new(0) };
5147}
5148
5149/// Current value of [`COMPOUND_WARP_HITS`].
5150#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5151pub(crate) fn compound_warp_hits() -> usize {
5152 COMPOUND_WARP_HITS.with(|c| c.get())
5153}
5154
5155// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
5156// arm ([`decode_inter_block8`]) -- that arm predicted both taps
5157// translationally until r3, so a gate needs to tell a warped 8x8 compound
5158// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
5159thread_local! {
5160 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
5161 const { std::cell::Cell::new(0) };
5162}
5163
5164/// Current value of [`COMPOUND_WARP_HITS_8`].
5165#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5166pub(crate) fn compound_warp_hits_8() -> usize {
5167 COMPOUND_WARP_HITS_8.with(|c| c.get())
5168}
5169
5170// lane-gmaffine r1: how many blocks built their prediction from a
5171// SIX-parameter (`AFFINE`) global-motion model through
5172// `crate::warp::global_warp_params` -- the gate's proof that a stream really
5173// carried an AFFINE `global_motion_params` AND that a block was predicted
5174// with it, not merely that the header parsed one.
5175thread_local! {
5176 static AFFINE_GM_HITS: std::cell::Cell<usize> =
5177 const { std::cell::Cell::new(0) };
5178}
5179
5180/// Current value of [`AFFINE_GM_HITS`].
5181#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5182pub(crate) fn affine_gm_hits() -> usize {
5183 AFFINE_GM_HITS.with(|c| c.get())
5184}
5185
5186// lane-av1distwtd: how many blocks took the DISTANCE-WEIGHTED compound
5187// combine rather than the simple average -- `compound_idx == 0` under
5188// `enable_jnt_comp`, whose weights come from
5189// [`crate::compound::dist_wtd_comp_weight_assign`] instead of the constant
5190// `(8, 8)` split. Counting the `idx == 0` arm (not merely the
5191// `compound_idx` symbol read) is what makes this a witness of the TOOL: a
5192// stream that carries `enable_jnt_comp = true` in its sequence header but
5193// codes every compound block with `compound_idx == 1` leaves this at 0 and
5194// decoded identically without the whole distance-weight path.
5195thread_local! {
5196 static DIST_WTD_COMP_HITS: std::cell::Cell<usize> =
5197 const { std::cell::Cell::new(0) };
5198}
5199
5200/// Current value of [`DIST_WTD_COMP_HITS`].
5201#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5202pub(crate) fn dist_wtd_comp_hits() -> usize {
5203 DIST_WTD_COMP_HITS.with(|c| c.get())
5204}
5205
5206/// Resets [`DIST_WTD_COMP_HITS`] to 0.
5207#[allow(dead_code)] // test-only
5208pub(crate) fn reset_dist_wtd_comp_hits() {
5209 DIST_WTD_COMP_HITS.with(|c| c.set(0));
5210}
5211
5212// lane-av1gwarp12: how many 16x16+ blocks built their SINGLE-reference
5213// prediction through `crate::warp::global_warp_params` with a FOUR-parameter
5214// (`ROTZOOM`) model. Vanilla aomenc pins its global-motion search to ROTZOOM
5215// (`global_motion_facade.c:24`), so this is the only >TRANSLATION single-ref
5216// global-warp arm a real aomenc stream can reach (AFFINE needs the widened
5217// side build and its own counter, [`AFFINE_GM_HITS`]).
5218thread_local! {
5219 static ROTZOOM_GM_WARP_HITS: std::cell::Cell<usize> =
5220 const { std::cell::Cell::new(0) };
5221}
5222
5223/// Current value of [`ROTZOOM_GM_WARP_HITS`].
5224#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5225pub(crate) fn rotzoom_gm_warp_hits() -> usize {
5226 ROTZOOM_GM_WARP_HITS.with(|c| c.get())
5227}
5228
5229// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
5230// differently at the block's WIDTH than at libaom's
5231// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
5232// pick the wrong motion_mode alphabet.
5233thread_local! {
5234 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5235}
5236
5237/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
5238pub fn tr_reach_longer_side_hits() -> usize {
5239 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
5240}
5241
5242// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
5243// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
5244// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
5245// reads its interp-filter symbol. Counts the blocks where that guard flips
5246// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
5247// and a 4-px side, which we used to suppress the interp read on (a pre-mode
5248// entropy desync one symbol wide).
5249thread_local! {
5250 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5251}
5252
5253/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
5254pub fn gm_nontrans_small_side_hits() -> usize {
5255 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
5256}
5257
5258// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
5259// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
5260// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
5261// only once `find_projection` returned a usable model, unlike
5262// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
5263// proof that the leaf path itself fired, not the 16x16+ one.
5264thread_local! {
5265 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5266 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5267}
5268
5269/// Current value of [`GLOBALMV_HITS_8`].
5270#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5271pub(crate) fn globalmv_hits_8() -> usize {
5272 GLOBALMV_HITS_8.with(|c| c.get())
5273}
5274
5275/// Current value of [`WARP_HITS_8`].
5276#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5277pub(crate) fn warp_hits_8() -> usize {
5278 WARP_HITS_8.with(|c| c.get())
5279}
5280
5281// How many blocks decoded `interintra == 1` with the non-wedge blended
5282// prediction applied (lane-interintra r1) -- the gate's proof that a
5283// stream actually exercised interintra.
5284thread_local! {
5285 static INTERINTRA_HITS: std::cell::Cell<usize> =
5286 const { std::cell::Cell::new(0) };
5287}
5288
5289/// Current value of [`INTERINTRA_HITS`].
5290#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5291pub(crate) fn interintra_hits() -> usize {
5292 INTERINTRA_HITS.with(|c| c.get())
5293}
5294
5295// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
5296// -- the shape `interintra_blend` used to build a square `side x side` intra
5297// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
5298// pre-existing interintra gate passed with that bug, so the rect arm needs
5299// its own counter to stop being vacuous.
5300thread_local! {
5301 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5302}
5303
5304/// Current value of [`INTERINTRA_RECT_HITS`].
5305pub fn interintra_rect_hits() -> usize {
5306 INTERINTRA_RECT_HITS.with(|c| c.get())
5307}
5308
5309// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
5310// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
5311// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
5312// gate fixture actually exercises this alphabet, even though the block
5313// still refuses (the mask blend itself is unported).
5314thread_local! {
5315 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5316 const { std::cell::Cell::new(0) };
5317}
5318
5319/// Current value of [`MASKED_COMPOUND_HITS`].
5320#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5321pub(crate) fn masked_compound_hits() -> usize {
5322 MASKED_COMPOUND_HITS.with(|c| c.get())
5323}
5324
5325// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
5326// masked-compound block whose true footprint is rectangular, i.e. the case
5327// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
5328// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
5329// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
5330thread_local! {
5331 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5332 const { std::cell::Cell::new(0) };
5333}
5334
5335/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
5336#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5337pub(crate) fn rect_masked_compound_hits() -> usize {
5338 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
5339}
5340
5341// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
5342// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
5343// actually exercised the wedge blend, not just the DIFFWTD half of
5344// `MASKED_COMPOUND_HITS`.
5345thread_local! {
5346 static WEDGE_HITS: std::cell::Cell<usize> =
5347 const { std::cell::Cell::new(0) };
5348}
5349
5350/// Current value of [`WEDGE_HITS`].
5351#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5352pub(crate) fn wedge_hits() -> usize {
5353 WEDGE_HITS.with(|c| c.get())
5354}
5355
5356// How many blocks decoded a real wedge-INTERINTRA block
5357// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
5358// a gate fixture exercised the wedge blend (fixed sign 0), not just the
5359// smooth arm counted by `INTERINTRA_HITS`.
5360thread_local! {
5361 static WII_HITS: std::cell::Cell<usize> =
5362 const { std::cell::Cell::new(0) };
5363}
5364
5365/// Current value of [`WII_HITS`].
5366#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5367pub(crate) fn wii_hits() -> usize {
5368 WII_HITS.with(|c| c.get())
5369}
5370
5371// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
5372// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
5373// wide <= 32 && high <= 32). The witness that a gate stream really carries a
5374// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
5375// frame carrying one.
5376thread_local! {
5377 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5378}
5379
5380/// Current value of [`NOCFL_UV_MODE_HITS`].
5381#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5382pub(crate) fn nocfl_uv_mode_hits() -> usize {
5383 NOCFL_UV_MODE_HITS.with(|c| c.get())
5384}
5385
5386/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
5387/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
5388pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
5389 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
5390
5391fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
5392 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
5393}
5394
5395// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
5396// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
5397// the rect wedge masks lifted this round actually fired, not just the square
5398// ones already counted by `WEDGE_HITS`/`WII_HITS`.
5399thread_local! {
5400 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5401 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5402}
5403
5404/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5405pub(crate) fn rect_wedge_hits() -> [usize; 6] {
5406 RECT_WEDGE_HITS.with(|c| c.get())
5407}
5408
5409/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5410pub(crate) fn rect_wii_hits() -> [usize; 6] {
5411 RECT_WII_HITS.with(|c| c.get())
5412}
5413
5414// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
5415// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
5416// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
5417// aomdec, neighbour list included).
5418thread_local! {
5419 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5420}
5421
5422/// Current value of [`OBMC_RECT_LEAF_HITS`].
5423pub(crate) fn obmc_rect_leaf_hits() -> usize {
5424 OBMC_RECT_LEAF_HITS.with(|c| c.get())
5425}
5426
5427// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
5428// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
5429// to be read from the pair's FIRST mi, which is a different block and, when
5430// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
5431// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
5432thread_local! {
5433 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5434}
5435
5436/// Current value of [`OBMC_PAIR_FILTER_HITS`].
5437pub(crate) fn obmc_pair_filter_hits() -> usize {
5438 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
5439}
5440
5441// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
5442// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
5443// own side, so a block overhanging the bottom/right still predicts the full
5444// neighbour strip (the destination write is what clips). We used to shrink the
5445// prediction to the visible part, which at 4 chroma rows/cols also swaps the
5446// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
5447thread_local! {
5448 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5449}
5450
5451/// Current value of [`OBMC_EDGE_SPAN_HITS`].
5452#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5453pub(crate) fn obmc_edge_span_hits() -> usize {
5454 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
5455}
5456
5457/// Current value of [`OBMC_HITS_8`].
5458#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5459pub(crate) fn obmc_hits_8() -> usize {
5460 OBMC_HITS_8.with(|c| c.get())
5461}
5462
5463// lane-rectgate r1: how many 32x32 quadrants actually decoded a
5464// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
5465// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
5466// `VERT_B` all still fall into the generic "a partition type this encoder
5467// never writes" refusal below) -- the gate's proof that a free-partition
5468// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
5469// coincidentally never selecting one.
5470thread_local! {
5471 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
5472 const { std::cell::Cell::new(0) };
5473}
5474
5475/// Current value of [`EXTENDED_PARTITION_HITS`].
5476#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5477pub(crate) fn extended_partition_hits() -> usize {
5478 EXTENDED_PARTITION_HITS.with(|c| c.get())
5479}
5480
5481// lane-partitions r1: how many 32x32 quadrants decoded a real
5482// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
5483// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
5484// gate's proof this round's arms actually fired.
5485thread_local! {
5486 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
5487 const { std::cell::Cell::new(0) };
5488}
5489
5490/// Current value of [`RECT_PARTITION_HITS`].
5491#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5492pub(crate) fn rect_partition_hits() -> usize {
5493 RECT_PARTITION_HITS.with(|c| c.get())
5494}
5495
5496// lane-inter8 r1: how many superblocks an inter tile coded as a single
5497// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
5498// static content, previously a named refusal).
5499thread_local! {
5500 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
5501 /// path decoded as one whole block (its gate's own witness).
5502 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5503 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
5504 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5505 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5506}
5507
5508/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
5509pub(crate) fn inter_sb128_horz_hits() -> usize {
5510 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
5511}
5512
5513/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
5514pub(crate) fn inter_sb128_vert_hits() -> usize {
5515 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
5516}
5517
5518/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
5519pub fn inter_sb128_none_hits() -> usize {
5520 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
5521}
5522
5523thread_local! {
5524 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
5525 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
5526 /// units) -- the gate's witness that the lifted refusal's case fired.
5527 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5528}
5529
5530/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
5531pub fn intra_128_in_inter_hits() -> usize {
5532 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
5533}
5534
5535thread_local! {
5536 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
5537 const { std::cell::Cell::new(0) };
5538}
5539
5540/// Current value of [`INTER_SB_NONE_HITS`].
5541#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5542pub(crate) fn inter_sb_none_hits() -> usize {
5543 INTER_SB_NONE_HITS.with(|c| c.get())
5544}
5545
5546// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
5547// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
5548// path has always run that loop, so only this counter proves the newly-lifted
5549// alphabet value fired.
5550thread_local! {
5551 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
5552 const { std::cell::Cell::new(0) };
5553}
5554
5555/// Current value of [`INTER_SUB16_SPLIT_HITS`].
5556#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5557pub(crate) fn inter_sub16_split_hits() -> usize {
5558 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
5559}
5560
5561// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
5562// while at least one reference picture was SCALED (superres) -- the counter
5563// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
5564thread_local! {
5565 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
5566 const { std::cell::Cell::new(0) };
5567}
5568
5569/// Current value of [`SCALED_LEAF8_HITS`].
5570pub fn scaled_leaf8_hits() -> usize {
5571 SCALED_LEAF8_HITS.with(|c| c.get())
5572}
5573
5574// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
5575// rect pair) were predicted from a SCALED reference -- the counter behind the
5576// lifted "sub-8x8 inter block under a scaled reference" refusal.
5577thread_local! {
5578 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
5579 const { std::cell::Cell::new(0) };
5580}
5581
5582/// Current value of [`SCALED_SUB8_HITS`].
5583pub fn scaled_sub8_hits() -> usize {
5584 SCALED_SUB8_HITS.with(|c| c.get())
5585}
5586
5587// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
5588// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
5589// rect coefficient reader itself fired, not just the strip-level partition
5590// symbol [`RECT_PARTITION_HITS`] already counts.
5591thread_local! {
5592 static RECT_COEFF_HITS: std::cell::Cell<usize> =
5593 const { std::cell::Cell::new(0) };
5594}
5595
5596/// Current value of [`RECT_COEFF_HITS`].
5597#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5598pub(crate) fn rect_coeff_hits() -> usize {
5599 RECT_COEFF_HITS.with(|c| c.get())
5600}
5601
5602// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
5603// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
5604// charter's real-aomenc gate hard-asserts.
5605thread_local! {
5606 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
5607 const { std::cell::Cell::new(0) };
5608}
5609
5610/// Current value of [`RECT_LEAF_COEFF_HITS`].
5611#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5612pub(crate) fn rect_leaf_coeff_hits() -> usize {
5613 RECT_LEAF_COEFF_HITS.with(|c| c.get())
5614}
5615
5616// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
5617// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
5618// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
5619// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
5620// needs rectangular intra prediction" before this round.
5621thread_local! {
5622 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
5623 const { std::cell::Cell::new([0; 3]) };
5624}
5625
5626/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
5627/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
5628#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5629pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
5630 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
5631}
5632
5633// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
5634// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
5635// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
5636// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
5637// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
5638// a single counter cannot tell an axis swap from a working arm
5639// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
5640thread_local! {
5641 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
5642 const { std::cell::Cell::new([0; 2]) };
5643}
5644
5645/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
5646/// (0 = 64x32, 1 = 32x64).
5647pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
5648 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
5649}
5650
5651// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
5652// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
5653// is never incremented) -- the gate's proof that the lifted path ran per depth.
5654thread_local! {
5655 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
5656 const { std::cell::Cell::new([0; 3]) };
5657}
5658
5659// lane-t900 r21: rect intra strips inside an inter frame that read the
5660// screen-content palette syntax (`allow_screen_content_tools` set and the
5661// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
5662// refusal used to guard, so this counter is what keeps its witness gate
5663// non-vacuous.
5664thread_local! {
5665 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5666}
5667
5668/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
5669#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5670pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
5671 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
5672}
5673
5674/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
5675#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5676pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
5677 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
5678}
5679
5680/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
5681#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5682pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
5683 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
5684}
5685
5686// lane-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid
5687// approximation would have resolved off a DIFFERENT CDF row than the real
5688// `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY
5689// frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block"
5690// tally is green on the old code too (class gate-blind-to-feature).
5691thread_local! {
5692 static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell<usize> =
5693 const { std::cell::Cell::new(0) };
5694}
5695
5696/// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`].
5697#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
5698pub(crate) fn txctx_deblock_divergence_hits() -> usize {
5699 TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get)
5700}
5701
5702// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
5703// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
5704// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
5705// rect strip on the inter block path" before this round.
5706thread_local! {
5707 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
5708 const { std::cell::Cell::new([0; 4]) };
5709}
5710
5711/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
5712/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
5713pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
5714 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
5715}
5716
5717// lane-av1444rect: how many 1:4 inter strips at `ss_x == 0` read their chroma
5718// coefficient context over the STRIP'S OWN extent instead of the 4:2:0 pair's
5719// (see [`decode_inter_block`]'s `around_c`). `is_chroma_reference`
5720// (av1_common_int.h:1454) is unconditionally true at ss (0,0), so no pair
5721// exists there; the counter keeps a 4:4:4 1:4-strip gate from passing
5722// vacuously (a 4:2:0 stream of the same content leaves it at 0). It proves
5723// REACH only, never that the fix bites -- that is the gate's byte compare and
5724// its mutation, not this count (skill://ec-av1-pipeline-gate-counters).
5725thread_local! {
5726 static RECT4_INTER_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5727}
5728
5729/// Current value of [`RECT4_INTER_OWN_CHROMA444_HITS`].
5730#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5731pub(crate) fn rect4_inter_own_chroma444_hits() -> usize {
5732 RECT4_INTER_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
5733}
5734
5735/// Resets [`RECT4_INTER_OWN_CHROMA444_HITS`] before a decode.
5736#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5737pub(crate) fn reset_rect4_inter_own_chroma444_hits() {
5738 RECT4_INTER_OWN_CHROMA444_HITS.with(|c| c.set(0));
5739}
5740
5741// lane-av1444rect r2: how many intra-BC 1:4 strips at `ss (0,0)` took the
5742// own-chroma arm of [`decode_rect4_16_intrabc`]'s `own444`. A 4:2:0 / 4:2:2
5743// stream of the same recipe leaves it at 0, which is what makes it the
5744// 4:4:4-only route.
5745//
5746// WHAT THIS COUNTER IS NOT: it is NOT evidence that the fix bites, and it
5747// never was. A route counter fires identically before and after a change that
5748// changes nothing downstream, so a non-zero count proves REACH and nothing
5749// more. On this lane it is also armed deliberately OUTSIDE the `own444`
5750// expression, so that the mutation (`own444 = false`) still increments it and
5751// the red comes from the pixel/entropy arm instead. The evidence that the ss
5752// gate bites is the measured fork move -- first entropy fork read 11750 ->
5753// 12465, luma first wrong sample 164416 -> 205264, 455240 -> 390380 total --
5754// not this count. See skill://ec-av1-pipeline-gate-counters: a counter needs
5755// a DIFFERS-style assertion to carry a claim.
5756thread_local! {
5757 static INTRABC_RECT4_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5758}
5759
5760/// Current value of [`INTRABC_RECT4_OWN_CHROMA444_HITS`].
5761#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5762pub(crate) fn intrabc_rect4_own_chroma444_hits() -> usize {
5763 INTRABC_RECT4_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
5764}
5765
5766/// Resets [`INTRABC_RECT4_OWN_CHROMA444_HITS`] before a decode.
5767#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5768pub(crate) fn reset_intrabc_rect4_own_chroma444_hits() {
5769 INTRABC_RECT4_OWN_CHROMA444_HITS.with(|c| c.set(0));
5770}
5771
5772// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
5773// through one of the key-frame rect readers ([`decode_block_rect4`],
5774// [`decode_block_rect64`]). `Some((size_group, skip))` tells
5775// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
5776// already read by [`decode_inter_block`] and (b) the luma mode comes off
5777// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
5778// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
5779
5780// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
5781// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
5782// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
5783// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
5784thread_local! {
5785 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
5786 const { std::cell::Cell::new(0) };
5787}
5788
5789/// Current value of [`MODE_MI_OVERRIDE_HITS`].
5790#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5791pub(crate) fn mode_mi_override_hits() -> usize {
5792 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
5793}
5794
5795// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
5796// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
5797// mode from the previous tile, where libaom's `up_available`/`left_available`
5798// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
5799// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
5800// per superblock row in `start_row`, so the luma fallback cannot leak the way
5801// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
5802// the invariant that makes the coarse fallback safe.
5803thread_local! {
5804 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
5805 const { std::cell::Cell::new(0) };
5806}
5807
5808/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
5809#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5810pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
5811 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
5812}
5813
5814// lane-cfl r1: how many times a chroma intra-edge filter-type read
5815// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
5816// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
5817// r1 defect would have filtered a chroma edge with the wrong strength.
5818thread_local! {
5819 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
5820 const { std::cell::Cell::new(0) };
5821}
5822
5823/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
5824#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5825pub(crate) fn uv_mode_mi_override_hits() -> usize {
5826 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
5827}
5828
5829// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
5830// `uv_mode` from the mi GRID where the one-slot-per-column map would have
5831// answered differently -- the sub-8x8 pair case where the pair's own first
5832// half had already overwritten the column slot the chroma-ref half reads.
5833thread_local! {
5834 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
5835 const { std::cell::Cell::new(0) };
5836}
5837
5838/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
5839pub fn uv_mode_grid_override_hits() -> usize {
5840 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
5841}
5842
5843// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
5844// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
5845// from an earlier block in that pixel row/column while the mi-exact map --
5846// which an inter block only started writing this round -- correctly says the
5847// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
5848// an INTER mode, and its `uv_mode` "is not set for inter blocks").
5849thread_local! {
5850 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
5851 const { std::cell::Cell::new(0) };
5852}
5853
5854/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
5855#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5856pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
5857 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
5858}
5859
5860// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
5861// suppressed at a TILE edge that is not a frame edge -- the above/left
5862// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
5863// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
5864// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
5865// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
5866// above would decide this tile's chroma edge filter strength.
5867thread_local! {
5868 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
5869 const { std::cell::Cell::new(0) };
5870}
5871
5872/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
5873#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5874pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
5875 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
5876}
5877
5878// lane-av1leftref: how many chroma intra-edge filter-type reads land on a
5879// left neighbour whose `uv_mode` at libaom's real read cell
5880// (`base_mi[ss_y * mi_stride - 1]` = row `+ss_y`, col `-1`) DIFFERS from the
5881// cell this decoder used to read (its own mi row). Two buckets: the raw mode
5882// value moved, and `is_smooth_mode` -- the boolean the read actually feeds --
5883// flipped. The second is the one that can move pixels.
5884thread_local! {
5885 static UV_LEFT_SS_Y_MODE_DIFF_HITS: std::cell::Cell<usize> =
5886 const { std::cell::Cell::new(0) };
5887 static UV_LEFT_SS_Y_SMOOTH_DIFF_HITS: std::cell::Cell<usize> =
5888 const { std::cell::Cell::new(0) };
5889}
5890thread_local! {
5891 static UV_LEFT_SS_Y_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5892}
5893
5894/// Current value of [`UV_LEFT_SS_Y_READS`].
5895pub fn uv_left_ss_y_reads() -> usize {
5896 UV_LEFT_SS_Y_READS.with(|c| c.get())
5897}
5898
5899/// Current value of [`UV_LEFT_SS_Y_MODE_DIFF_HITS`].
5900pub fn uv_left_ss_y_mode_diff_hits() -> usize {
5901 UV_LEFT_SS_Y_MODE_DIFF_HITS.with(|c| c.get())
5902}
5903
5904/// Current value of [`UV_LEFT_SS_Y_SMOOTH_DIFF_HITS`].
5905pub fn uv_left_ss_y_smooth_diff_hits() -> usize {
5906 UV_LEFT_SS_Y_SMOOTH_DIFF_HITS.with(|c| c.get())
5907}
5908
5909// lane-av1leftwit: decode-path chroma edge-filter-type reads at `ss_y > 0`
5910// whose left-neighbour COLUMN holds a run of length 1 -- the cell this
5911// decoder reads (its own mi row) and the cell libaom reads (one row down)
5912// were written by two DIFFERENT blocks, i.e. the left neighbour is at most
5913// 1 mi tall. That is the only geometry in which the `+ss_y` term can change
5914// the answer at all; `UV_LEFT_SS_Y_READS` alone proves nothing about it.
5915thread_local! {
5916 static UV_LEFT_1MI_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5917}
5918
5919/// Current value of [`UV_LEFT_1MI_SPLIT_HITS`].
5920pub fn uv_left_1mi_split_hits() -> usize {
5921 UV_LEFT_1MI_SPLIT_HITS.with(|c| c.get())
5922}
5923
5924// lane-av1leftwit: the per-tile epoch `uv_owner` cells are stamped with.
5925// Bumped in `Neighbours::start_tile`; never read by decode logic.
5926thread_local! {
5927 static UV_OWNER_EPOCH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
5928}
5929
5930// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
5931// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
5932// shapes the r1 chroma defect showed up on.
5933thread_local! {
5934 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5935 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5936}
5937
5938/// Current value of [`CFL_BLOCK_HITS`].
5939#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5940pub(crate) fn cfl_block_hits() -> usize {
5941 CFL_BLOCK_HITS.with(|c| c.get())
5942}
5943
5944/// Current value of [`UV_ANGLE_DELTA_HITS`].
5945#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5946pub(crate) fn uv_angle_delta_hits() -> usize {
5947 UV_ANGLE_DELTA_HITS.with(|c| c.get())
5948}
5949
5950// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
5951// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
5952// gate's proof this round's arms actually reached a real block, not just
5953// that `partition_w64` read one of those two symbol values.
5954thread_local! {
5955 static SB_RECT_HITS: std::cell::Cell<usize> =
5956 const { std::cell::Cell::new(0) };
5957}
5958
5959// Current value of [`SB_RECT_HITS`].
5960// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
5961// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
5962// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
5963// non-SPLIT edge arm actually decoded (before this round the bit was read and
5964// thrown away, so that arm was unreachable).
5965thread_local! {
5966 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
5967}
5968
5969/// Current value of [`EDGE_PART_HITS`].
5970#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5971pub(crate) fn edge_part_hits() -> [usize; 4] {
5972 EDGE_PART_HITS.with(|c| c.get())
5973}
5974
5975/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
5976#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5977pub(crate) fn reset_edge_part_hits() {
5978 EDGE_PART_HITS.with(|c| c.set([0; 4]));
5979}
5980
5981fn bump_edge_part(slot: usize) {
5982 hit_do! {
5983 EDGE_PART_HITS.with(|c| {
5984 let mut h = c.get();
5985 h[slot] += 1;
5986 c.set(h);
5987 });
5988 }
5989}
5990
5991#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5992pub(crate) fn sb_rect_hits() -> usize {
5993 SB_RECT_HITS.with(|c| c.get())
5994}
5995
5996// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
5997// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
5998// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
5999// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
6000// paths (intra and inter) feed the same counter.
6001//
6002// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
6003// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
6004// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
6005// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
6006// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
6007// every SB of the last row), so the 32-level slots stay 0 on that content and
6008// only these prove the arm fired.
6009thread_local! {
6010 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
6011 const { std::cell::Cell::new([0; 8]) };
6012}
6013
6014/// Current value of [`EDGE32_HITS`].
6015#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6016pub(crate) fn edge32_hits() -> [usize; 8] {
6017 EDGE32_HITS.with(|c| c.get())
6018}
6019
6020/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
6021/// reads are `if`-conditions, so the counter has to ride the expression.
6022fn bump_edge32_bit(base: usize, bit: usize) -> usize {
6023 bump_edge32(base + bit.min(1));
6024 bit
6025}
6026
6027fn bump_edge32(slot: usize) {
6028 hit_do! {
6029 EDGE32_HITS.with(|c| {
6030 let mut h = c.get();
6031 h[slot] += 1;
6032 c.set(h)
6033 });
6034 }
6035}
6036
6037// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
6038// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
6039// strip) fired. Real aomenc picks these at 64 even with
6040// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
6041// the counter the gate hard-asserts.
6042thread_local! {
6043 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
6044 const { std::cell::Cell::new([0; 4]) };
6045}
6046
6047/// Current value of [`SB_AB_HITS`], summed over the four arms.
6048#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6049pub(crate) fn sb_ab_hits() -> usize {
6050 SB_AB_HITS.with(|c| c.get().iter().sum())
6051}
6052
6053/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
6054/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
6055/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
6056/// proof of all four.
6057#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6058pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
6059 SB_AB_HITS.with(std::cell::Cell::get)
6060}
6061
6062// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
6063// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
6064// strips). Two counters, not one, because a gate that only proved "some 1:4
6065// strip fired" would pass on a stream that never coded the other axis, and
6066// every scan/context table this round added comes in a transposed pair.
6067thread_local! {
6068 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6069 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6070}
6071
6072/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
6073#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6074pub(crate) fn sb_rect4_horz_hits() -> usize {
6075 SB_RECT4_HORZ_HITS.with(|c| c.get())
6076}
6077
6078/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
6079#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6080pub(crate) fn sb_rect4_vert_hits() -> usize {
6081 SB_RECT4_VERT_HITS.with(|c| c.get())
6082}
6083
6084// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
6085// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
6086// strips), the arms the ReelB mid-film extract stops at.
6087thread_local! {
6088 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6089 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6090 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
6091 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
6092 /// `PARTITION_VERT_4`.
6093 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6094 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6095 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
6096 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
6097 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6098 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6099 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6100 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6101}
6102
6103// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
6104// a gate that only counted strips would pass on an all-skip stream, which
6105// exercises none of the new scan/context tables.
6106thread_local! {
6107 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6108}
6109
6110// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
6111// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
6112// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
6113// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
6114// counts the same for a 16x8/8x16 strip below 16x16.
6115thread_local! {
6116 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6117 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6118 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6119}
6120
6121/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
6122#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6123pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
6124 (
6125 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
6126 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
6127 )
6128}
6129
6130/// Current value of `SUB16_SPLIT_HITS`.
6131#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6132pub(crate) fn sub16_split_hits() -> usize {
6133 SUB16_SPLIT_HITS.with(|c| c.get())
6134}
6135
6136// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
6137// luma transform is SPLIT and which therefore leave through that fn's early
6138// return -- the arm that published no `TXFM_CONTEXT` band until this round.
6139thread_local! {
6140 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6141}
6142
6143/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
6144#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6145pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
6146 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
6147}
6148
6149/// Current value of `RECT4_COEFF_HITS`.
6150pub(crate) fn rect4_coeff_hits() -> usize {
6151 RECT4_COEFF_HITS.with(|c| c.get())
6152}
6153
6154// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
6155// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
6156// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
6157// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
6158// asserts the arms it proves separately so a run whose RD only picked one
6159// cannot pass as proof of the others.
6160thread_local! {
6161 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6162}
6163
6164/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
6165/// inter frame).
6166pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
6167 SB_AB_INTER_HITS.with(std::cell::Cell::get)
6168}
6169
6170// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
6171// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
6172// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
6173// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
6174// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
6175// arm separately so a run whose RD only picked one cannot pass as proof of
6176// four.
6177thread_local! {
6178 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6179}
6180
6181/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
6182/// inter frame).
6183pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
6184 AB16_INTER_HITS.with(std::cell::Cell::get)
6185}
6186
6187// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
6188// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
6189// counts the odd strips that close a 4:2:0 chroma pair
6190// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
6191// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
6192// the PREVIOUS strip's own mv/ref/filters -- libaom
6193// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
6194// through `is_sub8x8_inter` (same file, :54).
6195thread_local! {
6196 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6197 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6198 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6199 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6200}
6201
6202// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
6203// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
6204// pair's single 8x4 (4x8) chroma unit for BOTH strips.
6205thread_local! {
6206 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
6207 const { std::cell::Cell::new([0; 3]) };
6208}
6209
6210/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
6211/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
6212pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
6213 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
6214 (v[0], v[1], v[2])
6215}
6216
6217/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
6218/// strips, chroma pairs closed, chroma pairs built from two different
6219/// strips' motion vectors)`.
6220pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
6221 (
6222 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
6223 INTER16_VERT4_HITS.with(std::cell::Cell::get),
6224 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
6225 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
6226 )
6227}
6228
6229/// One 16x4 / 4x16 inter strip's chroma situation, handed to
6230/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
6231/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
6232/// that all mean "an ordinary block, chroma of its own".
6233#[derive(Clone, Copy)]
6234pub(crate) struct InterStripChroma {
6235 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
6236 /// read and reconstruct NO chroma at all.
6237 has_chroma: bool,
6238 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
6239 horz: bool,
6240 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
6241 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
6242 /// i.e. the origin of the 8x4 (4x8) chroma transform.
6243 pair_mi: (usize, usize),
6244 /// The previous (even) strip's single-reference MC parameters, `None`
6245 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
6246 /// and the whole chroma block is predicted from THIS strip's mv.
6247 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
6248}
6249
6250/// The single-reference MC parameters of the inter block that decoded
6251/// last -- read by the next 1:4 strip to build its pair's chroma.
6252
6253fn bump_ab16_inter(arm: usize) {
6254 hit_do! {
6255 AB16_INTER_HITS.with(|c| {
6256 let mut v = c.get();
6257 v[arm] += 1;
6258 c.set(v);
6259 });
6260 }
6261}
6262
6263// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
6264// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
6265// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
6266thread_local! {
6267 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6268 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6269 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6270 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6271 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6272 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
6273 /// base mi differs from what the strip's own (odd) mi would have said --
6274 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
6275 /// key frame miss by 1. Zero here means a gate never exercised the fix.
6276 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6277 /// lane-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s.
6278 static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6279 /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip.
6280 static RECT4_16_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6281 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
6282 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
6283 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6284 /// lane-av1-loss64: chroma transform units the frame-edge clip skipped
6285 /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in
6286 /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless
6287 /// block overhanging the frame does NOT code.
6288 static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6289 /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma
6290 /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`,
6291 /// decodeframe.c:1262) instead of leaking the previous occupant's.
6292 static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6293 /// lane-av1-llband: 4x4 chroma transform units a lossless HORZ/VERT strip
6294 /// walked at subsampling 0/0 (one unit per mi cell -- the geometry the
6295 /// hardcoded 4:2:0 span mis-stepped).
6296 static RECT_SPLIT_LOSSLESS_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6297 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma
6298 /// coefficients a lossless frame walked as per-4x4 inter units (the walk
6299 /// that replaced the single rect unit).
6300 static INTRABC_RECT8_LOSSLESS_LUMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6301 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a
6302 /// lossless 4:4:4 frame walked as per-4x4 [`TxbSet::Chroma4`] units.
6303 static INTRABC_RECT8_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6304 /// lane-av1loss444kf: 4:4:4 lossless sub-8x8 RECT (8x4 / 4x8) leaf chroma
6305 /// units whose libaom-faithful block-relative reach
6306 /// ([`Reach::of_tu`] over the leaf's own bsize) differs from the
6307 /// standalone-BLOCK_4X4 lookup that used to answer for them. Zero means
6308 /// no stream reached a rect leaf where the two disagree -- a gate
6309 /// asserting the reach fix must see this nonzero, or the fixture never
6310 /// exercised the fixed path.
6311 static SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6312}
6313
6314/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
6315/// that reconstructed as flat DC before lane-kf1200 r2).
6316pub fn skip_cfl_hits() -> usize {
6317 SKIP_CFL_HITS.with(|c| c.get())
6318}
6319
6320/// How many chroma transform units the frame-edge clip skipped in
6321/// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a
6322/// stream whose lossless blocks never overhang the frame -- a gate asserting
6323/// the clip fired must see this nonzero.
6324pub fn chroma_edge_tu_clip_hits() -> usize {
6325 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get())
6326}
6327
6328/// How many skipped lossless intrabc rect strips had their luma entropy
6329/// bands zeroed per unit (lane-av1-loss64).
6330pub fn skip_lossless_band_reset_hits() -> usize {
6331 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get())
6332}
6333
6334/// How many 4x4 chroma transform units a lossless HORZ/VERT strip walked at
6335/// subsampling 0/0 (lane-av1-llband). Zero means a stream never decoded the
6336/// 4:4:4 lossless unit walk this counter proves -- a gate asserting the fix
6337/// must see this nonzero.
6338pub fn rect_split_lossless_chroma444_hits() -> usize {
6339 RECT_SPLIT_LOSSLESS_CHROMA444_HITS.with(|c| c.get())
6340}
6341
6342/// How many unskipped intrabc 8x4/4x8 leaves a lossless frame walked luma as
6343/// per-4x4 inter units (lane-av1-ibc444rect).
6344pub fn intrabc_rect8_lossless_luma_hits() -> usize {
6345 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.get())
6346}
6347
6348/// How many unskipped intrabc 8x4/4x8 leaves a lossless 4:4:4 frame walked
6349/// chroma as per-4x4 [`TxbSet::Chroma4`] units (lane-av1-ibc444rect).
6350pub fn intrabc_rect8_lossless_chroma_hits() -> usize {
6351 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6352}
6353
6354/// How many 4:4:4 lossless sub-8x8 RECT leaf chroma units took the
6355/// block-relative reach libaom's `has_bottom_left` gives, where the
6356/// standalone-BLOCK_4X4 lookup that used to answer disagreed
6357/// (lane-av1loss444kf). Zero on a stream with no such leaf.
6358pub fn sub8_chroma444_lossless_tu_reach_hits() -> usize {
6359 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.get())
6360}
6361
6362/// Gate-side reset for [`SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS`].
6363pub fn reset_sub8_chroma444_tu_reach_hits() {
6364 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.set(0));
6365}
6366
6367/// Gate-side reset for the two lane-av1-ibc444rect counters above.
6368pub fn reset_ibc444rect_hits() {
6369 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.set(0));
6370 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6371}
6372
6373/// Gate-side reset for the two lane-av1-loss64 counters above.
6374pub fn reset_loss64_hits() {
6375 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0));
6376 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0));
6377}
6378
6379/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
6380/// from the pair's base mi than the strip's own mi would have given.
6381pub fn rect4_16_uv_pair_filt_hits() -> usize {
6382 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
6383}
6384
6385/// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane.
6386pub fn rect4_16_lossless_chroma_hits() -> usize {
6387 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6388}
6389
6390/// How many 16x4/4x16 strips reconstructed as intra block copy.
6391pub fn rect4_16_intrabc_hits() -> usize {
6392 RECT4_16_INTRABC_HITS.with(|c| c.get())
6393}
6394
6395/// Zero the lane-av1-rect14 pair counters so a gate measures one stream.
6396pub fn reset_rect4_16_pair_hits() {
6397 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6398 RECT4_16_INTRABC_HITS.with(|c| c.set(0));
6399}
6400
6401// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
6402// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
6403// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
6404// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
6405// intra-edge filter type must come from the chroma-reference position).
6406thread_local! {
6407 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6408 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6409}
6410
6411/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
6412pub fn reelc_chroma_counters() -> (usize, usize) {
6413 (
6414 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
6415 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
6416 )
6417}
6418
6419/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
6420/// strips, chroma-reference strips, strips with a coded residual, strips
6421/// whose luma transform is split)`.
6422pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
6423 (
6424 RECT4_16_HORZ_HITS.with(|c| c.get()),
6425 RECT4_16_VERT_HITS.with(|c| c.get()),
6426 RECT4_16_CHROMA_HITS.with(|c| c.get()),
6427 RECT4_16_COEFF_HITS.with(|c| c.get()),
6428 RECT4_16_SPLIT_HITS.with(|c| c.get()),
6429 )
6430}
6431
6432/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
6433pub(crate) fn rect4_32_horz_hits() -> usize {
6434 RECT4_32_HORZ_HITS.with(|c| c.get())
6435}
6436
6437/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
6438pub(crate) fn rect4_32_vert_hits() -> usize {
6439 RECT4_32_VERT_HITS.with(|c| c.get())
6440}
6441
6442/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
6443pub(crate) fn rect4_32_horz_inter_hits() -> usize {
6444 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
6445}
6446
6447/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
6448pub(crate) fn rect4_32_vert_inter_hits() -> usize {
6449 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
6450}
6451
6452/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
6453pub(crate) fn inter_sb_horz_hits() -> usize {
6454 INTER_SB_HORZ_HITS.with(|c| c.get())
6455}
6456
6457/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
6458pub(crate) fn inter_sb_vert_hits() -> usize {
6459 INTER_SB_VERT_HITS.with(|c| c.get())
6460}
6461
6462/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
6463pub(crate) fn inter_sb_horz4_hits() -> usize {
6464 INTER_SB_HORZ4_HITS.with(|c| c.get())
6465}
6466
6467/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
6468pub(crate) fn inter_sb_vert4_hits() -> usize {
6469 INTER_SB_VERT4_HITS.with(|c| c.get())
6470}
6471
6472// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
6473// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
6474// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
6475// just inert-compiled. Zero forever on a passing gate means that gate's
6476// stream never carries `delta_q_present=1` through a rect64 block.
6477thread_local! {
6478 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
6479 const { std::cell::Cell::new(0) };
6480}
6481
6482/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
6483#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6484pub(crate) fn rect64_qidx_drift_hits() -> usize {
6485 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
6486}
6487
6488// lane-partab r1: how many 32x32 quadrants decoded an AB partition
6489// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
6490// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
6491// free-partition gate's proof this round's arms actually fired.
6492thread_local! {
6493 static PARTAB_HITS: std::cell::Cell<usize> =
6494 const { std::cell::Cell::new(0) };
6495}
6496
6497/// Current value of [`PARTAB_HITS`].
6498#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6499pub(crate) fn partab_hits() -> usize {
6500 PARTAB_HITS.with(|c| c.get())
6501}
6502
6503// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
6504// one counter per arm rather than one shared total -- the gate hard-asserts
6505// each of these individually nonzero so a recipe that only ever fires
6506// HORZ_A can't silently stand in for the whole set.
6507thread_local! {
6508 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
6509 const { std::cell::Cell::new(0) };
6510 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
6511 const { std::cell::Cell::new(0) };
6512 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
6513 const { std::cell::Cell::new(0) };
6514 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
6515 const { std::cell::Cell::new(0) };
6516}
6517
6518/// Current value of [`INTRA_HORZ_A_HITS`].
6519#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6520pub(crate) fn intra_horz_a_hits() -> usize {
6521 INTRA_HORZ_A_HITS.with(|c| c.get())
6522}
6523/// Current value of [`INTRA_HORZ_B_HITS`].
6524#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6525pub(crate) fn intra_horz_b_hits() -> usize {
6526 INTRA_HORZ_B_HITS.with(|c| c.get())
6527}
6528/// Current value of [`INTRA_VERT_A_HITS`].
6529#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6530pub(crate) fn intra_vert_a_hits() -> usize {
6531 INTRA_VERT_A_HITS.with(|c| c.get())
6532}
6533/// Current value of [`INTRA_VERT_B_HITS`].
6534#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6535pub(crate) fn intra_vert_b_hits() -> usize {
6536 INTRA_VERT_B_HITS.with(|c| c.get())
6537}
6538
6539// How many [`read_inter_compound_mode`] reads actually happened
6540// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
6541// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
6542// mvstack build), not just that `comp_mode` fired. Still refused right
6543// after (no MV assignment or MC wired), so this only counts attempted
6544// reads.
6545thread_local! {
6546 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
6547 const { std::cell::Cell::new(0) };
6548}
6549
6550/// Current value of [`COMPOUND_MODE_HITS`].
6551#[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds
6552pub(crate) fn compound_mode_hits() -> usize {
6553 COMPOUND_MODE_HITS.with(|c| c.get())
6554}
6555
6556/// How many query blocks folded in at least one temporal MV candidate
6557/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
6558/// temporal-MV gate's own firing counter (lane-av1tmvp).
6559///
6560/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
6561/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
6562/// this file (`decode_inter_block`) still passes `tpl: None` -- this
6563/// counter compiles and the projection math it counts is unit-tested
6564/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
6565/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
6566/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
6567/// against any real stream today. See the module doc on
6568/// `crate::motion_field` and this crate's ledger for the remaining wiring.
6569#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6570pub(crate) fn tmv_hits() -> usize {
6571 crate::mvstack::tmv_hits()
6572}
6573
6574/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
6575/// produced on this thread, the 10-bit inter gate's firing proof.
6576#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6577pub(crate) fn inter_pred_hits() -> usize {
6578 crate::mc::inter_pred_hits()
6579}
6580
6581/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
6582/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
6583/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
6584/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
6585/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
6586/// needs to turn a query block's own resolved `ref_frame` into
6587/// `TplArgs::cur_offset_0` (spec 7.9.3).
6588pub(crate) struct TplFrameArgs<'a> {
6589 pub field: &'a crate::motion_field::TplField,
6590 pub order_hint_bits: u32,
6591 pub order_hint: u32,
6592 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
6593 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
6594 /// frame's own `ref_frame_idx` names for each single reference.
6595 pub ref_order_hints: [u32; 7],
6596}
6597
6598/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
6599/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
6600/// decoded `grid`: every 4x4 unit an inter block covers reads the same
6601/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
6602/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
6603/// exact — every block this crate ever codes is at least 8x8, so no 8x8
6604/// cell straddles two different blocks' values.
6605#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
6606pub(crate) fn build_motion_field(
6607 grid: &MiGrid,
6608 mi_cols: usize,
6609 mi_rows: usize,
6610 order_hint: u32,
6611 order_hint_bits: u32,
6612 ref_order_hints: [u32; 7],
6613 fctx: &FrameCtx,
6614) -> crate::motion_field::MotionField {
6615 let mut field =
6616 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
6617 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
6618 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
6619 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
6620 // referencing one stores only its OTHER side's mv. With
6621 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
6622 // nothing is skipped.
6623 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
6624 // only on the reference frame, so it is 7 table lookups per frame instead
6625 // of two per inter unit.
6626 let other_side: [bool; 8] = std::array::from_fn(|rf| {
6627 let i = rf.wrapping_sub(LAST_FRAME as usize);
6628 order_hint_bits != 0
6629 && i < 7
6630 && (crate::motion_field::get_relative_dist(
6631 order_hint_bits,
6632 ref_order_hints[i],
6633 order_hint,
6634 ) > 0
6635 || ref_order_hints[i] == order_hint)
6636 });
6637 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
6638 // capped at 12 bits per component; a longer one is not stored at all.
6639 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
6640 let (cols, rows, cells) = field.cells_mut();
6641 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
6642 // never touch each other (an 8x8 cell lives in one cell row, and mi row
6643 // `row` writes cell row `row / 2`).
6644 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
6645 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
6646 let out = &mut out[(row / 2 - r0) * cols..][..cols];
6647 for col in 0..mi_cols {
6648 let Some(info) = grid.get_frame(row, col) else {
6649 continue;
6650 };
6651 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
6652 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
6653 // so an intra block -- or an inter block whose every slot is on the
6654 // other side / over the limit -- wipes what an earlier block wrote
6655 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
6656 // share a cell).
6657 if !info.is_inter {
6658 out[col / 2] = None;
6659 continue;
6660 }
6661 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
6662 // qualifying one wins -- a compound block stores its second
6663 // reference's mv, never its first (unless the second is on the
6664 // other side or over the limit). Storing slot 0 unconditionally
6665 // put the wrong (mv, ref_frame_offset) pair in every compound
6666 // block's cell, which a later frame's temporal candidate then
6667 // projected with the wrong reference distance.
6668 let mut saved: Option<crate::motion_field::SavedMv> = None;
6669 for (rf, mv) in [
6670 (info.ref_frame, Some(mv32(info.mv))),
6671 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
6672 ] {
6673 let (Some(mv), true) = (mv, rf > 0) else {
6674 continue;
6675 };
6676 if other_side[rf as usize] {
6677 continue;
6678 }
6679 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
6680 continue;
6681 }
6682 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
6683 }
6684 out[col / 2] = saved;
6685 }
6686 }
6687 };
6688 // lane-mf: the whole-frame pass split over the filter pool in cell-row
6689 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
6690 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
6691 let bands = crate::par::bands(rows, crate::par::filter_threads());
6692 if bands.len() <= 1 {
6693 fill(0, rows, cells);
6694 } else {
6695 let shared = crate::par::Shared::new(cells);
6696 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
6697 // SAFETY: cell rows `r0..r1` are this band's alone.
6698 let cells = unsafe { shared.get() };
6699 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
6700 });
6701 }
6702 if crate::envflags::env_flag!("EC_TRACE_TPL") {
6703 eprintln!("EC_TPL_SAVED oh={order_hint}");
6704 for (r, row) in field.occupancy().iter().enumerate() {
6705 eprintln!("EC_TPL_SAVED r{r} {row}");
6706 }
6707 }
6708 field
6709}
6710
6711/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
6712/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
6713#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6714pub(crate) fn ref_hits(ref_frame: i8) -> usize {
6715 let c = match ref_frame {
6716 LAST2_FRAME => &LAST2_HITS,
6717 LAST3_FRAME => &LAST3_HITS,
6718 GOLDEN_FRAME => &GOLDEN_HITS,
6719 BWDREF_FRAME => &BWDREF_HITS,
6720 ALTREF2_FRAME => &ALTREF2_HITS,
6721 ALTREF_FRAME => &ALTREF_HITS,
6722 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
6723 };
6724 c.with(|v| v.get())
6725}
6726
6727/// The sequence header's `enable_intra_edge_filter`, set once per
6728/// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
6729/// own read of it, kept off the call stack (see that function's own doc
6730/// comment for why) rather than threaded through every `read_plane`/
6731/// `decode_block`/`decode_leaf8` call between here and there.
6732
6733/// Set [`ENABLE_EDGE_FILTER`] for this thread.
6734///
6735/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
6736/// never did -- so an inter frame's intra blocks read whatever value the last
6737/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
6738/// harmless (its own key frame sets it first), but a caller that decodes an
6739/// inter frame directly, or a test harness running several streams on one
6740/// thread, inherits a foreign sequence's bit: decode stops being a pure
6741/// function of the bitstream. `decode_stream` now calls this once per stream
6742/// from the sequence header, which covers every frame including inter ones.
6743pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
6744 fctx.enable_edge_filter.with(|f| f.set(value));
6745}
6746
6747/// Current value of [`ANGLE_DELTA_HITS`].
6748#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6749pub(crate) fn angle_delta_hits() -> usize {
6750 ANGLE_DELTA_HITS.with(|c| c.get())
6751}
6752
6753/// Current value of [`TX_CLASS1_HITS`].
6754#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6755pub(crate) fn tx_class1_hits() -> usize {
6756 TX_CLASS1_HITS.with(|c| c.get())
6757}
6758
6759// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
6760// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
6761// bottom) this thread's decode actually reconstructed -- the same
6762// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
6763// genuinely exercised the sub-8x8 leaf path rather than every attempt
6764// coincidentally landing on `PARTITION_NONE`.
6765thread_local! {
6766 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6767 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
6768 /// sub-blocks (lane-intersub8).
6769 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6770 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
6771 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
6772 /// `[1] = VERT` (two BLOCK_4X8).
6773 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
6774 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
6775 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
6776 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
6777 /// MIXED groups whose chroma reference is INTER while its sibling is
6778 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
6779 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
6780 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
6781 /// so only this cell separates the split arm from the HORZ/VERT one).
6782 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
6783}
6784
6785/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
6786/// mixed groups, split 4x4 leaves)`.
6787pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
6788 SUB8_INTRA_RECT_HITS.with(|c| {
6789 let h = c.get();
6790 (h[0], h[1], h[2], h[3], h[4])
6791 })
6792}
6793
6794/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
6795pub fn sub8_inter_rect_hits() -> (usize, usize) {
6796 SUB8_INTER_RECT_HITS.with(|c| {
6797 let h = c.get();
6798 (h[0], h[1])
6799 })
6800}
6801
6802// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
6803// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
6804// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
6805// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
6806// (b) was 0 for every stream before this round -- the leaf path never touched
6807// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
6808// filtered where libaom skips it. A gate asserts both are non-zero.
6809thread_local! {
6810 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6811 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6812 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
6813 // crosses the cropped frame edge -- the only units for which "clamp at
6814 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
6815 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
6816 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
6817 // whose width or height is not a multiple of 8 is the only shape that
6818 // produces one; the straddling-band gate arms assert it grew.
6819 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6820 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
6821 // (see `Neighbours::skip_written`).
6822 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6823 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
6824 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
6825 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
6826 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
6827 // 8-tall strip pair where only one half is skip must still be FILTERED.
6828 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6829 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6830}
6831
6832/// Current value of `RECT_SKIP_BAND_HITS`.
6833pub fn rect_skip_band_hits() -> usize {
6834 RECT_SKIP_BAND_HITS.with(|c| c.get())
6835}
6836
6837/// Current value of `CDEF_MIXED_SKIP_UNITS`.
6838pub fn cdef_mixed_skip_units() -> usize {
6839 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
6840}
6841
6842/// Current value of `CDEF_SKIPPED_UNITS`.
6843#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6844pub(crate) fn cdef_skipped_units() -> usize {
6845 CDEF_SKIPPED_UNITS.with(|c| c.get())
6846}
6847
6848/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
6849/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
6850pub fn cdef_unwritten_skip_units() -> usize {
6851 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
6852}
6853
6854/// Current value of `INTER8_SKIP_BAND_HITS`.
6855#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6856pub(crate) fn inter8_skip_band_hits() -> usize {
6857 INTER8_SKIP_BAND_HITS.with(|c| c.get())
6858}
6859
6860/// Current value of `CDEF_STRADDLE_UNITS`.
6861#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6862pub(crate) fn cdef_straddle_units() -> usize {
6863 CDEF_STRADDLE_UNITS.with(|c| c.get())
6864}
6865
6866/// Current value of [`SUB8_SPLIT_HITS`].
6867#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6868pub(crate) fn sub8_split_hits() -> usize {
6869 SUB8_SPLIT_HITS.with(|c| c.get())
6870}
6871
6872/// Current value of [`SUB8_INTER_SPLIT_HITS`].
6873pub fn sub8_inter_split_hits() -> usize {
6874 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
6875}
6876
6877// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
6878// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
6879// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
6880// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
6881// first sub-block's type is never the one). Reading it off sub-block 0
6882// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
6883// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
6884// see this rule through this counter.
6885thread_local! {
6886 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6887}
6888
6889/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
6890pub fn sub8_chroma_tx_from_ref_hits() -> usize {
6891 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
6892}
6893
6894fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
6895 if coeffs && first_sub != chroma_ref {
6896 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
6897 }
6898}
6899
6900// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
6901// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
6902// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
6903// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
6904// asserts on these two rather than a plain leaf count.
6905thread_local! {
6906 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6907 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6908 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
6909 /// two 4x4 transform units, predicted one after the other. A separate
6910 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
6911 /// the gate can prove THIS path fired.
6912 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6913 /// 16x8/8x16 intra strips whose prediction actually read past the block's
6914 /// own width (above-right) or height (below-left) -- the samples
6915 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
6916 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
6917 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6918 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
6919 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
6920 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6921}
6922
6923/// Current value of [`RECT8_SPLIT_TX_HITS`].
6924#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6925pub(crate) fn rect8_split_tx_hits() -> usize {
6926 RECT8_SPLIT_TX_HITS.with(|c| c.get())
6927}
6928
6929/// Current value of [`RECT_STRIP_PRED_HITS`].
6930#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6931pub(crate) fn rect_strip_pred_hits() -> usize {
6932 RECT_STRIP_PRED_HITS.with(|c| c.get())
6933}
6934
6935/// Current value of [`RECT_STRIP_REACH_HITS`].
6936#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6937pub(crate) fn rect_strip_reach_hits() -> usize {
6938 RECT_STRIP_REACH_HITS.with(|c| c.get())
6939}
6940
6941/// Current value of [`TX4X8_CODED_HITS`].
6942#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6943pub(crate) fn tx4x8_coded_hits() -> usize {
6944 TX4X8_CODED_HITS.with(|c| c.get())
6945}
6946
6947/// Current value of [`TX8X4_CODED_HITS`].
6948#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6949pub(crate) fn tx8x4_coded_hits() -> usize {
6950 TX8X4_CODED_HITS.with(|c| c.get())
6951}
6952
6953// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
6954// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
6955// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
6956// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
6957// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
6958// (`eob_pt_{16,64,128,256}_chroma_class1`).
6959thread_local! {
6960 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
6961 const { std::cell::Cell::new(0) };
6962}
6963
6964/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
6965#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6966pub(crate) fn chroma_eob_class1_hits() -> usize {
6967 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
6968}
6969
6970/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
6971/// `tx_type` put this block's `eob_pt` on the class-1 row.
6972fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
6973 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
6974 hit!(CHROMA_EOB_CLASS1_HITS);
6975 }
6976}
6977
6978const SUB_MI: u32 = 4;
6979const MI: usize = 4;
6980const SB: usize = 64;
6981/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
6982/// (tile start, superblock-row start).
6983///
6984/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
6985/// `av1_get_partition_plane_context` reads its own zero-initialised
6986/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
6987/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
6988/// (64), which reads identically at every level up to 64x64 but sets the bit
6989/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
6990/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
6991/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
6992const NO_NEIGHBOUR_SIDE: usize = 128;
6993const BLOCK: usize = 32;
6994const SUB: usize = 16;
6995const TX32: usize = 32;
6996const TX16: usize = 16;
6997const TX8: usize = 8;
6998const TX4: usize = 4;
6999const DC_PRED: usize = 0;
7000/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
7001/// carries an angle delta — [`crate::tile`]'s own private copy of the same
7002/// constant.
7003const V_PRED: usize = 1;
7004const H_PRED: usize = 2;
7005/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
7006/// `Fimode_To_Intradir`, libaom `blockd.h`).
7007const D157_PRED: usize = 6;
7008/// The last directional mode, `D67_PRED`.
7009const D67_PRED: usize = 8;
7010/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
7011/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
7012/// codes anything else, so this decoder never reads anything else either.
7013const ANGLE_DELTA_ZERO: usize = 3;
7014const NUM_BASE_LEVELS: i32 = 2;
7015const COEFF_BASE_RANGE: i32 = 12;
7016const BR_STEP: i32 = 3;
7017const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
7018
7019/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
7020/// whose probability mass a superblock or block half outside the frame
7021/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
7022/// duplicated here (that module is another lane's territory this round) and
7023/// kept in step with it by the byte-exact round-trip tests below rather than
7024/// by sharing code.
7025const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
7026const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
7027
7028fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
7029 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7030 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
7031 }
7032}
7033
7034fn element_prob(cdf: &[u16], element: usize) -> u16 {
7035 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
7036}
7037
7038/// The two-symbol CDF a partial superblock/block's forced-split flag is read
7039/// with: the mass of `elements` becomes the probability of the one partition
7040/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
7041/// (the encoder's non-adapting counterpart to this read).
7042fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
7043 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
7044 [32768 - split, 32768, 0]
7045}
7046
7047fn unsupported(what: impl Into<String>) -> Error {
7048 Error::unsupported("AV1 tile", what.into())
7049}
7050
7051/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
7052/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
7053/// same rule.
7054pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
7055 match base_q_idx {
7056 0..=20 => 0,
7057 21..=60 => 1,
7058 61..=120 => 2,
7059 _ => 3,
7060 }
7061}
7062
7063/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
7064/// [`crate::tile`]'s writer generates its scan tables with.
7065fn default_scan(side: usize) -> &'static [u16] {
7066 // One table per transform side (4/8/16/32), built once: this used to be a
7067 // fresh heap allocation plus the whole anti-diagonal walk on every
7068 // transform block read.
7069 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
7070 [
7071 default_scan_gen(4),
7072 default_scan_gen(8),
7073 default_scan_gen(16),
7074 default_scan_gen(32),
7075 ]
7076 });
7077 assert!(
7078 matches!(side, 4 | 8 | 16 | 32),
7079 "no default scan for a {side}-point transform"
7080 );
7081 &SCANS[side.trailing_zeros() as usize - 2]
7082}
7083
7084fn default_scan_gen(side: usize) -> Vec<u16> {
7085 let mut scan = Vec::with_capacity(side * side);
7086 for d in 0..(2 * side - 1) {
7087 let lo = d.saturating_sub(side - 1);
7088 let hi = d.min(side - 1);
7089 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
7090 if d % 2 == 0 {
7091 scan.extend(diagonal.rev());
7092 } else {
7093 scan.extend(diagonal);
7094 }
7095 }
7096 scan
7097}
7098
7099/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
7100/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
7101/// in, instead of the default zigzag. libaom's own tables are keyed by a
7102/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
7103/// physically column-major level buffer, but they decompose to the exact
7104/// same (row, col) walk as a flat row-major traversal of *our* row-major
7105/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
7106/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
7107/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
7108/// transposed (column 0 down every row, then column 1, ...).
7109pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
7110 class_scan_table_wh(side, side, class)
7111}
7112
7113/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
7114/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
7115/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
7116/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
7117/// transcribed with -- `mrow` is the plain row-major raster in our indexing
7118/// and `mcol` its transpose, at rect sizes exactly as at square ones.
7119fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
7120 match class {
7121 TxClass::Vert => (0..(w * h) as u16).collect(),
7122 TxClass::Horiz => (0..w)
7123 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
7124 .collect(),
7125 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
7126 }
7127}
7128
7129fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
7130 match scan_idx {
7131 0 => 0,
7132 i if i <= area / 8 => 1,
7133 i if i <= area / 4 => 2,
7134 _ => 3,
7135 }
7136}
7137
7138/// One cell of [`read_coeffs`]'s level buffer.
7139///
7140/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
7141/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
7142/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
7143/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
7144/// zero cells instead of needing the `row >= side || col >= side` edge test
7145/// this used to run five times per coefficient. Nothing writes a padding
7146/// cell, so the values are the same zeros the test returned.
7147#[inline]
7148fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7149 grid[row * stride + col] as i32
7150}
7151
7152/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
7153/// `txb_common.h`): everything but the two lone-axis-identity types this
7154/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
7155#[derive(Clone, Copy, PartialEq, Eq)]
7156pub(crate) enum TxClass {
7157 TwoD,
7158 Horiz,
7159 Vert,
7160}
7161
7162impl TxClass {
7163 pub(crate) fn of(tx_type: TxType) -> Self {
7164 match tx_type {
7165 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
7166 // key on axis alone -- FLIPADST is still ADST for this purpose.
7167 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
7168 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
7169 _ => Self::TwoD,
7170 }
7171 }
7172}
7173
7174/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
7175/// table (indexed by the position along the transform's *coded* axis --
7176/// `col` for horiz, `row` for vert) that places their contexts past the 2D
7177/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
7178/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
7179pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
7180 match i {
7181 0 => 26,
7182 1 => 31,
7183 _ => 36,
7184 }
7185}
7186
7187fn base_ctx(
7188 grid: &[u8],
7189 stride: usize,
7190 row: usize,
7191 col: usize,
7192 class: TxClass,
7193 rect_shape: Option<(usize, usize)>,
7194) -> usize {
7195 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
7196 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
7197 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
7198 // position through the full 1D neighbour sum and offset table. Skipping
7199 // that for every class desynced the last (DC) coefficient of a
7200 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
7201 // 0, which then read one extra `BR` symbol at the max and forced a
7202 // spurious third Golomb call).
7203 if class == TxClass::TwoD && row == 0 && col == 0 {
7204 return 0;
7205 }
7206 let offsets: [(usize, usize); 5] = match class {
7207 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7208 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7209 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7210 };
7211 let mag: i32 = offsets
7212 .iter()
7213 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
7214 .sum();
7215 let ctx = ((mag + 1) >> 1).min(4) as usize;
7216 match class {
7217 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
7218 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
7219 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
7220 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
7221 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
7222 // strip, which own a genuinely different table from the square one
7223 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
7224 // square table vs the real ctx 13 the rect table gives).
7225 TxClass::TwoD => {
7226 // lane-rectsplit r4: apply libaom's GENERATING RULE
7227 // (`txb_common.h:199-209`) directly instead of indexing the
7228 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
7229 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
7230 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
7231 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
7232 // so 32 consecutive entries are one COLUMN: the [`cdf`]
7233 // transcriptions are `[col][row]` and this read had them as
7234 // `[row][col]` -- the transpose, i.e. the other shape's rule with
7235 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
7236 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
7237 // pins the rule against the tables over their whole 5x5 domain.
7238 if let Some((w, h)) = rect_shape {
7239 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
7240 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
7241 }
7242 if w < h && row < 2 {
7243 return ctx + 11;
7244 }
7245 if w > h && col < 2 {
7246 return ctx + 16;
7247 }
7248 }
7249 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7250 }
7251 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7252 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7253 }
7254}
7255
7256/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
7257/// offsets into the padded level frame (lane-coefread): the tap pattern is a
7258/// function of the tx class alone, which is fixed for a whole transform unit,
7259/// so resolving it once per unit takes the class match and the `(dr, dc)`
7260/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
7261/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
7262/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
7263/// original `(dr, dc)` form.
7264fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
7265 match class {
7266 TxClass::TwoD => (
7267 [stride, 1, stride + 1, 2 * stride, 2],
7268 [stride, 1, stride + 1],
7269 ),
7270 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
7271 TxClass::Vert => (
7272 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
7273 [stride, 1, 2 * stride],
7274 ),
7275 }
7276}
7277
7278/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
7279/// neighbours) + 1) >> 1`, clamped to 4.
7280#[inline(always)]
7281fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
7282 let mut mag = 0u32;
7283 for &t in taps {
7284 mag += u32::from(grid[idx + t]).min(3);
7285 }
7286 (((mag + 1) >> 1) as usize).min(4)
7287}
7288
7289/// [`br_ctx`]'s neighbour sum, off flat taps.
7290#[inline(always)]
7291fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
7292 let mut mag = 0u32;
7293 for &t in taps {
7294 mag += u32::from(grid[idx + t]);
7295 }
7296 (((mag + 1) >> 1) as usize).min(6)
7297}
7298
7299/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
7300/// origin-offset tail the two coefficient readers state inline; kept as the
7301/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
7302/// flat one against.
7303#[cfg(test)]
7304fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7305 let extra = match class {
7306 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
7307 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
7308 TxClass::Vert => neighbour(grid, stride, row + 2, col),
7309 };
7310 let mag = neighbour(grid, stride, row + 1, col) + neighbour(grid, stride, row, col + 1) + extra;
7311 let mag = (((mag + 1) >> 1).min(6)) as usize;
7312 if row == 0 && col == 0 {
7313 return mag;
7314 }
7315 let near_origin = match class {
7316 TxClass::TwoD => row < 2 && col < 2,
7317 TxClass::Horiz => col == 0,
7318 TxClass::Vert => row == 0,
7319 };
7320 if near_origin { mag + 7 } else { mag + 14 }
7321}
7322
7323/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
7324/// transposed from libaom's column-major buffer into this decoder's row-major
7325/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
7326/// against the real table). Not the square zigzag formula generalized to
7327/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
7328const SCAN_32X16: [u16; 512] = [
7329 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7330 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39, 8,
7331 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72, 41,
7332 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229, 198,
7333 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, 13,
7334 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418, 387,
7335 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326, 295,
7336 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234, 203,
7337 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142, 111, 80,
7338 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19, 485, 454,
7339 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424, 393, 362,
7340 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332, 301, 270,
7341 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178,
7342 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148, 117, 86, 55,
7343 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, 491, 460, 429,
7344 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430, 399, 368, 337,
7345 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338, 307, 276, 245,
7346 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246, 215, 184, 153,
7347 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154, 123, 92, 61, 30,
7348 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 497, 466, 435,
7349 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405, 374, 343, 312,
7350 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251, 220, 189, 158,
7351 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439, 408, 377, 346,
7352 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503, 472, 441, 410,
7353 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443, 412, 381, 350,
7354 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415, 509, 478, 447,
7355 510, 479, 511,
7356];
7357
7358/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
7359/// [`SCAN_32X16`]'s doc comment).
7360const SCAN_16X32: [u16; 512] = [
7361 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,
7362 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
7363 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
7364 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
7365 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
7366 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
7367 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
7368 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
7369 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
7370 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
7371 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
7372 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
7373 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
7374 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
7375 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
7376 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
7377 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
7378 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
7379 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
7380 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
7381 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
7382 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
7383 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
7384 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
7385 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
7386 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
7387];
7388
7389/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
7390/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
7391/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
7392/// the same source).
7393const SCAN_4X8: [u16; 32] = [
7394 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,
7395 23, 26, 29, 27, 30, 31,
7396];
7397
7398/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
7399const SCAN_8X4: [u16; 32] = [
7400 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,
7401 29, 22, 15, 30, 23, 31,
7402];
7403
7404/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
7405/// [`SCAN_32X16`]'s doc comment).
7406const SCAN_16X8: [u16; 128] = [
7407 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,
7408 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
7409 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
7410 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
7411 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
7412 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
7413];
7414
7415/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
7416/// [`SCAN_32X16`]'s doc comment).
7417const SCAN_8X16: [u16; 128] = [
7418 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,
7419 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7420 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7421 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7422 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
7423 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
7424];
7425
7426/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
7427/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
7428/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
7429/// scans column-major (`p = col * height + row`), so a naive copy of
7430/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
7431/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
7432/// are byte-identical to this decoder's [`SCAN_8X16`].
7433const SCAN_32X8: [u16; 256] = [
7434 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7435 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226,
7436 195, 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104,
7437 73, 42, 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200,
7438 169, 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78,
7439 47, 16, 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205,
7440 174, 143, 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83,
7441 52, 21, 239, 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210,
7442 179, 148, 117, 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88,
7443 57, 26, 244, 213, 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215,
7444 184, 153, 122, 91, 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93,
7445 62, 31, 249, 218, 187, 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127,
7446 252, 221, 190, 159, 253, 222, 191, 254, 223, 255,
7447];
7448/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
7449/// 16x64 `PARTITION_VERT_4` strip).
7450const SCAN_8X32: [u16; 256] = [
7451 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,
7452 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7453 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7454 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7455 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
7456 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
7457 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
7458 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
7459 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
7460 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
7461 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
7462 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
7463 239, 246, 253, 247, 254, 255,
7464];
7465/// `Default_Scan_16x4`, this decoder's own row-major transcription of
7466/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
7467/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
7468/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
7469/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
7470/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
7471/// were emitted -- a naive copy installs the transpose (class
7472/// reference-layout-not-spec).
7473const SCAN_16X4: [u16; 64] = [
7474 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,
7475 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
7476 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
7477];
7478/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
7479/// 8x32 `PARTITION_VERT_4` strip).
7480const SCAN_4X16: [u16; 64] = [
7481 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,
7482 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
7483 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
7484];
7485
7486/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
7487/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
7488/// padding already holds.
7489#[inline]
7490fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7491 grid[row * stride + col] as i32
7492}
7493
7494/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
7495/// the rect generalization is libaom's own comment in
7496/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
7497/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
7498/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
7499/// [`decode_block_rect`] codes (see that function's own doc comment).
7500fn base_ctx_rect(
7501 grid: &[u8],
7502 stride: usize,
7503 w: usize,
7504 h: usize,
7505 row: usize,
7506 col: usize,
7507 class: TxClass,
7508) -> usize {
7509 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
7510 // the 2D class short-circuits the DC position.
7511 if class == TxClass::TwoD && row == 0 && col == 0 {
7512 return 0;
7513 }
7514 let offsets: [(usize, usize); 5] = match class {
7515 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7516 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7517 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7518 };
7519 let mag: i32 = offsets
7520 .iter()
7521 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
7522 .sum();
7523 let ctx = ((mag + 1) >> 1).min(4) as usize;
7524 match class {
7525 TxClass::TwoD => {
7526 if w < h && row < 2 {
7527 return ctx + 11;
7528 }
7529 if w > h && col < 2 {
7530 return ctx + 16;
7531 }
7532 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7533 }
7534 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
7535 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
7536 // position along one axis only).
7537 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7538 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7539 }
7540}
7541
7542/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
7543/// neighbour-offset math itself is shape-independent, only the boundary
7544/// clamp needs the real bound in each axis.
7545/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
7546/// its body was character-for-character [`br_ctx`]'s, which
7547/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
7548#[cfg(test)]
7549fn br_ctx_rect(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7550 let extra = match class {
7551 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
7552 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
7553 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
7554 };
7555 let mag = neighbour_rect(grid, stride, row + 1, col)
7556 + neighbour_rect(grid, stride, row, col + 1)
7557 + extra;
7558 let mag = (((mag + 1) >> 1).min(6)) as usize;
7559 if row == 0 && col == 0 {
7560 return mag;
7561 }
7562 let near_origin = match class {
7563 TxClass::TwoD => row < 2 && col < 2,
7564 TxClass::Horiz => col == 0,
7565 TxClass::Vert => row == 0,
7566 };
7567 if near_origin { mag + 7 } else { mag + 14 }
7568}
7569
7570fn dc_vote(dc: Option<bool>) -> i32 {
7571 match dc {
7572 None => 0,
7573 Some(true) => -1,
7574 Some(false) => 1,
7575 }
7576}
7577
7578fn dc_sign_ctx(vote: i32) -> usize {
7579 match vote.signum() {
7580 0 => 0,
7581 -1 => 1,
7582 _ => 2,
7583 }
7584}
7585
7586/// The `tx_type` a CDF symbol names, given the width of the row it was read
7587/// from.
7588///
7589/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
7590/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
7591/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
7592/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
7593/// members are a prefix of the five.
7594///
7595/// One function rather than a `match` at each reader, so
7596/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
7597/// tests the mapping the readers actually use.
7598pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
7599 match cdf_len {
7600 17 => TxType::from_symbol_all16(t),
7601 13 => TxType::from_symbol_set2_12(t),
7602 8 => TxType::from_symbol_set1(t),
7603 _ => TxType::from_symbol(t),
7604 }
7605}
7606
7607/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
7608/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
7609/// (class `table-and-reader-move-together` -- the writer picks its symbol
7610/// through the reader's own map, so the two cannot drift).
7611pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
7612 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
7613}
7614
7615/// The remainder of a level the base and base-range syntax could not reach
7616/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
7617/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
7618pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
7619 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
7620 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
7621 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
7622 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
7623 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
7624 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
7625 // stream_can_carry` enumerates that whole value domain.
7626 //
7627 // So this refusal never names a reader gap: it is always the SYMPTOM of an
7628 // earlier desync (class `refusal-hides-a-defect`), and every historical
7629 // instance was closed by fixing that desync -- lane-dgolomb's
7630 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
7631 // Raising the cap only trades a clean refusal for silent corruption:
7632 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
7633 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
7634 // from a refusal into a frame-0 LUMA MISMATCH.
7635 let mut length = 1u32;
7636 while dec.literal(1) == 0 {
7637 length += 1;
7638 if length > 20 {
7639 return Err(unsupported("a Golomb tail longer than this decoder reads"));
7640 }
7641 }
7642 let mut x = 1u32;
7643 for _ in 1..length {
7644 x = (x << 1) | dec.literal(1);
7645 }
7646 Ok(x - 1)
7647}
7648
7649/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
7650/// [`crate::tile`]'s `write_eob`.
7651fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
7652 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
7653 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
7654
7655 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
7656 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
7657 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
7658 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
7659 // `eob_multi_ctx`). Missing that split desynced the very first
7660 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
7661 // against a real aomdec trace).
7662 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
7663 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
7664 (_, Some(class1)) => class1,
7665 };
7666 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7667 let (range, value) = dec.debug_state();
7668 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
7669 }
7670 let group = dec.symbol(eob_pt) + 1;
7671 if trace {
7672 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
7673 }
7674 let bits = OFFSET_BITS[group];
7675 let mut offset = 0u32;
7676 if bits > 0 {
7677 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
7678 if trace {
7679 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
7680 }
7681 offset = top << (bits - 1);
7682 if bits > 1 {
7683 offset |= dec.literal(bits - 1);
7684 }
7685 }
7686 GROUP_START[group] + offset as usize
7687}
7688
7689/// One transform block's levels, the inverse of [`crate::tile`]'s
7690/// `write_coeffs`, returned as a `side * side` grid in raster order, along
7691/// with the transform type that grid was coded under (`DCT_DCT` when the
7692/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
7693/// 64-point transforms, which never code anything else).
7694///
7695/// # Errors
7696/// Returns an error if the `tx_type` symbol decodes to a value outside its
7697/// CDF's own set (a corrupt or unsupported bitstream) — every value the
7698/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
7699/// produce dispatches to a real inverse transform.
7700/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
7701/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
7702/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
7703/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
7704/// the plane's own predicted mode instead. Every entry this table can
7705/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
7706/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
7707/// table ever names), so unlike the CDF-coded luma path there is no
7708/// ext-tx-set membership check to fall back from here.
7709pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
7710 use crate::intra::{
7711 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
7712 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
7713 };
7714 match mode {
7715 DC_PRED | D45_PRED => TxType::DctDct,
7716 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
7717 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
7718 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
7719 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
7720 }
7721}
7722
7723/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
7724/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
7725/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
7726fn is_smooth_mode(mode: usize) -> bool {
7727 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
7728}
7729
7730/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
7731/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
7732/// nine of them inside the base/sign loops pinned nine sets of values in the
7733/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
7734/// traffic). Out of line, the loop keeps its values in registers and the
7735/// trace output is character-for-character what it was.
7736#[cold]
7737#[inline(never)]
7738fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
7739 eprintln!(
7740 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
7741 );
7742}
7743
7744#[cold]
7745#[inline(never)]
7746fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
7747 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
7748}
7749
7750#[cold]
7751#[inline(never)]
7752fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
7753 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
7754}
7755
7756#[cold]
7757#[inline(never)]
7758fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
7759 let (rng, _) = dec.debug_state();
7760 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
7761}
7762
7763#[cold]
7764#[inline(never)]
7765fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
7766 let (rng, _) = dec.debug_state();
7767 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
7768}
7769
7770#[cold]
7771#[inline(never)]
7772fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
7773 let (rng, _) = dec.debug_state();
7774 eprintln!(
7775 "EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}",
7776 negative as i32
7777 );
7778}
7779
7780#[cold]
7781#[inline(never)]
7782fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
7783 let (rng, _) = dec.debug_state();
7784 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
7785}
7786
7787#[cold]
7788#[inline(never)]
7789fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
7790 let (rng, _) = dec.debug_state();
7791 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
7792}
7793
7794fn read_coeffs(
7795 dec: &mut SymbolDecoder,
7796 coding: &mut TxbTables,
7797 scan: &[u16],
7798 skip_ctx: usize,
7799 sign_ctx: usize,
7800 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
7801 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
7802 // nothing at all; `DctDct` for every luma call and every chroma call at
7803 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
7804 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
7805 default_tx_type: TxType,
7806 // `Some((w, h))` with `w != h` when this read is a superblock-level
7807 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
7808 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
7809 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
7810 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
7811 // caller's block genuinely is `side` x `side`.
7812 rect_shape: Option<(usize, usize)>,
7813) -> Result<(Grid, TxType)> {
7814 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
7815 let side = coding.side;
7816 // lane-av1readcensus: this unit's own entry state, so the census line
7817 // carries the pre-read rng and pairs against the oracle's `EC_COEFF`
7818 // (which prints `r->ec.rng` before the same `txb_skip` read).
7819 let census_entry_rng = dec.debug_state().0;
7820 let (census_w, census_h) = rect_shape.unwrap_or((side, side));
7821 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7822 let (range, value) = dec.debug_state();
7823 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
7824 }
7825 if crate::envflags::env_flag!("EC_ECDUMP_IN") {
7826 let (range, value) = dec.debug_state();
7827 let bit = dec.debug_bitpos();
7828 eprintln!(
7829 "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})"
7830 );
7831 }
7832 let dbg_txbskip = if coeff_trace_on() {
7833 coding.txb_skip[skip_ctx]
7834 } else {
7835 [0; 3]
7836 };
7837 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
7838 if coeff_trace_on() {
7839 let (rng, _) = dec.debug_state();
7840 eprintln!(
7841 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
7842 coding.side, all_zero as i32
7843 );
7844 }
7845 if crate::envflags::env_flag!("EC_AV1_TELL") {
7846 eprintln!(
7847 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
7848 all_zero as u8,
7849 dec.debug_bitpos(),
7850 dec.debug_state().0
7851 );
7852 }
7853 if trace {
7854 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
7855 }
7856 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7857 let (range, value) = dec.debug_state();
7858 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
7859 }
7860 if all_zero {
7861 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
7862 // shared zero grid instead of allocating and zeroing its own.
7863 census_unit(
7864 census_w,
7865 census_h,
7866 TxType::DctDct,
7867 0,
7868 true,
7869 census_entry_rng,
7870 dec,
7871 );
7872 return Ok((Grid::Zero(side * side), TxType::DctDct));
7873 }
7874 let mut grid = vec![0i32; side * side];
7875 let mut tx_type = default_tx_type;
7876 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
7877 // The CDF row's own width names its set (lane-cdffwd2: extended
7878 // past the original two-way intra split once wider `reduced_tx_set
7879 // == 0` inter sets joined the table): 17 slots (16 symbols) is
7880 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
7881 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
7882 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
7883 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
7884 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
7885 let len = tx_type_cdf.len();
7886 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
7887 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
7888 }
7889 let t = dec.symbol(tx_type_cdf);
7890 crate::census::tx_type(len, t);
7891 if coeff_trace_on() {
7892 let (rng, _) = dec.debug_state();
7893 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
7894 }
7895 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7896 let (range, value) = dec.debug_state();
7897 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
7898 }
7899 if trace {
7900 eprintln!("TRACE tx_type value={t} len={len}");
7901 }
7902 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
7903 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
7904 })?;
7905 }
7906
7907 let class = TxClass::of(tx_type);
7908 if class != TxClass::TwoD {
7909 hit!(TX_CLASS1_HITS);
7910 hit!(RECT_CLASS1_HITS);
7911 }
7912 let eob = read_eob(dec, coding, class);
7913 if trace {
7914 eprintln!("TRACE eob value={eob}");
7915 }
7916 let ec_trace_coeff = coeff_trace_on();
7917 if ec_trace_coeff {
7918 let (rng, _) = dec.debug_state();
7919 let cls = match class {
7920 TxClass::TwoD => "2d",
7921 TxClass::Horiz => "horiz",
7922 TxClass::Vert => "vert",
7923 };
7924 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
7925 }
7926 let class_scan;
7927 let scan: &[u16] = if class == TxClass::TwoD {
7928 scan
7929 } else {
7930 class_scan = class_scan_table(side, class);
7931 &class_scan
7932 };
7933 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
7934 // coefficient `pos / side`, `pos % side` was a hardware divide where a
7935 // shift and a mask say the same thing, and the level buffer fits a fixed
7936 // 32x32 frame of stack instead of a heap allocation per transform block.
7937 debug_assert!(side.is_power_of_two() && side <= 32);
7938 let sh = side.trailing_zeros();
7939 let col_mask = side - 1;
7940 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
7941 // `stride = side + 4` columns and four spare rows, so the widest read
7942 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
7943 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
7944 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
7945 let stride = side + 4;
7946 let mut levels_buf = [0u8; 36 * 36];
7947 let levels = &mut levels_buf[..stride * stride];
7948 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
7949 // `pos >> sh` / `& mask` decomposition and load the level back out of the
7950 // padded frame just to skip the zeros. The base pass already knows both,
7951 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
7952 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
7953 // pass walks that list in reverse (the base pass runs in reverse scan
7954 // order, so reversing it is forward scan order: the same coefficients, in
7955 // the same order, with the same `c` the trace prints).
7956 let mut nz_buf = [0u16; 1024];
7957 let mut nz_n = 0usize;
7958 let (base_taps, br_taps) = flat_taps(stride, class);
7959 for scan_idx in (0..eob).rev() {
7960 let pos = scan[scan_idx] as usize;
7961 let (row, col) = (pos >> sh, pos & col_mask);
7962 let idx = row * stride + col;
7963 let level = if scan_idx == eob - 1 {
7964 let ctx = eob_coeff_ctx(scan_idx, side * side);
7965 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
7966 if trace {
7967 trace_base_eob(scan_idx, pos, row, col, ctx, v);
7968 }
7969 v
7970 } else {
7971 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
7972 if row == 0 && col == 0 {
7973 0
7974 } else {
7975 base_mag(levels, idx, &base_taps)
7976 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7977 }
7978 } else {
7979 base_ctx(levels, stride, row, col, class, rect_shape)
7980 };
7981 let v = dec.symbol(&mut coding.base[ctx]) as i32;
7982 if ec_trace_coeff {
7983 // `pos` in libaom's column-major `coeff_idx` convention, so
7984 // the ladder lines up with instrumented `aomdec`.
7985 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
7986 }
7987 if trace {
7988 trace_base(scan_idx, pos, row, col, ctx, v);
7989 }
7990 v
7991 };
7992 let level = if level > NUM_BASE_LEVELS {
7993 let ctx = {
7994 let mag = br_mag(levels, idx, &br_taps);
7995 if row == 0 && col == 0 {
7996 mag
7997 } else {
7998 let near_origin = match class {
7999 TxClass::TwoD => row < 2 && col < 2,
8000 TxClass::Horiz => col == 0,
8001 TxClass::Vert => row == 0,
8002 };
8003 if near_origin { mag + 7 } else { mag + 14 }
8004 }
8005 };
8006 let mut level = level;
8007 let mut sent = 0;
8008 loop {
8009 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8010 if ec_trace_coeff {
8011 // lane-leaf8tx r3: the `br` rung was missing from THIS
8012 // path's trace, so the cross-decoder range ladder was
8013 // blind to every base-range symbol and mis-reported the
8014 // first divergence (class [[gate-blind-to-feature]]).
8015 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
8016 }
8017 if trace {
8018 trace_br(scan_idx, pos, row, col, ctx, k);
8019 }
8020 level += k;
8021 sent += BR_STEP;
8022 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8023 break;
8024 }
8025 }
8026 level
8027 } else {
8028 level
8029 };
8030 if ec_trace_coeff && scan_idx == eob - 1 {
8031 coeff_step_base_eob_level(dec, level);
8032 }
8033 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
8034 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
8035 // added in the sign pass below, straight into `grid`), so the context
8036 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
8037 // byte gather (lane-coefbuf).
8038 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8039 levels[idx] = level as u8;
8040 if level != 0 {
8041 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8042 nz_n += 1;
8043 }
8044 }
8045 if ec_trace_coeff {
8046 let (rng, _) = dec.debug_state();
8047 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8048 }
8049
8050 for &packed in nz_buf[..nz_n].iter().rev() {
8051 let c = (packed >> 4) as usize;
8052 let pos = scan[c] as usize;
8053 let level = (packed & 15) as i32;
8054 let negative = if pos == 0 {
8055 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
8056 if trace {
8057 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
8058 }
8059 v
8060 } else {
8061 dec.literal(1) == 1
8062 };
8063 if ec_trace_coeff {
8064 coeff_step_sign(dec, c, negative);
8065 }
8066 let level = if level > MAX_BR_LEVEL {
8067 let g = read_golomb(dec)?;
8068 if trace {
8069 eprintln!("TRACE golomb pos={pos} value={g}");
8070 }
8071 level + g as i32
8072 } else {
8073 level
8074 };
8075 if ec_trace_coeff {
8076 coeff_step_post_golomb(dec, c, level);
8077 }
8078 grid[pos] = if negative { -level } else { level };
8079 }
8080 census_unit(
8081 census_w,
8082 census_h,
8083 tx_type,
8084 eob,
8085 false,
8086 census_entry_rng,
8087 dec,
8088 );
8089 Ok((Grid::Own(grid), tx_type))
8090}
8091
8092/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
8093/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
8094/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
8095/// can ever produce, since every `tx_type` this decoder's rect sets can read
8096/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
8097/// rather than guess-decode if a non-2D class ever shows up here, since
8098/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
8099/// form for those.
8100
8101fn read_coeffs_rect(
8102 dec: &mut SymbolDecoder,
8103 coding: &mut TxbTables,
8104 scan: &[u16],
8105 w: usize,
8106 h: usize,
8107 skip_ctx: usize,
8108 sign_ctx: usize,
8109 default_tx_type: TxType,
8110 // lane-av1chrtx: the plane this unit belongs to (0 luma, 1 U, 2 V) --
8111 // printed by the two `EC_COEFF_STEP` traces below, which hardcoded
8112 // `plane=0` and so mis-attributed a CHROMA read as a luma one in two
8113 // independent lane reports.
8114 plane: usize,
8115) -> Result<(Grid, TxType)> {
8116 let rect_trace = coeff_trace_on();
8117 let entry_rng = dec.debug_state().0;
8118 // lane-av1readcensus: this reader is handed the real plane (lane-av1chrtx
8119 // threaded it in for the `EC_COEFF_STEP` traces), so it stamps the census
8120 // plane itself rather than inheriting whichever reader did last. The
8121 // luma-only readers (`decode_rect_split`, `decode_block_rect64`,
8122 // `read_inter_plane_rect`'s corner) are all plane 0 -- the stamp's initial
8123 // value -- and the other plane-owning readers stamp on entry.
8124 set_census_plane(plane);
8125 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
8126 if rect_trace {
8127 eprintln!(
8128 "EC_COEFF_STEP tag=all_zero plane={plane} ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
8129 all_zero as i32,
8130 dec.debug_state().0
8131 );
8132 }
8133 if all_zero {
8134 census_unit(w, h, TxType::DctDct, 0, true, entry_rng, dec);
8135 return Ok((Grid::Zero(w * h), TxType::DctDct));
8136 }
8137 let mut grid = vec![0i32; w * h];
8138 hit!(RECT_COEFF_TU_HITS);
8139 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
8140 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
8141 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
8142 // context offsets -- both of which now have rect forms
8143 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
8144 // The rect sets that carry no symbol at all still pass `None` here.
8145 let mut tx_type = default_tx_type;
8146 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
8147 let len = tx_type_cdf.len();
8148 let t = dec.symbol(tx_type_cdf);
8149 crate::census::tx_type(len, t);
8150 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
8151 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
8152 })?;
8153 if rect_trace {
8154 eprintln!(
8155 "EC_COEFF_STEP tag=tx_type plane={plane} rng={}",
8156 dec.debug_state().0
8157 );
8158 }
8159 }
8160 let class = TxClass::of(tx_type);
8161 if class != TxClass::TwoD {
8162 hit!(TX_CLASS1_HITS);
8163 }
8164 let eob = read_eob(dec, coding, class);
8165 if rect_trace {
8166 eprintln!(
8167 "EC_COEFF_STEP tag=eob eob={eob} rng={}",
8168 dec.debug_state().0
8169 );
8170 }
8171 let class_scan;
8172 let scan: &[u16] = if class == TxClass::TwoD {
8173 scan
8174 } else {
8175 class_scan = class_scan_table_wh(w, h, class);
8176 &class_scan
8177 };
8178 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
8179 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
8180 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
8181 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
8182 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
8183 // mask rather than a hardware divide.
8184 let stride = w + 4;
8185 let n = stride * (h + 4);
8186 if !(w.is_power_of_two() && n <= 36 * 36) {
8187 panic!("rect coeff scratch w={w} h={h} n={n}");
8188 }
8189 let (mut b96, mut b256, mut b768);
8190 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
8191 let levels: &mut [u8] = if n <= 96 {
8192 b96 = [0u8; 96];
8193 &mut b96[..n]
8194 } else if n <= 256 {
8195 b256 = [0u8; 256];
8196 &mut b256[..n]
8197 } else {
8198 b768 = [0u8; 768];
8199 &mut b768[..n]
8200 };
8201 let wsh = w.trailing_zeros();
8202 let wmask = w - 1;
8203 // lane-coefread: the non-zero list [`read_coeffs`] documents.
8204 let mut nz_buf = [0u16; 1024];
8205 let mut nz_n = 0usize;
8206 let (base_taps, br_taps) = flat_taps(stride, class);
8207 let (wlt, wgt) = (w < h, w > h);
8208 for scan_idx in (0..eob).rev() {
8209 let pos = scan[scan_idx] as usize;
8210 let (row, col) = (pos >> wsh, pos & wmask);
8211 let idx = row * stride + col;
8212 // libaom's column-major `coeff_idx`, for ladder comparison.
8213 let _apos = col * h + row;
8214 let level = if scan_idx == eob - 1 {
8215 let ctx = eob_coeff_ctx(scan_idx, w * h);
8216 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
8217 if rect_trace {
8218 eprintln!(
8219 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
8220 dec.debug_state().0
8221 );
8222 }
8223 v
8224 } else {
8225 let ctx = if class == TxClass::TwoD {
8226 if row == 0 && col == 0 {
8227 0
8228 } else {
8229 let m = base_mag(levels, idx, &base_taps);
8230 if wlt && row < 2 {
8231 m + 11
8232 } else if wgt && col < 2 {
8233 m + 16
8234 } else {
8235 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8236 }
8237 }
8238 } else {
8239 base_ctx_rect(levels, stride, w, h, row, col, class)
8240 };
8241 let v = dec.symbol(&mut coding.base[ctx]) as i32;
8242 if rect_trace {
8243 eprintln!(
8244 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
8245 dec.debug_state().0
8246 );
8247 }
8248 v
8249 };
8250 let level = if level > NUM_BASE_LEVELS {
8251 let ctx = {
8252 let mag = br_mag(levels, idx, &br_taps);
8253 if row == 0 && col == 0 {
8254 mag
8255 } else {
8256 let near_origin = match class {
8257 TxClass::TwoD => row < 2 && col < 2,
8258 TxClass::Horiz => col == 0,
8259 TxClass::Vert => row == 0,
8260 };
8261 if near_origin { mag + 7 } else { mag + 14 }
8262 }
8263 };
8264 let mut level = level;
8265 let mut sent = 0;
8266 loop {
8267 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8268 if rect_trace {
8269 eprintln!(
8270 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
8271 dec.debug_state().0
8272 );
8273 }
8274 level += k;
8275 sent += BR_STEP;
8276 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8277 break;
8278 }
8279 }
8280 level
8281 } else {
8282 level
8283 };
8284 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8285 levels[idx] = level as u8;
8286 if level != 0 {
8287 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8288 nz_n += 1;
8289 }
8290 if rect_trace {
8291 let (rng, _) = dec.debug_state();
8292 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
8293 }
8294 }
8295 if rect_trace {
8296 let (rng, _) = dec.debug_state();
8297 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8298 }
8299 for &packed in nz_buf[..nz_n].iter().rev() {
8300 let pos = scan[(packed >> 4) as usize] as usize;
8301 let level = (packed & 15) as i32;
8302 let negative = if pos == 0 {
8303 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
8304 } else {
8305 dec.literal(1) == 1
8306 };
8307 if rect_trace {
8308 let (rng, _) = dec.debug_state();
8309 eprintln!(
8310 "EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}",
8311 u8::from(negative)
8312 );
8313 }
8314 let level = if level > MAX_BR_LEVEL {
8315 let g = read_golomb(dec)?;
8316 level + g as i32
8317 } else {
8318 level
8319 };
8320 grid[pos] = if negative { -level } else { level };
8321 }
8322 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
8323 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
8324 // grids differ is a reader defect, one whose grids agree is a transform
8325 // defect.
8326 if crate::envflags::env_flag!("EC_DQCOEFF") {
8327 let nz: Vec<String> = grid
8328 .iter()
8329 .enumerate()
8330 .filter(|&(_, &v)| v != 0)
8331 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
8332 .collect();
8333 eprintln!(
8334 "OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}",
8335 nz.join(",")
8336 );
8337 }
8338 census_unit(w, h, tx_type, eob, false, entry_rng, dec);
8339 Ok((Grid::Own(grid), tx_type))
8340}
8341
8342/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
8343/// [`read_plane`] family already has.
8344///
8345/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
8346/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
8347/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
8348/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
8349/// enforces that for every strip that reads its chroma through it, but the rect
8350/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
8351/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
8352/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
8353/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
8354/// chroma read desyncs at the FIRST rect leaf of the frame and every later
8355/// symbol -- and therefore every later pixel -- is decoded from the wrong
8356/// place, without ever tripping a refusal (the desynced values stay inside
8357/// every coded alphabet).
8358fn read_chroma_coeffs_rect(
8359 dec: &mut SymbolDecoder,
8360 coding: &mut TxbTables,
8361 scan: &[u16],
8362 w: usize,
8363 h: usize,
8364 skip_ctx: usize,
8365 sign_ctx: usize,
8366 default_tx_type: TxType,
8367 fctx: &crate::decode::FrameCtx,
8368 // lane-av1chrtx: the plane index, threaded to `read_coeffs_rect`'s
8369 // `EC_COEFF_STEP` traces (they used to print a hardcoded `plane=0`, so a
8370 // V-plane read was indistinguishable from a luma one in the log).
8371 plane: usize,
8372) -> Result<(Grid, TxType)> {
8373 if mono(fctx) {
8374 return Ok((Grid::Zero(w * h), TxType::DctDct));
8375 }
8376 read_coeffs_rect(
8377 dec,
8378 coding,
8379 scan,
8380 w,
8381 h,
8382 skip_ctx,
8383 sign_ctx,
8384 default_tx_type,
8385 plane,
8386 )
8387}
8388
8389/// What one coded block leaves behind for the blocks that read it as a
8390/// neighbour: whether it coded anything at all, and the sign of its DC —
8391/// [`crate::tile`]'s own private `Neighbour`.
8392#[derive(Clone, Copy, Default)]
8393struct Neighbour {
8394 /// The transform unit's cumulative coefficient level (spec `cul_level`,
8395 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
8396 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
8397 /// boolean (`level != 0`) is enough for every context this decoder read
8398 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
8399 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
8400 /// needs the actual magnitude tier of its above/left neighbours, not
8401 /// just whether they coded anything.
8402 level: u8,
8403 dc: Option<bool>,
8404}
8405
8406/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
8407/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
8408/// grid is dropped, never a panic. One `memset` per grid row instead of a
8409/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
8410/// is contiguous, so this writes exactly the cells the cell loop did,
8411/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
8412/// next row.
8413#[inline]
8414fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
8415 let end = (start + n).min(dst.len());
8416 if start < end {
8417 dst[start..end].fill(v);
8418 }
8419}
8420
8421fn neighbour_state(grid: &[i32]) -> Neighbour {
8422 // lane-coefgrid: the shared zero grid sums to zero by construction; this
8423 // sum has no early exit, so the 60% of units that code nothing used to
8424 // walk their whole grid here.
8425 if is_zero_grid(grid) {
8426 return Neighbour::default();
8427 }
8428 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
8429 Neighbour {
8430 level: cul.min(7) as u8,
8431 dc: (grid[0] != 0).then_some(grid[0] < 0),
8432 }
8433}
8434
8435/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
8436/// transform unit smaller than the block it sits in): `top`/`left` are the
8437/// above/left neighbours' magnitude tiers, each already clamped to 4.
8438pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
8439 [1, 2, 2, 2, 3],
8440 [2, 4, 4, 4, 5],
8441 [2, 4, 4, 4, 5],
8442 [2, 4, 4, 4, 5],
8443 [3, 5, 5, 5, 6],
8444];
8445
8446/// The `skip` flag, its written-instrument bit, and the covering coded
8447/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
8448/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
8449/// nothing else, so a block's row is one fill instead of four, and the
8450/// deblocker's `pu_edge` reads origin and dims off one cache line.
8451#[derive(Clone, Copy)]
8452struct BlkCell {
8453 skip: bool,
8454 written: bool,
8455 org: [u16; 2],
8456 dim: [u8; 2],
8457}
8458
8459/// The neighbour state a block's contexts are read from — a duplicate of
8460/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
8461/// territory this round), kept at the same two granularities the real writer
8462/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
8463/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
8464/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
8465/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
8466/// chroma transform straddling the true, odd-sized frame edge see its
8467/// neighbour's state clamped at its own subsampled edge rather than luma's.
8468#[derive(Clone)]
8469struct Neighbours {
8470 above: Vec<[Neighbour; 3]>,
8471 left: Vec<[Neighbour; 3]>,
8472 above_mode: Vec<usize>,
8473 left_mode: Vec<usize>,
8474 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
8475 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
8476 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
8477 /// luma one -- the same block can (and often does) code a different
8478 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
8479 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
8480 /// within-block neighbour finer than this grid) is luma-only -- a known,
8481 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
8482 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
8483 above_uv_mode: Vec<usize>,
8484 left_uv_mode: Vec<usize>,
8485 above_side: Vec<usize>,
8486 left_side: Vec<usize>,
8487 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
8488 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
8489 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
8490 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
8491 /// array cannot tell the second leaf's partition symbol that the first
8492 /// one was coded at 8x8.
8493 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
8494 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
8495 above_side_mi: Vec<u8>,
8496 left_side_mi: Vec<u8>,
8497 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
8498 /// / row, with the mi position it was written at
8499 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
8500 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
8501 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
8502 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
8503 /// leaf whose neighbour is another split group needs that group's leaf 3
8504 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
8505 /// and read only by [`decode_leaf_split4`]; the position guard makes it
8506 /// fall back to the coarse slot whenever the real neighbour was a block
8507 /// of 8x8 or larger (whose one mode is correct for every row it spans).
8508 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
8509 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
8510 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
8511 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
8512 /// frame is 65536 px = 16384 mi).
8513 sub8_mode_col: Vec<(u16, u8)>,
8514 sub8_mode_row: Vec<(u16, u8)>,
8515 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
8516 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
8517 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
8518 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
8519 /// the leaf above writes the same row slot the block to the left owns.
8520 uv_mode_col: Vec<(u16, u8)>,
8521 uv_mode_row: Vec<(u16, u8)>,
8522 /// Every mi cell's own `uv_mode`, the mi grid libaom's
8523 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
8524 /// blockd.h). lane-t900 r12: the one-slot-per-column
8525 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
8526 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
8527 /// overwrote the row the pair's chroma-ref half then wanted to read --
8528 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
8529 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
8530 uv_mode_grid: Vec<u8>,
8531 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
8532 /// every other band here).
8533 uv_grid_cols: usize,
8534 /// lane-av1leftwit: which BLOCK wrote each cell of [`Self::uv_mode_grid`],
8535 /// as `(epoch << 24) | (mi_r << 12) | mi_c` of the writing block's own
8536 /// top-left mi. The `uv_mode` value alone cannot answer "are the two cells
8537 /// the `+ss_y` read compares written by the same block?", which is the
8538 /// whole question the `+ss_y` term turns on: the term is only observable
8539 /// when the left neighbour is 1 mi tall, i.e. when the cell this decoder
8540 /// used to read and the cell libaom reads hold DIFFERENT blocks. `epoch`
8541 /// is [`UV_OWNER_EPOCH`], bumped once per tile, so a cell no block wrote
8542 /// in this tile can never be mistaken for a written one.
8543 uv_owner: Vec<u32>,
8544 /// Whether the block above/left of this column/row was coded `skip` --
8545 /// an inter frame's own `skip` context (spec `SkipContext`), which the
8546 /// key-frame writer never tracks (its skip context is always zero); a
8547 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
8548 /// `left_skip`.
8549 above_skip: Vec<bool>,
8550 left_skip: Vec<bool>,
8551 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
8552 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
8553 /// pixels last written over each unit by `set_txfm_ctxs`/
8554 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
8555 /// symbol reads its context from (lane-txselect, spec 5.11.17).
8556 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
8557 /// array is exactly libaom's per-superblock-row reset, since each mi row
8558 /// is only ever visited inside one superblock row.
8559 above_txfm: Vec<u8>,
8560 left_txfm: Vec<u8>,
8561 /// Whether the block above/left of this column/row coded `skip_mode`
8562 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
8563 /// lane-av1comp round 14.
8564 above_skip_mode: Vec<bool>,
8565 left_skip_mode: Vec<bool>,
8566 /// Whether the block above/left was coded inter -- the `is_inter`
8567 /// context (spec `av1_get_intra_inter_context`), a duplicate of
8568 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
8569 above_inter: Vec<bool>,
8570 left_inter: Vec<bool>,
8571 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
8572 /// alphabet) the block above/left of this column/row coded, or `-1` for
8573 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
8574 /// functions (`mvstack::ref_ctx` family) need the real reference, not
8575 /// just "was it inter" (lane-av1refs: every inter block used to be
8576 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
8577 /// enough).
8578 above_ref: Vec<i8>,
8579 left_ref: Vec<i8>,
8580 /// The block above/left's *second* reference frame when it was coded
8581 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
8582 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
8583 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
8584 /// `i8`, once a compound `read_ref_frames` lands.
8585 /// lane-publish2 audit: the "always `None` today" note this doc used to
8586 /// carry is long stale -- compound blocks do occur, and
8587 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
8588 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
8589 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
8590 /// [`crate::mvstack::NeighbourRef`] construction (class
8591 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
8592 above_ref1: Vec<Option<i8>>,
8593 left_ref1: Vec<Option<i8>>,
8594 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
8595 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
8596 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
8597 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
8598 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
8599 above_comp_group_idx: Vec<u8>,
8600 left_comp_group_idx: Vec<u8>,
8601 above_compound_idx: Vec<u8>,
8602 left_compound_idx: Vec<u8>,
8603 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
8604 /// `3` = "no info": an intra neighbour or the frame's own border) of the
8605 /// block above/left of this column/row -- spec
8606 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
8607 above_filter: Vec<[u8; 2]>,
8608 left_filter: Vec<[u8; 2]>,
8609 mi_cols: usize,
8610 mi_rows: usize,
8611 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
8612 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
8613 /// 7.15) never filters an 8x8 luma block whose covering coded block read
8614 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
8615 /// grain [`Self::record_mi`] already writes at), read back at 8x8
8616 /// granularity by [`apply_cdef`] since `skip` is constant across every
8617 /// mi cell one coded block covers.
8618 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
8619 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
8620 /// the `skip` bit at this mi cell during this frame. A fresh
8621 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
8622 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
8623 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
8624 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
8625 /// unobservable from the pixels alone. Counted by
8626 /// [`cdef_unwritten_skip_units`].
8627 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
8628 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
8629 /// which re-enables the loop filter at a prediction boundary between two
8630 /// skipped inter blocks (lane-mergefix r4). Written by
8631 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
8632 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
8633 /// that cell -- the other half of `pu_edge`: libaom tests the edge
8634 /// coordinate against the block's size in the FILTERED plane's own
8635 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
8636 blk_grid: Vec<BlkCell>,
8637 skip_grid_cols_mi: usize,
8638 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
8639 /// never splits a coded block's transform below its own size (round 2:
8640 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
8641 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
8642 /// edge-length lookup (`apply_deblock`).
8643 tx_grid: Vec<u8>,
8644 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
8645 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
8646 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
8647 tx_h_grid: Vec<u8>,
8648 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
8649 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
8650 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
8651 /// does NOT follow luma's `tx_depth` split, so deriving it as
8652 /// `tx_grid / 2` invented chroma transform edges the deblocker then
8653 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
8654 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
8655 /// every caller routes through.
8656 uv_tx_grid: Vec<u8>,
8657 uv_tx_h_grid: Vec<u8>,
8658 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
8659 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
8660 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
8661 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
8662 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
8663 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
8664 /// reference onto `LAST_FRAME`'s own delta).
8665 ref_grid: Vec<i8>,
8666 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
8667 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
8668 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
8669 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
8670 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
8671 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
8672 /// to know which mode produced the value.
8673 delta_lf_grid: Vec<[i8; 4]>,
8674 /// The block above/left's own palette-Y size (0 = not a palette block)
8675 /// and its base colours -- `av1_get_palette_mode_ctx`/
8676 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
8677 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
8678 above_palette_size: Vec<u8>,
8679 left_palette_size: Vec<u8>,
8680 above_palette_colors: Vec<[u16; 8]>,
8681 left_palette_colors: Vec<[u16; 8]>,
8682 /// As the four fields above, for the neighbour's own chroma (U-channel
8683 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
8684 /// palette size/colours (lane-palette2 r1).
8685 above_palette_uv_size: Vec<u8>,
8686 left_palette_uv_size: Vec<u8>,
8687 above_palette_uv_colors: Vec<[u16; 8]>,
8688 left_palette_uv_colors: Vec<[u16; 8]>,
8689 /// This tile's own top-left corner, in 4x4 mode-info units (spec
8690 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
8691 /// neighbour" check compares against this instead of literal `0`, since a
8692 /// block at the tile's own top/left edge has no usable neighbour even
8693 /// though a decoded block sits there in the picture (spec `decode_tile`'s
8694 /// per-tile `clear_above_context`/`left_available`/`up_available`).
8695 /// `0` for a single-tile frame, matching every existing caller exactly.
8696 tile_row0_mi: usize,
8697 tile_col0_mi: usize,
8698}
8699
8700#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8701impl Neighbours {
8702 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
8703 /// true (unpadded) size in 4x4 mode-info units.
8704 fn new(
8705 cols: usize,
8706 rows: usize,
8707 mi_cols: usize,
8708 mi_rows: usize,
8709 fctx: &crate::decode::FrameCtx,
8710 ) -> Self {
8711 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
8712 // neighbour state over the whole 64-row extent, past the frame's last
8713 // mi row (mi_rows 198, block rows 192..208). libaom's own context
8714 // buffers are superblock-aligned for exactly that reason
8715 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
8716 // side arrays to a superblock multiple and leave those cells unread --
8717 // every availability check uses the true `mi_rows`/`mi_cols` below.
8718 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
8719 let (cols, rows) = (cols.next_multiple_of(sb_sub), rows.next_multiple_of(sb_sub));
8720 Self {
8721 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
8722 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
8723 above_mode: vec![DC_PRED; cols],
8724 left_mode: vec![DC_PRED; rows],
8725 above_uv_mode: vec![DC_PRED; cols],
8726 left_uv_mode: vec![DC_PRED; rows],
8727 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
8728 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
8729 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
8730 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
8731 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
8732 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
8733 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
8734 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
8735 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
8736 uv_grid_cols: cols * (SUB / MI),
8737 uv_owner: vec![0; cols * (SUB / MI) * rows * (SUB / MI)],
8738 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
8739 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
8740 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
8741 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
8742 // 16x16 block beside it, which a SUB-grid slot cannot name
8743 // (class context-read-from-one-cell).
8744 above_skip: vec![false; cols * (SUB / MI)],
8745 left_skip: vec![false; rows * (SUB / MI)],
8746 above_skip_mode: vec![false; cols * (SUB / MI)],
8747 left_skip_mode: vec![false; rows * (SUB / MI)],
8748 above_inter: vec![false; cols * (SUB / MI)],
8749 left_inter: vec![false; rows * (SUB / MI)],
8750 above_ref: vec![-1; cols * (SUB / MI)],
8751 left_ref: vec![-1; rows * (SUB / MI)],
8752 above_ref1: vec![None; cols * (SUB / MI)],
8753 left_ref1: vec![None; rows * (SUB / MI)],
8754 above_comp_group_idx: vec![0; cols * (SUB / MI)],
8755 left_comp_group_idx: vec![0; rows * (SUB / MI)],
8756 above_compound_idx: vec![0; cols * (SUB / MI)],
8757 left_compound_idx: vec![0; rows * (SUB / MI)],
8758 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
8759 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
8760 mi_cols,
8761 mi_rows,
8762 blk_grid: vec![
8763 BlkCell {
8764 skip: false,
8765 written: false,
8766 org: [0; 2],
8767 dim: [1; 2]
8768 };
8769 cols * (SUB / MI) * rows * (SUB / MI)
8770 ],
8771 skip_grid_cols_mi: cols * (SUB / MI),
8772 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8773 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8774 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8775 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8776 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
8777 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
8778 above_palette_size: vec![0; cols * (SUB / MI)],
8779 left_palette_size: vec![0; rows * (SUB / MI)],
8780 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
8781 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
8782 above_palette_uv_size: vec![0; cols * (SUB / MI)],
8783 left_palette_uv_size: vec![0; rows * (SUB / MI)],
8784 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
8785 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
8786 tile_row0_mi: 0,
8787 tile_col0_mi: 0,
8788 }
8789 }
8790
8791 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
8792 /// tile's own column span (`col1_mi` exclusive), plus recording
8793 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
8794 /// availability check below. Left context resets every superblock row
8795 /// regardless of tile ([`Self::start_row`], already called once per SB
8796 /// row by every caller) so it needs no tile-specific reset here.
8797 fn start_tile(
8798 &mut self,
8799 row0_mi: usize,
8800 col0_mi: usize,
8801 col1_mi: usize,
8802 fctx: &crate::decode::FrameCtx,
8803 ) {
8804 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
8805 // are tile-relative, same as every other neighbour lookup here.
8806 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
8807 // lane-av1leftwit: a fresh epoch stamps every `uv_owner` cell this
8808 // tile writes, so the `+ss_y` read's "different block?" probe never
8809 // compares against a cell a previous tile left behind.
8810 UV_OWNER_EPOCH.with(|c| c.set(c.get().wrapping_add(1) | (1 << 24)));
8811 self.tile_row0_mi = row0_mi;
8812 self.tile_col0_mi = col0_mi;
8813 let end = col1_mi.min(self.above.len());
8814 for i in col0_mi.min(end)..end {
8815 self.above[i] = Default::default();
8816 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
8817 }
8818 let (sc0, sc1) = (
8819 col0_mi / (SUB / MI),
8820 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
8821 );
8822 for i in sc0.min(sc1)..sc1 {
8823 self.above_mode[i] = DC_PRED;
8824 self.above_side[i] = NO_NEIGHBOUR_SIDE;
8825 }
8826 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
8827 // the tile's own mi column span directly.
8828 let mend = col1_mi.min(self.above_skip.len());
8829 for i in col0_mi.min(mend)..mend {
8830 self.above_skip[i] = false;
8831 self.above_skip_mode[i] = false;
8832 self.above_inter[i] = false;
8833 self.above_ref[i] = -1;
8834 self.above_ref1[i] = None;
8835 self.above_comp_group_idx[i] = 0;
8836 self.above_compound_idx[i] = 0;
8837 self.above_filter[i] = [3u8; 2];
8838 }
8839 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
8840 // stale `(row, mode)` from the tile to the LEFT names an mi row this
8841 // tile's first block would read as its own above neighbour.
8842 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
8843 for i in col0_mi.min(mcol_end)..mcol_end {
8844 self.sub8_mode_col[i] = (u16::MAX, 0);
8845 self.uv_mode_col[i] = (u16::MAX, 0);
8846 }
8847 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
8848 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
8849 // not zero) -- without it a second tile column reads the first one's
8850 // resolved transform sizes as its own above context.
8851 let tend = col1_mi.min(self.above_txfm.len());
8852 for i in col0_mi.min(tend)..tend {
8853 self.above_txfm[i] = TXFM_CTX_INIT;
8854 }
8855 }
8856
8857 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
8858 /// for a non-palette block, clearing any stale neighbour state) into every
8859 /// [`SUB`]-grid cell it covers on both the above and left edges --
8860 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
8861 /// call sites are all square blocks).
8862 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
8863 self.record_palette_y_rect(
8864 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
8865 side,
8866 side,
8867 size,
8868 colors,
8869 );
8870 }
8871
8872 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
8873 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
8874 /// [`Self::record`]): a true rect strip's above/left neighbour spans
8875 /// differ.
8876 fn record_palette_y_rect(
8877 &mut self,
8878 mi: (usize, usize),
8879 w: usize,
8880 h: usize,
8881 size: usize,
8882 colors: [u16; 8],
8883 ) {
8884 let (r, c) = mi;
8885 if crate::envflags::env_flag!("EC_PALPUB") {
8886 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
8887 }
8888 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
8889 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
8890 // cell immediately left of the block, not its 16px [`SUB`] cell. The
8891 // old SUB grid let a 16x8 strip pair share one slot, so the second
8892 // strip of mi(0,8) read the FIRST strip's palette size and the colour
8893 // cache came out one entry short (class [[context-read-from-one-cell]]).
8894 for cell in 0..(w / MI).max(1) {
8895 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
8896 *e = size as u8;
8897 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
8898 // neighbour's colours only where its palette size > 0, so a
8899 // non-palette block need not stamp 16 bytes of zeroes here.
8900 if size > 0 {
8901 self.above_palette_colors[c + cell] = colors;
8902 }
8903 }
8904 }
8905 for cell in 0..(h / MI).max(1) {
8906 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
8907 *e = size as u8;
8908 if size > 0 {
8909 self.left_palette_colors[r + cell] = colors;
8910 }
8911 }
8912 }
8913 }
8914
8915 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
8916 /// neighbours that are themselves a palette-Y block, plus
8917 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
8918 /// cache (pred_common.c:73).
8919 ///
8920 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
8921 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
8922 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
8923 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
8924 /// the ctx too made every superblock in the frame's second SB row read
8925 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
8926 /// palette block decoded as "no palette" and the tile desynced from
8927 /// there (class [[cdf-row-held-constant]]).
8928 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
8929 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
8930 }
8931
8932 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
8933 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
8934 /// drops the above neighbour on a 64-px superblock boundary
8935 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
8936 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
8937 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
8938 /// every strip in an SB's top cell row, which libaom does not do.
8939 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
8940 let (r, c) = mi;
8941 let above_ok = r % 16 != 0;
8942 // `xd->above_mbmi` exists for every row but the tile's own first.
8943 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
8944 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
8945 (
8946 usize::from(self.above_palette_size[c]),
8947 self.above_palette_colors[c],
8948 )
8949 } else {
8950 (0, [0u16; 8])
8951 };
8952 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
8953 // is NULL whenever the block sits at its TILE's own left column
8954 // (`left_available`), not the frame's -- without this guard a second
8955 // tile column reads the previous tile's palette colours into its cache
8956 // and its `palette_y_mode` ctx.
8957 let left_ok = c > self.tile_col0_mi;
8958 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
8959 (
8960 usize::from(self.left_palette_size[r]),
8961 self.left_palette_colors[r],
8962 )
8963 } else {
8964 (0, [0u16; 8])
8965 };
8966 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
8967 let mut cache = Vec::with_capacity(16);
8968 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
8969 if cache.last() != Some(&v) {
8970 cache.push(v);
8971 }
8972 };
8973 let (mut ai, mut li) = (0usize, 0usize);
8974 while ai < above_n && li < left_n {
8975 let (va, vl) = (above_colors[ai], left_colors[li]);
8976 if vl < va {
8977 push_dedup(&mut cache, vl);
8978 li += 1;
8979 } else {
8980 push_dedup(&mut cache, va);
8981 ai += 1;
8982 if vl == va {
8983 li += 1;
8984 }
8985 }
8986 }
8987 while ai < above_n {
8988 push_dedup(&mut cache, above_colors[ai]);
8989 ai += 1;
8990 }
8991 while li < left_n {
8992 push_dedup(&mut cache, left_colors[li]);
8993 li += 1;
8994 }
8995 (ctx, cache)
8996 }
8997
8998 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
8999 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
9000 /// same way (lane-palette2 r1).
9001 fn record_palette_uv(
9002 &mut self,
9003 at: (usize, usize),
9004 side: usize,
9005 size: usize,
9006 colors: [u16; 8],
9007 ) {
9008 self.record_palette_uv_rect(
9009 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
9010 side,
9011 side,
9012 size,
9013 colors,
9014 );
9015 }
9016
9017 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
9018 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
9019 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
9020 /// luma resolution regardless of which plane the recorded state is for).
9021 fn record_palette_uv_rect(
9022 &mut self,
9023 mi: (usize, usize),
9024 w: usize,
9025 h: usize,
9026 size: usize,
9027 colors: [u16; 8],
9028 ) {
9029 let (r, c) = mi;
9030 // mi granularity, see [`Self::record_palette_y_rect`].
9031 for cell in 0..(w / MI).max(1) {
9032 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
9033 *e = size as u8;
9034 if size > 0 {
9035 self.above_palette_uv_colors[c + cell] = colors;
9036 }
9037 }
9038 }
9039 for cell in 0..(h / MI).max(1) {
9040 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
9041 *e = size as u8;
9042 if size > 0 {
9043 self.left_palette_uv_colors[r + cell] = colors;
9044 }
9045 }
9046 }
9047 }
9048
9049 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
9050 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
9051 /// no neighbour lookup at all (it is this block's own just-decided Y
9052 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
9053 /// so only the cache is wanted here.
9054 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
9055 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
9056 }
9057
9058 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
9059 /// [`Self::palette_ctx_and_cache_mi`].
9060 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
9061 let (r, c) = mi;
9062 let above_ok = r % 16 != 0;
9063 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
9064 (
9065 usize::from(self.above_palette_uv_size[c]),
9066 self.above_palette_uv_colors[c],
9067 )
9068 } else {
9069 (0, [0u16; 8])
9070 };
9071 // Same tile-relative left availability as the luma cache above.
9072 let left_ok = c > self.tile_col0_mi;
9073 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
9074 (
9075 usize::from(self.left_palette_uv_size[r]),
9076 self.left_palette_uv_colors[r],
9077 )
9078 } else {
9079 (0, [0u16; 8])
9080 };
9081 let mut cache = Vec::with_capacity(16);
9082 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
9083 if cache.last() != Some(&v) {
9084 cache.push(v);
9085 }
9086 };
9087 let (mut ai, mut li) = (0usize, 0usize);
9088 while ai < above_n && li < left_n {
9089 let (va, vl) = (above_colors[ai], left_colors[li]);
9090 if vl < va {
9091 push_dedup(&mut cache, vl);
9092 li += 1;
9093 } else {
9094 push_dedup(&mut cache, va);
9095 ai += 1;
9096 if vl == va {
9097 li += 1;
9098 }
9099 }
9100 }
9101 while ai < above_n {
9102 push_dedup(&mut cache, above_colors[ai]);
9103 ai += 1;
9104 }
9105 while li < left_n {
9106 push_dedup(&mut cache, left_colors[li]);
9107 li += 1;
9108 }
9109 cache
9110 }
9111
9112 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
9113 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
9114 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
9115 /// units as [`Self::fill_skip_grid`].
9116 fn fill_lf_grid(
9117 &mut self,
9118 at_mi: (usize, usize),
9119 side_mi: usize,
9120 tx_px: u8,
9121 ref_frame: i8,
9122 fctx: &crate::decode::FrameCtx,
9123 ) {
9124 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
9125 }
9126
9127 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
9128 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
9129 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
9130 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
9131 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
9132 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
9133 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
9134 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
9135 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
9136 /// block's published transform extent to its own size is exactly that
9137 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
9138 /// that needs it is the 128 root, whose chroma extent (64) is the one
9139 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
9140 /// never suppressed (libaom's `is_inter_block` term), so this is called
9141 /// only from the skipped-inter branch.
9142 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
9143 let (mi_r, mi_c) = at_mi;
9144 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
9145 for rr in 0..h_mi {
9146 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9147 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
9148 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
9149 }
9150 }
9151
9152 fn fill_lf_grid_rect(
9153 &mut self,
9154 at_mi: (usize, usize),
9155 w_mi: usize,
9156 h_mi: usize,
9157 tx_px: u8,
9158 tx_h_px: u8,
9159 ref_frame: i8,
9160 fctx: &crate::decode::FrameCtx,
9161 ) {
9162 let (mi_r, mi_c) = at_mi;
9163 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
9164 // half its luma one (min 4 px, the smallest transform), capped at
9165 // TX_32X32 -- independent of this block's luma `tx_depth`.
9166 let uv_tx_w = (((w_mi * MI) >> ss_x(fctx)).max(4).min(32)) as u8;
9167 let uv_tx_h = (((h_mi * MI) >> ss_y(fctx)).max(4).min(32)) as u8;
9168 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9169 eprintln!(
9170 "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}"
9171 );
9172 }
9173 crate::census::tx(tx_px, tx_h_px);
9174 let cur = fctx.current_delta_lf.with(|c| c.get());
9175 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
9176 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
9177 } else {
9178 [cur[0].clamp(-63, 63) as i8; 4]
9179 };
9180 for rr in 0..h_mi {
9181 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9182 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9183 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9184 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
9185 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
9186 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
9187 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
9188 }
9189 if fctx.intra_only.with(std::cell::Cell::get) {
9190 // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size,
9191 // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi),
9192 // xd)` for EVERY block, an intra-only frame's included, and
9193 // `get_tx_size_context` / `txfm_partition_context` read those two
9194 // `TXFM_CONTEXT` bands. This grid carries the same transform size
9195 // over the same footprint, so the publish is this write: the
9196 // `skip && is_inter` term is 0 for every intra-only block that is
9197 // not an intrabc one, and the bodies that can code an intrabc
9198 // block publish their own (the term is then the BLOCK size, a value
9199 // this grid cannot express -- see `decode_block`/`decode_leaf8`).
9200 // Inter frames publish at their own sites and are excluded here
9201 // because their skipped-block term needs the block size too.
9202 txfm_partition_update_rect(
9203 self,
9204 at_mi,
9205 (tx_px as usize, tx_h_px as usize),
9206 (w_mi * MI, h_mi * MI),
9207 );
9208 // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`),
9209 // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size
9210 // instead of its transform band. Every block stamps its own cells
9211 // here; the intrabc bodies re-stamp theirs `true` afterwards
9212 // (`record_intrabc_inter_bands`).
9213 for i in 0..w_mi {
9214 if let Some(cell) = self.above_inter.get_mut(mi_c + i) {
9215 *cell = false;
9216 }
9217 }
9218 for i in 0..h_mi {
9219 if let Some(cell) = self.left_inter.get_mut(mi_r + i) {
9220 *cell = false;
9221 }
9222 }
9223 }
9224 // lane-av1-intrabc r4: publish this coded block's own mi footprint
9225 // into the intrabc MV grid's block-COVERAGE map -- every coded block,
9226 // not just the intrabc ones. A later intrabc block's DV predictor is
9227 // built by libaom's own row/col scans over `xd->mi[]`, which holds an
9228 // `MB_MODE_INFO` for EVERY block and steps by
9229 // `mi_size_wide/height[candidate->bsize]`; without this footprint a
9230 // non-intrabc neighbour reads as uncovered and the scan advances it
9231 // by one cell instead of by its real width.
9232 fctx.intrabc_mi_grid.with(|g| {
9233 if let Some((grid, _, _)) = g.borrow_mut().as_mut() {
9234 grid.cover_rect(mi_r, mi_c, w_mi, h_mi);
9235 }
9236 });
9237 }
9238
9239 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
9240 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
9241 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
9242 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
9243 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
9244 /// dims from the LEAF span and so invented chroma transform edges the
9245 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
9246 /// are already correct from the block's own fill over the same span.
9247 fn fill_lf_grid_leaf_luma(
9248 &mut self,
9249 at_mi: (usize, usize),
9250 w_mi: usize,
9251 h_mi: usize,
9252 tx_px: u8,
9253 tx_h_px: u8,
9254 ) {
9255 let (mi_r, mi_c) = at_mi;
9256 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9257 eprintln!(
9258 "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}"
9259 );
9260 }
9261 for rr in 0..h_mi {
9262 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9263 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9264 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9265 }
9266 }
9267
9268 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
9269 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
9270 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
9271 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
9272 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
9273 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
9274 }
9275
9276 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
9277 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
9278 let (mi_r, mi_c) = at_mi;
9279 if skip && w_mi != h_mi {
9280 hit!(RECT_SKIP_BAND_HITS);
9281 }
9282 // lane-census: an INTRA frame's blocks never reach the inter
9283 // publisher, and this one is what every coded block writes.
9284 crate::census::block_intra_frame(w_mi, h_mi, skip);
9285 for rr in 0..h_mi {
9286 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9287 fill_span(
9288 &mut self.blk_grid,
9289 start,
9290 w_mi,
9291 BlkCell {
9292 skip,
9293 written: true,
9294 org: [mi_r as u16, mi_c as u16],
9295 dim: [w_mi as u8, h_mi as u8],
9296 },
9297 );
9298 }
9299 }
9300
9301 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
9302 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
9303 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
9304 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
9305 /// straddle the region with a mix of skip/non-skip blocks).
9306 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
9307 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
9308 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
9309 /// filtered edge's two sides are each exactly one coded block wide.
9310 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
9311 self.blk_grid
9312 .get(mi_r * self.skip_grid_cols_mi + mi_c)
9313 .is_some_and(|c| c.skip)
9314 }
9315
9316 /// The `skip_txfm` context of a block whose top-left mi cell is
9317 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
9318 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
9319 /// with an absent neighbour contributing 0. The mi grid is per tile, so
9320 /// row/column 0 is a tile edge and has no neighbour on that axis.
9321 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
9322 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
9323 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
9324 }
9325
9326 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
9327 (0..2).all(|rr| {
9328 (0..2).all(|cc| {
9329 self.blk_grid
9330 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
9331 .is_some_and(|c| c.skip)
9332 })
9333 })
9334 }
9335
9336 fn start_row(&mut self) {
9337 self.left.iter_mut().for_each(|l| *l = Default::default());
9338 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
9339 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
9340 self.left_side
9341 .iter_mut()
9342 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
9343 self.left_side_mi
9344 .iter_mut()
9345 .for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
9346 self.left_skip.iter_mut().for_each(|s| *s = false);
9347 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
9348 self.left_inter.iter_mut().for_each(|i| *i = false);
9349 self.left_ref.iter_mut().for_each(|r| *r = -1);
9350 self.left_ref1.iter_mut().for_each(|r| *r = None);
9351 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
9352 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
9353 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
9354 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
9355 // context (a tile/SB-row boundary has no left neighbour).
9356 self.sub8_mode_row
9357 .iter_mut()
9358 .for_each(|s| *s = (u16::MAX, 0));
9359 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
9360 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
9361 // are per-mi maps like every other one here, so they reset with the
9362 // row too -- the left guard above is what actually stops a cross-tile
9363 // read, this keeps a stale colour out of the arrays at all.
9364 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
9365 self.left_palette_colors
9366 .iter_mut()
9367 .for_each(|c| *c = [0u16; 8]);
9368 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
9369 self.left_palette_uv_colors
9370 .iter_mut()
9371 .for_each(|c| *c = [0u16; 8]);
9372 // lane-mergefix r2: `av1_zero_left_context` memsets
9373 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
9374 // every superblock row of every tile -- the var-tx left context does
9375 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
9376 // previous tile column's last block otherwise).
9377 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
9378 }
9379
9380 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
9381 /// block that reads it as a neighbour -- [`crate::tile`]'s
9382 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
9383 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
9384 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
9385 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
9386 /// the real value, not just `is_inter`).
9387 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9388 fn record_inter(
9389 &mut self,
9390 at: (usize, usize),
9391 side: usize,
9392 skip: bool,
9393 is_inter: bool,
9394 ref_frame: i8,
9395 filter: [u8; 2],
9396 skip_mode: bool,
9397 ) {
9398 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
9399 }
9400
9401 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
9402 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
9403 /// r1: a true rectangular strip's above-context span (its own width) and
9404 /// left-context span (its own height) differ, unlike every caller before
9405 /// this round (class neighbour-votes-all-its-fields).
9406 #[allow(clippy::too_many_arguments)]
9407 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9408 fn record_inter_rect(
9409 &mut self,
9410 at: (usize, usize),
9411 w_sub: usize,
9412 h_sub: usize,
9413 skip: bool,
9414 is_inter: bool,
9415 ref_frame: i8,
9416 filter: [u8; 2],
9417 skip_mode: bool,
9418 ) {
9419 let (r, c) = at;
9420 self.record_inter_rect_mi(
9421 (r * (SUB / MI), c * (SUB / MI)),
9422 w_sub / MI,
9423 h_sub / MI,
9424 skip,
9425 is_inter,
9426 ref_frame,
9427 filter,
9428 skip_mode,
9429 );
9430 }
9431
9432 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
9433 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
9434 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
9435 /// routes through the wrapper above.
9436 #[allow(clippy::too_many_arguments)]
9437 fn record_inter_rect_mi(
9438 &mut self,
9439 at_mi: (usize, usize),
9440 w_mi: usize,
9441 h_mi: usize,
9442 skip: bool,
9443 is_inter: bool,
9444 ref_frame: i8,
9445 filter: [u8; 2],
9446 skip_mode: bool,
9447 ) {
9448 let (r, c) = at_mi;
9449 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
9450 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
9451 // writes for a whole block class): an INTER block left the luma mode
9452 // map untouched, so a later intra block's `get_intra_edge_filter_type`
9453 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
9454 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
9455 // block in that pixel row -- the directional edge filter then ran at
9456 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
9457 // which for an inter block is an INTER mode (>= NEARESTMV) and is
9458 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
9459 // already stamped it).
9460 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
9461 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
9462 // uv map must read DC_PRED over an inter block's cells too.
9463 if is_inter {
9464 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9465 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9466 }
9467 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
9468 self.above_skip[c..c + w_mi].fill(skip);
9469 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
9470 self.above_inter[c..c + w_mi].fill(is_inter);
9471 self.above_ref[c..c + w_mi].fill(ref_frame);
9472 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
9473 // this with the block's real second reference for a compound block,
9474 // called right after this one (lane-publish2 audit).
9475 self.above_ref1[c..c + w_mi].fill(None);
9476 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
9477 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
9478 // as `3`/`1` even though this block has no second reference.
9479 // `record_compound_ctx` overwrites this with the real bit for an
9480 // actual compound block's cells, called right after this one.
9481 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
9482 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
9483 self.above_filter[c..c + w_mi].fill(filter);
9484 self.left_skip[r..r + h_mi].fill(skip);
9485 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
9486 self.left_inter[r..r + h_mi].fill(is_inter);
9487 self.left_ref[r..r + h_mi].fill(ref_frame);
9488 self.left_ref1[r..r + h_mi].fill(None);
9489 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
9490 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
9491 self.left_filter[r..r + h_mi].fill(filter);
9492 }
9493
9494 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
9495 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
9496 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
9497 /// `get_comp_index_context`) -- called right after `record_inter` for
9498 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
9499 /// stamps `above_ref1`/`left_ref1` with the block's real second
9500 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
9501 /// this is the one caller that actually knows it) -- so the next block's
9502 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
9503 /// neighbour instead of `record_inter`'s single-ref default.
9504 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9505 fn record_compound_ctx(
9506 &mut self,
9507 at: (usize, usize),
9508 side: usize,
9509 ref1: i8,
9510 comp_group_idx: u8,
9511 compound_idx: u8,
9512 ) {
9513 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
9514 }
9515
9516 /// [`Self::record_compound_ctx`] with independent above/left extents,
9517 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
9518 #[allow(clippy::too_many_arguments)]
9519 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9520 fn record_compound_ctx_rect(
9521 &mut self,
9522 at: (usize, usize),
9523 w_sub: usize,
9524 h_sub: usize,
9525 ref1: i8,
9526 comp_group_idx: u8,
9527 compound_idx: u8,
9528 ) {
9529 let (r, c) = at;
9530 self.record_compound_ctx_rect_mi(
9531 (r * (SUB / MI), c * (SUB / MI)),
9532 w_sub / MI,
9533 h_sub / MI,
9534 ref1,
9535 comp_group_idx,
9536 compound_idx,
9537 );
9538 }
9539
9540 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
9541 /// [`Self::record_inter_rect_mi`]).
9542 fn record_compound_ctx_rect_mi(
9543 &mut self,
9544 at_mi: (usize, usize),
9545 w_mi: usize,
9546 h_mi: usize,
9547 ref1: i8,
9548 comp_group_idx: u8,
9549 compound_idx: u8,
9550 ) {
9551 let (r, c) = at_mi;
9552 crate::census::compound();
9553 for cell in 0..w_mi {
9554 self.above_ref1[c + cell] = Some(ref1);
9555 self.above_comp_group_idx[c + cell] = comp_group_idx;
9556 self.above_compound_idx[c + cell] = compound_idx;
9557 }
9558 for cell in 0..h_mi {
9559 self.left_ref1[r + cell] = Some(ref1);
9560 self.left_comp_group_idx[r + cell] = comp_group_idx;
9561 self.left_compound_idx[r + cell] = compound_idx;
9562 }
9563 }
9564
9565 /// The context of a block's partition symbol: delegates to the mi-precise
9566 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
9567 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
9568 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
9569 /// only touches the finer mi arrays -- leaves them stale for the *next*
9570 /// sibling's own partition symbol.
9571 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
9572 let (r, c) = at;
9573 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
9574 }
9575
9576 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
9577 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
9578 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
9579 /// than the enclosing 16x16 slot's stale, shared state.
9580 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
9581 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
9582 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
9583 }
9584
9585 /// The gathered coded/DC-sign state of the blocks above and to the left
9586 /// of a block `side` samples across, per plane.
9587 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
9588 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
9589 }
9590
9591 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
9592 /// units, for the same reason [`Self::record_mi`] does.
9593 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
9594 let side_mi = side / MI;
9595 // One pass over the cells accumulating all three planes, not one pass
9596 // per plane: the three planes of a cell live in the same
9597 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
9598 // cache lines three times (lane-publish). Clamp each edge to the true
9599 // frame extent: a block at the right/bottom edge may be padded beyond
9600 // `mi_cols`/`mi_rows`, and libaom's unavailable context is zero there.
9601 let above_mi = side_mi.min(self.mi_cols.saturating_sub(mi_c));
9602 let left_mi = side_mi.min(self.mi_rows.saturating_sub(mi_r));
9603 let mut out = [(false, false, 0i32); 3];
9604 for cell in 0..above_mi {
9605 let above = &self.above[mi_c + cell];
9606 for (plane, o) in out.iter_mut().enumerate() {
9607 o.0 |= above[plane].level != 0;
9608 o.2 += dc_vote(above[plane].dc);
9609 }
9610 }
9611 for cell in 0..left_mi {
9612 let left = &self.left[mi_r + cell];
9613 for (plane, o) in out.iter_mut().enumerate() {
9614 o.1 |= left[plane].level != 0;
9615 o.2 += dc_vote(left[plane].dc);
9616 }
9617 }
9618 out
9619 }
9620
9621 /// [`Self::around_mi_rect`] for the CHROMA planes of a 4:2:2 frame
9622 /// (lane-av1-422f): libaom `get_txb_ctx_general` reads its above votes
9623 /// over `txb_w_unit` CHROMA 4-px cells, and at ss_x 1 one chroma cell
9624 /// spans TWO luma mi columns. Both cells of a column carry the covering
9625 /// unit's whole-unit dc sign (the same value libaom stores), so the
9626 /// per-luma-mi sum counts each chroma column twice -- and
9627 /// `dc_sign_ctx`'s signum flips whenever the above and left votes have
9628 /// opposite signs with equal magnitude (measured at mi(4,4) plane 1 of
9629 /// the t422 fixture: ours read `dc_sign_cdf[1]`, the oracle row 0).
9630 /// Sampling every second above cell counts each chroma column once,
9631 /// which IS libaom's sum. The left extent is unsubsquared at ss_y 0, so
9632 /// its per-mi cells already line up one-to-one. The level booleans are
9633 /// ORs over duplicated cells, so the sampling cannot change them.
9634 fn around_mi_422_chroma(
9635 &self,
9636 (mi_r, mi_c): (usize, usize),
9637 w: usize,
9638 h: usize,
9639 ) -> [(bool, bool, i32); 3] {
9640 let (w_mi, h_mi) = (w / MI, h / MI);
9641 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9642 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9643 let mut out = [(false, false, 0i32); 3];
9644 for cell in (0..above_mi).step_by(2) {
9645 let above = &self.above[mi_c + cell];
9646 for (plane, o) in out.iter_mut().enumerate() {
9647 o.0 |= above[plane].level != 0;
9648 o.2 += dc_vote(above[plane].dc);
9649 }
9650 }
9651 for cell in 0..left_mi {
9652 let left = &self.left[mi_r + cell];
9653 for (plane, o) in out.iter_mut().enumerate() {
9654 o.1 |= left[plane].level != 0;
9655 o.2 += dc_vote(left[plane].dc);
9656 }
9657 }
9658 if crate::envflags::env_flag!("EC_DCDUMP") {
9659 // lane-av1422mi24: same dump [`Self::around_mi_rect`] prints, so
9660 // a rerouted 4:2:2 chroma gather stays visible under EC_DCDUMP=1.
9661 // The above rows are the SAMPLED (every-second) cells.
9662 for (plane, o) in out.iter().enumerate() {
9663 let vote = o.2;
9664 let ab: Vec<String> = (0..above_mi)
9665 .step_by(2)
9666 .map(|k| {
9667 format!(
9668 "{:?}/{}",
9669 self.above[mi_c + k][plane].dc,
9670 self.above[mi_c + k][plane].level
9671 )
9672 })
9673 .collect();
9674 let lf: Vec<String> = (0..left_mi)
9675 .map(|k| {
9676 format!(
9677 "{:?}/{}",
9678 self.left[mi_r + k][plane].dc,
9679 self.left[mi_r + k][plane].level
9680 )
9681 })
9682 .collect();
9683 eprintln!(
9684 "EC_DCDUMP422 mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
9685 ab.join(","),
9686 lf.join(",")
9687 );
9688 }
9689 }
9690 out
9691 }
9692
9693 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
9694 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
9695 /// extent pattern for a true rectangular strip's own coefficient context.
9696 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
9697 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
9698 }
9699
9700 /// [`Self::around_rect`] taking the block's position directly in 4x4
9701 /// mode-info units, mirroring [`Self::around_mi`].
9702 fn around_mi_rect(
9703 &self,
9704 (mi_r, mi_c): (usize, usize),
9705 w: usize,
9706 h: usize,
9707 ) -> [(bool, bool, i32); 3] {
9708 let (w_mi, h_mi) = (w / MI, h / MI);
9709 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9710 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9711 // [`Self::around_mi`]'s single pass, with the two extents split.
9712 let mut out = [(false, false, 0i32); 3];
9713 for cell in 0..above_mi {
9714 let above = &self.above[mi_c + cell];
9715 for (plane, o) in out.iter_mut().enumerate() {
9716 o.0 |= above[plane].level != 0;
9717 o.2 += dc_vote(above[plane].dc);
9718 }
9719 }
9720 for cell in 0..left_mi {
9721 let left = &self.left[mi_r + cell];
9722 for (plane, o) in out.iter_mut().enumerate() {
9723 o.1 |= left[plane].level != 0;
9724 o.2 += dc_vote(left[plane].dc);
9725 }
9726 }
9727 if crate::envflags::env_flag!("EC_DCDUMP") {
9728 for (plane, o) in out.iter().enumerate() {
9729 let vote = o.2;
9730 let ab: Vec<String> = (0..above_mi)
9731 .map(|k| {
9732 format!(
9733 "{:?}/{}",
9734 self.above[mi_c + k][plane].dc,
9735 self.above[mi_c + k][plane].level
9736 )
9737 })
9738 .collect();
9739 let lf: Vec<String> = (0..left_mi)
9740 .map(|k| {
9741 format!(
9742 "{:?}/{}",
9743 self.left[mi_r + k][plane].dc,
9744 self.left[mi_r + k][plane].level
9745 )
9746 })
9747 .collect();
9748 eprintln!(
9749 "EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
9750 ab.join(","),
9751 lf.join(",")
9752 );
9753 }
9754 }
9755 out
9756 }
9757
9758 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
9759 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
9760 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
9761 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
9762 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
9763 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
9764 /// is always 0, spec's `plane_bsize == tx_size` branch).
9765 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
9766 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
9767 }
9768
9769 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
9770 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
9771 /// context over `tx_size_wide` and the left one over `tx_size_high`.
9772 fn luma_skip_ctx_rect(&self, (mi_r, mi_c): (usize, usize), w_mi: usize, h_mi: usize) -> usize {
9773 let side_mi = w_mi;
9774 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9775 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9776 let mut top = 0u8;
9777 let mut left = 0u8;
9778 for cell in 0..above_mi {
9779 top |= self.above[mi_c + cell][0].level;
9780 }
9781 for cell in 0..left_mi {
9782 left |= self.left[mi_r + cell][0].level;
9783 }
9784 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
9785 if crate::envflags::env_flag!("EC_ECDUMP") {
9786 let ab: Vec<String> = (0..above_mi)
9787 .map(|k| self.above[mi_c + k][0].level.to_string())
9788 .collect();
9789 let lf: Vec<String> = (0..left_mi)
9790 .map(|k| self.left[mi_r + k][0].level.to_string())
9791 .collect();
9792 // lane-av1mix: the last few msac register states, so the
9793 // byte-position of the `all_zero` read can be matched against
9794 // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a
9795 // second run.
9796 let recent = crate::msac::symtrace::ecdump_recent(4)
9797 .iter()
9798 .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})"))
9799 .collect::<Vec<_>>()
9800 .join(" ");
9801 eprintln!(
9802 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]",
9803 ab.join(","),
9804 lf.join(","),
9805 recent
9806 );
9807 }
9808 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9809 eprintln!(
9810 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
9811 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
9812 );
9813 }
9814 ctx
9815 }
9816
9817 /// Writes one coded block into every cell it covers, on both grids: the
9818 /// mode/side arrays up to `side`'s own width, and the coefficient-context
9819 /// arrays up to the true frame edge — the units past it are left at their
9820 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
9821 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
9822 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
9823 /// not from this block's own side).
9824 fn record(
9825 &mut self,
9826 at: (usize, usize),
9827 side: usize,
9828 mode: usize,
9829 uv_mode: usize,
9830 grids: &[&[i32]; 3],
9831 ) {
9832 self.record_rect(at, side, side, mode, uv_mode, grids);
9833 }
9834
9835 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
9836 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
9837 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
9838 /// spec's per-edge partition-context rule, so a true rectangular block
9839 /// naturally wants two different values here rather than one.
9840 /// Writes this block's luma `mode` into the mi-granular
9841 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
9842 /// position a *later* neighbour would read it from: the block's LAST mi
9843 /// row for every column it spans (what the block below reads via
9844 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
9845 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
9846 /// read these back, and only when the recorded position is exactly their
9847 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
9848 fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) {
9849 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
9850 let mode = mode as u8;
9851 for cell in 0..mi_w {
9852 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
9853 *slot = (last_r, mode);
9854 }
9855 }
9856 for cell in 0..mi_h {
9857 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
9858 *slot = (last_c, mode);
9859 }
9860 }
9861 }
9862
9863 /// The mi-exact above/left neighbour luma mode for a block whose top-left
9864 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
9865 /// mi position (then the coarse [`SUB`]-grid slot is right by
9866 /// construction). See [`Self::record_mode_mi`].
9867 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
9868 match self.sub8_mode_col.get(mi_c) {
9869 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => {
9870 Some(usize::from(m))
9871 }
9872 _ => None,
9873 }
9874 }
9875
9876 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
9877 match self.sub8_mode_row.get(mi_r) {
9878 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => {
9879 Some(usize::from(m))
9880 }
9881 _ => None,
9882 }
9883 }
9884
9885 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
9886 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
9887 fn record_uv_mode_mi(
9888 &mut self,
9889 mi_r: usize,
9890 mi_c: usize,
9891 mi_w: usize,
9892 mi_h: usize,
9893 uv_mode: usize,
9894 ) {
9895 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
9896 fill_span(
9897 &mut self.uv_mode_col,
9898 mi_c,
9899 mi_w,
9900 (last_r as u16, uv_mode as u8),
9901 );
9902 fill_span(
9903 &mut self.uv_mode_row,
9904 mi_r,
9905 mi_h,
9906 (last_c as u16, uv_mode as u8),
9907 );
9908 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
9909 // covers, so the chroma neighbour read below is a plain grid read.
9910 let stride = self.uv_grid_cols;
9911 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
9912 for row in mi_r..=last_r {
9913 fill_span(
9914 &mut self.uv_mode_grid,
9915 row * stride + mi_c,
9916 n,
9917 uv_mode as u8,
9918 );
9919 }
9920 // lane-av1leftwit: stamp the writing block's own mi over its extent,
9921 // the same cells and the same clipping as `uv_mode_grid` above.
9922 let owner = UV_OWNER_EPOCH.with(|c| c.get()) | ((mi_r as u32) << 12) | mi_c as u32;
9923 for row in mi_r..=last_r {
9924 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);
9925 }
9926 if crate::envflags::env_flag!("EC_LEFTSSY") {
9927 eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}");
9928 }
9929 }
9930
9931 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
9932 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
9933 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
9934 /// block has recorded the exact neighbouring mi.
9935 fn smooth_uv_neighbour(
9936 &self,
9937 mi_r: usize,
9938 mi_c: usize,
9939 r: usize,
9940 c: usize,
9941 fctx: &crate::decode::FrameCtx,
9942 ) -> bool {
9943 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
9944 // REFERENCE block, not off the mi that carries the chroma syntax.
9945 // `set_mi_row_col` (`blockd.h`) takes
9946 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
9947 // only then `chroma_above_mbmi = base_mi[-stride]` /
9948 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
9949 // the ODD mi, so without the snap we looked one mi row/column too far
9950 // down/right -- the mi-exact slot never matched and the coarse
9951 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
9952 // 8x4 at (688, 100) = mi (51, 344): libaom's
9953 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
9954 // `UV_SMOOTH_PRED`), ours was 0, which flips
9955 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
9956 // false for type 1, TRUE for type 0) and upsampled an edge libaom
9957 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
9958 // predicting from it (class `context-read-from-one-cell`).
9959 // lane-av1-444: the snap is the SEQUENCE's subsampling, hardcoded
9960 // `& !1` before -- at subsampling 0/0 libaom's `mi_row & 0` snaps
9961 // nothing, and the hardcoded snap read a 4x4 leaf's smooth
9962 // neighbour two mi away (frame 0 of `av1-profile1-444.ivf`, leaf
9963 // mi(5,15): left neighbour SMOOTH_V at mi(5,14), read at mi(4,13)).
9964 let snap_y = (1usize << ss_y(fctx)) - 1;
9965 let snap_x = (1usize << ss_x(fctx)) - 1;
9966 // The snap IS libaom's `base_mi` de-offsetting (`set_mi_row_col`,
9967 // `av1_common_int.h:1395-1412`): `base_mi` is the block's own mi moved
9968 // by `-(mi_row & ss_y) * stride - (mi_col & ss_x)`. The helper applies
9969 // the two chroma-reference offsets on top of it -- see its own comment
9970 // for which axis each one moves.
9971 self.smooth_uv_neighbour_unsnapped(
9972 mi_r & !snap_y,
9973 mi_c & !snap_x,
9974 r,
9975 c,
9976 ss_x(fctx),
9977 ss_y(fctx),
9978 true,
9979 )
9980 }
9981
9982 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
9983 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
9984 /// counter wants this: it measures how often the snap CHANGES the answer,
9985 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
9986 /// decode path uses the snapping form.
9987 /// `decode_path` is `true` only for the snapping form every decode call
9988 /// site uses; the 16x4/4x16 pair witness's mirror passes `false`, so the
9989 /// `+ss_y` counters measure a read that actually filters a chroma edge and
9990 /// not the counter-only one.
9991 ///
9992 /// lane-av1leftwit: the mirror's justification used to be "no committed
9993 /// fixture reaches the shape on the decode path", and that was false --
9994 /// `UV_LEFT_1MI_SPLIT_HITS` fires on five of them. The flag stays (a
9995 /// counter-only mirror at an ODD mi row is still not a decode-path read,
9996 /// and its result feeds only `RECT4_16_UV_PAIR_FILT_HITS`), but it is no
9997 /// longer evidence about the `+ss_y` term, and nothing may cite it as such.
9998 /// The decode path's own reach is `uv_left_1mi_split_hits()`.
9999 fn smooth_uv_neighbour_unsnapped(
10000 &self,
10001 mi_r: usize,
10002 mi_c: usize,
10003 r: usize,
10004 c: usize,
10005 ss_x: usize,
10006 ss_y: usize,
10007 decode_path: bool,
10008 ) -> bool {
10009 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
10010 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
10011 // array that `start_tile` does not clear, so a block on a tile's first
10012 // mi row used to read the uv_mode of the block above it in the tile
10013 // ABOVE and filter its chroma edge at that neighbour's strength
10014 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
10015 // at chroma (120, 32), the top-right tile's first block).
10016 let have_above = mi_r > self.tile_row0_mi;
10017 let have_left = mi_c > self.tile_col0_mi;
10018 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
10019 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
10020 {
10021 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
10022 }
10023 // The mi grid is libaom's own read; the two maps below stay as the
10024 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
10025 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
10026 (col < self.uv_grid_cols)
10027 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
10028 .flatten()
10029 .filter(|&m| m != u8::MAX)
10030 .map(usize::from)
10031 };
10032 // libaom's two chroma-reference mi, from `set_mi_row_col`
10033 // (`av1_common_int.h:1400-1401`), with `mi_r`/`mi_c` already
10034 // de-offset by the caller's `(mi_row & ss_y)` / `(mi_col & ss_x)`
10035 // snap -- i.e. already libaom's `base_mi`:
10036 //
10037 // chroma_above_mi = base_mi[-mi_stride + ss_x] row -1, col +ss_x
10038 // chroma_left_mi = base_mi[ss_y*mi_stride - 1] row +ss_y, col -1
10039 //
10040 // SHIPPED: the above COLUMN. It is `+ss_x` wherever `ss_x == 1` --
10041 // 4:2:0, 4:2:2 AND 4:4:0 all carry that column shift, and only 4:4:4
10042 // (`ss_x == 0`) leaves the read where it was. Measured: folding it in
10043 // leaves the 4:2:0 control byte-identical to `aomdec --rawvideo`; the
10044 // boolean it feeds is simply not exercised differently by that stream
10045 // at its blocks. One chroma column spans two luma mi columns, so the
10046 // chroma edge reaches into the right-hand luma block, and that is where
10047 // its reference lives.
10048 //
10049 // SHIPPED (lane-av1leftref): the left read's `+ss_y` ROW term -- the
10050 // last open item lane-av1422warp carried. libaom puts the left
10051 // reference one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`) and on
10052 // its own row at 4:2:2 (`ss_y == 0`); this read its own row at every
10053 // subsampling. An earlier attempt applied the `ss_y` term to the WRONG
10054 // read (the above) and regressed the byte-exact 4:2:0 control, which
10055 // is what exposed the crossing. lane-av1leftwit CORRECTED the claim
10056 // this comment used to make: "six committed 4:2:0 fixtures reach it,
10057 // and on `reelb_ss600_key_frame.obu` the boolean flips" was never
10058 // measured. Measured over all 48 committed fixtures that decode
10059 // (`lanes/av1leftwit.report.md`), `reelb_ss600_key_frame.obu` reads
10060 // `mode_diff=0 smooth_diff=0 split1mi=0`, and exactly FIVE fixtures
10061 // put a 1-mi-tall left neighbour in front of a decode-path read at
10062 // all -- `gm_small_side_witness` (5), `reelc_sb128_inter_witness` (7),
10063 // `av112bit-{inter,compound,compound-masked}` (1 each) -- and in every
10064 // one of those reads the two blocks agree on `uv_mode`. So the SHAPE is
10065 // reachable (see `UV_LEFT_1MI_SPLIT_HITS`) and the term's VALUE
10066 // changing is what is still unwitnessed.
10067 let above_mi = (mi_r.saturating_sub(1), mi_c + ss_x);
10068 // lane-av1leftref: libaom's LEFT read carries the `+ss_y` ROW term --
10069 // `base_mi[ss_y * mi_stride - 1]` (`av1_common_int.h:1400-1401`) is
10070 // one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`), and on its own
10071 // row at 4:2:2 (`ss_y == 0`) and 4:4:4. The read below used its own
10072 // row at every subsampling. The term is only observable when the two
10073 // cells hold DIFFERENT blocks, i.e. the left neighbour is 1 mi tall or
10074 // shorter -- then `(row, col-1)` and `(row+1, col-1)` are two blocks
10075 // and only libaom's is the chroma reference. Three counters measure
10076 // that, and the third is the one the other two need: a read can only
10077 // differ if the two cells are written by DIFFERENT blocks, which
10078 // `UV_LEFT_1MI_SPLIT_HITS` counts off the per-cell owner stamp
10079 // (`uv_owner`, below). A DIFF bucket that reads 0 while SPLIT reads 0
10080 // was never in contention; a DIFF bucket that reads 0 while SPLIT
10081 // reads > 0 is the term being unobservable on real material, not
10082 // unreachable. `..._MODE_DIFF_HITS` / `..._SMOOTH_DIFF_HITS` then say
10083 // whether the mode value, and the boolean this feeds
10084 // (`is_smooth_mode` -> `av1_get_intra_edge_filter_type` -> the chroma
10085 // edge filter), actually moved.
10086 let left_mi = (mi_r + ss_y, mi_c.saturating_sub(1));
10087 let read_left = |row: usize| -> usize {
10088 match self.uv_mode_row.get(row) {
10089 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, row, left_mi.1) => m,
10090 Some(&(col, m)) if have_left && usize::from(col) == left_mi.1 => usize::from(m),
10091 _ if have_left => self.left_uv_mode[r],
10092 _ => DC_PRED,
10093 }
10094 };
10095 let above = match self.uv_mode_col.get(above_mi.1) {
10096 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, above_mi.0, above_mi.1) => m,
10097 Some(&(row, m)) if have_above && usize::from(row) == above_mi.0 => usize::from(m),
10098 _ if have_above => self.above_uv_mode[c],
10099 _ => DC_PRED,
10100 };
10101 let left = read_left(left_mi.0);
10102 // lane-av1leftref: the gate's reach + load-bearing counters. `READS` is
10103 // how many chroma edge-filter-type reads took this path at all, so a
10104 // gate can tell "the arm never ran" from "the arm ran and the `+ss_y`
10105 // term did not change the answer". The two DIFF buckets compare
10106 // libaom's read cell against the pre-lane own-row cell; both read 0 on
10107 // every committed fixture and every one of the ~1000 encodes swept in
10108 // `lanes/av1leftref.report.md`, which is what makes the read change a
10109 // proven no-op on today's material rather than an unmeasured guess.
10110 if decode_path && have_left && ss_y > 0 {
10111 hit!(UV_LEFT_SS_Y_READS);
10112 // The pre-lane read, kept as the counter's own-row arm: it is what
10113 // this decoder answered before the `+ss_y` term landed, and
10114 // comparing against it is what proves the term is load-bearing.
10115 let own_row = read_left(mi_r);
10116 if own_row != left {
10117 hit!(UV_LEFT_SS_Y_MODE_DIFF_HITS);
10118 }
10119 if is_smooth_mode(own_row) != is_smooth_mode(left) {
10120 hit!(UV_LEFT_SS_Y_SMOOTH_DIFF_HITS);
10121 }
10122 // lane-av1leftwit: the geometry the `+ss_y` term needs. The two
10123 // cells are one left mi column apart, so they are two different
10124 // blocks exactly when the left neighbour is 1 mi tall or shorter.
10125 let col = left_mi.1;
10126 let epoch = UV_OWNER_EPOCH.with(|c| c.get()) & 0xff00_0000;
10127 let own = (col < self.uv_grid_cols)
10128 .then(|| self.uv_owner.get(mi_r * self.uv_grid_cols + col).copied())
10129 .flatten()
10130 .filter(|o| o & 0xff00_0000 == epoch)
10131 .unwrap_or(0);
10132 let down = self
10133 .uv_owner
10134 .get((mi_r + ss_y) * self.uv_grid_cols + col)
10135 .copied()
10136 .filter(|o| o & 0xff00_0000 == epoch)
10137 .unwrap_or(0);
10138 if own != 0 && down != 0 && own != down {
10139 hit!(UV_LEFT_1MI_SPLIT_HITS);
10140 if crate::envflags::env_flag!("EC_LEFTSSY") {
10141 eprintln!(
10142 "EC_LEFTSSY epoch={} mi=({mi_r},{mi_c}) left_col={col} \
10143 owners=({},{})->({},{}) modes={own_row}/{left}",
10144 epoch >> 24,
10145 own >> 12 & 0xfff,
10146 own & 0xfff,
10147 down >> 12 & 0xfff,
10148 down & 0xfff,
10149 );
10150 }
10151 }
10152 }
10153 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
10154 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
10155 }) || have_left && cell(&self.uv_mode_grid, left_mi.0, left_mi.1).is_some_and(|m| {
10156 !matches!(self.uv_mode_row.get(left_mi.0), Some(&(col, cm)) if usize::from(col) == left_mi.1 && usize::from(cm) == m)
10157 }) {
10158 hit!(UV_MODE_GRID_OVERRIDE_HITS);
10159 }
10160 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
10161 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
10162 // have been filtered at the wrong strength by the coarse map alone.
10163 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
10164 hit!(UV_MODE_MI_OVERRIDE_HITS);
10165 }
10166 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
10167 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
10168 {
10169 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10170 }
10171 is_smooth_mode(above) || is_smooth_mode(left)
10172 }
10173
10174 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
10175 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
10176 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
10177 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
10178 /// holding an OLDER, larger block's mode -- it only ever recorded into the
10179 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
10180 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
10181 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
10182 /// a different CDF for the same mode value).
10183 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
10184 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
10185 /// only when `up_available` and `left_mbmi` only when `left_available`;
10186 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
10187 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
10188 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
10189 /// strip's mode as its "left neighbour" (measured on the band fixture at
10190 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
10191 fn modes_above_left_mi(
10192 &self,
10193 mi_r: usize,
10194 mi_c: usize,
10195 fallback: (usize, usize),
10196 ) -> (usize, usize) {
10197 let above = if mi_r > self.tile_row0_mi {
10198 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
10199 } else {
10200 DC_PRED
10201 };
10202 let left = if mi_c > self.tile_col0_mi {
10203 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
10204 } else {
10205 DC_PRED
10206 };
10207 (above, left)
10208 }
10209
10210 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
10211 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
10212 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
10213 /// per superblock row and never per tile, so the first block column of
10214 /// tile 2..N read the previous tile's mode as its left neighbour, and the
10215 /// above band survives across a tile ROW boundary the same way lane-mtfix's
10216 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
10217 /// `up_available`/`left_available` and uses DC_PRED otherwise
10218 /// ([`Self::modes_above_left_mi`]).
10219 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
10220 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10221 let (above, left) =
10222 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
10223 if above != self.above_mode[c] || left != self.left_mode[r] {
10224 hit!(MODE_MI_OVERRIDE_HITS);
10225 }
10226 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
10227 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
10228 {
10229 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10230 }
10231 // A neighbour the coarse band offered where the tile edge makes it
10232 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
10233 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
10234 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
10235 {
10236 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
10237 }
10238 (above, left)
10239 }
10240
10241 fn record_rect(
10242 &mut self,
10243 at: (usize, usize),
10244 w: usize,
10245 h: usize,
10246 mode: usize,
10247 uv_mode: usize,
10248 grids: &[&[i32]; 3],
10249 ) {
10250 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
10251 }
10252
10253 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
10254 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
10255 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
10256 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
10257 /// the [`SUB`]-unit path does).
10258 fn record_rect_mi(
10259 &mut self,
10260 at_mi: (usize, usize),
10261 w: usize,
10262 h: usize,
10263 mode: usize,
10264 uv_mode: usize,
10265 grids: &[&[i32]; 3],
10266 ) {
10267 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
10268 // lane-inter4 r2: a strip whose own footprint runs past the frame's
10269 // last 16-px column/row stamps only the cells that exist (libaom's
10270 // arrays are padded past the frame and those cells are never read).
10271 for cell in 0..w / SUB {
10272 if c + cell >= self.above_mode.len() {
10273 break;
10274 }
10275 self.above_mode[c + cell] = mode;
10276 self.above_uv_mode[c + cell] = uv_mode;
10277 self.above_side[c + cell] = w;
10278 }
10279 for cell in 0..h / SUB {
10280 if r + cell >= self.left_mode.len() {
10281 break;
10282 }
10283 self.left_mode[r + cell] = mode;
10284 self.left_uv_mode[r + cell] = uv_mode;
10285 self.left_side[r + cell] = h;
10286 }
10287 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
10288 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
10289 self.record_mi_rect(at_mi, w, h, grids);
10290 }
10291
10292 /// The coefficient-context half of [`Self::record`], taking the block's
10293 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
10294 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
10295 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
10296 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
10297 self.record_mi_rect(at_mi, side, side, grids);
10298 }
10299
10300 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
10301 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
10302 fn record_mi_rect(&mut self, at_mi: (usize, usize), w: usize, h: usize, grids: &[&[i32]; 3]) {
10303 let (mi_r, mi_c) = at_mi;
10304 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
10305 let (w_mi, h_mi) = (w / MI, h / MI);
10306 if crate::envflags::env_flag!("EC_ECPUB") {
10307 eprintln!(
10308 "EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}",
10309 states[0].level
10310 );
10311 }
10312 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
10313 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
10314 // A chroma 4x4 unit straddling the true luma edge is still whole in
10315 // chroma's own halved grid, so libaom rounds the luma bound up to the
10316 // plane's own 4x4 unit before clamping a subsampled plane
10317 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
10318 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10319 let bound_h = [
10320 self.mi_rows,
10321 round_up_even(self.mi_rows),
10322 round_up_even(self.mi_rows),
10323 ];
10324 let bound_w = [
10325 self.mi_cols,
10326 round_up_even(self.mi_cols),
10327 round_up_even(self.mi_cols),
10328 ];
10329 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
10330 // past the padded side arrays (mi_rows 198, block rows 192..208);
10331 // libaom's own arrays are superblock-sized, so those cells simply
10332 // have no reader -- [`fill_span`] drops them, as the `break` did.
10333 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
10334 // predicate is three contiguous runs: all planes, chroma only, none
10335 // (lane-mi).
10336 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
10337 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
10338 let uv_only = [Neighbour::default(), states[1], states[2]];
10339 fill_span(&mut self.left, mi_r, luma_h, states);
10340 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
10341 fill_span(
10342 &mut self.left,
10343 mi_r + chroma_h,
10344 h_mi - chroma_h,
10345 [Neighbour::default(); 3],
10346 );
10347 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
10348 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
10349 let uv_only_w = [Neighbour::default(), states[1], states[2]];
10350 fill_span(&mut self.above, mi_c, luma_w, states);
10351 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
10352 fill_span(
10353 &mut self.above,
10354 mi_c + chroma_w,
10355 w_mi - chroma_w,
10356 [Neighbour::default(); 3],
10357 );
10358 }
10359
10360 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
10361 /// inside a coded block whose luma transform is smaller than its own
10362 /// side (`TxMode::Select`): the real per-transform-unit coefficient
10363 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
10364 /// coarse per-block `tx_grid`/`fill_lf_grid` state
10365 /// [`Self::record_split_luma`] still writes once for the whole block.
10366 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
10367 /// the caller's own [`Self::record_split_luma`] call sets those once,
10368 /// at the block's own true side, not this TU's.
10369 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
10370 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
10371 }
10372
10373 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
10374 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
10375 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
10376 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
10377 /// coefficient-context arrays are indexed by luma mi, the convention
10378 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
10379 /// clamp included.
10380 fn record_mi_chroma(
10381 &mut self,
10382 (mi_r, mi_c): (usize, usize),
10383 w_px: usize,
10384 h_px: usize,
10385 plane: usize,
10386 grid: &[i32],
10387 ) {
10388 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10389 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
10390 let state = neighbour_state(grid);
10391 if crate::envflags::env_flag!("EC_CHROMA_PUB") {
10392 eprintln!(
10393 "EC_CHROMA_PUB plane={plane} mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={} dc={}",
10394 state.level,
10395 state.dc.map_or(-1, |s| i32::from(s))
10396 );
10397 }
10398 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
10399 self.left[mi_r + cell][plane] = state;
10400 }
10401 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
10402 self.above[mi_c + cell][plane] = state;
10403 }
10404 }
10405
10406 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
10407 /// r1): the above context spans the unit's width, the left context its
10408 /// height, which for a square unit is the same loop it always was.
10409 fn record_mi_luma_rect(
10410 &mut self,
10411 (mi_r, mi_c): (usize, usize),
10412 w_px: usize,
10413 h_px: usize,
10414 grid: &[i32],
10415 ) {
10416 let state = neighbour_state(grid);
10417 if crate::envflags::env_flag!("EC_ECPUB") {
10418 eprintln!(
10419 "EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}",
10420 state.level
10421 );
10422 }
10423 for cell in 0..h_px / MI {
10424 if mi_r + cell < self.mi_rows {
10425 self.left[mi_r + cell][0] = state;
10426 }
10427 }
10428 for cell in 0..w_px / MI {
10429 if mi_c + cell < self.mi_cols {
10430 self.above[mi_c + cell][0] = state;
10431 }
10432 }
10433 }
10434
10435 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
10436 /// block whose luma was decoded as several transform units through
10437 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
10438 /// whole-block luma write -- everything [`Self::record`] does except
10439 /// plane 0, which is already correct per-TU by the time this runs.
10440 fn record_split_luma(
10441 &mut self,
10442 at: (usize, usize),
10443 side: usize,
10444 mode: usize,
10445 uv_mode: usize,
10446 chroma_grids: [&[i32]; 2],
10447 ) {
10448 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
10449 }
10450
10451 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
10452 /// extents in pixels (lane-rectsplit r1), the same relationship
10453 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
10454 /// luma transform split into several square units needs exactly this
10455 /// bookkeeping, at its own true rectangular extents.
10456 fn record_split_luma_rect(
10457 &mut self,
10458 at: (usize, usize),
10459 w: usize,
10460 h: usize,
10461 mode: usize,
10462 uv_mode: usize,
10463 chroma_grids: [&[i32]; 2],
10464 ) {
10465 let (r, c) = at;
10466 self.record_split_luma_rect_mi(
10467 (r * (SUB / MI), c * (SUB / MI)),
10468 w,
10469 h,
10470 mode,
10471 uv_mode,
10472 chroma_grids,
10473 );
10474 }
10475
10476 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
10477 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
10478 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
10479 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
10480 /// convention [`decode_block_rect4`] already established for 1:4 strips.
10481 fn record_split_luma_rect_mi(
10482 &mut self,
10483 at_mi: (usize, usize),
10484 w: usize,
10485 h: usize,
10486 mode: usize,
10487 uv_mode: usize,
10488 chroma_grids: [&[i32]; 2],
10489 ) {
10490 let (mi_r, mi_c) = at_mi;
10491 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
10492 for cell in 0..w.div_ceil(SUB) {
10493 if c + cell >= self.above_mode.len() {
10494 break;
10495 }
10496 self.above_mode[c + cell] = mode;
10497 self.above_uv_mode[c + cell] = uv_mode;
10498 self.above_side[c + cell] = w;
10499 }
10500 for cell in 0..h.div_ceil(SUB) {
10501 if r + cell >= self.left_mode.len() {
10502 break;
10503 }
10504 self.left_mode[r + cell] = mode;
10505 self.left_uv_mode[r + cell] = uv_mode;
10506 self.left_side[r + cell] = h;
10507 }
10508
10509 let (w_mi, h_mi) = (w / MI, h / MI);
10510 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
10511 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
10512 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
10513 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
10514 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10515 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
10516 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
10517 let plane = plane_idx + 1;
10518 let state = neighbour_state(grid);
10519 for cell in 0..h_mi {
10520 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
10521 self.left[mi_r + cell][plane] = state;
10522 }
10523 }
10524 for cell in 0..w_mi {
10525 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
10526 self.above[mi_c + cell][plane] = state;
10527 }
10528 }
10529 }
10530 }
10531}
10532
10533/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
10534/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
10535/// exactly — including its skip context, which the real key-frame writer
10536/// always writes at a fixed context of zero (it never tracks a neighbour-based
10537/// one for intra blocks; that is the inter-frame writer's rule instead).
10538/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
10539/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
10540/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
10541/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
10542/// plain DC chroma.
10543/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
10544/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
10545/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
10546/// instead (the defect commit 1a89ed9 fixed at the square sites).
10547pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
10548 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
10549 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
10550}
10551
10552/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
10553/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
10554/// bound (spec `filter_intra_mode_info` never reads a symbol there).
10555pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
10556 match side {
10557 4 => Some(0),
10558 8 => Some(1),
10559 16 => Some(2),
10560 32 => Some(3),
10561 _ => None,
10562 }
10563}
10564
10565/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
10566/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
10567/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
10568/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
10569fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
10570 match (bw, bh) {
10571 (32, 16) => Some(4),
10572 (16, 32) => Some(5),
10573 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
10574 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
10575 // here dropped that symbol on every DC_PRED strip of that size and
10576 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
10577 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
10578 (16, 8) => Some(6),
10579 (8, 16) => Some(7),
10580 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
10581 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
10582 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
10583 (4, 8) => Some(8),
10584 (8, 4) => Some(9),
10585 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
10586 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
10587 // `use_filter_intra` symbol on those strips although aomenc writes
10588 // one for every DC_PRED block of that shape with
10589 // `--enable-filter-intra=1` (its default), silently desyncing the
10590 // tile (class symbol-consumption-gap).
10591 (32, 8) => Some(10),
10592 (8, 32) => Some(11),
10593 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
10594 // strips), rows 17/16 of `default_filter_intra_cdfs`.
10595 (16, 4) => Some(12),
10596 (4, 16) => Some(13),
10597 _ if bw == bh => filter_intra_size_class(bw),
10598 _ => None,
10599 }
10600}
10601
10602/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
10603/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
10604/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
10605/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
10606/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
10607pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
10608 palette_bsize_ctx_wh(side, side)
10609}
10610
10611/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
10612/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
10613/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
10614/// for ANY bsize, not just the square ones a hand-picked table happened to
10615/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
10616/// row breaks the moment its indexing field moves off the diagonal, and a
10617/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
10618/// block dimension is a power of two, so `bw*bh` always is too and
10619/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
10620/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
10621fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
10622 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
10623 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
10624 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
10625 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
10626 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
10627 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
10628 if bw > 64 || bh > 64 || bw * bh < 64 {
10629 return None;
10630 }
10631 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
10632}
10633
10634/// A just-decoded palette-Y block's own size, base colours (only the first
10635/// `size` entries are real), and per-pixel colour-index map (`side*side`,
10636/// row-major, each entry `< size`).
10637struct PaletteY {
10638 size: usize,
10639 colors: [u16; 8],
10640 map: Vec<u8>,
10641}
10642
10643/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
10644/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
10645/// shared between U and V, both co-located after 4:2:0 subsampling) plus
10646/// each plane's own base colours.
10647struct PaletteUv {
10648 size: usize,
10649 u_colors: [u16; 8],
10650 v_colors: [u16; 8],
10651 map: Vec<u8>,
10652}
10653
10654/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
10655/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
10656/// `get_unsigned_bits`, which is the same formula): smallest `n` with
10657/// `2^n >= x`, `0` for `x <= 1`.
10658pub(crate) fn ceil_log2(x: u32) -> u32 {
10659 if x < 2 {
10660 0
10661 } else {
10662 32 - (x - 1).leading_zeros()
10663 }
10664}
10665
10666/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
10667/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
10668fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
10669 let l = ceil_log2(n as u32);
10670 let m = (1usize << l) - n;
10671 let v = dec.literal(l - 1) as usize;
10672 if v < m {
10673 v
10674 } else {
10675 (v << 1) - m + dec.literal(1) as usize
10676 }
10677}
10678
10679/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
10680/// colours (already-known, from the above/left neighbours) with the
10681/// ascending `transmitted` ones (delta-coded off the wire) back into one
10682/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
10683/// value picks the cached copy first, matching the C `<=`.
10684fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
10685 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
10686 let (mut ci, mut ti) = (0, 0);
10687 while ci < cached.len() && ti < transmitted.len() {
10688 if cached[ci] <= transmitted[ti] {
10689 out.push(cached[ci]);
10690 ci += 1;
10691 } else {
10692 out.push(transmitted[ti]);
10693 ti += 1;
10694 }
10695 }
10696 out.extend_from_slice(&cached[ci..]);
10697 out.extend_from_slice(&transmitted[ti..]);
10698 out
10699}
10700
10701/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
10702/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
10703/// each delta's width, the `range` bound and the clamp) is sized by
10704/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
10705/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
10706/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
10707/// the msac range, so a cross-decoder range ladder stays bit-identical
10708/// through the whole miscount -- only the decoded VALUE differs (class
10709/// `compare-range-not-tell`'s blind spot). (this
10710/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
10711/// (one flag bit each, in cache order), then delta-codes the remainder
10712/// (first value raw, each following delta `>= 1` off a shrinking bit width),
10713/// and merges the two ascending lists back together.
10714fn read_palette_colors_y(
10715 dec: &mut SymbolDecoder,
10716 n: usize,
10717 cache: &[u16],
10718 fctx: &crate::decode::FrameCtx,
10719) -> [u16; 8] {
10720 let mut cached = Vec::with_capacity(n);
10721 for &c in cache {
10722 if cached.len() >= n {
10723 break;
10724 }
10725 if dec.literal(1) == 1 {
10726 cached.push(c);
10727 }
10728 }
10729 let bd = u32::from(bit_depth(fctx));
10730 let max_val = (1i32 << bd) - 1;
10731 let mut colors = [0u16; 8];
10732 let n_cached = cached.len();
10733 if n_cached < n {
10734 let mut transmitted = Vec::with_capacity(n - n_cached);
10735 let first = dec.literal(bd) as u16;
10736 transmitted.push(first);
10737 if n_cached + 1 < n {
10738 let min_bits = bd - 3;
10739 let mut bits = min_bits + dec.literal(2);
10740 let mut range = (1i32 << bd) - i32::from(first) - 1;
10741 for _ in (n_cached + 1)..n {
10742 let delta = dec.literal(bits) as i32 + 1;
10743 let prev = *transmitted.last().unwrap();
10744 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
10745 range -= i32::from(val) - i32::from(prev);
10746 bits = bits.min(ceil_log2(range.max(0) as u32));
10747 transmitted.push(val);
10748 }
10749 }
10750 let merged = merge_colors(&transmitted, &cached);
10751 colors[..n].copy_from_slice(&merged);
10752 } else {
10753 colors[..n].copy_from_slice(&cached[..n]);
10754 }
10755 colors
10756}
10757
10758/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
10759/// `bit_depth` (see [`read_palette_colors_y`]): U reads
10760/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
10761/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
10762/// unbiased by `+1` -- both differences from Y's own reader, matching the C
10763/// side by side). V never uses a cache: a leading bit picks either `n` raw
10764/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
10765/// rather than clamp.
10766fn read_palette_colors_uv(
10767 dec: &mut SymbolDecoder,
10768 n: usize,
10769 cache: &[u16],
10770 fctx: &crate::decode::FrameCtx,
10771) -> ([u16; 8], [u16; 8]) {
10772 let mut cached = Vec::with_capacity(n);
10773 for &c in cache {
10774 if cached.len() >= n {
10775 break;
10776 }
10777 if dec.literal(1) == 1 {
10778 cached.push(c);
10779 }
10780 }
10781 let bd = u32::from(bit_depth(fctx));
10782 let max_val = 1i32 << bd;
10783 let mut u_colors = [0u16; 8];
10784 let n_cached = cached.len();
10785 if n_cached < n {
10786 let mut transmitted = Vec::with_capacity(n - n_cached);
10787 let first = dec.literal(bd) as u16;
10788 transmitted.push(first);
10789 if n_cached + 1 < n {
10790 let min_bits = bd - 3;
10791 let mut bits = min_bits + dec.literal(2);
10792 let mut range = max_val - i32::from(first);
10793 for _ in (n_cached + 1)..n {
10794 let delta = dec.literal(bits) as i32;
10795 let prev = *transmitted.last().unwrap();
10796 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
10797 range -= i32::from(val) - i32::from(prev);
10798 bits = bits.min(ceil_log2(range.max(0) as u32));
10799 transmitted.push(val);
10800 }
10801 }
10802 let merged = merge_colors(&transmitted, &cached);
10803 u_colors[..n].copy_from_slice(&merged);
10804 } else {
10805 u_colors[..n].copy_from_slice(&cached[..n]);
10806 }
10807 let mut v_colors = [0u16; 8];
10808 if dec.literal(1) == 1 {
10809 let min_bits_v = bd - 4;
10810 let bits = min_bits_v + dec.literal(2);
10811 v_colors[0] = dec.literal(bd) as u16;
10812 for i in 1..n {
10813 let mut delta = dec.literal(bits) as i32;
10814 if delta != 0 && dec.literal(1) == 1 {
10815 delta = -delta;
10816 }
10817 let mut val = i32::from(v_colors[i - 1]) + delta;
10818 if val < 0 {
10819 val += max_val;
10820 }
10821 if val >= max_val {
10822 val -= max_val;
10823 }
10824 v_colors[i] = val as u16;
10825 }
10826 } else {
10827 for i in 0..n {
10828 v_colors[i] = dec.literal(bd) as u16;
10829 }
10830 }
10831 (u_colors, v_colors)
10832}
10833
10834/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
10835/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
10836/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
10837const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
10838
10839/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
10840/// map's own per-pixel context and colour-order permutation, from the
10841/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
10842/// selection sort). `map`'s stride is `side` (this decoder never crops a
10843/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
10844/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
10845/// actual colour index to store.
10846pub(crate) fn palette_color_index_context(
10847 map: &[u8],
10848 side: usize,
10849 row: usize,
10850 col: usize,
10851 n: usize,
10852) -> (usize, [u8; 8]) {
10853 let left = if col >= 1 {
10854 Some(map[row * side + col - 1])
10855 } else {
10856 None
10857 };
10858 let up_left = if col >= 1 && row >= 1 {
10859 Some(map[(row - 1) * side + col - 1])
10860 } else {
10861 None
10862 };
10863 let up = if row >= 1 {
10864 Some(map[(row - 1) * side + col])
10865 } else {
10866 None
10867 };
10868 let mut scores = [0i32; 8];
10869 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
10870 if let Some(v) = neighbour {
10871 scores[v as usize] += weight;
10872 }
10873 }
10874 let mut color_order = [0u8; 8];
10875 for i in 0..8 {
10876 color_order[i] = i as u8;
10877 }
10878 for i in 0..3 {
10879 let mut max = scores[i];
10880 let mut max_idx = i;
10881 for j in (i + 1)..n {
10882 if scores[j] > max {
10883 max = scores[j];
10884 max_idx = j;
10885 }
10886 }
10887 if max_idx != i {
10888 let max_score = scores[max_idx];
10889 let max_color = color_order[max_idx];
10890 for k in (i + 1..=max_idx).rev() {
10891 scores[k] = scores[k - 1];
10892 color_order[k] = color_order[k - 1];
10893 }
10894 scores[i] = max_score;
10895 color_order[i] = max_color;
10896 }
10897 }
10898 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
10899 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
10900 (ctx as usize, color_order)
10901}
10902
10903/// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512):
10904/// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block
10905/// cut by the frame's bottom or right mi edge codes its colour-index map only
10906/// over this part and replicates it outward -- reading the full `bw x bh` grid
10907/// consumed symbols libaom never wrote and desynced the rest of the tile
10908/// (lane-svtinter; class map-read-past-frame-edge).
10909fn palette_onscreen(
10910 mi_r: usize,
10911 mi_c: usize,
10912 bw: usize,
10913 bh: usize,
10914 fctx: &crate::decode::FrameCtx,
10915) -> (usize, usize) {
10916 // lane-palw: the ENCODER's own in-process reconstruct runs on a
10917 // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
10918 // frame encoders publish the header's mi dims onto it themselves
10919 // (`encode.rs`, beside their `true_width`/`true_height`) so that this
10920 // clamp and `tile::write_color_index_map`'s now agree there too.
10921 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
10922 palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
10923}
10924
10925/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
10926/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
10927/// compute the same on-screen extent or the decoder reads a different number
10928/// of symbols than the encoder wrote.
10929pub(crate) fn palette_onscreen_dims(
10930 mi_r: usize,
10931 mi_c: usize,
10932 bw: usize,
10933 bh: usize,
10934 (mi_rows, mi_cols): (usize, usize),
10935) -> (usize, usize) {
10936 (
10937 bw.min(mi_cols.saturating_sub(mi_c) * MI),
10938 bh.min(mi_rows.saturating_sub(mi_r) * MI),
10939 )
10940}
10941
10942/// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus
10943/// the SAME sub-8 bump the caller's own `(bw >> ss).max(4)` applies to the
10944/// block dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move
10945/// together or a cut 8-wide block reads its chroma map at the wrong width.
10946/// lane-av1-444: the shifts are the sequence's own subsampling (a 4:4:4
10947/// intra-in-inter palette read its chroma map at the 4:2:0 extent and
10948/// panicked feeding the 4:2:0-sized prediction to a full-size reconstruct).
10949pub(crate) fn palette_onscreen_uv(
10950 luma: (usize, usize),
10951 on: (usize, usize),
10952 chroma: (usize, usize),
10953 ss: (usize, usize),
10954) -> (usize, usize) {
10955 (
10956 (on.0 >> ss.0) + (chroma.0 - (luma.0 >> ss.0)),
10957 (on.1 >> ss.1) + (chroma.1 - (luma.1 >> ss.1)),
10958 )
10959}
10960
10961/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
10962/// map's wavefront decode over a `side x side` grid, read over the on-screen
10963/// `on_side x on_side` corner (see [`palette_onscreen`]).
10964fn decode_color_index_map(
10965 dec: &mut SymbolDecoder,
10966 cdfs: &mut Cdfs,
10967 n: usize,
10968 side: usize,
10969 on: (usize, usize),
10970 uv: bool,
10971) -> Vec<u8> {
10972 decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv)
10973}
10974
10975/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
10976/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
10977/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
10978/// independently rather than one shared `side` -- the square call above is
10979/// just `bw == bh`.
10980fn decode_color_index_map_wh(
10981 dec: &mut SymbolDecoder,
10982 cdfs: &mut Cdfs,
10983 n: usize,
10984 bw: usize,
10985 bh: usize,
10986 // `(onscreenWidth, onscreenHeight)` in this plane's own units.
10987 on: (usize, usize),
10988 uv: bool,
10989) -> Vec<u8> {
10990 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
10991 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
10992 if on_bw < bw || on_bh < bh {
10993 hit!(PALETTE_ONSCREEN_CUT_HITS);
10994 }
10995 let mut map = vec![0u8; bw * bh];
10996 if trace {
10997 let (rng, _) = dec.debug_state();
10998 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
10999 }
11000 map[0] = read_uniform(dec, n) as u8;
11001 if trace {
11002 let (rng, _) = dec.debug_state();
11003 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
11004 }
11005 for i in 1..(on_bw + on_bh - 1) {
11006 let j_hi = i.min(on_bw - 1);
11007 let j_lo = i.saturating_sub(on_bh - 1);
11008 for j in (j_lo..=j_hi).rev() {
11009 let row = i - j;
11010 let col = j;
11011 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
11012 if trace {
11013 let (rng, _) = dec.debug_state();
11014 let row_cdf = if uv {
11015 &cdfs.palette_uv_color_index[n - 2][ctx]
11016 } else {
11017 &cdfs.palette_y_color_index[n - 2][ctx]
11018 };
11019 eprintln!(
11020 "EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}",
11021 row_cdf[0], row_cdf[n]
11022 );
11023 }
11024 let symbol = if uv {
11025 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
11026 } else {
11027 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
11028 };
11029 map[row * bw + col] = color_order[symbol];
11030 if trace {
11031 let (rng, _) = dec.debug_state();
11032 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
11033 }
11034 }
11035 }
11036 palette_replicate(&mut map, bw, bh, on);
11037 map
11038}
11039
11040/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
11041/// last on-screen column then the last on-screen row are replicated over the
11042/// off-screen remainder, so the prediction still covers the whole block. The
11043/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
11044/// so the pixels it prices and reconstructs are the ones the on-screen
11045/// symbols it writes really decode to.
11046pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
11047 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
11048 for row in 0..on_bh {
11049 let last = map[row * bw + on_bw - 1];
11050 map[row * bw + on_bw..row * bw + bw].fill(last);
11051 }
11052 for row in on_bh..bh {
11053 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
11054 }
11055}
11056
11057/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
11058/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
11059/// size class comes from [`filter_intra_size_class_rect`] instead of the
11060/// square-only [`filter_intra_size_class`], and the palette read (when
11061/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
11062/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
11063/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
11064/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
11065#[allow(clippy::too_many_arguments)]
11066fn read_intra_mode_rect(
11067 dec: &mut SymbolDecoder,
11068 cdfs: &mut Cdfs,
11069 above_mode: usize,
11070 left_mode: usize,
11071 cfl: bool,
11072 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
11073 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
11074 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
11075 // chroma is coded once, on the closing strip). Every other caller is a
11076 // block big enough to own its chroma and passes `true`.
11077 has_chroma: bool,
11078 bw: usize,
11079 bh: usize,
11080 enable_filter_intra: bool,
11081 skip_ctx: usize,
11082 allow_screen_content_tools: bool,
11083 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
11084 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
11085 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
11086 palette: Option<(usize, &[u16])>,
11087 palette_uv_cache: &[u16],
11088 mi_r: usize,
11089 mi_c: usize,
11090 fctx: &crate::decode::FrameCtx,
11091) -> Result<(
11092 bool,
11093 usize,
11094 i32,
11095 usize,
11096 i32,
11097 Option<(i32, i32)>,
11098 Option<usize>,
11099 Option<PaletteY>,
11100 Option<PaletteUv>,
11101 // lane-av1-intrabc: the block vector, `Some` exactly when this block's
11102 // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns
11103 // straight out of `read_intra_frame_mode_info` then, so every later field
11104 // of the tuple is at its default (mode/uv_mode DC, no angle, no palette,
11105 // no filter intra). A caller that can reconstruct intrabc at its shape
11106 // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by
11107 // name with the same string it always did.
11108 Option<(i32, i32)>,
11109)> {
11110 // lane-av1mono: libaom guards every chroma symbol read with
11111 // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
11112 // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
11113 // `palette_uv` even on a chroma-reference strip. Fold the plane count
11114 // into the same `has_chroma` this reader already gates on.
11115 let has_chroma = has_chroma && !mono(fctx);
11116 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
11117 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
11118 if ec_istep {
11119 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
11120 // (decodemv.c:818), printed at the same point: before the first
11121 // mode-info symbol of the block, so a cross-decoder range ladder can
11122 // be keyed on the BLOCK, not just on the symbol sequence.
11123 eprintln!(
11124 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}",
11125 enable_filter_intra as i32,
11126 filter_intra_size_class_rect(bw, bh),
11127 dec.debug_state().0
11128 );
11129 }
11130 macro_rules! istep {
11131 ($name:literal, $val:expr) => {
11132 if ec_istep {
11133 let (rng, _) = dec.debug_state();
11134 eprintln!(
11135 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
11136 $name, $val
11137 );
11138 }
11139 };
11140 }
11141 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
11142 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
11143 // the one point every rect caller routes through, so no call site can
11144 // offer the 14-symbol CFL alphabet on a 64-axis block (class
11145 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
11146 let cfl = if cfl && bw.max(bh) > 32 {
11147 hit!(NOCFL_UV_MODE_HITS);
11148 false
11149 } else {
11150 cfl
11151 };
11152 // lane-intra14 r1: on the INTER block path everything up to and including
11153 // `is_inter` was already read by [`decode_inter_block`], so this reader
11154 // starts at the mode syntax with the `skip` that caller read.
11155 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
11156 let skip = if let Some((_, skip)) = inter {
11157 skip
11158 } else {
11159 // Same `intra_segment_id` placement as the square reader above.
11160 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
11161 if seg_id_pre_skip(fctx) {
11162 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
11163 }
11164 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
11165 istep!("skip", skip as i32);
11166 if !seg_id_pre_skip(fctx) {
11167 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
11168 }
11169 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
11170 istep!("cdef", 0);
11171 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
11172 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
11173 // `false`.
11174 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11175 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11176 istep!("dq", 0);
11177 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
11178 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
11179 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
11180 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
11181 // rect strips read it exactly like square leaves ([`read_intra_mode`],
11182 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
11183 // decoder at the FIRST symbol of the first rect block of every
11184 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
11185 // block at this shape is out of scope, so the flag is consumed and
11186 // refused by name when it fires.
11187 if allow_intrabc_frame(fctx) {
11188 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
11189 hit!(RECT_INTRABC_READS);
11190 istep!("intrabc", use_intrabc as i32);
11191 if use_intrabc {
11192 hit!(INTRABC_HITS);
11193 // libaom `read_intrabc_info`: the DV read, then an immediate
11194 // return out of the mode-info read -- no `y_mode`, no `uv_mode`,
11195 // no angle deltas, no palette, no filter intra. The caller owns
11196 // the reconstruction at its own shape.
11197 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx);
11198 return Ok((
11199 skip,
11200 DC_PRED,
11201 0,
11202 DC_PRED,
11203 0,
11204 None,
11205 None,
11206 None,
11207 None,
11208 Some(dv),
11209 ));
11210 }
11211 }
11212 skip
11213 };
11214 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
11215 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
11216 // off `kf_y_mode_cdf[above][left]`).
11217 let mode = if let Some((size_group, _)) = inter {
11218 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
11219 dec.symbol(&mut cdfs.y_mode[size_group])
11220 } else {
11221 let above_ctx = INTRA_MODE_CTX[above_mode];
11222 let left_ctx = INTRA_MODE_CTX[left_mode];
11223 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
11224 };
11225 istep!("mode", mode as i32);
11226 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
11227 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
11228 } else {
11229 0
11230 };
11231 istep!("angle_y", angle_delta_y);
11232 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
11233 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
11234 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
11235 // here, from the block's own size, is the single point every caller routes
11236 // through -- a caller passing `true` for a >32 strip used to pick the
11237 // 14-symbol CFL CDF, same value but a different range (class
11238 // wrong-alphabet-same-value).
11239 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
11240 let uv_mode = if !has_chroma {
11241 DC_PRED
11242 } else if cfl {
11243 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
11244 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
11245 } else {
11246 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
11247 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
11248 };
11249 istep!("uv_mode", uv_mode as i32);
11250 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
11251 Some(read_cfl_alphas(dec, cdfs))
11252 } else {
11253 None
11254 };
11255 if has_chroma && (9..=12).contains(&uv_mode) {
11256 hit!(SMOOTH_UV_HITS);
11257 }
11258 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
11259 hit!(DIRECTIONAL_UV_HITS);
11260 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
11261 } else {
11262 0
11263 };
11264 istep!("angle_uv", angle_delta_uv);
11265 if angle_delta_uv != 0 {
11266 hit!(UV_ANGLE_DELTA_HITS);
11267 }
11268 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
11269 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
11270 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
11271 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
11272 // colours only here, the colour-index maps deferred past `filter_intra`
11273 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
11274 // runs from the caller, after the whole mode-info read).
11275 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
11276 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
11277 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
11278 // r6: this is the exact site the removed blanket refusal used to
11279 // guard -- reached for EVERY rect strip in a screen-content frame,
11280 // independent of whether the block ends up using a palette.
11281 hit!(RECT_SCREEN_CONTENT_HITS);
11282 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
11283 let use_palette_y =
11284 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
11285 if use_palette_y {
11286 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
11287 let colors = read_palette_colors_y(dec, n, cache, fctx);
11288 palette_y_pending = Some((n, colors));
11289 }
11290 let palette_uv_mode_ctx = usize::from(use_palette_y);
11291 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
11292 if has_chroma
11293 && uv_mode == DC_PRED
11294 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
11295 {
11296 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
11297 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
11298 palette_uv_pending = Some((n, u_colors, v_colors));
11299 }
11300 }
11301 let mut filter_intra = None;
11302 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11303 let (rng, _) = dec.debug_state();
11304 eprintln!(
11305 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
11306 class={:?} rng={rng}",
11307 enable_filter_intra as i32,
11308 filter_intra_size_class_rect(bw, bh)
11309 );
11310 }
11311 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
11312 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
11313 if mode == DC_PRED
11314 && enable_filter_intra
11315 && palette_y_pending.is_none()
11316 && let Some(class) = filter_intra_size_class_rect(bw, bh)
11317 {
11318 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
11319 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11320 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
11321 }
11322 istep!("use_filter_intra", use_filter_intra as i32);
11323 if use_filter_intra {
11324 hit!(FILTER_INTRA_HITS);
11325 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
11326 istep!("filter_intra_mode", fi_mode as i32);
11327 filter_intra = Some(fi_mode);
11328 }
11329 }
11330 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
11331 // same order as [`read_intra_mode`]'s own square path.
11332 let palette_y = palette_y_pending.map(|(n, colors)| {
11333 let map = decode_color_index_map_wh(
11334 dec,
11335 cdfs,
11336 n,
11337 bw,
11338 bh,
11339 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
11340 false,
11341 );
11342 hit!(PALETTE_HITS);
11343 hit!(PALETTE_RECT_HITS);
11344 PaletteY {
11345 size: n,
11346 colors,
11347 map,
11348 }
11349 });
11350 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
11351 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
11352 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
11353 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
11354 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
11355 // chroma palette and desynced the tile from there.
11356 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
11357 let on = palette_onscreen_uv(
11358 (bw, bh),
11359 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
11360 (cw, ch),
11361 (ss_x(fctx), ss_y(fctx)),
11362 );
11363 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
11364 hit!(PALETTE_UV_HITS);
11365 PaletteUv {
11366 size: n,
11367 u_colors,
11368 v_colors,
11369 map,
11370 }
11371 });
11372 Ok((
11373 skip,
11374 mode,
11375 angle_delta_y,
11376 uv_mode,
11377 angle_delta_uv,
11378 alpha,
11379 filter_intra,
11380 palette_y,
11381 palette_uv,
11382 None,
11383 ))
11384}
11385
11386/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
11387/// at the strip's REAL mi position. `av1_get_palette_cache` reads
11388/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
11389/// block, so each strip owns its own rows and columns and no aliasing rule
11390/// is needed (lane-kf900 r6).
11391#[allow(clippy::too_many_arguments)]
11392fn record_strip_palette(
11393 n: &mut Neighbours,
11394 mi: (usize, usize),
11395 bw: usize,
11396 bh: usize,
11397 y_size: usize,
11398 y_colors: [u16; 8],
11399 uv_size: usize,
11400 uv_colors: [u16; 8],
11401) {
11402 let (r, c) = mi;
11403 // lane-t900 r23 rung: every publication of a block's palette state into
11404 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
11405 // path left a stale `left_palette_size` behind when
11406 // `av1_get_palette_mode_ctx` disagrees with libaom's.
11407 if crate::envflags::env_flag!("EC_PALPUB") {
11408 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
11409 }
11410 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
11411 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
11412 // existed because the 16px [`SUB`] cell held one slot for all the strips
11413 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
11414 // real neighbour leaf 1 reads.
11415 {
11416 for cell in 0..(bw / MI).max(1) {
11417 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
11418 *e = y_size as u8;
11419 n.above_palette_uv_size[c + cell] = uv_size as u8;
11420 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
11421 // colours of a size-0 neighbour are never read.
11422 if y_size > 0 {
11423 n.above_palette_colors[c + cell] = y_colors;
11424 }
11425 if uv_size > 0 {
11426 n.above_palette_uv_colors[c + cell] = uv_colors;
11427 }
11428 }
11429 }
11430 }
11431 {
11432 for cell in 0..(bh / MI).max(1) {
11433 if n.left_palette_size.get(r + cell).is_none() {
11434 break;
11435 }
11436 n.left_palette_size[r + cell] = y_size as u8;
11437 n.left_palette_uv_size[r + cell] = uv_size as u8;
11438 if y_size > 0 {
11439 n.left_palette_colors[r + cell] = y_colors;
11440 }
11441 if uv_size > 0 {
11442 n.left_palette_uv_colors[r + cell] = uv_colors;
11443 }
11444 }
11445 }
11446}
11447
11448/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
11449fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
11450 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| {
11451 i32::from(y.data[ly * y.width + lx])
11452 })
11453}
11454
11455/// Everything a rect strip already read out of the stream before its luma
11456/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
11457/// (nine values that would otherwise be nine more parameters).
11458struct RectStripModes {
11459 skip: bool,
11460 mode: usize,
11461 angle_delta_y: i32,
11462 uv_predict_mode: usize,
11463 angle_delta_uv: i32,
11464 alpha: Option<(i32, i32)>,
11465 filter_intra: Option<usize>,
11466 smooth_neighbor: bool,
11467 smooth_neighbor_uv: bool,
11468 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
11469 /// mapped through the colour table), sliced per transform unit below --
11470 /// palette prediction reads no edge pixels, so a unit's slice of the
11471 /// whole-block map IS its prediction. Without this a palette strip whose
11472 /// transform splits predicted DC and came out flat grey while the entropy
11473 /// stream stayed in sync (the coefficients are read either way).
11474 palette_y: Option<Vec<u16>>,
11475 /// As `palette_y`, for the un-split chroma transform (U, V).
11476 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
11477}
11478
11479/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
11480/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
11481/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
11482/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
11483/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
11484/// TX_32X16`) and only the second reaches a square -- the reason
11485/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
11486/// already square) mis-tiled 1:4 strips.
11487fn depth_to_tx_wh(
11488 bw: usize,
11489 bh: usize,
11490 depth: usize,
11491 fctx: &crate::decode::FrameCtx,
11492) -> (usize, usize) {
11493 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
11494 // `read_tx_size`: the lossless early return comes before
11495 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
11496 if lossless(fctx) {
11497 return (4, 4);
11498 }
11499 let (mut w, mut h) = (bw.min(64), bh.min(64));
11500 for _ in 0..depth {
11501 match w.cmp(&h) {
11502 std::cmp::Ordering::Greater => w /= 2,
11503 std::cmp::Ordering::Less => h /= 2,
11504 std::cmp::Ordering::Equal => {
11505 w /= 2;
11506 h /= 2;
11507 }
11508 }
11509 }
11510 (w, h)
11511}
11512
11513/// lane-av1-422stripanchor: [`decode_rect_split`]'s 4-wide-strip port of the
11514/// split4 floored-pair anchor ([`sub8_leaf_chroma422`]'s rule). A 1-mi-wide
11515/// strip (luma `(4, 16)` / `(4, 8)`) has NO chroma plane block of its own at
11516/// ss (1, 0) -- `av1_ss_size_lookup[BLOCK_4X16][1][0]` and
11517/// `[BLOCK_4X8][1][0]` are both BLOCK_INVALID (`common_data.c`), and a
11518/// 2-px-wide area is not a transform shape. The strip pairs with its
11519/// even-column sibling (`is_chroma_reference`'s `mi_col & 1` column clause,
11520/// the rule [`decode_rect4_16_strip`] implements one partition level up), and
11521/// the ODD-column strip codes the PAIR's `(4, bh)` plane anchored at
11522/// `av1_setup_dst_planes`' mi-exact floor `(mi_col & !1) * MI >> ss_x`, with
11523/// the entropy context on the floored cell. Returns
11524/// `(pair block width, pair block height, write anchor x, entropy mi column)`
11525/// for that pair, or `None` when the strip keeps its own plane block at its
11526/// own origin -- which is every 4:2:0 and 4:4:4 cell (their chroma is never
11527/// 2 px wide) and every 4:2:2 strip of 8 px or more.
11528fn chroma422_pair_plane(
11529 ss_x: bool,
11530 ss_y: bool,
11531 mi_col: usize,
11532 bw: usize,
11533 bh: usize,
11534) -> Option<(usize, usize, usize, usize)> {
11535 if ss_x && !ss_y && (bw >> 1) == 2 {
11536 Some((4, bh, ((mi_col & !1) * MI) >> 1, mi_col & !1))
11537 } else {
11538 None
11539 }
11540}
11541
11542/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
11543/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
11544/// rect path here refused by name until now ("per-unit rect prediction is not
11545/// ported").
11546///
11547/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
11548/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
11549/// strip the very first step already lands on a SQUARE transform
11550/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
11551/// every further step halves a square) -- so each unit is square and reads
11552/// through the ordinary square [`read_plane`]. What is genuinely rectangular
11553/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
11554/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
11555/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
11556/// split by luma's depth.
11557///
11558/// Each unit predicts off whatever the earlier units of this same block
11559/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
11560/// inside `av1_foreach_transformed_block`, raster order), which is exactly
11561/// what predicting the whole strip in one shot got wrong.
11562#[allow(clippy::too_many_arguments)]
11563fn decode_rect_split(
11564 dec: &mut SymbolDecoder,
11565 cdfs: &mut Cdfs,
11566 neighbours: &mut Neighbours,
11567 at_mi: (usize, usize),
11568 bw: usize,
11569 bh: usize,
11570 // The transform unit's own width and height in pixels. Square for every
11571 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
11572 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
11573 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
11574 tx_w: usize,
11575 tx_h: usize,
11576 m: &RectStripModes,
11577 y: &mut PlaneBuf<'static>,
11578 u: &mut PlaneBuf<'static>,
11579 v: &mut PlaneBuf<'static>,
11580 base_q_idx: u8,
11581 reduced_tx_set: bool,
11582 fctx: &crate::decode::FrameCtx,
11583) -> Result<()> {
11584 let (mi_r, mi_c) = at_mi;
11585 let (px, py) = (mi_c * MI, mi_r * MI);
11586 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
11587 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
11588 // lane-av1-422blockhalf: at ss (1,0) the tall/wide 1:2 and 1:4 strips'
11589 // chroma plane block is BLOCK_INVALID (`av1_ss_size_lookup[...][1][0]`,
11590 // blockd.h -- the 4:2:2 column maps BLOCK_8X16/16X32/32X64/64X128 and
11591 // BLOCK_8X32/16X64, plus 4-wide BLOCK_4X16, to BLOCK_INVALID), so
11592 // `av1_get_max_uv_txsize` indexes `max_txsize_rect_lookup` OUT OF BOUNDS
11593 // and the pinned Release oracle byte there is TX_4X8 (the lane-av1-422m
11594 // measurement). The plane is still coded -- `decode_token_recon_block`
11595 // steps it in that (4, 8) unit shape -- so the strip's chroma tiles into
11596 // 4x8 rect units, plane-major.
11597 let chroma_422_oob = ss_x(fctx) == 1
11598 && ss_y(fctx) == 0
11599 && matches!(
11600 (bw, bh),
11601 (8, 16) | (16, 32) | (32, 64) | (64, 128) | (8, 32) | (16, 64)
11602 );
11603 // lane-av1-422stripanchor: the 4-wide strips' PAIR chroma -- the ported
11604 // floored-pair anchor. `chroma422_pair_plane` is `Some` exactly when this
11605 // strip's own chroma block would be 2 px wide at ss (1, 0); the pair's
11606 // plane is then `(4, chroma_h)` written at the FLOORED cell
11607 // (`chroma_x`), and the skip/tiled chroma arms below tile it in (4, 8)
11608 // units (the OOB `max_txsize_rect_lookup[BLOCK_INVALID]` byte, TX_4X8 --
11609 // the same walk the (8, 32) class takes). The lossless raster arm keeps
11610 // the strip's own geometry: no caller of this function can present a
11611 // 4-wide strip yet (the enumeration test pins the five callers at
11612 // `8 <= min`), and the skip/tiled arms are the routes a future caller
11613 // needs.
11614 let chroma422_pair = chroma422_pair_plane(ss_x(fctx) == 1, ss_y(fctx) == 0, mi_c, bw, bh);
11615 let chroma_422_pair_wide = chroma422_pair.is_some();
11616 let (chroma_block_w, chroma_block_h, chroma_x) =
11617 chroma422_pair.map_or((chroma_w, chroma_h, cpx), |(w, h, x, _)| (w, h, x));
11618 // The chroma transform is picked before any symbol is read, so an
11619 // unsupported chroma shape refuses before this strip desyncs the tile.
11620 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
11621 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
11622 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
11623 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
11624 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
11625 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
11626 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
11627 // squares a rect transform down to a CDF set by
11628 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
11629 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
11630 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
11631 // paths already prove for these same shapes.
11632 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
11633 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
11634 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
11635 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
11636 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
11637 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
11638 _ => None,
11639 };
11640 // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted
11641 // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled
11642 // below; everything else still needs a single-unit table.
11643 // lane-av1-422: a 4:2:2 strip's chroma plane keeps the strip's HEIGHT and
11644 // halves only the width, so a rect luma strip codes a SQUARE chroma block
11645 // (16x8 luma -> 8x8 chroma) -- the square rows below. At 4:2:0 and 4:4:4 a
11646 // rect strip's chroma is itself rect, so the square rows are unreachable
11647 // there and cannot change their results.
11648 // lane-av1-422blockhalf: the tiled arms below handle every shape this
11649 // strip can carry (including the 4:2:2 BLOCK_INVALID planes), so the
11650 // diagnostic names only the shapes that would actually refuse -- it used
11651 // to fire for every tiled square too (the parent lane's `chroma=8x8`
11652 // rows) and sent the next lane chasing handled shapes.
11653 let chroma_tiled = chroma_422_pair_wide
11654 || chroma_422_oob
11655 || matches!(
11656 (chroma_w, chroma_h),
11657 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)
11658 );
11659 if !m.skip {
11660 if let Some(i) = match (chroma_w, chroma_h) {
11661 (32, 8) => Some(0),
11662 (8, 32) => Some(1),
11663 (8, 4) => Some(2),
11664 (4, 8) => Some(3),
11665 _ => None,
11666 } {
11667 hit_do! {
11668 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
11669 let mut hits = c.get();
11670 hits[i] += 1;
11671 c.set(hits);
11672 });
11673 }
11674 }
11675 if !m.skip && chroma.is_none() && !chroma_tiled {
11676 // Diagnostic for the next caller that lands here (class
11677 // refusal-names-a-correlate: the message names the tool, not the
11678 // shape); the refusal below keeps its inventory-pinned wording.
11679 eprintln!(
11680 "EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} \
11681 chroma={chroma_w}x{chroma_h}"
11682 );
11683 }
11684 }
11685 // lane-rectsplit r2 (verifier finding): with both callers wired
11686 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
11687 // 64x32/32x64) every shape that reaches here has a table above, so this
11688 // arm is UNREACHABLE today. It stays as the shape guard for the next
11689 // caller -- a new strip size would otherwise hit the `expect` below and
11690 // panic instead of refusing by name -- and so stays in
11691 // `refusal_inventory::REFUSALS`.
11692 if !m.skip && chroma.is_none() && !chroma_tiled {
11693 return Err(unsupported(
11694 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
11695 ));
11696 }
11697 hit!(RECT_SPLIT_TX_HITS);
11698 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
11699 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
11700 }
11701 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
11702 // A square unit reads through the ordinary square [`read_plane`]; a rect
11703 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
11704 // the very tables the unsplit 16x8/32x16 paths use.
11705 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
11706 (w, h) if w == h => None,
11707 (16, 8) | (8, 16) => Some((
11708 if reduced_tx_set {
11709 TxbSet::LumaRect16x8
11710 } else {
11711 TxbSet::LumaRect16x8Set1
11712 },
11713 if tx_w == 16 {
11714 &SCAN_16X8[..]
11715 } else {
11716 &SCAN_8X16[..]
11717 },
11718 )),
11719 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
11720 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
11721 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
11722 // strip, read through the `luma_64corner` arm below instead of a rect
11723 // table -- a 64-length axis codes only its low 32 coefficients
11724 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
11725 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
11726 // depth-0 arm already reads on the key-frame path.
11727 //
11728 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
11729 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
11730 // sub-8x8 intra leaves still refused: with those lifted (r2) the
11731 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
11732 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
11733 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
11734 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
11735 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
11736 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
11737 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
11738 (64, 32) | (32, 64) => None,
11739 _ => {
11740 return Err(unsupported(format!(
11741 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
11742 coefficient tables for that shape here)"
11743 )));
11744 }
11745 };
11746 // The `None` above that is NOT the square arm.
11747 let luma_64corner = tx_w != tx_h;
11748 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
11749 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
11750 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
11751 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
11752 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
11753 // per-unit rect walk stay wired above/below; the round that finds that
11754 // defect deletes this refusal and nothing else.
11755 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
11756 let luma_scan = default_scan(tx_w.min(tx_h));
11757 let zero_tu = vec![0i32; tx_w * tx_h];
11758 // The strip's OWN edge availability, the fallback for a transform unit
11759 // whose top-right/bottom-left pixels fall outside the strip.
11760 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11761 for tu_row in 0..bh / tx_h {
11762 for tu_col in 0..bw / tx_w {
11763 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
11764 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
11765 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
11766 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
11767 // libaom clips `av1_foreach_transformed_block_in_plane` to
11768 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
11769 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
11770 // TOP-LEFT sample falls outside the frame is never coded. We read
11771 // coefficients for those phantom units and desynced the stream at
11772 // the very next symbol.
11773 if tu_px >= y.true_width || tu_py >= y.true_height {
11774 continue;
11775 }
11776 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
11777 // transform unit INSIDE a block, which is a different rule from
11778 // the standalone-block table [`Reach::of`] applies -- and the
11779 // reason a depth-2 superblock strip came out one sample off
11780 // before this: `Reach::of(tx, ..)` answered as if the unit were
11781 // its own block at that superblock position.
11782 // * top-right: if the unit's right neighbour is still inside the
11783 // strip the pixels are already reconstructed (`col_off +
11784 // tx_wide < plane_bw`); otherwise only the strip's own top row
11785 // of units can reach past it, through the block-level answer.
11786 // * bottom-left: a unit that is not in the strip's left column
11787 // has none (`col_off > 0` returns 0); inside the strip
11788 // (`row_off + tx_high < plane_bh`) they are the left
11789 // neighbour's, already reconstructed; the last row falls back
11790 // to the block-level answer.
11791 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
11792 // The unit's own window on the block's palette prediction.
11793 if let Some(buf) = &m.palette_y {
11794 let tu_buf: Vec<u16> = (0..tx_h)
11795 .flat_map(|i| {
11796 let base = (row_off + i) * bw + col_off;
11797 buf[base..base + tx_w].iter().copied()
11798 })
11799 .collect();
11800 set_palette_pred(tu_buf, fctx);
11801 }
11802 if m.skip {
11803 push_intra_rect(
11804 0,
11805 tu_px,
11806 tu_py,
11807 tx_w,
11808 tx_h,
11809 m.mode,
11810 m.angle_delta_y,
11811 tu_reach,
11812 &zero_tu,
11813 None,
11814 m.filter_intra,
11815 m.smooth_neighbor,
11816 fctx,
11817 );
11818 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
11819 } else if luma_64corner && luma_rect.is_none() {
11820 // The un-split 64-level luma transform: `read_coeffs` on the
11821 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
11822 // and the real rect shape passed through for
11823 // `av1_nz_map_ctx_offset` -- byte for byte
11824 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
11825 // 64-level strip gate already proves. `tx_type` is not coded
11826 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
11827 // the square-up size is TX_64X64), and this unit covers its
11828 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
11829 if crate::envflags::env_flag!("EC_RECT64TU") {
11830 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
11831 }
11832 hit_do! {
11833 RECT64_CORNER_TU_HITS.with(|c| {
11834 let mut v = c.get();
11835 v[usize::from(tx_h > tx_w)] += 1;
11836 c.set(v);
11837 });
11838 }
11839 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
11840 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
11841 let (corner, tu_tx_type) = read_coeffs(
11842 dec,
11843 &mut coding,
11844 default_scan(TX32),
11845 0,
11846 dc_sign_ctx(tu_around.2),
11847 TxType::DctDct,
11848 Some((tx_w, tx_h)),
11849 )?;
11850 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
11851 let mut tu_grid = vec![0i32; tx_w * tx_h];
11852 for row in 0..ch {
11853 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
11854 }
11855 let residual = dequant_and_inverse_typed_wh(
11856 &tu_grid,
11857 tx_w,
11858 tx_h,
11859 crate::decode::bit_depth(fctx),
11860 block_q_idx(fctx),
11861 plane_q_delta(0, fctx).0,
11862 plane_q_delta(0, fctx).1,
11863 tu_tx_type,
11864 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
11865 );
11866 push_intra_rect(
11867 0,
11868 tu_px,
11869 tu_py,
11870 tx_w,
11871 tx_h,
11872 m.mode,
11873 m.angle_delta_y,
11874 tu_reach,
11875 &residual,
11876 None,
11877 m.filter_intra,
11878 m.smooth_neighbor,
11879 fctx,
11880 );
11881 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
11882 } else if let Some((rect_set, rect_scan)) = luma_rect {
11883 // The rect-unit twin of the square arm below: same contexts,
11884 // same order, through the rect coefficient reader. The
11885 // `tx_type` CDF row of a filter-intra block is
11886 // `fimode_to_intradir[filter_intra_mode]`, never the block's
11887 // own (always DC_PRED) mode -- [`read_plane`] applies that
11888 // for the square arm, so this one must too.
11889 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
11890 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
11891 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
11892 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
11893 // neighbour-magnitude table is for a unit SMALLER than its
11894 // block. [`decode_block_rect`]'s own unsplit read passes a
11895 // literal 0 for the same reason; this arm applied the table
11896 // unconditionally and desynced every depth-0 rect strip that
11897 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
11898 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
11899 0
11900 } else {
11901 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
11902 };
11903 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
11904 let (tu_grid, tu_tx_type) = read_coeffs_rect(
11905 dec,
11906 &mut coding,
11907 rect_scan,
11908 tx_w,
11909 tx_h,
11910 tu_skip_ctx,
11911 dc_sign_ctx(tu_around.2),
11912 TxType::DctDct,
11913 0,
11914 )?;
11915 let residual = dequant_and_inverse_typed_wh(
11916 &tu_grid,
11917 tx_w,
11918 tx_h,
11919 crate::decode::bit_depth(fctx),
11920 block_q_idx(fctx),
11921 plane_q_delta(0, fctx).0,
11922 plane_q_delta(0, fctx).1,
11923 tu_tx_type,
11924 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
11925 );
11926 push_intra_rect(
11927 0,
11928 tu_px,
11929 tu_py,
11930 tx_w,
11931 tx_h,
11932 m.mode,
11933 m.angle_delta_y,
11934 tu_reach,
11935 &residual,
11936 None,
11937 m.filter_intra,
11938 m.smooth_neighbor,
11939 fctx,
11940 );
11941 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
11942 } else {
11943 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
11944 // This unit is smaller than the block it sits in, so
11945 // `txb_skip_ctx` is the neighbour-magnitude table, not the
11946 // lone-TU 0 (spec `get_txb_ctx_general`).
11947 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
11948 let tu_grid = read_plane(
11949 dec,
11950 cdfs,
11951 luma_set,
11952 &luma_scan,
11953 0,
11954 tu_around,
11955 m.mode,
11956 m.mode,
11957 m.angle_delta_y,
11958 tu_reach,
11959 y,
11960 tu_px,
11961 tu_py,
11962 tx_w,
11963 tx_w,
11964 base_q_idx,
11965 None,
11966 m.filter_intra,
11967 Some(tu_skip_ctx),
11968 m.smooth_neighbor,
11969 fctx,
11970 )?;
11971 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
11972 }
11973 }
11974 }
11975 // CHROMA: one un-split rect transform for the whole strip.
11976 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
11977 // units -- each stamps its own neighbour context as it is read, and the
11978 // whole-block `record_split_luma_rect_mi` below would overwrite all of
11979 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
11980 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
11981 // collected here and replayed after that record.
11982 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
11983 // The chroma_tiled arm below stamps each unit's coefficient context
11984 // immediately (so the NEXT unit reads it), then the whole-strip
11985 // `record_split_luma_rect_mi` rewrites every chroma cell with ONE
11986 // whole-strip state and the per-unit DC signs and levels are lost
11987 // (class `override-slot-on-one-arm`). The units are collected here and
11988 // replayed after that record, the way the lossless arm's
11989 // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail
11990 // already do.
11991 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
11992 let ac = m.alpha.map(|_| {
11993 // lane-av1-422stripanchor: the pair unit's CfL source is the PAIR's
11994 // luma -- the 8-px-wide region the floored 4-px chroma block covers
11995 // (`av1_setup_dst_planes`' floor), never the odd strip's own 4 px.
11996 if chroma_422_pair_wide {
11997 cfl_src_rect((mi_c & !1) * MI, py, 8, bh)
11998 } else {
11999 cfl_src_rect(px, py, bw, bh)
12000 }
12001 });
12002 let reach = if chroma_422_pair_wide {
12003 // The chroma units predict off the PAIR block's edges: an odd-column
12004 // strip's pair starts 4 luma px to the strip's left, so the strip's
12005 // own answer names the wrong above/right samples (the pair16 arm's
12006 // `pair_reach`, one partition level up).
12007 Reach::of_rect(8, bh, (mi_c & !1) * MI, py, y.width, y.height, fctx)
12008 } else {
12009 block_reach
12010 };
12011 let (u_grid, v_grid) = if mono(fctx) {
12012 // lane-av1mono: a monochrome frame codes no chroma coefficients on
12013 // any block (`plane < av1_num_planes == 1`), so the whole chroma
12014 // section -- the skipped-strip pushes, the lossless raster and the
12015 // un-split `read_coeffs_rect` below -- is bypassed.
12016 let zero = Grid::Zero(chroma_w * chroma_h);
12017 (zero.clone(), zero)
12018 } else if m.skip {
12019 let zero = Grid::Zero(chroma_block_w * chroma_block_h);
12020 if chroma_422_pair_wide || chroma_422_oob {
12021 // lane-av1-422blockhalf: libaom predicts an INTRA strip's chroma
12022 // per transform unit even when the strip is skipped
12023 // (`decode_token_recon_block`'s per-TU plane walk runs before the
12024 // skip guard), so the BLOCK_INVALID plane predicts as (4, 8)
12025 // units -- one whole-plane push here would ask the intra
12026 // predictor for a 1:8 rect it never needs.
12027 // lane-av1-422stripanchor: the 4-wide strip's PAIR plane does the
12028 // same, over the pair's own `(chroma_block_w, chroma_block_h)`
12029 // grid at the floored anchor `chroma_x`.
12030 let (uw, uh) = (4usize, 8usize);
12031 for plane_idx in 1..=2 {
12032 if let Some((ub, vb)) = &m.palette_uv {
12033 let buf = if plane_idx == 1 { ub } else { vb };
12034 set_palette_pred(buf.clone(), fctx);
12035 }
12036 for cu_row in 0..chroma_block_h / uh {
12037 for cu_col in 0..chroma_block_w / uw {
12038 push_intra_rect(
12039 plane_idx,
12040 chroma_x + cu_col * uw,
12041 cpy + cu_row * uh,
12042 uw,
12043 uh,
12044 m.uv_predict_mode,
12045 m.angle_delta_uv,
12046 reach,
12047 &ZERO_RESIDUAL[..uw * uh],
12048 m.alpha
12049 .zip(ac.clone())
12050 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
12051 None,
12052 m.smooth_neighbor_uv,
12053 fctx,
12054 );
12055 }
12056 }
12057 }
12058 } else {
12059 if let Some((ub, _)) = &m.palette_uv {
12060 set_palette_pred(ub.clone(), fctx);
12061 }
12062 push_intra_rect(
12063 1,
12064 cpx,
12065 cpy,
12066 chroma_w,
12067 chroma_h,
12068 m.uv_predict_mode,
12069 m.angle_delta_uv,
12070 reach,
12071 &zero,
12072 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12073 None,
12074 m.smooth_neighbor_uv,
12075 fctx,
12076 );
12077 if let Some((_, vb)) = &m.palette_uv {
12078 set_palette_pred(vb.clone(), fctx);
12079 }
12080 push_intra_rect(
12081 2,
12082 cpx,
12083 cpy,
12084 chroma_w,
12085 chroma_h,
12086 m.uv_predict_mode,
12087 m.angle_delta_uv,
12088 reach,
12089 &zero,
12090 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12091 None,
12092 m.smooth_neighbor_uv,
12093 fctx,
12094 );
12095 }
12096 (zero.clone(), zero)
12097 } else if lossless(fctx) {
12098 // lane-lossless: the strip's chroma plane block is coded as 4x4
12099 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
12100 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
12101 // (`decode_token_recon_block`'s mu-chunk loop, measured against
12102 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
12103 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
12104 // offset (our `+3` row base) whenever the plane block is bigger than
12105 // the transform.
12106 let scan4 = default_scan(4);
12107 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
12108 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
12109 // lane-av1-llband: one 4x4 chroma unit's extent in LUMA pixels -- 4
12110 // chroma px scaled by the plane's own subsampling. The hardcoded 8
12111 // was the 4:2:0 unit's span; at 4:4:4 a unit is 4x4 LUMA px (one mi
12112 // cell), and the 8-px step made every unit past the first column/row
12113 // read its `txb_skip` context at the WRONG mi (two cells over) and
12114 // stamp a 2-cell span with one unit's state -- the polluted above-band
12115 // cell behind a 16x8 leaf's U bc=2 unit of the 444 lossless key frame
12116 // (measured: oracle `EC_DBGCTX` reads 1-cell spans at 1-mi steps;
12117 // ours read `above[28..29]` where the oracle read `above[26]`).
12118 let span_x = 4 << ss_x(fctx);
12119 let span_y = 4 << ss_y(fctx);
12120 let mut last = [Grid::Zero(16), Grid::Zero(16)];
12121 for plane_idx in 1..=2 {
12122 for cu_row in 0..ch_n {
12123 for cu_col in 0..cw_n {
12124 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
12125 let cu_around = neighbours.around_mi_rect(cu_mi, span_x, span_y);
12126 let cu_reach = tu_reach(
12127 bw,
12128 bh,
12129 cu_col * span_x,
12130 cu_row * span_y,
12131 span_x,
12132 block_reach,
12133 px,
12134 py,
12135 y.width,
12136 y.height,
12137 fctx,
12138 );
12139 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
12140 if let Some((ub, vb)) = &m.palette_uv {
12141 let pbuf = if plane_idx == 1 { ub } else { vb };
12142 set_palette_pred(
12143 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
12144 fctx,
12145 );
12146 }
12147 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12148 let grid = read_plane(
12149 dec,
12150 cdfs,
12151 TxbSet::Chroma4,
12152 &scan4,
12153 plane_idx,
12154 cu_around[plane_idx],
12155 m.mode,
12156 m.uv_predict_mode,
12157 m.angle_delta_uv,
12158 cu_reach,
12159 plane,
12160 cu_x,
12161 cu_y,
12162 4,
12163 4,
12164 base_q_idx,
12165 m.alpha
12166 .zip(ac)
12167 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
12168 None,
12169 offset,
12170 m.smooth_neighbor_uv,
12171 fctx,
12172 )?;
12173 if span_x == 4 && span_y == 4 {
12174 hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS);
12175 }
12176 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid);
12177 ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y));
12178 last[plane_idx - 1] = grid;
12179 }
12180 }
12181 }
12182 let [ug, vg] = last;
12183 (ug, vg)
12184 } else if chroma_tiled {
12185 let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) =
12186 if chroma_422_pair_wide || chroma_422_oob {
12187 // lane-av1-422blockhalf / lane-av1-422stripanchor: the
12188 // BLOCK_INVALID-plane chroma's (4, 8) units -- the Release
12189 // oracle's out-of-bounds `max_txsize_rect_lookup` byte (TX_4X8,
12190 // see above). For the 4-wide strip the units tile the PAIR's
12191 // plane, stepping from the floored anchor.
12192 (4, 8, TxbSet::ChromaRect8x4, &SCAN_4X8)
12193 } else {
12194 match (chroma_w, chroma_h) {
12195 (64, 32) | (32, 64) | (32, 32) => (32, 32, TxbSet::Chroma32, default_scan(32)),
12196 (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16),
12197 (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32),
12198 // lane-av1-422: the 4:2:2 square chroma planes (height unhalved),
12199 // through the square reader like every other square chroma unit.
12200 (16, 16) => (16, 16, TxbSet::Chroma16, default_scan(16)),
12201 (8, 8) => (8, 8, TxbSet::Chroma8, default_scan(8)),
12202 _ => unreachable!("chroma_tiled"),
12203 }
12204 };
12205 // lane-av1-422: the witness counter, keyed to ss (1,0) so only a 4:2:2
12206 // frame's square chroma units count it.
12207 if uw == uh && ss_x(fctx) == 1 && ss_y(fctx) == 0 {
12208 hit!(CHROMA422_SQUARE_HITS);
12209 }
12210 if chroma_422_pair_wide {
12211 hit!(CHROMA422_PAIR_WIDE_HITS);
12212 }
12213 let (nw, nh) = (chroma_block_w / uw, chroma_block_h / uh);
12214 // lane-av1-422stripanchor: the pair's plane block is BLOCK_INVALID
12215 // whatever the pair size (`num_pels_log2_lookup[255]` reads 0xff in
12216 // the pinned Release oracle), so its txb_skip rows always carry the
12217 // bigger-plane +3 (the av1422q rule the pair16 arm measures).
12218 let bigger = chroma_422_pair_wide || chroma_w * chroma_h > uw * uh;
12219 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
12220 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra;
12221 // smaller rect units (the 4:2:2 BLOCK_INVALID-plane (4, 8)s) take the
12222 // mode-indexed default, the same rule the unsplit arm below applies.
12223 let default_tx = if uw.max(uh) >= 32 {
12224 TxType::DctDct
12225 } else {
12226 default_intra_tx_type(m.uv_predict_mode as u8)
12227 };
12228 let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)];
12229 for plane_idx in 1..=2 {
12230 for cu_row in 0..nh {
12231 for cu_col in 0..nw {
12232 let luma_span_x = uw << ss_x(fctx);
12233 let luma_span_y = uh << ss_y(fctx);
12234 let cu_mi = (
12235 mi_r + cu_row * (luma_span_y / MI),
12236 if chroma_422_pair_wide {
12237 mi_c & !1
12238 } else {
12239 mi_c
12240 } + cu_col * (luma_span_x / MI),
12241 );
12242 // lane-av1-422blockhalf: the 4:2:2 (4, 8) units read their
12243 // chroma context per chroma cell
12244 // ([`Neighbours::around_mi_422_chroma`], the block-8
12245 // rule) -- the plain rect walk samples one chroma cell
12246 // twice at ss_x 1. Every pre-existing shape keeps its own
12247 // walk.
12248 // lane-av1422mi24: the plain rect walk's double-count
12249 // hits EVERY unit shape at ss (1,0), not just the (4, 8)
12250 // one -- the (8, 8) unit of a 16x8 intra-in-inter strip
12251 // read its above dc votes twice and its U dc_sign one
12252 // ctx row high (t422 frame 1). Route every ss (1,0)
12253 // unit through the every-second-above-cell sampling;
12254 // 4:2:0/4:4:4 keep the plain walk verbatim.
12255 let cu_around = if chroma_422_oob || (ss_x(fctx) == 1 && ss_y(fctx) == 0) {
12256 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
12257 } else {
12258 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
12259 };
12260 let (cu_x, cu_y) = (chroma_x + cu_col * uw, cpy + cu_row * uh);
12261 let cfl = m.alpha.map(|(au, av)| {
12262 let alpha = if plane_idx == 1 { au } else { av };
12263 (
12264 alpha,
12265 if chroma_422_pair_wide {
12266 // The unit's co-located luma is the PAIR's
12267 // 8-px-wide band at the floored mi column.
12268 cfl_src_rect(
12269 (mi_c & !1) * MI + cu_col * luma_span_x,
12270 py + cu_row * luma_span_y,
12271 luma_span_x,
12272 luma_span_y,
12273 )
12274 } else {
12275 cfl_src_rect(
12276 px + cu_col * luma_span_x,
12277 py + cu_row * luma_span_y,
12278 luma_span_x,
12279 luma_span_y,
12280 )
12281 },
12282 )
12283 });
12284 // lane-av1-422kf: the palette colour map is consumed per
12285 // unit here like every other chroma arm (`av1_visit_palette`
12286 // feeds the whole plane block; window it to this unit).
12287 // Without this the square chroma rows decoded a uv-palette
12288 // strip's chroma as plain DC (class same-symbols-silent-
12289 // prediction: the rng stayed in sync, only the prediction
12290 // was dropped).
12291 if let Some((ub, vb)) = &m.palette_uv {
12292 let buf = if plane_idx == 1 { ub } else { vb };
12293 set_palette_pred(
12294 palette_window(buf, chroma_block_w, cu_col * uw, cu_row * uh, uw, uh),
12295 fctx,
12296 );
12297 }
12298 // 32x32 does not fit read_coeffs_rect's scratch (768). The
12299 // square reader is the path every other 32x32 chroma unit uses.
12300 let levels = if uw == uh {
12301 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12302 read_plane(
12303 dec,
12304 cdfs,
12305 set,
12306 scan,
12307 plane_idx,
12308 cu_around[plane_idx],
12309 m.mode,
12310 m.uv_predict_mode,
12311 m.angle_delta_uv,
12312 reach,
12313 plane,
12314 cu_x,
12315 cu_y,
12316 uw,
12317 uw,
12318 base_q_idx,
12319 cfl,
12320 None,
12321 bigger.then_some(3),
12322 m.smooth_neighbor_uv,
12323 fctx,
12324 )?
12325 } else {
12326 let skip_ctx = usize::from(cu_around[plane_idx].0)
12327 + usize::from(cu_around[plane_idx].1)
12328 + usize::from(bigger) * 3;
12329 let mut coding = cdfs.txb(set, m.uv_predict_mode);
12330 let (levels, tx_type) = read_coeffs_rect(
12331 dec,
12332 &mut coding,
12333 scan,
12334 uw,
12335 uh,
12336 skip_ctx,
12337 dc_sign_ctx(cu_around[plane_idx].2),
12338 default_tx,
12339 plane_idx,
12340 )?;
12341 let residual = dequant_and_inverse_typed_wh(
12342 &levels,
12343 uw,
12344 uh,
12345 crate::decode::bit_depth(fctx),
12346 block_q_idx(fctx),
12347 plane_q_delta(plane_idx, fctx).0,
12348 plane_q_delta(plane_idx, fctx).1,
12349 tx_type,
12350 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
12351 );
12352 push_intra_rect(
12353 plane_idx,
12354 cu_x,
12355 cu_y,
12356 uw,
12357 uh,
12358 m.uv_predict_mode,
12359 m.angle_delta_uv,
12360 reach,
12361 &residual,
12362 cfl,
12363 None,
12364 m.smooth_neighbor_uv,
12365 fctx,
12366 );
12367 levels
12368 };
12369 neighbours.record_mi_chroma(
12370 cu_mi,
12371 luma_span_x,
12372 luma_span_y,
12373 plane_idx,
12374 &levels,
12375 );
12376 tiled_chroma_units.push((
12377 cu_mi,
12378 plane_idx,
12379 levels.clone(),
12380 luma_span_x,
12381 luma_span_y,
12382 ));
12383 last[plane_idx - 1] = levels;
12384 }
12385 }
12386 }
12387 (last[0].clone(), last[1].clone())
12388 } else {
12389 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
12390 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
12391 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
12392 // so only the 16x8/8x16 pair takes the mode-indexed default.
12393 let default_tx = if chroma_w.max(chroma_h) >= 32 {
12394 TxType::DctDct
12395 } else {
12396 default_intra_tx_type(m.uv_predict_mode as u8)
12397 };
12398 // lane-av1422mi24: at ss (1,0) the chroma above span is `bw >> 1`
12399 // chroma cells spread over `bw` luma mi columns -- the per-mi gather
12400 // counts every chroma column's whole-unit dc sign twice (the t422
12401 // frame-1 mi(26,60) intra-in-inter strip's U dc_sign read one ctx
12402 // row high). Luma keeps the per-mi gather; the two chroma planes
12403 // take [`Neighbours::around_mi_422_chroma`]'s every-second
12404 // above-cell sampling, like every other 4:2:2 chroma gather.
12405 let mut around = neighbours.around_mi_rect(at_mi, bw, bh);
12406 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
12407 let c = neighbours.around_mi_422_chroma(at_mi, bw, bh);
12408 around[1] = c[1];
12409 around[2] = c[2];
12410 }
12411 let mut grids: Vec<Grid> = Vec::with_capacity(2);
12412 for plane_idx in 1..=2 {
12413 let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
12414 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
12415 let (levels, tx_type) = read_coeffs_rect(
12416 dec,
12417 &mut coding,
12418 chroma_scan,
12419 chroma_w,
12420 chroma_h,
12421 skip_ctx,
12422 dc_sign_ctx(around[plane_idx].2),
12423 default_tx,
12424 plane_idx,
12425 )?;
12426 // The same delta_q proof the unsplit rect64 path records
12427 // (lane-rectsplit r4: lifting the split-transform refusal moved
12428 // superblock strips onto this path, so only counting there would
12429 // leave the delta_q gate's counter silent for them).
12430 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
12431 hit!(RECT64_QIDX_DRIFT_HITS);
12432 }
12433 let residual = dequant_and_inverse_typed_wh(
12434 &levels,
12435 chroma_w,
12436 chroma_h,
12437 crate::decode::bit_depth(fctx),
12438 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
12439 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
12440 // reading `current_q_idx` here dropped the segment feature
12441 // that every other dequant site applies (class
12442 // `parsed-then-discarded`).
12443 block_q_idx(fctx),
12444 plane_q_delta(plane_idx, fctx).0,
12445 plane_q_delta(plane_idx, fctx).1,
12446 tx_type,
12447 block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, tx_type),
12448 );
12449 let cfl = m
12450 .alpha
12451 .zip(ac)
12452 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
12453 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12454 if let Some((ub, vb)) = &m.palette_uv {
12455 let buf = if plane_idx == 1 { ub } else { vb };
12456 set_palette_pred(buf.clone(), fctx);
12457 }
12458 push_intra_rect(
12459 plane_idx,
12460 cpx,
12461 cpy,
12462 chroma_w,
12463 chroma_h,
12464 m.uv_predict_mode,
12465 m.angle_delta_uv,
12466 reach,
12467 &residual,
12468 cfl,
12469 None,
12470 m.smooth_neighbor_uv,
12471 fctx,
12472 );
12473 grids.push(levels);
12474 }
12475 let mut it = grids.into_iter();
12476 (it.next().unwrap(), it.next().unwrap())
12477 };
12478 neighbours.record_split_luma_rect_mi(
12479 at_mi,
12480 bw,
12481 bh,
12482 m.mode,
12483 m.uv_predict_mode,
12484 [&u_grid, &v_grid],
12485 );
12486 for (cu_mi, plane, unit, span_w, span_h) in &ll_chroma_units {
12487 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
12488 }
12489 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
12490 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
12491 }
12492 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
12493 neighbours.fill_lf_grid_rect(
12494 (mi_r, mi_c),
12495 bw / MI,
12496 bh / MI,
12497 tx_w as u8,
12498 tx_h as u8,
12499 0,
12500 fctx,
12501 );
12502 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12503 let (rng, _) = dec.debug_state();
12504 eprintln!(
12505 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
12506 tx={tx_w}x{tx_h} rng={rng}"
12507 );
12508 }
12509 Ok(())
12510}
12511
12512/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
12513/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
12514/// because it predicts squares only. Every pixel here goes through the rect
12515/// machinery the key-frame paths already prove: [`decode_rect_split`], which
12516/// at `depth == 0` is the unsplit strip as a single transform unit and
12517/// beyond it the per-unit walk of [`depth_to_tx_wh`].
12518///
12519/// What is genuinely different from [`decode_block_rect`] is the mode
12520/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
12521/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
12522/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
12523/// intra-in-inter arm's own reads at the rect footprint, including its
12524/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
12525/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
12526/// square and this arm) and a nonzero luma angle delta refused by name.
12527///
12528/// The strip's own neighbour records (luma per transform unit, chroma, skip
12529/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
12530/// inter-side bands and the mi map.
12531#[allow(clippy::too_many_arguments)]
12532/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
12533/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
12534/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
12535/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
12536/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
12537/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
12538/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
12539/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
12540/// table here rather than a shift of `bw.min(bh)`.
12541fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
12542 Some(match (bw.min(bh), bw.max(bh)) {
12543 (8, 16) => (1usize, 1usize),
12544 (16, 32) => (2, 2),
12545 (32, 64) => (3, 3),
12546 (8, 32) => (1, 2),
12547 (16, 64) => (2, 3),
12548 _ => return None,
12549 })
12550}
12551
12552/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
12553/// block path"): the shapes that can reach that arm, enumerated against the
12554/// MEASURED domain of the inter block path
12555/// ([`INTER_BLOCK_SHAPES`], the census the gate
12556/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
12557/// fills from three real streams).
12558///
12559/// [`decode_intra_rect_in_inter`] is called from one site, under
12560/// `write_w != side || write_h != side`, and only after two earlier arms have
12561/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
12562/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
12563/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
12564/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
12565/// and each of those has a row, so the refusal names a shape no measured
12566/// stream can present.
12567#[test]
12568fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
12569 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
12570 // names that string exactly (placeholders included) and pins its guard
12571 // site. The enumeration below establishes the shape domain; on its own it
12572 // never said WHICH string the domain was about, so under a real function
12573 // boundary -- rather than a window that ran into the next test -- the row
12574 // read as unanchored.
12575 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)";
12576 assert!(
12577 include_str!("decode.rs").contains(REFUSAL),
12578 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
12579 );
12580 let mut checked = 0;
12581 for &(side, w, h) in &INTER_BLOCK_SHAPES {
12582 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
12583 continue;
12584 }
12585 assert!(
12586 intra_in_inter_size_row(w, h).is_some(),
12587 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
12588 the \"no size-group/tx-category row\" refusal"
12589 );
12590 checked += 1;
12591 }
12592 assert_eq!(
12593 checked, 10,
12594 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
12595 lookup, not the 10 this claim was measured over"
12596 );
12597}
12598
12599/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
12600/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
12601/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
12602/// matched before the square arm's `log2` shortcut).
12603///
12604/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
12605/// row here"; the enumeration below is what proves no conformant block can
12606/// reach it.
12607pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
12608 Some(match (write_w, write_h) {
12609 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
12610 // below maps 128 to row 4 (BLOCK_16X32).
12611 (64, 128) => 14,
12612 (128, 64) => 15,
12613 (128, 128) => 16,
12614 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
12615 (16, 32) => 4,
12616 (32, 16) => 5,
12617 (32, 64) => 6,
12618 (64, 32) => 7,
12619 (8, 32) => 8,
12620 (32, 8) => 9,
12621 (16, 64) => 10,
12622 (64, 16) => 11,
12623 // lane-inter4 r3: the 16x16-level rect inter leaves.
12624 (8, 16) => 12,
12625 (16, 8) => 13,
12626 _ => return None,
12627 })
12628}
12629
12630/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
12631/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
12632/// `block_size_wide`/`block_size_high`).
12633#[cfg(test)]
12634const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
12635 (4, 4),
12636 (4, 8),
12637 (8, 4),
12638 (8, 8),
12639 (8, 16),
12640 (16, 8),
12641 (16, 16),
12642 (16, 32),
12643 (32, 16),
12644 (32, 32),
12645 (32, 64),
12646 (64, 32),
12647 (64, 64),
12648 (64, 128),
12649 (128, 64),
12650 (128, 128),
12651 (4, 16),
12652 (16, 4),
12653 (8, 32),
12654 (32, 8),
12655 (16, 64),
12656 (64, 16),
12657];
12658
12659/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
12660/// shape with no CDF row here" names a shape no conformant stream can present.
12661///
12662/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
12663/// whose `write_w.min(write_h) >= 8` clause is libaom's
12664/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
12665/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
12666/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
12667/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
12668/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
12669/// clause rejects before the lookup.
12670#[test]
12671fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
12672 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
12673 // names it and pins its guard site.
12674 const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here";
12675 assert!(
12676 crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), REFUSAL),
12677 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
12678 );
12679 let mut rows = std::collections::BTreeSet::new();
12680 let mut excluded = 0;
12681 for (w, h) in BLOCK_SIZES_ALL_WH {
12682 if w.min(h) < 8 {
12683 excluded += 1;
12684 assert!(
12685 w == 4 || h == 4,
12686 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
12687 );
12688 continue;
12689 }
12690 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
12691 panic!(
12692 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
12693 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
12694 )
12695 });
12696 assert!(
12697 row < 17,
12698 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
12699 );
12700 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
12701 }
12702 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
12703 assert_eq!(
12704 rows.len(),
12705 17,
12706 "17 eligible footprints must fill all 17 rows of the motion_mode table"
12707 );
12708}
12709
12710/// lane-av1-422stripanchor, format-cell census for the 4-wide-strip pair port
12711/// ([`chroma422_pair_plane`], [`decode_rect_split`]'s chroma routing): over
12712/// every `BLOCK_SIZES_ALL` footprint at every subsampling cell, the pair arm
12713/// fires exactly when libaom's own `av1_ss_size_lookup[..][1][0]` column
12714/// (`common_data.c`) marks the plane block BLOCK_INVALID AND the plane would
12715/// be 2 px wide -- the 4-wide footprints. The tall/wide BLOCK_INVALID shapes
12716/// stay on the pre-existing `chroma_422_oob` (4, 8) tiling, and 4:2:0 /
12717/// 4:4:4 never enter either arm (the byte-identical claim, checked per cell).
12718#[test]
12719fn chroma422_pair_plane_matches_the_ss_size_lookup_cells() {
12720 // The `av1_ss_size_lookup[..][1][0]` column verbatim (pinned oracle,
12721 // `common_data.c`), keyed by footprint: `true` = BLOCK_INVALID.
12722 let ss10_invalid: &[(&str, bool)] = &[
12723 ("4x4", false),
12724 ("4x8", true),
12725 ("8x4", false),
12726 ("8x8", false),
12727 ("8x16", true),
12728 ("16x8", false),
12729 ("16x16", false),
12730 ("16x32", true),
12731 ("32x16", false),
12732 ("32x32", false),
12733 ("32x64", true),
12734 ("64x32", false),
12735 ("64x64", false),
12736 ("64x128", true),
12737 ("128x64", false),
12738 ("128x128", false),
12739 ("4x16", true),
12740 ("16x4", false),
12741 ("8x32", true),
12742 ("32x8", false),
12743 ("16x64", true),
12744 ("64x16", false),
12745 ];
12746 for (footprint, invalid10) in ss10_invalid {
12747 let (w, h) = footprint.split_once('x').unwrap();
12748 let (bw, bh) = (w.parse::<usize>().unwrap(), h.parse::<usize>().unwrap());
12749 // BLOCK_4X4 is the SQUARE path's leaf, never a strip: its ss cell is
12750 // valid because a (2, 4) plane area rounds UP to the 4x4 read
12751 // (`sub8_leaf_chroma422`'s own rule), and it never reaches
12752 // [`decode_rect_split`] at all.
12753 if (bw, bh) == (4, 4) {
12754 continue;
12755 }
12756 // 4:2:0 and 4:4:4: the port never fires, whatever the footprint.
12757 for (ss_x, ss_y) in [(false, false), (true, true)] {
12758 assert!(
12759 chroma422_pair_plane(ss_x, ss_y, 7, bw, bh).is_none(),
12760 "{bw}x{bh} at ss ({ss_x}, {ss_y}) must keep its own plane block"
12761 );
12762 }
12763 // 4:2:2: the pair arm is exactly the 2-px-wide (4-wide) slice of the
12764 // BLOCK_INVALID column, anchored at the floored mi column.
12765 let pair = chroma422_pair_plane(true, false, 7, bw, bh);
12766 assert_eq!(
12767 pair.is_some(),
12768 *invalid10 && bw == 4,
12769 "{bw}x{bh} at ss (1, 0): pair routing disagrees with ss_size_lookup"
12770 );
12771 if let Some((block_w, block_h, x, ctx_col)) = pair {
12772 assert_eq!((block_w, block_h), (4, bh), "{bw}x{bh} pair plane shape");
12773 assert_eq!(x, ((7 & !1) * MI) >> 1, "{bw}x{bh} floored write anchor");
12774 assert_eq!(ctx_col, 6, "{bw}x{bh} entropy cell is the floored column");
12775 // An even-column strip anchors at its own cell.
12776 let (x_even, col_even) = match chroma422_pair_plane(true, false, 6, bw, bh) {
12777 Some((_, _, x, c)) => (x, c),
12778 None => panic!("{bw}x{bh} lost its pair arm at an even mi_col"),
12779 };
12780 assert_eq!(
12781 (x_even, col_even),
12782 (12, 6),
12783 "even column keeps its own cell"
12784 );
12785 }
12786 }
12787 // The tall/wide BLOCK_INVALID shapes (8 px wide or more) are the
12788 // `chroma_422_oob` tiling's residents, not the pair arm's: both are
12789 // 4:2:2-only, so the two arms partition the BLOCK_INVALID column.
12790 for (bw, bh) in [
12791 (8usize, 16),
12792 (16, 32),
12793 (32, 64),
12794 (64, 128),
12795 (8, 32),
12796 (16, 64),
12797 ] {
12798 assert!(chroma422_pair_plane(true, false, 7, bw, bh).is_none());
12799 }
12800}
12801
12802fn decode_intra_rect_in_inter(
12803 dec: &mut SymbolDecoder,
12804 cdfs: &mut Cdfs,
12805 neighbours: &mut Neighbours,
12806 at: (usize, usize),
12807 bw: usize,
12808 bh: usize,
12809 skip: bool,
12810 allow_screen_content_tools: bool,
12811 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
12812 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
12813 strip16: Option<(bool, bool)>,
12814 y: &mut PlaneBuf<'static>,
12815 u: &mut PlaneBuf<'static>,
12816 v: &mut PlaneBuf<'static>,
12817 base_q_idx: u8,
12818 fctx: &crate::decode::FrameCtx,
12819) -> Result<()> {
12820 // `at` is in MI units (the inter path's own unit since lane-inter4);
12821 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
12822 // below are still keyed by.
12823 let (mi_r, mi_c) = at;
12824 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
12825 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
12826 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
12827 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
12828 // finding -- the category is NOT the same for every strip size).
12829 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
12830 // it is refused by name rather than read from the wrong CDF row.
12831 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
12832 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
12833 // tx-depth category is 1 -- but nothing here has to know either, because
12834 // the strip decodes through the very body the KEY FRAME path proves for
12835 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
12836 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
12837 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
12838 // inter-frame difference is the mode-info read, which
12839 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
12840 // `y_mode[0]` plus the `skip` this caller already read.
12841 if let Some((horz, has_chroma)) = strip16 {
12842 // lane-t900 r22: the screen-content refusal here was STALE (class
12843 // stale-premise): [`decode_rect4_16_strip`] takes
12844 // `allow_screen_content_tools` and reads the whole palette syntax
12845 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
12846 // pair) -- the key frame proves that body. Lifted with the 10-bit
12847 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
12848 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
12849 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
12850 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
12851 let res = decode_rect4_16_strip(
12852 dec,
12853 cdfs,
12854 neighbours,
12855 (mi_r, mi_c),
12856 horz,
12857 has_chroma,
12858 // The inter strips of the same partition publish their own
12859 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
12860 // has nothing to add here.
12861 None,
12862 y,
12863 u,
12864 v,
12865 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
12866 allow_screen_content_tools,
12867 base_q_idx,
12868 fctx.tx_select_inter.with(std::cell::Cell::get),
12869 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
12870 fctx,
12871 );
12872 fctx.intra_in_inter_mode.with(|c| c.set(None));
12873 let (mode, uv, (tx_w, tx_h)) = res?;
12874 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
12875 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
12876 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
12877 // block of an inter frame, intra ones included, and
12878 // `txfm_partition_update` for the var-tx context. The key-frame body
12879 // writes neither (a key frame has no var-tx tree and its own readers
12880 // use the deblock grid), so the block AFTER this strip read a stale
12881 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
12882 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
12883 // 16x16 row.
12884 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12885 for i in 0..bw / MI {
12886 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
12887 *cell = tx_w as u8;
12888 }
12889 }
12890 for i in 0..bh / MI {
12891 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
12892 *cell = tx_h as u8;
12893 }
12894 }
12895 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
12896 // coarse 16-px cell holds one entry for the whole 16x16 and the last
12897 // block to write it wins).
12898 neighbours.above_mode[c] = mode;
12899 neighbours.left_mode[r] = mode;
12900 if let Some(uvm) = uv {
12901 neighbours.above_uv_mode[c] = uvm;
12902 neighbours.left_uv_mode[r] = uvm;
12903 }
12904 neighbours.above_side[c] = bw;
12905 neighbours.left_side[r] = bh;
12906 if crate::envflags::env_flag!("EC_INTRA16X4") {
12907 eprintln!(
12908 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
12909 mi_c * MI,
12910 mi_r * MI
12911 );
12912 }
12913 hit_do! {
12914 INTRA16X4_IN_INTER_HITS.with(|h| {
12915 let mut v = h.get();
12916 v[usize::from(!horz)] += 1;
12917 v[2] += usize::from(has_chroma);
12918 h.set(v);
12919 });
12920 }
12921 return Ok(());
12922 }
12923 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
12924 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
12925 // puts BLOCK_128X64/64X128/128X128 in group 3 and
12926 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
12927 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
12928 // block decodes through the very body the KEY FRAME path proves for this
12929 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
12930 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
12931 // `Reach` rule and the frame-edge write clip). The only inter-frame
12932 // differences live inside that body: the mode-info read
12933 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
12934 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
12935 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
12936 // palette (>64) do not exist at this size and are refused by name there.
12937 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
12938 // `intra128_in_inter_witness2.obu` (gate
12939 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
12940 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
12941 // all 15 frames, so the hits are counted out of exact frames (class
12942 // `counter-from-refused-stream`). What r16/r17 could not find, and what
12943 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
12944 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
12945 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
12946 // where the frame EDGE forces it: a partial last superblock row has
12947 // `has_rows128 == false`, so the 128x64 top half is implied, and a
12948 // partial last column implies the 64x128 left half. Put content no
12949 // reference holds (a fresh smooth ramp) in exactly those two bands of an
12950 // inter frame and the encoder codes those forced halves INTRA.
12951 if bw.max(bh) == 128 {
12952 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
12953 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
12954 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
12955 // palette_syntax`), so a 128-root half consumes no palette syntax and
12956 // a screen-content frame's half is syntactically identical to the
12957 // non-screen one this arm already decodes byte-exact.
12958 if coeff_trace_on() {
12959 // lane-t900 r16: which decode-order frame this arm fires in --
12960 // interleaved with the `EC_COEFF_FRAME` markers, this is what
12961 // proves the hit is counted out of a frame that compares exact
12962 // (class `counter-from-refused-stream`).
12963 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
12964 }
12965 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
12966 let res = decode_block_128rect(
12967 dec,
12968 cdfs,
12969 neighbours,
12970 (r, c),
12971 bw,
12972 bh,
12973 y,
12974 u,
12975 v,
12976 base_q_idx,
12977 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
12978 allow_screen_content_tools,
12979 fctx.tx_select_inter.with(std::cell::Cell::get),
12980 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
12981 fctx,
12982 );
12983 fctx.intra_in_inter_mode.with(|c| c.set(None));
12984 return res;
12985 }
12986 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
12987 if crate::envflags::env_flag!("EC_OBMCREC") {
12988 eprintln!(
12989 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
12990 );
12991 }
12992 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
12993 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
12994 // can arrive here are enumerated against the measured block-shape
12995 // census ([`INTER_BLOCK_SHAPES`]) by
12996 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
12997 // -- every one of them has a row, so this arm names a shape no stream
12998 // has been able to present.
12999 return Err(unsupported(format!(
13000 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
13001 )));
13002 };
13003 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
13004 // screen-content frame ("palette syntax is consumed for square blocks
13005 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
13006 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
13007 // it, while the 2:1 reader inlined further down now codes the same syntax
13008 // itself. A real `--tune-content=screen` inter stream reached this refusal
13009 // on 8x16 / 16x8 strips (gate
13010 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
13011 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
13012 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
13013 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
13014 // luma/chroma transform tables, the per-unit split walk and the strip's
13015 // own neighbour records). The ONLY difference on an inter frame is the
13016 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
13017 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
13018 // this caller already read. `tx_cat` above is the same category those
13019 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
13020 // `decode_block_rect64`), asserted here so a future shape cannot drift.
13021 if bw.max(bh) == 4 * bw.min(bh) {
13022 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
13023 fctx.intra_in_inter_mode
13024 .with(|c| c.set(Some((size_group, skip))));
13025 let res = if bw.max(bh) == 64 {
13026 decode_block_rect64(
13027 dec,
13028 cdfs,
13029 neighbours,
13030 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
13031 bw,
13032 bh,
13033 y,
13034 u,
13035 v,
13036 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13037 allow_screen_content_tools,
13038 base_q_idx,
13039 fctx.tx_select_inter.with(std::cell::Cell::get),
13040 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13041 fctx,
13042 )
13043 } else {
13044 decode_block_rect4(
13045 dec,
13046 cdfs,
13047 neighbours,
13048 (mi_r, mi_c),
13049 bw,
13050 bh,
13051 None,
13052 y,
13053 u,
13054 v,
13055 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13056 allow_screen_content_tools,
13057 base_q_idx,
13058 fctx.tx_select_inter.with(std::cell::Cell::get),
13059 fctx,
13060 )
13061 .map(|_| ())
13062 };
13063 fctx.intra_in_inter_mode.with(|c| c.set(None));
13064 res?;
13065 let shape = match (bw, bh) {
13066 (64, 16) => 0,
13067 (16, 64) => 1,
13068 (32, 8) => 2,
13069 _ => 3,
13070 };
13071 hit_do! {
13072 INTRA_RECT4_IN_INTER_HITS.with(|h| {
13073 let mut v = h.get();
13074 v[shape] += 1;
13075 h.set(v);
13076 });
13077 }
13078 return Ok(());
13079 }
13080 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
13081 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
13082 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
13083 // own, so a cross-decoder bisection could only see the block's first
13084 // coefficient. Same names/format as [`read_tx_size`]'s rung.
13085 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
13086 if step_trace {
13087 eprintln!(
13088 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
13089 dec.debug_state().0
13090 );
13091 }
13092 if mode >= 13 {
13093 return Err(unsupported(
13094 "an intra mode this decoder does not code (round 2)",
13095 ));
13096 }
13097 // lane-angleinter (merged on main for the square intra-in-inter arm):
13098 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
13099 // directional predictor; this arm refused a nonzero one before the merge.
13100 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
13101 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
13102 } else {
13103 0
13104 };
13105 if angle_delta_y != 0 {
13106 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
13107 }
13108 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
13109 // superblock-level strip reads the no-CFL alphabet -- the same split
13110 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
13111 //
13112 // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
13113 // (libaom `decodemv.c:933`).
13114 let has_chroma = !mono(fctx);
13115 let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
13116 let uv_mode = if !has_chroma {
13117 DC_PRED
13118 } else if cfl_allowed {
13119 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
13120 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
13121 } else {
13122 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
13123 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
13124 };
13125 if step_trace {
13126 eprintln!(
13127 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
13128 u8::from(cfl_allowed),
13129 dec.debug_state().0
13130 );
13131 }
13132 if (9..=12).contains(&uv_mode) {
13133 hit!(SMOOTH_UV_HITS);
13134 }
13135 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
13136 Some(read_cfl_alphas(dec, cdfs))
13137 } else {
13138 None
13139 };
13140 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
13141 DC_PRED
13142 } else {
13143 uv_mode
13144 };
13145 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
13146 hit!(DIRECTIONAL_UV_HITS);
13147 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
13148 } else {
13149 0
13150 };
13151 if angle_delta_uv != 0 {
13152 hit!(UV_ANGLE_DELTA_HITS);
13153 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
13154 }
13155 // `read_palette_mode_info` (spec 5.11.13), in the position
13156 // `read_intra_block_mode_info` writes it: after the chroma mode and
13157 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
13158 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
13159 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
13160 // skipping the syntax here desynced the tile at the strip's own symbol.
13161 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
13162 // context and colour cache at its own mi position, and the two
13163 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
13164 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
13165 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
13166 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
13167 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
13168 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
13169 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
13170 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
13171 let use_palette_y =
13172 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
13173 if use_palette_y {
13174 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
13175 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
13176 }
13177 // A 2:1 strip of at least 8x8 is always a chroma reference, so
13178 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
13179 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
13180 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
13181 let use_palette_uv = has_chroma
13182 && uv_mode == DC_PRED
13183 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
13184 if crate::envflags::env_flag!("EC_PALSYN") {
13185 eprintln!(
13186 "EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
13187 use_palette_y as i32,
13188 use_palette_uv as i32,
13189 dec.debug_state().0
13190 );
13191 }
13192 if use_palette_uv {
13193 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
13194 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
13195 palette_uv_pending = Some((n, u_colors, v_colors));
13196 }
13197 }
13198 // lane-fiinter (merged on main for the square intra-in-inter arm):
13199 // `read_filter_intra_mode_info` is the tail of
13200 // `read_intra_block_mode_info`, after the palette syntax (refused whole
13201 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
13202 // 2:1 strips with both sides <= 32 -- their own CDF rows
13203 // ([`filter_intra_size_class_rect`]).
13204 let mut filter_intra = None;
13205 if mode == DC_PRED
13206 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
13207 // `av1_filter_intra_allowed` excludes a palette-Y block.
13208 && palette_y_pending.is_none()
13209 && let Some(class) = filter_intra_size_class_rect(bw, bh)
13210 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
13211 {
13212 hit!(FILTER_INTRA_HITS);
13213 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
13214 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
13215 }
13216 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
13217 let palette_y = palette_y_pending.map(|(n, colors)| {
13218 let map = decode_color_index_map_wh(
13219 dec,
13220 cdfs,
13221 n,
13222 bw,
13223 bh,
13224 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
13225 false,
13226 );
13227 hit!(PALETTE_HITS);
13228 hit!(PALETTE_RECT_HITS);
13229 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
13230 PaletteY {
13231 size: n,
13232 colors,
13233 map,
13234 }
13235 });
13236 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
13237 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
13238 let on = palette_onscreen_uv(
13239 (bw, bh),
13240 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
13241 (cw, ch),
13242 (ss_x(fctx), ss_y(fctx)),
13243 );
13244 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
13245 hit!(PALETTE_UV_HITS);
13246 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
13247 PaletteUv {
13248 size: n,
13249 u_colors,
13250 v_colors,
13251 map,
13252 }
13253 });
13254 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
13255 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
13256 // chroma ones -- [`decode_block_rect`]'s own pair.
13257 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
13258 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
13259 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
13260 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
13261 // one exactly as [`decode_leaf8`] already does (class
13262 // context-read-from-one-cell).
13263 let coarse_pair = neighbours.modes_above_left(r, c);
13264 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
13265 if (nb_above_mode, nb_left_mode) != coarse_pair {
13266 hit!(EDGE_FILTER_MI_FIX_HITS);
13267 }
13268 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
13269 if smooth_neighbor {
13270 hit!(SMOOTH_LUMA_HITS);
13271 }
13272 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
13273 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
13274 // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside
13275 // an inter frame codes no depth symbol either (`xd->lossless` is per
13276 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
13277 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
13278 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
13279 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
13280 let d = match tx_cat {
13281 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
13282 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
13283 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
13284 };
13285 if step_trace {
13286 eprintln!(
13287 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
13288 dec.debug_state().0
13289 );
13290 }
13291 d
13292 } else {
13293 0
13294 };
13295 if depth != 0 || lossless(fctx) {
13296 hit!(TX_DEPTH_HITS);
13297 // lane-intrasplit r1: a split intra strip in an inter frame walks the
13298 // key frame's own per-TU path ([`decode_rect_split`] below); what was
13299 // wrong when this refusal was written was the depth SYMBOL, not the walk.
13300 hit_do! {
13301 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
13302 let mut v = h.get();
13303 v[depth.min(2)] += 1;
13304 h.set(v);
13305 });
13306 }
13307 }
13308 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
13309 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
13310 // the two are indistinguishable when the diagnostic fires on splits alone.
13311 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
13312 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
13313 }
13314 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
13315 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
13316 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
13317 // of an inter frame, intra ones included -- with the skip term 0 it
13318 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
13319 // and `left_txfm_context` to `tx_size_high` over its height. This strip
13320 // wrote neither, so the next block's var-tx `txfm_partition` context read
13321 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
13322 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
13323 // mi(16,0) and desyncing the tile at that symbol.
13324 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13325 let modes = RectStripModes {
13326 skip,
13327 mode,
13328 angle_delta_y,
13329 uv_predict_mode,
13330 angle_delta_uv,
13331 alpha,
13332 filter_intra,
13333 smooth_neighbor,
13334 smooth_neighbor_uv,
13335 palette_y: palette_y
13336 .as_ref()
13337 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
13338 palette_uv: palette_uv.as_ref().map(|p| {
13339 (
13340 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
13341 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
13342 )
13343 }),
13344 };
13345 decode_rect_split(
13346 dec,
13347 cdfs,
13348 neighbours,
13349 (mi_r, mi_c),
13350 bw,
13351 bh,
13352 tx_w,
13353 tx_h,
13354 &modes,
13355 y,
13356 u,
13357 v,
13358 base_q_idx,
13359 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13360 fctx,
13361 )?;
13362 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
13363 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
13364 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
13365 // left column over its height. This arm wrote neither before lane-intrasplit
13366 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
13367 // context across the strip's footprint.
13368 for i in 0..bw / MI {
13369 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
13370 *cell = tx_w as u8;
13371 }
13372 }
13373 for i in 0..bh / MI {
13374 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
13375 *cell = tx_h as u8;
13376 }
13377 }
13378 // The strip's own palette state into the mi-granular neighbour bands, so
13379 // the next block's colour cache and `palette_y_mode` context are libaom's.
13380 record_strip_palette(
13381 neighbours,
13382 (mi_r, mi_c),
13383 bw,
13384 bh,
13385 palette_y.as_ref().map_or(0, |p| p.size),
13386 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
13387 palette_uv.as_ref().map_or(0, |p| p.size),
13388 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
13389 );
13390 let class = match bw.max(bh) {
13391 64 => 0,
13392 32 => 1,
13393 _ => 2,
13394 };
13395 hit_do! {
13396 INTRA_RECT_IN_INTER_HITS.with(|h| {
13397 let mut v = h.get();
13398 v[class] += 1;
13399 h.set(v);
13400 });
13401 }
13402 Ok(())
13403}
13404
13405/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real
13406/// mi `(mi_r, mi_c)` (lane-av1-intrabc).
13407///
13408/// libaom treats an intrabc block as INTER for everything except the mode-info
13409/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA`
13410/// (`blockd.h:373`), so
13411///
13412/// * `parse_decode_block` reads the transform size through the INTER var-tx
13413/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose
13414/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and
13415/// whose leaves publish their own resolved size back;
13416/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT
13417/// frame's own pre-loop-filter reconstruction, at the coded block vector
13418/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`);
13419/// * `decode_token_recon_block`'s inter branch then reads one residual per
13420/// transform unit, through the INTER coefficient sets
13421/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane
13422/// inheriting the colocated luma unit's coded `tx_type`.
13423///
13424/// Text order is libaom's: transform tree, prediction, luma residual, chroma
13425/// residual, bookkeeping. A skipped block codes no residual at all -- the
13426/// prediction is the reconstruction.
13427#[allow(clippy::too_many_arguments)]
13428fn decode_intrabc_rect(
13429 dec: &mut SymbolDecoder,
13430 cdfs: &mut Cdfs,
13431 neighbours: &mut Neighbours,
13432 (mi_r, mi_c): (usize, usize),
13433 (bw, bh): (usize, usize),
13434 skip: bool,
13435 (dv_row, dv_col): (i32, i32),
13436 y: &mut PlaneBuf<'static>,
13437 u: &mut PlaneBuf<'static>,
13438 v: &mut PlaneBuf<'static>,
13439 base_q_idx: u8,
13440 fctx: &crate::decode::FrameCtx,
13441) -> Result<()> {
13442 hit!(INTRABC_RECT_HITS);
13443 // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
13444 let idx = usize::from(bh > bw);
13445 if skip {
13446 INTRABC_RECT_SKIPPED_HITS.with(|c| {
13447 let mut seen = c.get();
13448 seen[idx] += 1;
13449 c.set(seen);
13450 });
13451 } else {
13452 INTRABC_RECT_CODED_HITS.with(|c| {
13453 let mut seen = c.get();
13454 seen[idx] += 1;
13455 c.set(seen);
13456 });
13457 }
13458 let (px, py) = (mi_c * MI, mi_r * MI);
13459 // lane-whtshape: a LOSSLESS block's chroma plane block is
13460 // `bw >> ss_x` by `bh >> ss_y` at its own origin -- `av1_get_max_uv_txsize`
13461 // is `ss_size_lookup[bsize]` (no halving of its own), so at 4:4:4 that is
13462 // the block's OWN footprint, not the 4:2:0 halving the lossy arm hard-codes.
13463 // Measured on this lane's 4:4:4 lossless witness: with the halving, a
13464 // 16x8 intrabc block's chroma plane block came out 8x4 and the lossless
13465 // walk below coded 2 units per plane where libaom codes 8.
13466 //
13467 // Scoped to `lossless` ON PURPOSE. The 4:2:0 halving is right at 4:2:0,
13468 // and every pinned 4:4:4 stream that reaches this helper does so LOSSY
13469 // (measured: zero pinned fixtures decode a LOSSLESS intrabc rect block),
13470 // whose footprint is a separate, already-named open cell --
13471 // lanes/av1444rect.report.md's 4:4:4 intra-BC chroma. This lane must not
13472 // move it, and a lossless-only split here changes no green pin either way.
13473 let (cpx, cpy) = if lossless(fctx) {
13474 (px >> ss_x(fctx), py >> ss_y(fctx))
13475 } else {
13476 (px / 2, py / 2)
13477 };
13478 // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the
13479 // halved shape's own `max_txsize_rect_lookup` entry IS that size for every
13480 // shape this helper is called at, so the uv plane block is ONE unit --
13481 // the same call `decode_token_recon_block`'s own chroma loop makes.
13482 let (cw, ch) = if lossless(fctx) {
13483 (bw >> ss_x(fctx), bh >> ss_y(fctx))
13484 } else {
13485 (bw / 2, bh / 2)
13486 };
13487 // lane-av1-intrabc r2: the square stride the proven INTER path uses
13488 // (`side`). The residual grids, the prediction windows AND
13489 // `TxParams::stride` are all laid out at it -- the block's own width
13490 // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h`
13491 // exceeds the stride).
13492 let side = bw.max(bh);
13493 let cside = cw.max(ch);
13494 // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right
13495 // or bottom frame edge reads no transform-tree symbol for the units
13496 // outside it.
13497 let mi_cols = 2 * y.true_width.div_ceil(8);
13498 let mi_rows = 2 * y.true_height.div_ceil(8);
13499 let leaves = read_block_tx_size_rect(
13500 dec,
13501 cdfs,
13502 neighbours,
13503 (mi_r, mi_c),
13504 (bw, bh),
13505 (mi_cols, mi_rows),
13506 skip,
13507 fctx,
13508 )?;
13509 if leaves.is_some() {
13510 hit!(INTRABC_RECT_VARTX_HITS);
13511 }
13512 // The whole-block prediction: `predict_inter_block` runs once, before any
13513 // coefficient is read. `flush_recon` first -- the source is this frame's
13514 // own reconstruction, including the writes this superblock has queued.
13515 flush_recon(fctx, y, u, v);
13516 // `mc::predict_with_filter` writes a DENSE window; the residual machinery
13517 // reads it at the square stride, so re-lay it -- the same step the inter
13518 // path takes for its own square prediction buffer.
13519 let mut pred_y_dense = vec![0u16; bw * bh];
13520 mc::predict_with_filter(
13521 &y.data,
13522 y.width,
13523 y.true_width,
13524 y.true_height,
13525 mv_to_q4(px, dv_col, 0),
13526 mv_to_q4(py, dv_row, 0),
13527 bw,
13528 bh,
13529 mc::InterpFilterKind::Bilinear,
13530 &mut pred_y_dense,
13531 fctx,
13532 );
13533 let mut pred_y = vec![0u16; side * side];
13534 for row in 0..bh {
13535 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
13536 }
13537 let mut pred_u_dense = vec![0u16; cw * ch];
13538 mc::predict_with_filter(
13539 &u.data,
13540 u.width,
13541 u.true_width,
13542 u.true_height,
13543 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13544 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13545 cw,
13546 ch,
13547 mc::InterpFilterKind::Bilinear,
13548 &mut pred_u_dense,
13549 fctx,
13550 );
13551 let mut pred_u = vec![0u16; cside * cside];
13552 for row in 0..ch {
13553 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
13554 }
13555 let mut pred_v_dense = vec![0u16; cw * ch];
13556 mc::predict_with_filter(
13557 &v.data,
13558 v.width,
13559 v.true_width,
13560 v.true_height,
13561 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13562 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13563 cw,
13564 ch,
13565 mc::InterpFilterKind::Bilinear,
13566 &mut pred_v_dense,
13567 fctx,
13568 );
13569 let mut pred_v = vec![0u16; cside * cside];
13570 for row in 0..ch {
13571 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
13572 }
13573 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
13574 let luma_tx_type: TxType;
13575 let (luma_grid, u_grid, v_grid);
13576 // lane-whtshape: the LOSSLESS chroma walk's composed plane-major grids,
13577 // kept so their per-4x4 slices can be re-stamped over the whole-block
13578 // record in the tail. `None` on every other arm.
13579 let mut ll_chroma: Option<(Vec<i32>, Vec<i32>)> = None;
13580 if skip {
13581 // No residual syntax at all: the prediction IS the block.
13582 // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes
13583 // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip
13584 // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm.
13585 push_mc_rect(
13586 0,
13587 px,
13588 py,
13589 side,
13590 bw,
13591 bh,
13592 Pred::Inline(&pred_y, side),
13593 &ZERO_RESIDUAL[..side * side],
13594 fctx,
13595 );
13596 push_mc_rect(
13597 1,
13598 cpx,
13599 cpy,
13600 cside,
13601 cw,
13602 ch,
13603 Pred::Inline(&pred_u, cside),
13604 &ZERO_RESIDUAL[..cside * cside],
13605 fctx,
13606 );
13607 push_mc_rect(
13608 2,
13609 cpx,
13610 cpy,
13611 cside,
13612 cw,
13613 ch,
13614 Pred::Inline(&pred_v, cside),
13615 &ZERO_RESIDUAL[..cside * cside],
13616 fctx,
13617 );
13618 if let Some(ls) = leaves.as_ref() {
13619 // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s
13620 // skip arm performs -- libaom `av1_reset_entropy_context`
13621 // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a
13622 // SKIPPED block zeroes its whole entropy-band footprint. This
13623 // helper serves `decode_block_rect4`'s 1:4 strips on this tree,
13624 // so a skipped lossless strip whose `leaves` resolved (every
13625 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
13626 // returns the 4x4 grid before it looks at `skip`) left the
13627 // PREVIOUS occupant's luma bands standing and the NEXT block's
13628 // partition parse diverged from libaom's: the 320x242 lossless
13629 // sb128 gate read a phantom unskipped 8x32 intrabc strip at
13630 // mi(56,66) right after the skipped 8x16 one at mi(48,66).
13631 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
13632 for &(row, col, tw, th) in ls {
13633 neighbours.record_mi_luma_rect(
13634 (mi_r + row, mi_c + col),
13635 tw,
13636 th,
13637 &ZERO_RESIDUAL[..tw * th],
13638 );
13639 }
13640 }
13641 luma_tx_type = TxType::DctDct;
13642 luma_grid = Grid::Zero(side * side);
13643 u_grid = Grid::Zero(cside * cside);
13644 v_grid = Grid::Zero(cside * cside);
13645 } else {
13646 match leaves.as_ref() {
13647 None => {
13648 // One whole-block rectangular transform unit.
13649 // lane-av1422mi24: at ss (1,0) the chroma above span is
13650 // `bw >> 1` chroma cells spread over `bw` luma mi columns --
13651 // the per-mi gather counts every chroma column's whole-unit
13652 // dc sign twice (t422 frame 1, the mi(26,60) intra-in-inter
13653 // strip's U dc_sign read ctx 1 where the oracle's cell sum
13654 // is 0 -> ctx 0). Luma keeps the per-mi gather; the two
13655 // chroma planes take
13656 // [`Neighbours::around_mi_422_chroma`]'s every-second
13657 // above-cell sampling, like every other 4:2:2 chroma gather.
13658 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
13659 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
13660 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
13661 around[1] = c[1];
13662 around[2] = c[2];
13663 }
13664 let (grid, tx_type) = read_inter_plane_rect(
13665 dec,
13666 cdfs,
13667 rect_inter_luma_set(bw, bh, fctx)?,
13668 (bw, bh),
13669 side,
13670 0,
13671 around[0],
13672 0,
13673 y,
13674 px,
13675 py,
13676 Pred::Inline(&pred_y, side),
13677 None,
13678 None,
13679 fctx,
13680 )?;
13681 luma_tx_type = tx_type;
13682 luma_grid = embed_grid_stride(&grid, bw, bh, side);
13683 let (ug, _) = read_inter_plane_rect(
13684 dec,
13685 cdfs,
13686 rect_inter_chroma_set(cw, ch)?,
13687 (cw, ch),
13688 cside,
13689 1,
13690 around[1],
13691 0,
13692 u,
13693 cpx,
13694 cpy,
13695 Pred::Inline(&pred_u, cside),
13696 Some(luma_tx_type),
13697 None,
13698 fctx,
13699 )?;
13700 u_grid = embed_grid_stride(&ug, cw, ch, cside);
13701 let (vg, _) = read_inter_plane_rect(
13702 dec,
13703 cdfs,
13704 rect_inter_chroma_set(cw, ch)?,
13705 (cw, ch),
13706 cside,
13707 2,
13708 around[2],
13709 0,
13710 v,
13711 cpx,
13712 cpy,
13713 Pred::Inline(&pred_v, cside),
13714 Some(luma_tx_type),
13715 None,
13716 fctx,
13717 )?;
13718 v_grid = embed_grid_stride(&vg, cw, ch, cside);
13719 }
13720 Some(leaves) => {
13721 // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies
13722 // the split override to LUMA only, per leaf -- the step the
13723 // proven inter var-tx path applies right after its own residual
13724 // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the
13725 // leaf's own transform edges are never filtered.
13726 for &(row, col, tw, th) in leaves.iter() {
13727 neighbours.fill_lf_grid_leaf_luma(
13728 (mi_r + row, mi_c + col),
13729 tw / MI,
13730 th / MI,
13731 tw as u8,
13732 th as u8,
13733 );
13734 }
13735 // One residual per transform unit, in the order the tree coded
13736 // them; each unit reads its own neighbour-magnitude context off
13737 // the units already decoded before it, and every unit adds onto
13738 // its own window of the block's single prediction.
13739 let mut first_tx_type = TxType::DctDct;
13740 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
13741 let tu_mi = (mi_r + row, mi_c + col);
13742 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
13743 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
13744 let (tu_grid, tu_tx_type) = if tw == th {
13745 let scan = default_scan(tw.min(32));
13746 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
13747 read_inter_plane(
13748 dec,
13749 cdfs,
13750 inter_txbset_for(tw, reduced),
13751 scan,
13752 0,
13753 neighbours.around_mi(tu_mi, tw)[0],
13754 0,
13755 y,
13756 tu_px,
13757 tu_py,
13758 tw,
13759 base_q_idx,
13760 tu_pred,
13761 None,
13762 Some(tu_skip_ctx),
13763 fctx,
13764 )?
13765 } else {
13766 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
13767 read_inter_plane_rect(
13768 dec,
13769 cdfs,
13770 rect_inter_luma_set(tw, th, fctx)?,
13771 (tw, th),
13772 side,
13773 0,
13774 neighbours.around_mi_rect(tu_mi, tw, th)[0],
13775 0,
13776 y,
13777 tu_px,
13778 tu_py,
13779 tu_pred,
13780 None,
13781 Some(tu_skip_ctx),
13782 fctx,
13783 )?
13784 };
13785 if idx == 0 {
13786 first_tx_type = tu_tx_type;
13787 }
13788 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
13789 }
13790 // `av1_get_tx_type`'s chroma lookup lands on the colocated
13791 // LUMA unit, which for a split block is the top-left one.
13792 luma_tx_type = first_tx_type;
13793 // lane-av1422mi24: same 4:2:2 chroma gather rule as the
13794 // `None` arm above -- the per-mi rect gather double-counts
13795 // each chroma column's whole-unit dc sign at ss (1,0).
13796 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
13797 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
13798 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
13799 around[1] = c[1];
13800 around[2] = c[2];
13801 }
13802 if lossless(fctx) {
13803 // lane-whtshape: at lossless libaom codes TX_4X4 on EVERY
13804 // plane of a block -- `read_tx_size` returns `TX_4X4` for a
13805 // lossless block before it looks at a tree, `read_tx_mode`
13806 // already forced `ONLY_4X4` for the frame, and
13807 // `get_vartx_max_txsize` returns `TX_4X4` for every plane
13808 // -- so this block's chroma plane block is a
13809 // `(cw/4) * (ch/4)` raster of 4x4 units, PLANE-MAJOR
13810 // (`decode_token_recon_block`: every U unit, then every V
13811 // unit), not the single rect unit the two
13812 // `read_inter_plane_rect` calls below read. That single
13813 // 8x4 unit is what reached the lossless WHT with the wrong
13814 // shape (the `debug_assert_eq!((w, h), (4, 4))` this lane
13815 // replaced). Same helper, same walk, as the inter 8x8 and
13816 // 128 paths.
13817 hit!(INTRABC_RECT_LOSSLESS_CHROMA4_HITS);
13818 let mut uo = vec![0i32; cside * cside];
13819 let mut vo = vec![0i32; cside * cside];
13820 read_inter_chroma_lossless(
13821 dec,
13822 cdfs,
13823 neighbours,
13824 u,
13825 v,
13826 Pred::Inline(&pred_u, cside),
13827 Pred::Inline(&pred_v, cside),
13828 (mi_r, mi_c),
13829 (cpx, cpy),
13830 (0, 0),
13831 (cw, ch),
13832 (cw, ch),
13833 cside,
13834 0,
13835 base_q_idx,
13836 &mut uo,
13837 &mut vo,
13838 fctx,
13839 )?;
13840 // The per-unit walk stamped every unit's own coefficient
13841 // context, but the whole-block `record_split_luma_rect_mi`
13842 // in the tail rewrites every chroma cell with ONE composed
13843 // state, which drops the per-unit DC signs and levels (class
13844 // `override-slot-on-one-arm` -- the same one
13845 // `decode_rect_split`'s `ll_chroma_units` replay exists
13846 // for). The grids are kept here and replayed AFTER that
13847 // record, from the same 4x4 slices, so the same states.
13848 u_grid = embed_grid_stride(&Grid::Own(uo.clone()), cw, ch, cside);
13849 v_grid = embed_grid_stride(&Grid::Own(vo.clone()), cw, ch, cside);
13850 ll_chroma = Some((uo, vo));
13851 luma_grid = Grid::Zero(side * side);
13852 } else {
13853 let (ug, _) = read_inter_plane_rect(
13854 dec,
13855 cdfs,
13856 rect_inter_chroma_set(cw, ch)?,
13857 (cw, ch),
13858 cside,
13859 1,
13860 around[1],
13861 0,
13862 u,
13863 cpx,
13864 cpy,
13865 Pred::Inline(&pred_u, cside),
13866 Some(luma_tx_type),
13867 None,
13868 fctx,
13869 )?;
13870 u_grid = embed_grid_stride(&ug, cw, ch, cside);
13871 let (vg, _) = read_inter_plane_rect(
13872 dec,
13873 cdfs,
13874 rect_inter_chroma_set(cw, ch)?,
13875 (cw, ch),
13876 cside,
13877 2,
13878 around[2],
13879 0,
13880 v,
13881 cpx,
13882 cpy,
13883 Pred::Inline(&pred_v, cside),
13884 Some(luma_tx_type),
13885 None,
13886 fctx,
13887 )?;
13888 v_grid = embed_grid_stride(&vg, cw, ch, cside);
13889 luma_grid = Grid::Zero(side * side);
13890 }
13891 }
13892 }
13893 }
13894 let _ = luma_tx_type;
13895 // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the
13896 // next block reads a neighbour mode, its own block size in both `TXFM`
13897 // bands (already done by `read_block_tx_size_rect`), a zeroed palette
13898 // state (a stale entry would feed the next block's colour cache), and its
13899 // DV into the intrabc mi grid the next block's DV predictor reads.
13900 if leaves.is_some() {
13901 neighbours.record_split_luma_rect_mi(
13902 (mi_r, mi_c),
13903 bw,
13904 bh,
13905 DC_PRED,
13906 DC_PRED,
13907 [&u_grid, &v_grid],
13908 );
13909 } else {
13910 neighbours.record_rect_mi(
13911 (mi_r, mi_c),
13912 bw,
13913 bh,
13914 DC_PRED,
13915 DC_PRED,
13916 &[&luma_grid, &u_grid, &v_grid],
13917 );
13918 }
13919 // lane-whtshape: replay the LOSSLESS walk's per-4x4 chroma states over
13920 // the whole-block record above, so the NEXT block reads the per-unit DC
13921 // signs and levels libaom's plane-major walk left behind instead of one
13922 // composed state for the whole plane block.
13923 if let Some((uo, vo)) = ll_chroma {
13924 for (plane_idx, comp) in [(1usize, &uo), (2, &vo)] {
13925 for ur in 0..ch / 4 {
13926 for uc in 0..cw / 4 {
13927 let mut unit = Vec::with_capacity(16);
13928 for r in 0..4 {
13929 unit.extend_from_slice(&comp[(ur * 4 + r) * cside + uc * 4..][..4]);
13930 }
13931 neighbours.record_mi_chroma(
13932 // lane-av1lm444loss-corr: the MI STEP between chroma
13933 // units is that same footprint expressed in luma mi
13934 // cells, `(4 << ss) / MI` -- which is exactly what
13935 // `decode_inter_block`'s reference `mu_chroma_units`
13936 // construction writes (decode.rs:43688,
13937 // `at.0 + cr * ((cu << ss_y(fctx)) / MI)` with
13938 // `cu = 4` on a lossless frame). The `4 >> ss_y` form
13939 // this replaces is 4:2:0-only arithmetic that happens
13940 // to agree there: at ss (1,1) it is `4 >> 1` = 2 mi
13941 // and the footprint form is `(4 << 1) / 4` = 2 mi, the
13942 // SAME value, so 4:2:0 is unchanged by construction.
13943 // At ss (0,0) it is `4 >> 0` = 4 mi -- four luma mi
13944 // (16 luma px) per 4x4 chroma unit, where a TX_4X4
13945 // chroma unit covers `4 << 0` = 4 luma px = ONE mi.
13946 // The step therefore lands every replayed unit at 4x
13947 // its own mi row/column on a 4:4:4 lossless frame, and
13948 // the whole block's per-unit states are stamped over
13949 // cells that belong to other blocks (or to nothing).
13950 (
13951 mi_r + ur * ((4 << ss_y(fctx)) / MI),
13952 mi_c + uc * ((4 << ss_x(fctx)) / MI),
13953 ),
13954 4 << ss_x(fctx),
13955 4 << ss_y(fctx),
13956 plane_idx,
13957 &Grid::Own(unit),
13958 );
13959 }
13960 }
13961 }
13962 }
13963 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
13964 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
13965 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
13966 neighbours.fill_lf_grid_rect(
13967 (mi_r, mi_c),
13968 bw / MI,
13969 bh / MI,
13970 bw.min(64) as u8,
13971 bh.min(64) as u8,
13972 0,
13973 fctx,
13974 );
13975 record_intrabc_mi_rect(
13976 mi_r,
13977 mi_c,
13978 bw / MI,
13979 bh / MI,
13980 Some((dv_row, dv_col)),
13981 neighbours,
13982 fctx,
13983 );
13984 Ok(())
13985}
13986
13987/// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root
13988/// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape
13989/// `decode_block_128rect` refused by name before this port. libaom decodes
13990/// such a block through the INTER machinery (an intrabc block
13991/// `is_inter_block`): `predict_inter_block` copies the whole block from this
13992/// frame's own reconstruction at the integer block vector once, then
13993/// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks --
13994/// per chunk every plane, luma units at the block's own resolved transform
13995/// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at
13996/// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per
13997/// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits
13998/// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`,
13999/// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in
14000/// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here.
14001#[allow(clippy::too_many_arguments)]
14002fn decode_intrabc_128rect(
14003 dec: &mut SymbolDecoder,
14004 cdfs: &mut Cdfs,
14005 neighbours: &mut Neighbours,
14006 (mi_r, mi_c): (usize, usize),
14007 (bw, bh): (usize, usize),
14008 skip: bool,
14009 (dv_row, dv_col): (i32, i32),
14010 y: &mut PlaneBuf<'static>,
14011 u: &mut PlaneBuf<'static>,
14012 v: &mut PlaneBuf<'static>,
14013 base_q_idx: u8,
14014 fctx: &crate::decode::FrameCtx,
14015) -> Result<()> {
14016 hit!(INTRABC_128RECT_HITS);
14017 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14018 let (rng, _) = dec.debug_state();
14019 eprintln!(
14020 "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}"
14021 );
14022 }
14023 let (px, py) = (mi_c * MI, mi_r * MI);
14024 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis
14025 // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's
14026 // `mv_to_q4(cpy, dv_row, ss_y(fctx))` calls two lines below already
14027 // scaled the DV on the y axis by ITS OWN subsampling, so the hardcoded
14028 // `/2` origin and extent made the prediction window half as tall as
14029 // the motion vector asked for), 4:2:2 is HALF-WIDTH and FULL-HEIGHT,
14030 // 4:4:4 is luma-sized. At ss (1,1) every value below is the old
14031 // `bw / 2, bh / 2` line-for-line.
14032 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14033 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14034 // The square strides the proven INTER path lays its residual grids,
14035 // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2
14036 // note): 128/64 here.
14037 let side = bw.max(bh);
14038 let cside = cw.max(ch);
14039 // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code
14040 // nothing (`decode_reconstruct_tx`'s max_blocks_* early return).
14041 let mi_cols = 2 * y.true_width.div_ceil(8);
14042 let mi_rows = 2 * y.true_height.div_ceil(8);
14043 // An intrabc block is is_inter_block: the tx tree is the INTER one, and
14044 // [`read_block_tx_size_rect`]'s 128-root branch already carries the
14045 // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree
14046 // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid)
14047 // arms (lane-sb128c r7).
14048 let leaves = read_block_tx_size_rect(
14049 dec,
14050 cdfs,
14051 neighbours,
14052 (mi_r, mi_c),
14053 (bw, bh),
14054 (mi_cols, mi_rows),
14055 skip,
14056 fctx,
14057 )?;
14058 // Whole-block prediction, once, before any coefficient is read
14059 // (`predict_inter_block`); the source is this frame's own
14060 // reconstruction, including the writes this superblock has queued.
14061 flush_recon(fctx, y, u, v);
14062 let mut pred_y_dense = vec![0u16; bw * bh];
14063 mc::predict_with_filter(
14064 &y.data,
14065 y.width,
14066 y.true_width,
14067 y.true_height,
14068 mv_to_q4(px, dv_col, 0),
14069 mv_to_q4(py, dv_row, 0),
14070 bw,
14071 bh,
14072 mc::InterpFilterKind::Bilinear,
14073 &mut pred_y_dense,
14074 fctx,
14075 );
14076 let mut pred_y = vec![0u16; side * side];
14077 for row in 0..bh {
14078 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
14079 }
14080 let mut pred_u_dense = vec![0u16; cw * ch];
14081 mc::predict_with_filter(
14082 &u.data,
14083 u.width,
14084 u.true_width,
14085 u.true_height,
14086 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14087 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14088 cw,
14089 ch,
14090 mc::InterpFilterKind::Bilinear,
14091 &mut pred_u_dense,
14092 fctx,
14093 );
14094 let mut pred_u = vec![0u16; cside * cside];
14095 for row in 0..ch {
14096 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
14097 }
14098 let mut pred_v_dense = vec![0u16; cw * ch];
14099 mc::predict_with_filter(
14100 &v.data,
14101 v.width,
14102 v.true_width,
14103 v.true_height,
14104 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14105 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14106 cw,
14107 ch,
14108 mc::InterpFilterKind::Bilinear,
14109 &mut pred_v_dense,
14110 fctx,
14111 );
14112 let mut pred_v = vec![0u16; cside * cside];
14113 for row in 0..ch {
14114 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
14115 }
14116 let (luma_grid, u_grid, v_grid);
14117 // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour
14118 // contexts per transform unit -- the replay after this fn's end-of-block
14119 // record restores them (the record itself re-stamps both planes with ONE
14120 // composed state, class `override-slot-on-one-arm`).
14121 let mut mu_chroma = false;
14122 if skip {
14123 // No residual syntax at all: the prediction IS the block. Strides are
14124 // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes
14125 // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun).
14126 push_mc_rect(
14127 0,
14128 px,
14129 py,
14130 side,
14131 bw,
14132 bh,
14133 Pred::Inline(&pred_y, side),
14134 &ZERO_RESIDUAL[..side * side],
14135 fctx,
14136 );
14137 push_mc_rect(
14138 1,
14139 cpx,
14140 cpy,
14141 cside,
14142 cw,
14143 ch,
14144 Pred::Inline(&pred_u, cside),
14145 &ZERO_RESIDUAL[..cside * cside],
14146 fctx,
14147 );
14148 push_mc_rect(
14149 2,
14150 cpx,
14151 cpy,
14152 cside,
14153 cw,
14154 ch,
14155 Pred::Inline(&pred_v, cside),
14156 &ZERO_RESIDUAL[..cside * cside],
14157 fctx,
14158 );
14159 if let Some(ls) = leaves.as_ref() {
14160 // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4
14161 // grid before it looks at `skip`; the skipped block still zeroes
14162 // its entropy-band footprint over every unit (libaom
14163 // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) --
14164 // the same arm [`decode_intrabc_rect`]'s loss64 merge added.
14165 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
14166 for &(row, col, tw, th) in ls {
14167 neighbours.record_mi_luma_rect(
14168 (mi_r + row, mi_c + col),
14169 tw,
14170 th,
14171 &ZERO_RESIDUAL[..tw * th],
14172 );
14173 }
14174 }
14175 luma_grid = Grid::Zero(side * side);
14176 u_grid = Grid::Zero(cside * cside);
14177 v_grid = Grid::Zero(cside * cside);
14178 } else {
14179 let leaves = leaves
14180 .expect("read_block_tx_size_rect returns None only for skip below 128 at this shape");
14181 // libaom `get_transform_size`'s split override applies to LUMA only,
14182 // per leaf -- each unit's own transform edges get filtered
14183 // ([`decode_intrabc_rect`]'s P2, the proven inter path's step).
14184 for &(row, col, tw, th) in leaves.iter() {
14185 neighbours.fill_lf_grid_leaf_luma(
14186 (mi_r + row, mi_c + col),
14187 tw / MI,
14188 th / MI,
14189 tw as u8,
14190 th as u8,
14191 );
14192 }
14193 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
14194 let mut u_units: Vec<i32> = Vec::new();
14195 let mut v_units: Vec<i32> = Vec::new();
14196 let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new();
14197 // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose
14198 // top-left sample is outside the frame codes nothing.
14199 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
14200 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
14201 // lane-av1h5: chunk-major token order at 128 (see [`mu_chunk_order`]).
14202 let (order, _mu_reordered) = mu_chunk_order(&leaves, side);
14203 for (pos, &idx) in order.iter().enumerate() {
14204 let (row, col, tw, th) = leaves[idx];
14205 debug_assert_eq!(
14206 tw, th,
14207 "a square TX_64X64 tree root only yields square leaves"
14208 );
14209 let tu_mi = (mi_r + row, mi_c + col);
14210 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14211 if tu_px >= y.true_width || tu_py >= y.true_height {
14212 continue;
14213 }
14214 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
14215 let scan = default_scan(tw.min(32));
14216 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
14217 let (tu_grid, tu_tx_type) = read_inter_plane(
14218 dec,
14219 cdfs,
14220 inter_txbset_for(tw, reduced),
14221 &scan,
14222 0,
14223 neighbours.around_mi(tu_mi, tw)[0],
14224 0,
14225 y,
14226 tu_px,
14227 tu_py,
14228 tw,
14229 base_q_idx,
14230 tu_pred,
14231 None,
14232 Some(tu_skip_ctx),
14233 fctx,
14234 )?;
14235 leaf_tx_types.push((row, col, tw, th, tu_tx_type));
14236 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
14237 // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64
14238 // mu chunk before the next one starts: once this chunk's leaves
14239 // are done, its chroma is read immediately (the inter 128 path's
14240 // interleave).
14241 let chunk = (row / 16, col / 16);
14242 let done = pos + 1 == order.len()
14243 || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 1]].1 / 16) != chunk;
14244 if done {
14245 let (cr, cc) = chunk;
14246 // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one
14247 // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster
14248 // within the chunk, plane-major inside the chunk.
14249 let cu_tx = 32usize;
14250 // lane-av1-ibc128chunk: a 64x64 mu chunk's chroma plane
14251 // block is PER-AXIS `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at
14252 // 4:2:0, TWO STACKED TX_32X32 at 4:2:2 (the chunk's chroma
14253 // plane block is 32x64 there), four at 4:4:4. The old
14254 // `chunk_chroma = cside * 64 / side` walked a
14255 // `chroma_side`-SQUARE chunk, i.e. the 4:2:0 count on both
14256 // axes: at 4:2:2 it read HALF the chroma units of a chunk
14257 // (one 32x32 at the chunk's top-left instead of two), left
14258 // the chunk's lower 32 chroma rows with no residual at all,
14259 // and stamped every unit's entropy context over a 16x16-mi
14260 // luma span instead of 16x8. The same defect and the same
14261 // per-axis repair as `decode_inter_block`'s
14262 // `chunk_chroma_w/chunk_chroma_h` (lane-av1-422bigblock,
14263 // witnessed on `422_sb128_3f.obu`).
14264 let chunk_chroma_w = (64usize) >> ss_x(fctx);
14265 let chunk_chroma_h = (64usize) >> ss_y(fctx);
14266 // The unit's own footprint on the LUMA mi grid, per axis:
14267 // `(32 << ss) px` = `(32 << ss) / MI` mi -- 16x16 at 4:2:0,
14268 // 16x8 at 4:2:2, 8x8 at 4:4:4. `around_mi_rect` reads and
14269 // `record_mi_chroma` stamp exactly the unit's own cells.
14270 let unit_luma_w = cu_tx << ss_x(fctx);
14271 let unit_luma_h = cu_tx << ss_y(fctx);
14272 INTRABC_128RECT_CHUNK_SHAPE.with(|c| {
14273 c.set((chunk_chroma_w << 8) | chunk_chroma_h);
14274 });
14275 let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16));
14276 let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16));
14277 let units_x = chunk_w_mi / (unit_luma_w / MI);
14278 let units_y = chunk_h_mi / (unit_luma_h / MI);
14279 if lossless(fctx) {
14280 // TX_4X4 chroma units over this chunk (lane-lossless2's
14281 // walk, shared with the inter 128 path).
14282 read_inter_chroma_lossless(
14283 dec,
14284 cdfs,
14285 neighbours,
14286 u,
14287 v,
14288 Pred::Inline(&pred_u, cside),
14289 Pred::Inline(&pred_v, cside),
14290 (mi_r, mi_c),
14291 (cpx, cpy),
14292 (cc * chunk_chroma_w, cr * chunk_chroma_h),
14293 (chunk_chroma_w, chunk_chroma_h),
14294 (cw, ch),
14295 cside,
14296 0,
14297 base_q_idx,
14298 &mut u_units,
14299 &mut v_units,
14300 fctx,
14301 )?;
14302 // lane-av1-ibcrect: read_inter_chroma_lossless stamped
14303 // every TX_4X4 unit's own context (`record_mi_chroma`
14304 // inside the walk) -- the end-of-block record below must
14305 // not overwrite them with the composed grid (the inter
14306 // 128 path sets the same flag on this arm).
14307 mu_chroma = true;
14308 continue;
14309 }
14310 let cu_scan = default_scan(cu_tx);
14311 for plane_idx in 1..3 {
14312 let (src, buf) = if plane_idx == 1 {
14313 (Pred::Inline(&pred_u, cside), &mut *u)
14314 } else {
14315 (Pred::Inline(&pred_v, cside), &mut *v)
14316 };
14317 for ur in 0..units_y {
14318 for uc in 0..units_x {
14319 let unit_mi = (
14320 mi_r + cr * 16 + ur * (unit_luma_h / MI),
14321 mi_c + cc * 16 + uc * (unit_luma_w / MI),
14322 );
14323 // Per unit, AFTER the earlier units' stamps: this
14324 // unit's coefficient context must see them.
14325 let cu_around =
14326 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h);
14327 if crate::envflags::env_flag!("EC_ECDUMP") {
14328 for p in 1..3 {
14329 let ab: Vec<String> = (0..unit_luma_w / MI)
14330 .map(|k| {
14331 format!(
14332 "{:?}/{}",
14333 neighbours.above[unit_mi.1 + k][p].dc,
14334 neighbours.above[unit_mi.1 + k][p].level
14335 )
14336 })
14337 .collect();
14338 let lf: Vec<String> = (0..unit_luma_h / MI)
14339 .map(|k| {
14340 format!(
14341 "{:?}/{}",
14342 neighbours.left[unit_mi.0 + k][p].dc,
14343 neighbours.left[unit_mi.0 + k][p].level
14344 )
14345 })
14346 .collect();
14347 eprintln!(
14348 "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]",
14349 cu_around[p].0,
14350 cu_around[p].1,
14351 cu_around[p].2,
14352 ab.join(","),
14353 lf.join(",")
14354 );
14355 }
14356 }
14357 let (cu_x, cu_y) = (
14358 cpx + cc * chunk_chroma_w + uc * cu_tx,
14359 cpy + cr * chunk_chroma_h + ur * cu_tx,
14360 );
14361 // `av1_get_tx_type` (blockd.h:1291): an inter
14362 // block's chroma unit never codes a tx_type; it
14363 // inherits the coded type of the luma leaf
14364 // covering its own quadrant (all of this chunk's
14365 // leaves are read by now).
14366 let unit_rel_mi = (unit_mi.0 - mi_r, unit_mi.1 - mi_c);
14367 let covering = covering_leaf_tx_type(&leaf_tx_types, unit_rel_mi);
14368 // The prediction window is the block's own square
14369 // `cside` buffer with the unit's true per-axis
14370 // position inside it.
14371 let cu_pred = src.offset(
14372 (cr * chunk_chroma_h + ur * cu_tx) * cside
14373 + cc * chunk_chroma_w
14374 + uc * cu_tx,
14375 );
14376 let cu_grid = read_inter_plane(
14377 dec,
14378 cdfs,
14379 TxbSet::Chroma32,
14380 &cu_scan,
14381 plane_idx,
14382 cu_around[plane_idx],
14383 0,
14384 buf,
14385 cu_x,
14386 cu_y,
14387 cu_tx,
14388 base_q_idx,
14389 cu_pred,
14390 Some(covering.unwrap_or(TxType::DctDct)),
14391 Some(3),
14392 fctx,
14393 )?
14394 .0;
14395 // Immediately, so the NEXT unit reads this one's
14396 // coefficient context.
14397 neighbours.record_mi_chroma(
14398 unit_mi,
14399 unit_luma_w,
14400 unit_luma_h,
14401 plane_idx,
14402 &cu_grid,
14403 );
14404 if crate::envflags::env_flag!("EC_ECDUMP") {
14405 let st = crate::decode::neighbour_state(&cu_grid);
14406 eprintln!(
14407 "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})",
14408 st.dc, st.level
14409 );
14410 }
14411 hit!(CHROMA_SPLIT_TX_HITS);
14412 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(c.get() + 1));
14413 // lane-av1-ibcrect: per-unit chroma context -- the
14414 // end-of-block record's composed-grid re-stamp
14415 // must not stand (replayed below).
14416 mu_chroma = true;
14417 let dst = mu_units(
14418 if plane_idx == 1 {
14419 &mut u_units
14420 } else {
14421 &mut v_units
14422 },
14423 cside * cside,
14424 );
14425 for rr in 0..cu_tx {
14426 let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * cside
14427 + cc * chunk_chroma_w
14428 + uc * cu_tx;
14429 dst[start..start + cu_tx]
14430 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
14431 }
14432 }
14433 }
14434 }
14435 }
14436 }
14437 // The block-level luma bands were recorded per leaf above; the
14438 // composed chroma grids carry every unit in place.
14439 luma_grid = Grid::Zero(side * side);
14440 u_grid = if u_units.is_empty() {
14441 Grid::Zero(cside * cside)
14442 } else {
14443 Grid::Own(std::mem::take(&mut u_units))
14444 };
14445 v_grid = if v_units.is_empty() {
14446 Grid::Zero(cside * cside)
14447 } else {
14448 Grid::Own(std::mem::take(&mut v_units))
14449 };
14450 }
14451 // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a
14452 // neighbour reads a mode, zeroed palette state, the skip grid, the
14453 // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them),
14454 // and the DV into the intrabc mi grid.
14455 if skip {
14456 neighbours.record_rect_mi(
14457 (mi_r, mi_c),
14458 bw,
14459 bh,
14460 DC_PRED,
14461 DC_PRED,
14462 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
14463 );
14464 } else {
14465 neighbours.record_split_luma_rect_mi(
14466 (mi_r, mi_c),
14467 bw,
14468 bh,
14469 DC_PRED,
14470 DC_PRED,
14471 [&u_grid[..], &v_grid[..]],
14472 );
14473 }
14474 // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER
14475 // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside
14476 // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps
14477 // both planes with ONE `neighbour_state(composed_grid)` over the whole
14478 // span -- level = the SUM of every unit's levels and dc = the top-left
14479 // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128
14480 // inter block: the next block read a stale `dc_sign_ctx` one row low).
14481 // Measured on this shape: the 128x64 block at mi(64,32) of the
14482 // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared
14483 // into chunk-0's cells and the block below read `txb_skip` off the sum.
14484 // Replay every coded unit's own state after the record, in mu-chunk order
14485 // so a later unit still wins over an earlier one on the shared seam cells
14486 // (the composed construction `mu_chroma_units` uses, transcribed here).
14487 if mu_chroma {
14488 let cu = if lossless(fctx) { 4usize } else { 32usize };
14489 // The unit's own footprint on the LUMA mi grid (the chroma context
14490 // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s
14491 // convention), PER AXIS: `cu << ss` px, i.e. 8 px per TX_4x4 unit and
14492 // 64 px per TX_32X32 one at 4:2:0 -- 4 px / 32 px at 4:2:2.
14493 let unit_luma_w = cu << ss_x(fctx);
14494 let unit_luma_h = cu << ss_y(fctx);
14495 // A 64x64 mu chunk's chroma plane block is PER-AXIS
14496 // `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at 4:2:0 (ONE TX_32X32 per
14497 // chunk), 32x64 at 4:2:2 (TWO STACKED), 64x64 at 4:4:4 (FOUR);
14498 // `av1_get_max_uv_txsize` caps the unit at 32 on each axis.
14499 let chunk_chroma_w = (64usize) >> ss_x(fctx);
14500 let chunk_chroma_h = (64usize) >> ss_y(fctx);
14501 if lossless(fctx) {
14502 // lane-av1-ibc128chunk, PRE-EXISTING and NOT this lane's: on a
14503 // LOSSLESS frame `cu` is 4 and the composed plane grid is a raster
14504 // of TX_4x4 units, not a `cu`-per-chunk tiling -- so `rows`/`cols`
14505 // below (which count mu CHUNKS at the 4:2:0 chunk extent) do not
14506 // enumerate it, and this arm re-stamps only the 4x4 at each
14507 // chunk's top-left with a 2x2-mi span. The twin
14508 // (`decode_inter_block`'s `mu_chroma_units`, lane-av1-llinter)
14509 // instead raster-walks the WHOLE plane block at `cu` steps, and
14510 // that is the correct shape here too. It is left as-is on purpose:
14511 // it is a 4:2:0 defect, not a subsampling square-cut, and fixing
14512 // it would change 4:2:0 LOSSLESS output -- which this lane's
14513 // byte-identity requirement forbids doing on an unverified
14514 // reconstruction. Measured unreachability: this arm is entered
14515 // 0 times by the whole `lossless` and `intrabc` gate battery
14516 // (temporary env-gated counter in the arm). Unblock: one
14517 // lossless sb128 4:2:0 stream coding a NON-SKIP 128-root
14518 // intrabc strip (`--lossless=1 --sb-size=128
14519 // --min-partition-size=64 --enable-rect-partitions=1
14520 // --enable-intrabc=1` over near-match screen content).
14521 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
14522 for cr in 0..rows {
14523 for cc in 0..cols {
14524 let unit_mi = (
14525 mi_r + cr * (unit_luma_h / MI),
14526 mi_c + cc * (unit_luma_w / MI),
14527 );
14528 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
14529 let mut unit = Vec::with_capacity(cu * cu);
14530 for rr in 0..cu {
14531 let start = (cr * chunk_chroma_h + rr) * cside + cc * chunk_chroma_w;
14532 unit.extend_from_slice(&grid[start..start + cu]);
14533 }
14534 neighbours.record_mi_chroma(
14535 unit_mi,
14536 unit_luma_w,
14537 unit_luma_h,
14538 plane_idx,
14539 &unit,
14540 );
14541 }
14542 }
14543 }
14544 } else {
14545 // The chunk count on each axis, then EVERY unit inside each
14546 // chunk at its own mi origin, its own `(cu << ss)`-px entropy-cell
14547 // span, and its own quadrant of the composed plane grid -- the
14548 // twin's loop (decode_inter_block's `mu_chroma_units`,
14549 // lane-av1-444 c8). lane-av1-ibc128chunk: the loop used to count
14550 // mu CHUNKS in `rows`/`cols` and then step the mi origin and read
14551 // the grid PER UNIT, which only agrees when a chunk holds exactly
14552 // one unit. At 4:2:0 (`chunk_chroma == cu`) it is
14553 // line-identical to the old walk; at 4:2:2 and 4:4:4 a chunk holds
14554 // 2 or 4, so the old body reached only the first of the stacked
14555 // units and the rest of the chunk kept the composed-grid smearing
14556 // this replay exists to undo. A unit the frame edge clipped codes
14557 // nothing and carries no composed samples beyond the clip, so it
14558 // replays as the zero state exactly like libaom's uncoded unit.
14559 let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);
14560 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
14561 for cr in 0..rows {
14562 for cc in 0..cols {
14563 for kr in 0..ur {
14564 for kc in 0..uc {
14565 let unit_mi = (
14566 mi_r + (cr * 64 + kr * unit_luma_h) / MI,
14567 mi_c + (cc * 64 + kc * unit_luma_w) / MI,
14568 );
14569 let (cy, cx) =
14570 (cr * chunk_chroma_h + kr * cu, cc * chunk_chroma_w + kc * cu);
14571 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
14572 let mut unit = Vec::with_capacity(cu * cu);
14573 for rr in 0..cu {
14574 let start = (cy + rr) * cside + cx;
14575 unit.extend_from_slice(&grid[start..start + cu]);
14576 }
14577 neighbours.record_mi_chroma(
14578 unit_mi,
14579 unit_luma_w,
14580 unit_luma_h,
14581 plane_idx,
14582 &unit,
14583 );
14584 }
14585 }
14586 }
14587 }
14588 }
14589 }
14590 }
14591 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14592 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14593 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14594 neighbours.fill_lf_grid_rect(
14595 (mi_r, mi_c),
14596 bw / MI,
14597 bh / MI,
14598 bw.min(64) as u8,
14599 bh.min(64) as u8,
14600 0,
14601 fctx,
14602 );
14603 record_intrabc_mi_rect(
14604 mi_r,
14605 mi_c,
14606 bw / MI,
14607 bh / MI,
14608 Some((dv_row, dv_col)),
14609 neighbours,
14610 fctx,
14611 );
14612 Ok(())
14613}
14614
14615/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
14616/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
14617/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
14618/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
14619/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
14620/// has no rectangular-transform coefficient reader, and a chroma plane here
14621/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
14622/// with no depth-based square-tiling escape the way luma's own resolved
14623/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
14624/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
14625#[allow(clippy::too_many_arguments)]
14626fn decode_block_rect(
14627 dec: &mut SymbolDecoder,
14628 cdfs: &mut Cdfs,
14629 neighbours: &mut Neighbours,
14630 at: (usize, usize),
14631 bw: usize,
14632 bh: usize,
14633 y: &mut PlaneBuf<'static>,
14634 u: &mut PlaneBuf<'static>,
14635 v: &mut PlaneBuf<'static>,
14636 enable_filter_intra: bool,
14637 allow_screen_content_tools: bool,
14638 base_q_idx: u8,
14639 tx_select: bool,
14640 reduced_tx_set: bool,
14641 fctx: &crate::decode::FrameCtx,
14642) -> Result<()> {
14643 let (r, c) = at;
14644 let (px, py) = (c * SUB, r * SUB);
14645 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14646 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14647 let palette_uv_cache = neighbours.palette_uv_cache(at);
14648 let (
14649 skip,
14650 mode,
14651 angle_delta_y,
14652 uv_mode,
14653 angle_delta_uv,
14654 alpha,
14655 filter_intra,
14656 palette_y,
14657 palette_uv,
14658 intrabc,
14659 ) = read_intra_mode_rect(
14660 dec,
14661 cdfs,
14662 nb_above_mode,
14663 nb_left_mode,
14664 true,
14665 true,
14666 bw,
14667 bh,
14668 enable_filter_intra,
14669 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
14670 allow_screen_content_tools,
14671 Some((palette_ctx, &palette_cache)),
14672 &palette_uv_cache,
14673 r * (SUB / MI),
14674 c * (SUB / MI),
14675 fctx,
14676 )?;
14677
14678 if let Some((dv_row, dv_col)) = intrabc {
14679 return decode_intrabc_rect(
14680 dec,
14681 cdfs,
14682 neighbours,
14683 (r * (SUB / MI), c * (SUB / MI)),
14684 (bw, bh),
14685 skip,
14686 (dv_row, dv_col),
14687 y,
14688 u,
14689 v,
14690 base_q_idx,
14691 fctx,
14692 );
14693 }
14694 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14695 if smooth_neighbor {
14696 hit!(SMOOTH_LUMA_HITS);
14697 }
14698 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
14699 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
14700 // `uv_mode`, not the luma one.
14701 let smooth_neighbor_uv =
14702 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
14703 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
14704 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
14705 // rectangle just as happily), so a `use_filter_intra` strip at this level
14706 // predicts instead of refusing. The below-16x16 leaf arm
14707 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
14708 if filter_intra.is_some() {
14709 hit!(FILTER_INTRA_RECT_HITS);
14710 }
14711 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14712 DC_PRED
14713 } else {
14714 uv_mode
14715 };
14716 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14717 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
14718 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
14719 // one did not, so with `--enable-tx-size-search=0` -- which several gate
14720 // recipes use -- the decoder consumed a symbol the encoder never wrote and
14721 // desynced the tile from that point on. That is why both strips of the
14722 // pinned HORZ quadrant were wrong from their very first pixel, and why our
14723 // range after the read equalled the oracle's range for the whole block.
14724 // lane-av1mixloss: the lossless-segment early return
14725 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment
14726 // rect block codes no depth symbol here either (class sweep of the sub8
14727 // leaf's fix).
14728 let depth = if tx_select && !lossless(fctx) {
14729 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
14730 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
14731 // intra-only frame publishes them from every block too
14732 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
14733 // 1920x792 128-superblock stream,
14734 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
14735 // `tx_size_cat2` row 1 where libaom reads row 2.
14736 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
14737 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
14738 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14739 eprintln!(
14740 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
14741 dec.debug_state().0
14742 );
14743 }
14744 d
14745 } else {
14746 0
14747 };
14748 // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame
14749 // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
14750 publish_txfm_bands_if_in_inter(
14751 neighbours,
14752 (mi_r, mi_c),
14753 depth_to_tx_wh(bw, bh, depth, fctx),
14754 (bw, bh),
14755 fctx,
14756 );
14757 if depth != 0 || lossless(fctx) {
14758 hit!(TX_DEPTH_HITS);
14759 // lane-rectsplit r1: a split transform is predicted and reconstructed
14760 // per transform unit, each unit taking its edges from the previous
14761 // unit's reconstruction inside this same strip (spec 5.11.36) --
14762 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
14763 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
14764 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
14765 eprintln!(
14766 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
14767 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
14768 angle_y={angle_delta_y}"
14769 );
14770 }
14771 let modes = RectStripModes {
14772 skip,
14773 mode,
14774 angle_delta_y,
14775 uv_predict_mode,
14776 angle_delta_uv,
14777 alpha,
14778 filter_intra,
14779 smooth_neighbor,
14780 smooth_neighbor_uv,
14781 palette_y: palette_y
14782 .as_ref()
14783 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
14784 palette_uv: palette_uv.as_ref().map(|p| {
14785 (
14786 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
14787 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
14788 )
14789 }),
14790 };
14791 if palette_y.is_some() || palette_uv.is_some() {
14792 hit!(PALETTE_SPLIT_TX_HITS);
14793 }
14794 decode_rect_split(
14795 dec,
14796 cdfs,
14797 neighbours,
14798 (mi_r, mi_c),
14799 bw,
14800 bh,
14801 tx_w,
14802 tx_h,
14803 &modes,
14804 y,
14805 u,
14806 v,
14807 base_q_idx,
14808 reduced_tx_set,
14809 fctx,
14810 )?;
14811 // This early return skips this fn's own tail, so the palette
14812 // neighbour state has to be stamped HERE too: without it a split-tx
14813 // strip left the above/left palette arrays holding a DEAD block's
14814 // colours, and the next block's colour cache
14815 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
14816 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
14817 // and only those pixels were wrong (lane-palette2 r10).
14818 let (py_size, py_colors) = palette_y
14819 .as_ref()
14820 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14821 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
14822 let (puv_size, puv_colors) = palette_uv
14823 .as_ref()
14824 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14825 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
14826 hit!(RECT_PARTITION_HITS);
14827 return Ok(());
14828 }
14829 let (tx_w, tx_h) = (bw, bh);
14830 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14831 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14832 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
14833 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14834 let (rng, _) = dec.debug_state();
14835 eprintln!(
14836 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
14837 skip={} tx={depth} rng={rng}",
14838 skip as i32
14839 );
14840 }
14841 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
14842 // block's prediction is the reconstructed colour-index map, set fresh
14843 // right before each `reconstruct_rect` call below (lane-palette2 r4).
14844 if let Some(ref pyv) = palette_y {
14845 let buf: Vec<u16> = pyv
14846 .map
14847 .iter()
14848 .map(|&idx| pyv.colors[idx as usize])
14849 .collect();
14850 set_palette_pred(buf, fctx);
14851 }
14852 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
14853 (
14854 puv.map
14855 .iter()
14856 .map(|&idx| puv.u_colors[idx as usize])
14857 .collect(),
14858 puv.map
14859 .iter()
14860 .map(|&idx| puv.v_colors[idx as usize])
14861 .collect(),
14862 )
14863 });
14864 if skip {
14865 push_intra_rect(
14866 0,
14867 px,
14868 py,
14869 bw,
14870 bh,
14871 mode,
14872 angle_delta_y,
14873 reach,
14874 &ZERO_RESIDUAL[..bw * bh],
14875 None,
14876 filter_intra,
14877 smooth_neighbor,
14878 fctx,
14879 );
14880 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
14881 if let Some((ub, _)) = &palette_uv_bufs {
14882 set_palette_pred(ub.clone(), fctx);
14883 }
14884 push_intra_rect(
14885 1,
14886 cpx,
14887 cpy,
14888 chroma_w,
14889 chroma_h,
14890 uv_predict_mode,
14891 angle_delta_uv,
14892 reach,
14893 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14894 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14895 None,
14896 smooth_neighbor_uv,
14897 fctx,
14898 );
14899 if let Some((_, vb)) = &palette_uv_bufs {
14900 set_palette_pred(vb.clone(), fctx);
14901 }
14902 push_intra_rect(
14903 2,
14904 cpx,
14905 cpy,
14906 chroma_w,
14907 chroma_h,
14908 uv_predict_mode,
14909 angle_delta_uv,
14910 reach,
14911 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14912 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14913 None,
14914 smooth_neighbor_uv,
14915 fctx,
14916 );
14917 neighbours.record_rect(
14918 at,
14919 bw,
14920 bh,
14921 mode,
14922 uv_predict_mode,
14923 &[
14924 &ZERO_RESIDUAL[..bw * bh],
14925 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14926 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14927 ],
14928 );
14929 } else {
14930 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
14931 // reduces both size pairs to their square-up CDF sets
14932 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
14933 // doc comments); the scan order and 2D context tables are the real
14934 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
14935 let luma_scan: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 };
14936 // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a
14937 // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16
14938 // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis).
14939 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
14940 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
14941 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
14942 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8),
14943 (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16),
14944 // lane-av1-422: a 4:2:2 strip halves only the width. A 32x16
14945 // luma strip's chroma is a 16x16 SQUARE (`TxbSet::Chroma16`, the
14946 // set any 16x16 chroma plane reads); a 16x32 strip's chroma is
14947 // 8x32, whose entropy set is the 16x16 one and whose DCT-only
14948 // default follows the >=32 rule below -- the same pairing the
14949 // (8,32) row of [`decode_rect_split`]'s chroma table proves. At
14950 // 4:2:0 and 4:4:4 a strip's chroma is itself rect, so neither row
14951 // is reachable there.
14952 (16, 16) => (TxbSet::Chroma16, default_scan(16)),
14953 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
14954 _ => {
14955 return Err(unsupported(
14956 "a rectangular chroma transform whose size has no coefficient table",
14957 ));
14958 }
14959 };
14960 let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 {
14961 TxType::DctDct
14962 } else {
14963 default_intra_tx_type(uv_predict_mode as u8)
14964 };
14965 // lane-rectwire r3: real coefficients desync a pixel-exact gate
14966 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
14967 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
14968 // pixel (not a subtle context-table off-by-one), while the sibling
14969 // non-rect quadrants of the same frame match. Range-ladder bisection
14970 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
14971 // but the intra key-frame path has no traced symbol between the
14972 // partition read and the first coefficient block (mode/skip/tx_depth
14973 // reads are all untraced in libaom's decodeframe.c intra path, unlike
14974 // the inter EC_TRACE_MODE this round added), so a same-length range
14975 // comparison wasn't reachable within budget -- see
14976 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
14977 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
14978 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
14979 // libaom and match). lane-rectwire r4: range-ladder against the
14980 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
14981 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
14982 // both confirmed in sync -- rng=58692 on both sides right after
14983 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
14984 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
14985 // immediately after: ours moves rng 58692 -> 43570, which cannot be
14986 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
14987 // its own tx_size read) unless oracle's tx symbol is a near-certainty
14988 // CDF that barely narrows the range -- i.e. this decoder's
14989 // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for
14990 // a 32x16/16x32 strip is the first diverging symbol, not the
14991 // coefficient-context math r3 already cleared. Not confirmed byte-
14992 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
14993 // `read_tx_size`'s own rng, not attempted this round -- budget), so
14994 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
14995 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
14996 // it unconditionally where both square paths gate on `tx_select`. With
14997 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
14998 // decoder consumed one that was never there.
14999 {
15000 // lane-av1422warp r20: this 32x16/16x32 strip reader is the SIBLING of
15001 // `decode_leaf_rect`, and it was the one left ungated: at ss (1,0) the
15002 // strip's chroma is a square (side/2, side) block whose above cells
15003 // spread over `side` LUMA mi columns, so the per-mi rect gather
15004 // double-counts every chroma column's whole-unit dc sign. Measured on
15005 // the pinned 4:2:2 rotzoom stream (a1.obu frame 0): the chroma-U 4x4
15006 // transform of the 32x16 strip at mi(68,16) reads its DC sign from
15007 // `dc_sign_ctx` 1 where libaom reads row 0 -- the first read of
15008 // 45260 whose pre-state, bit position and symbol all match and only
15009 // the CDF row differs, and the first divergence in the EC_SYMR
15010 // sequence (all 45259 reads before it pair exactly). Luma keeps the
15011 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
15012 let mut around = neighbours.around_rect(at, bw, bh);
15013 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
15014 let c2 =
15015 neighbours.around_mi_422_chroma((at.0 * (SUB / MI), at.1 * (SUB / MI)), bw, bh);
15016 around[1] = c2[1];
15017 around[2] = c2[2];
15018 }
15019 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
15020 let (luma_levels, luma_tx_type) = read_coeffs_rect(
15021 dec,
15022 &mut luma_coding,
15023 luma_scan,
15024 bw,
15025 bh,
15026 0,
15027 dc_sign_ctx(around[0].2),
15028 TxType::DctDct,
15029 0,
15030 )?;
15031 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15032 let (rng, _) = dec.debug_state();
15033 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15034 }
15035 let luma_residual = dequant_and_inverse_typed_wh(
15036 &luma_levels,
15037 bw,
15038 bh,
15039 crate::decode::bit_depth(fctx),
15040 block_q_idx(fctx),
15041 plane_q_delta(0, fctx).0,
15042 plane_q_delta(0, fctx).1,
15043 luma_tx_type,
15044 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15045 );
15046 push_intra_rect(
15047 0,
15048 px,
15049 py,
15050 bw,
15051 bh,
15052 mode,
15053 angle_delta_y,
15054 reach,
15055 &luma_residual,
15056 None,
15057 filter_intra,
15058 smooth_neighbor,
15059 fctx,
15060 );
15061 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15062 if let Some((ub, _)) = &palette_uv_bufs {
15063 set_palette_pred(ub.clone(), fctx);
15064 }
15065 let u_default_tx = chroma_default_tx;
15066 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
15067 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
15068 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
15069 dec,
15070 &mut u_coding,
15071 chroma_scan,
15072 chroma_w,
15073 chroma_h,
15074 u_skip_ctx,
15075 dc_sign_ctx(around[1].2),
15076 u_default_tx,
15077 fctx,
15078 1,
15079 )?;
15080 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15081 let (rng, _) = dec.debug_state();
15082 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15083 }
15084 let u_residual = dequant_and_inverse_typed_wh(
15085 &u_levels,
15086 chroma_w,
15087 chroma_h,
15088 crate::decode::bit_depth(fctx),
15089 block_q_idx(fctx),
15090 plane_q_delta(1, fctx).0,
15091 plane_q_delta(1, fctx).1,
15092 u_tx_type,
15093 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
15094 );
15095 push_intra_rect(
15096 1,
15097 cpx,
15098 cpy,
15099 chroma_w,
15100 chroma_h,
15101 uv_predict_mode,
15102 angle_delta_uv,
15103 reach,
15104 &u_residual,
15105 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15106 None,
15107 smooth_neighbor_uv,
15108 fctx,
15109 );
15110 if let Some((_, vb)) = &palette_uv_bufs {
15111 set_palette_pred(vb.clone(), fctx);
15112 }
15113 let v_default_tx = chroma_default_tx;
15114 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
15115 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
15116 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
15117 dec,
15118 &mut v_coding,
15119 chroma_scan,
15120 chroma_w,
15121 chroma_h,
15122 v_skip_ctx,
15123 dc_sign_ctx(around[2].2),
15124 v_default_tx,
15125 fctx,
15126 2,
15127 )?;
15128 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15129 let (rng, _) = dec.debug_state();
15130 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15131 }
15132 let v_residual = dequant_and_inverse_typed_wh(
15133 &v_levels,
15134 chroma_w,
15135 chroma_h,
15136 crate::decode::bit_depth(fctx),
15137 block_q_idx(fctx),
15138 plane_q_delta(2, fctx).0,
15139 plane_q_delta(2, fctx).1,
15140 v_tx_type,
15141 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
15142 );
15143 push_intra_rect(
15144 2,
15145 cpx,
15146 cpy,
15147 chroma_w,
15148 chroma_h,
15149 uv_predict_mode,
15150 angle_delta_uv,
15151 reach,
15152 &v_residual,
15153 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15154 None,
15155 smooth_neighbor_uv,
15156 fctx,
15157 );
15158 neighbours.record_rect(
15159 at,
15160 bw,
15161 bh,
15162 mode,
15163 uv_predict_mode,
15164 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
15165 );
15166 hit!(RECT_COEFF_HITS);
15167 }
15168 }
15169 let (py_size, py_colors) = palette_y
15170 .as_ref()
15171 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15172 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
15173 let (puv_size, puv_colors) = palette_uv
15174 .as_ref()
15175 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15176 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
15177 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
15178 neighbours.fill_lf_grid_rect(
15179 (mi_r, mi_c),
15180 bw / MI,
15181 bh / MI,
15182 tx_w as u8,
15183 tx_h as u8,
15184 0,
15185 fctx,
15186 );
15187 hit!(RECT_PARTITION_HITS);
15188 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15189 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
15190 }
15191 Ok(())
15192}
15193
15194/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
15195/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
15196/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
15197/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
15198/// the second strip of a HORZ/VERT split sits offset by half the 16x16
15199/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
15200/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
15201/// previous strip is directly above (same column, `mi_h` rows up) or
15202/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
15203/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
15204/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
15205/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
15206/// this strip's real position, never the coarse `record_rect` (which the
15207/// caller uses once, after both strips, exactly like the `VERT_B` arm next
15208/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
15209/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
15210/// chroma half (`TxbSet::ChromaRect8x4`) at 4:2:0 -- an 8x8 *square* chroma
15211/// plane (`TxbSet::Chroma8` + the default scan) at 4:2:2 (lane-av1-422e:
15212/// half-width, unhalved height), the two size classes one level
15213/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
15214#[allow(clippy::too_many_arguments)]
15215fn decode_leaf_rect(
15216 dec: &mut SymbolDecoder,
15217 cdfs: &mut Cdfs,
15218 neighbours: &mut Neighbours,
15219 outer_at: (usize, usize),
15220 leaf_mi: (usize, usize),
15221 bw: usize,
15222 bh: usize,
15223 prev_leaf: Option<((usize, usize), usize)>,
15224 y: &mut PlaneBuf<'static>,
15225 u: &mut PlaneBuf<'static>,
15226 v: &mut PlaneBuf<'static>,
15227 enable_filter_intra: bool,
15228 allow_screen_content_tools: bool,
15229 base_q_idx: u8,
15230 tx_select: bool,
15231 reduced_tx_set: bool,
15232 fctx: &crate::decode::FrameCtx,
15233) -> Result<usize> {
15234 let _ = base_q_idx;
15235 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15236 eprintln!(
15237 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
15238 dec.debug_state().0
15239 );
15240 }
15241 let (r, c) = outer_at;
15242 let mut above_mode = neighbours.above_mode[c];
15243 let mut left_mode = neighbours.left_mode[r];
15244 let (mi_w, mi_h) = (bw / MI, bh / MI);
15245 if let Some(((pr, pc), pmode)) = prev_leaf {
15246 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
15247 above_mode = pmode;
15248 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
15249 left_mode = pmode;
15250 }
15251 }
15252 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
15253 // cannot hold the modes a split (or a pair of strips) leaves behind, so
15254 // when the map holds the block at exactly this strip's above/left mi it
15255 // is the neighbour libaom's `above_mi`/`left_mi` reads.
15256 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
15257 // availability-correct -- four 16x8 strips share one coarse 16x16
15258 // `left_mode` cell too, so the fallback must not stand in for an absent
15259 // tile-edge neighbour.
15260 let (above_mode, left_mode) =
15261 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
15262 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
15263 if smooth_neighbor {
15264 hit!(SMOOTH_LUMA_HITS);
15265 }
15266 // The palette-Y mode CDF row is picked by the neighbours' palette use
15267 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
15268 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
15269 // a palette narrows the wrong interval and desyncs the tile even when the
15270 // decoded bit is the same. The cell is the 16px-SUB cell containing the
15271 // leaf (the palette neighbour arrays have no finer granularity).
15272 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
15273 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
15274 // exclusion and the neighbour palette lookup itself are mi-granular
15275 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
15276 let pal_at = leaf_mi;
15277 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
15278 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
15279 let (
15280 skip,
15281 mode,
15282 angle_delta_y,
15283 uv_mode,
15284 angle_delta_uv,
15285 alpha,
15286 filter_intra,
15287 palette_y,
15288 palette_uv,
15289 intrabc,
15290 ) = read_intra_mode_rect(
15291 dec,
15292 cdfs,
15293 above_mode,
15294 left_mode,
15295 true,
15296 true,
15297 bw,
15298 bh,
15299 enable_filter_intra,
15300 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
15301 allow_screen_content_tools,
15302 Some((palette_ctx, &palette_cache)),
15303 &palette_uv_cache,
15304 leaf_mi.0,
15305 leaf_mi.1,
15306 fctx,
15307 )?;
15308
15309 if let Some((dv_row, dv_col)) = intrabc {
15310 decode_intrabc_rect(
15311 dec,
15312 cdfs,
15313 neighbours,
15314 leaf_mi,
15315 (bw, bh),
15316 skip,
15317 (dv_row, dv_col),
15318 y,
15319 u,
15320 v,
15321 base_q_idx,
15322 fctx,
15323 )?;
15324 return Ok(DC_PRED);
15325 }
15326 // lane-kf900 r4: palette prediction on this shape, the same colour-index
15327 // map -> base colours buffer [`decode_block_rect`] hands each
15328 // `reconstruct_rect` through [`set_palette_pred`].
15329 if palette_y.is_some() || palette_uv.is_some() {
15330 hit!(RECT4_PALETTE_HITS);
15331 }
15332 let palette_y_buf: Option<Vec<u16>> = palette_y
15333 .as_ref()
15334 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
15335 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
15336 (
15337 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15338 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15339 )
15340 });
15341 let (pal_y_size, pal_y_colors) = palette_y
15342 .as_ref()
15343 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15344 let (pal_uv_size, pal_uv_colors) = palette_uv
15345 .as_ref()
15346 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15347 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15348 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
15349 }
15350 if filter_intra.is_some() {
15351 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
15352 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
15353 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
15354 // below already makes; this refusal was square-only prose.
15355 hit!(FILTER_INTRA_RECT_HITS);
15356 hit!(FILTER_INTRA_RECT_SUB16_HITS);
15357 }
15358 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15359 DC_PRED
15360 } else {
15361 uv_mode
15362 };
15363 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
15364 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
15365 // a constant `false`.
15366 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
15367 let depth = if tx_select && !lossless(fctx) {
15368 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
15369 // every other rect reader now does -- a no-op on a key frame.
15370 // lane-av1mixloss: libaom `read_tx_size`'s first line
15371 // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return
15372 // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment
15373 // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4).
15374 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
15375 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
15376 // read was the leaf's own txb_skip.
15377 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
15378 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
15379 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
15380 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
15381 // count (3), different CDF row: a wrong-table read of a real symbol,
15382 // the class that cost lane-rectsplit r1 its 64x32 depth.
15383 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
15384 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
15385 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
15386 // function also decodes) sit at depth 2, so they read
15387 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
15388 // while `tx_size_cat2` belongs to the 32-level shapes
15389 // ([`decode_block_rect`]). Both tables carry three symbols, so the
15390 // wrong one decodes a plausible depth from the wrong probabilities:
15391 // the range diverges silently at the first such leaf and every later
15392 // symbol in the tile is read from the wrong place (class
15393 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
15394 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
15395 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15396 eprintln!(
15397 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
15398 leaf_mi.0,
15399 leaf_mi.1,
15400 dec.debug_state().0
15401 );
15402 }
15403 d
15404 } else {
15405 0
15406 };
15407 // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads
15408 // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
15409 publish_txfm_bands_if_in_inter(
15410 neighbours,
15411 leaf_mi,
15412 depth_to_tx_wh(bw, bh, depth, fctx),
15413 (bw, bh),
15414 fctx,
15415 );
15416 if depth != 0 || lossless(fctx) {
15417 // The same per-transform-unit walk the bigger strips take
15418 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
15419 // depth 2), addressed at this leaf's own mi position.
15420 hit!(TX_DEPTH_HITS);
15421 hit!(SUB16_SPLIT_HITS);
15422 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
15423 let modes = RectStripModes {
15424 skip,
15425 mode,
15426 angle_delta_y,
15427 uv_predict_mode,
15428 angle_delta_uv,
15429 alpha,
15430 filter_intra,
15431 smooth_neighbor,
15432 // lane-rectsplitx r3: the split arm hard-coded `false` here while
15433 // the unsplit arm below passes the real neighbour answer -- chroma
15434 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
15435 smooth_neighbor_uv,
15436 palette_y: palette_y_buf.clone(),
15437 palette_uv: palette_uv_bufs.clone(),
15438 };
15439 if palette_y.is_some() || palette_uv.is_some() {
15440 hit!(PALETTE_SPLIT_TX_HITS);
15441 }
15442 decode_rect_split(
15443 dec,
15444 cdfs,
15445 neighbours,
15446 leaf_mi,
15447 bw,
15448 bh,
15449 tx_w,
15450 tx_h,
15451 &modes,
15452 y,
15453 u,
15454 v,
15455 base_q_idx,
15456 reduced_tx_set,
15457 fctx,
15458 )?;
15459 record_strip_palette(
15460 neighbours,
15461 pal_at,
15462 bw,
15463 bh,
15464 pal_y_size,
15465 pal_y_colors,
15466 pal_uv_size,
15467 pal_uv_colors,
15468 );
15469 return Ok(mode);
15470 }
15471 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15472 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15473 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
15474 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
15475 let (luma_levels, u_levels, v_levels);
15476 if skip {
15477 luma_levels = Grid::Zero(bw * bh);
15478 u_levels = Grid::Zero(chroma_w * chroma_h);
15479 v_levels = Grid::Zero(chroma_w * chroma_h);
15480 if let Some(b) = &palette_y_buf {
15481 set_palette_pred(b.clone(), fctx);
15482 }
15483 push_intra_rect(
15484 0,
15485 px,
15486 py,
15487 bw,
15488 bh,
15489 mode,
15490 angle_delta_y,
15491 reach,
15492 &luma_levels,
15493 None,
15494 filter_intra,
15495 smooth_neighbor,
15496 fctx,
15497 );
15498 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15499 if let Some((ub, _)) = &palette_uv_bufs {
15500 set_palette_pred(ub.clone(), fctx);
15501 }
15502 push_intra_rect(
15503 1,
15504 cpx,
15505 cpy,
15506 chroma_w,
15507 chroma_h,
15508 uv_predict_mode,
15509 angle_delta_uv,
15510 reach,
15511 &u_levels,
15512 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15513 None,
15514 smooth_neighbor_uv,
15515 fctx,
15516 );
15517 if let Some((_, vb)) = &palette_uv_bufs {
15518 set_palette_pred(vb.clone(), fctx);
15519 }
15520 push_intra_rect(
15521 2,
15522 cpx,
15523 cpy,
15524 chroma_w,
15525 chroma_h,
15526 uv_predict_mode,
15527 angle_delta_uv,
15528 reach,
15529 &v_levels,
15530 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15531 None,
15532 smooth_neighbor_uv,
15533 fctx,
15534 );
15535 } else {
15536 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
15537 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
15538 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
15539 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
15540 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
15541 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
15542 // lane-av1-422e: a 4:2:2 strip halves only the width, so the chroma
15543 // half of a 16x8/8x16 luma leaf is an 8x8 SQUARE (`TxbSet::Chroma8` +
15544 // the default scan -- the pairing any 8x8 chroma plane reads). 4:2:0
15545 // halves both axes (8x4/4x8 rect, `TxbSet::ChromaRect8x4`); 4:4:4
15546 // leaves the full 16x8/8x16 rect (`TxbSet::ChromaRect16x8`).
15547 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
15548 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 {
15549 if bw == 16 {
15550 (&SCAN_16X8, &SCAN_16X8)
15551 } else {
15552 (&SCAN_8X16, &SCAN_8X16)
15553 }
15554 } else if chroma_422 {
15555 if bw == 16 {
15556 (&SCAN_16X8, default_scan(8))
15557 } else {
15558 (&SCAN_8X16, default_scan(8))
15559 }
15560 } else if bw == 16 {
15561 (&SCAN_16X8, &SCAN_8X4)
15562 } else {
15563 (&SCAN_8X16, &SCAN_4X8)
15564 };
15565 let chroma_rect_set = if ss_x(fctx) == 0 {
15566 TxbSet::ChromaRect16x8
15567 } else if chroma_422 {
15568 TxbSet::Chroma8
15569 } else {
15570 TxbSet::ChromaRect8x4
15571 };
15572 // lane-av1422warp: at ss (1,0) this leaf's chroma is a SQUARE
15573 // (side/2, side) block, so `side` chroma 4-px cells above it spread
15574 // over `side` LUMA mi columns -- one chroma column per PAIR of luma
15575 // mi cells, and both carry the covering unit's whole-unit dc sign.
15576 // The per-mi rect gather therefore double-counts every chroma
15577 // column's sign. `around_mi_422_chroma`'s every-second above-cell
15578 // sampling is libaom's `txb_w_unit` sum, and every other 4:2:2 chroma
15579 // gather in this file already routes through it (see the gate at this
15580 // arm's siblings); this one did not, so a 4:2:2 rect leaf voted over
15581 // luma unit counts. Measured on the pinned 4:2:2 rotzoom stream
15582 // (a1.obu frame 0): the 16x8 leaf at mi(48,28) resolved its V plane's
15583 // dc sign from vote 0 (`dc_sign_cdf[0]`) where the oracle resolves a
15584 // negative vote (`dc_sign_cdf[1]`), which is the first bit-position
15585 // divergence in the frame (the bit offset is a clean constant through
15586 // coefficient unit 1418 and turns 6 bits at 1419). Luma keeps the
15587 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
15588 let mut around = neighbours.around_mi_rect(leaf_mi, bw, bh);
15589 if chroma_422 {
15590 let c = neighbours.around_mi_422_chroma(leaf_mi, bw, bh);
15591 around[1] = c[1];
15592 around[2] = c[2];
15593 }
15594 let luma_set = if reduced_tx_set {
15595 TxbSet::LumaRect16x8
15596 } else {
15597 TxbSet::LumaRect16x8Set1
15598 };
15599 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
15600 let (l_levels, luma_tx_type) = read_coeffs_rect(
15601 dec,
15602 &mut luma_coding,
15603 luma_scan,
15604 bw,
15605 bh,
15606 0,
15607 dc_sign_ctx(around[0].2),
15608 TxType::DctDct,
15609 0,
15610 )?;
15611 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15612 let nz: Vec<(usize, i32)> = l_levels
15613 .iter()
15614 .copied()
15615 .enumerate()
15616 .filter(|(_, v)| *v != 0)
15617 .collect();
15618 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
15619 }
15620 luma_levels = l_levels;
15621 let luma_residual = dequant_and_inverse_typed_wh(
15622 &luma_levels,
15623 bw,
15624 bh,
15625 crate::decode::bit_depth(fctx),
15626 block_q_idx(fctx),
15627 plane_q_delta(0, fctx).0,
15628 plane_q_delta(0, fctx).1,
15629 luma_tx_type,
15630 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15631 );
15632 if let Some(b) = &palette_y_buf {
15633 set_palette_pred(b.clone(), fctx);
15634 }
15635 push_intra_rect(
15636 0,
15637 px,
15638 py,
15639 bw,
15640 bh,
15641 mode,
15642 angle_delta_y,
15643 reach,
15644 &luma_residual,
15645 None,
15646 filter_intra,
15647 smooth_neighbor,
15648 fctx,
15649 );
15650 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15651 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
15652 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
15653 let mut u_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
15654 let (u_l, u_tx_type) = read_chroma_coeffs_rect(
15655 dec,
15656 &mut u_coding,
15657 chroma_scan,
15658 chroma_w,
15659 chroma_h,
15660 u_skip_ctx,
15661 dc_sign_ctx(around[1].2),
15662 u_default_tx,
15663 fctx,
15664 1,
15665 )?;
15666 u_levels = u_l;
15667 let u_residual = dequant_and_inverse_typed_wh(
15668 &u_levels,
15669 chroma_w,
15670 chroma_h,
15671 crate::decode::bit_depth(fctx),
15672 block_q_idx(fctx),
15673 plane_q_delta(1, fctx).0,
15674 plane_q_delta(1, fctx).1,
15675 u_tx_type,
15676 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
15677 );
15678 if let Some((ub, _)) = &palette_uv_bufs {
15679 set_palette_pred(ub.clone(), fctx);
15680 }
15681 push_intra_rect(
15682 1,
15683 cpx,
15684 cpy,
15685 chroma_w,
15686 chroma_h,
15687 uv_predict_mode,
15688 angle_delta_uv,
15689 reach,
15690 &u_residual,
15691 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15692 None,
15693 smooth_neighbor_uv,
15694 fctx,
15695 );
15696 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
15697 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
15698 let mut v_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
15699 let (v_l, v_tx_type) = read_chroma_coeffs_rect(
15700 dec,
15701 &mut v_coding,
15702 chroma_scan,
15703 chroma_w,
15704 chroma_h,
15705 v_skip_ctx,
15706 dc_sign_ctx(around[2].2),
15707 v_default_tx,
15708 fctx,
15709 2,
15710 )?;
15711 v_levels = v_l;
15712 let v_residual = dequant_and_inverse_typed_wh(
15713 &v_levels,
15714 chroma_w,
15715 chroma_h,
15716 crate::decode::bit_depth(fctx),
15717 block_q_idx(fctx),
15718 plane_q_delta(2, fctx).0,
15719 plane_q_delta(2, fctx).1,
15720 v_tx_type,
15721 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
15722 );
15723 if let Some((_, vb)) = &palette_uv_bufs {
15724 set_palette_pred(vb.clone(), fctx);
15725 }
15726 push_intra_rect(
15727 2,
15728 cpx,
15729 cpy,
15730 chroma_w,
15731 chroma_h,
15732 uv_predict_mode,
15733 angle_delta_uv,
15734 reach,
15735 &v_residual,
15736 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15737 None,
15738 smooth_neighbor_uv,
15739 fctx,
15740 );
15741 hit!(RECT_LEAF_COEFF_HITS);
15742 }
15743 neighbours.record_mi_rect(
15744 leaf_mi,
15745 bw,
15746 bh,
15747 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
15748 );
15749 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
15750 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
15751 // The leaf's own palette state (`0` clears, as this site always did
15752 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
15753 // AXIS only until the pair's closing leaf: the coarse cell holds one
15754 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
15755 // real left neighbour leaf 1 reads (lane-kf900 r4).
15756 record_strip_palette(
15757 neighbours,
15758 pal_at,
15759 bw,
15760 bh,
15761 pal_y_size,
15762 pal_y_colors,
15763 pal_uv_size,
15764 pal_uv_colors,
15765 );
15766 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
15767 // rows -- record the whole span, not one cell.
15768 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
15769 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
15770 Ok(mode)
15771}
15772
15773/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
15774/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
15775/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
15776/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
15777/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
15778/// strip's mode so this one's mode context sees its true above/left
15779/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
15780///
15781/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
15782/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
15783/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
15784/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
15785/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
15786/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
15787/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
15788///
15789/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
15790/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
15791/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
15792/// unexamined.
15793#[allow(clippy::too_many_arguments)]
15794fn decode_block_rect4(
15795 dec: &mut SymbolDecoder,
15796 cdfs: &mut Cdfs,
15797 neighbours: &mut Neighbours,
15798 strip_mi: (usize, usize),
15799 bw: usize,
15800 bh: usize,
15801 prev_strip: Option<((usize, usize), usize)>,
15802 y: &mut PlaneBuf<'static>,
15803 u: &mut PlaneBuf<'static>,
15804 v: &mut PlaneBuf<'static>,
15805 enable_filter_intra: bool,
15806 allow_screen_content_tools: bool,
15807 base_q_idx: u8,
15808 tx_select: bool,
15809 fctx: &crate::decode::FrameCtx,
15810) -> Result<(usize, usize)> {
15811 let _ = base_q_idx;
15812 let (mi_r, mi_c) = strip_mi;
15813 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
15814 let (mi_w, mi_h) = (bw / MI, bh / MI);
15815 let mut above_mode = neighbours.above_mode[c];
15816 let mut left_mode = neighbours.left_mode[r];
15817 if let Some(((pr, pc), pmode)) = prev_strip {
15818 if pc == mi_c && mi_r == pr + mi_h {
15819 above_mode = pmode;
15820 } else if pr == mi_r && mi_c == pc + mi_w {
15821 left_mode = pmode;
15822 }
15823 }
15824 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
15825 // availability-correct neighbour modes (see
15826 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
15827 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
15828 let (above_mode, left_mode) =
15829 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
15830 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
15831 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
15832 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
15833 // wrong interval, so a screen-content tile desynced at the first strip
15834 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
15835 let pal_at = (mi_r, mi_c);
15836 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
15837 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
15838 let (
15839 skip,
15840 mode,
15841 angle_delta_y,
15842 uv_mode,
15843 angle_delta_uv,
15844 alpha,
15845 filter_intra,
15846 palette_y,
15847 palette_uv,
15848 intrabc,
15849 ) = read_intra_mode_rect(
15850 dec,
15851 cdfs,
15852 above_mode,
15853 left_mode,
15854 true,
15855 true,
15856 bw,
15857 bh,
15858 enable_filter_intra,
15859 neighbours.skip_txfm_ctx(mi_r, mi_c),
15860 allow_screen_content_tools,
15861 Some((palette_ctx, &palette_cache)),
15862 &palette_uv_cache,
15863 mi_r,
15864 mi_c,
15865 fctx,
15866 )?;
15867 if let Some((dv_row, dv_col)) = intrabc {
15868 decode_intrabc_rect(
15869 dec,
15870 cdfs,
15871 neighbours,
15872 strip_mi,
15873 (bw, bh),
15874 skip,
15875 (dv_row, dv_col),
15876 y,
15877 u,
15878 v,
15879 base_q_idx,
15880 fctx,
15881 )?;
15882 return Ok((DC_PRED, DC_PRED));
15883 }
15884 // lane-kf900 r4: palette prediction on this shape, exactly as
15885 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
15886 // mapped through the base colours IS the prediction (it reads no edge
15887 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
15888 if palette_y.is_some() || palette_uv.is_some() {
15889 hit!(RECT4_PALETTE_HITS);
15890 }
15891 let palette_y_buf: Option<Vec<u16>> = palette_y
15892 .as_ref()
15893 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
15894 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
15895 (
15896 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15897 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15898 )
15899 });
15900 let (pal_y_size, pal_y_colors) = palette_y
15901 .as_ref()
15902 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15903 let (pal_uv_size, pal_uv_colors) = palette_uv
15904 .as_ref()
15905 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15906 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
15907 if smooth_neighbor {
15908 hit!(SMOOTH_LUMA_HITS);
15909 }
15910 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
15911 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
15912 // `r * (SUB / MI)` names a different mi column and the chroma
15913 // edge-filter strength was read from the wrong neighbour (measured:
15914 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
15915 // with luma bit-exact).
15916 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
15917 if filter_intra.is_some() {
15918 hit!(FILTER_INTRA_RECT_HITS);
15919 if bw > bh {
15920 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
15921 } else {
15922 hit!(FILTER_INTRA_RECT4_VERT_HITS);
15923 }
15924 }
15925 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15926 DC_PRED
15927 } else {
15928 uv_mode
15929 };
15930 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
15931 // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no
15932 // depth symbol here either (class sweep of the sub8 leaf's fix).
15933 let depth = if tx_select && !lossless(fctx) {
15934 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
15935 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
15936 // intra-only frame publishes them from every block too
15937 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
15938 // 1920x792 128-superblock stream,
15939 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
15940 // `tx_size_cat2` row 1 where libaom reads row 2.
15941 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
15942 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
15943 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15944 eprintln!(
15945 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
15946 dec.debug_state().0
15947 );
15948 }
15949 d
15950 } else {
15951 0
15952 };
15953 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
15954 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
15955 publish_txfm_bands_if_in_inter(
15956 neighbours,
15957 (mi_r, mi_c),
15958 depth_to_tx_wh(bw, bh, depth, fctx),
15959 (bw, bh),
15960 fctx,
15961 );
15962 if depth != 0 || lossless(fctx) {
15963 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
15964 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
15965 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
15966 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
15967 // both interleave in every real stream.
15968 hit!(TX_DEPTH_HITS);
15969 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
15970 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
15971 // predicted -- depth 1 fires FIRST in every attempt that splits at
15972 // all, so a depth-2-only lift could never be gated. The r1 mismatch
15973 // was never the rect unit: it was the neighbour MODE the strip reads
15974 // (see `modes_above_left_mi`).
15975 let which = if depth == 1 {
15976 &RECT4_SPLIT_DEPTH1_HITS
15977 } else {
15978 &RECT4_SPLIT_DEPTH2_HITS
15979 };
15980 hit_do! { which.with(|c| c.set(c.get() + 1)); }
15981 let modes = RectStripModes {
15982 skip,
15983 mode,
15984 angle_delta_y,
15985 uv_predict_mode,
15986 angle_delta_uv,
15987 alpha,
15988 filter_intra,
15989 smooth_neighbor,
15990 smooth_neighbor_uv,
15991 palette_y: palette_y_buf.clone(),
15992 palette_uv: palette_uv_bufs.clone(),
15993 };
15994 if palette_y.is_some() || palette_uv.is_some() {
15995 hit!(PALETTE_SPLIT_TX_HITS);
15996 }
15997 decode_rect_split(
15998 dec,
15999 cdfs,
16000 neighbours,
16001 (mi_r, mi_c),
16002 bw,
16003 bh,
16004 tx_w,
16005 tx_h,
16006 &modes,
16007 y,
16008 u,
16009 v,
16010 base_q_idx,
16011 false,
16012 fctx,
16013 )?;
16014 record_strip_palette(
16015 neighbours,
16016 pal_at,
16017 bw,
16018 bh,
16019 pal_y_size,
16020 pal_y_colors,
16021 pal_uv_size,
16022 pal_uv_colors,
16023 );
16024 if bw > bh {
16025 hit!(RECT4_32_HORZ_HITS);
16026 } else {
16027 hit!(RECT4_32_VERT_HITS);
16028 }
16029 if !skip {
16030 hit!(RECT4_COEFF_HITS);
16031 }
16032 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16033 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16034 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16035 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16036 // transform size in both TXFM_CONTEXT bands. Without it the next block
16037 // reads the row's stale value.
16038 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
16039 return Ok((mode, uv_predict_mode));
16040 }
16041 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
16042 // that is 8 px tall, so each strip stamps every cell it touches and the
16043 // LAST strip wins -- which is the right answer for the block below/right
16044 // of the 32x32, the only reader outside it. Written after this strip's
16045 // own context read above, never before.
16046 for cell in 0..bw.div_ceil(SUB) {
16047 neighbours.above_mode[c + cell] = mode;
16048 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
16049 neighbours.above_side[c + cell] = bw;
16050 }
16051 for cell in 0..bh.div_ceil(SUB) {
16052 neighbours.left_mode[r + cell] = mode;
16053 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
16054 neighbours.left_side[r + cell] = bh;
16055 }
16056 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
16057 // [`decode_leaf_rect`] does (the split arm above records these through
16058 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
16059 // `sub8_mode_row` holding the previous block, and the next 32x32's
16060 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
16061 // fixture).
16062 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
16063 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
16064 let (px, py) = (mi_c * MI, mi_r * MI);
16065 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
16066 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
16067 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16068 // lane-av1-444: the strip's chroma shape follows the subsampling.
16069 // 4:2:0 codes 16x4/4x16 (`TxbSet::Chroma8`); 4:4:4 codes the strip
16070 // itself, 32x8/8x32 (`get_txsize_entropy_ctx(TX_32X8)` =
16071 // `(wide_log2 + high_log2 + 1) >> 1` = the 16x16 set,
16072 // `TxbSet::Chroma16`). The caller set is closed -- this reader only
16073 // ever sees 32x8 / 8x32 luma and the sequence header admits ss 0/0
16074 // and 1/1 only -- so the table is exhaustive.
16075 let chroma422_rect32 = (chroma_w, chroma_h) == (4, 32) && ss_x(fctx) == 1 && ss_y(fctx) == 0;
16076 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
16077 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
16078 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
16079 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8[..]),
16080 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32[..]),
16081 // lane-av1-422: a 4:2:2 1:4 strip halves only the width, so the
16082 // landscape leaves (32x8, 16x4 luma) code their chroma as the RECT
16083 // (16,8)/(8,4) -- the same TxbSet/scan pair the (16,8)/(8,4) rows of
16084 // [`decode_rect_split`]'s chroma table use.
16085 // lane-av1-422p: the PORTRAIT leaf occurs too -- the pinned
16086 // fixture's frame 2 carries an 8x32 strip at ss(1,0), whose (4, 32)
16087 // chroma block `ss_size_lookup[BLOCK_8X32][1][0]` marks
16088 // BLOCK_INVALID (255, enums.h). BLOCK_INVALID does not mean
16089 // "uncodable": `av1_get_tx_size` reads `max_txsize_rect_lookup[255]`
16090 // OUT OF BOUNDS there, the byte at +255 in the pinned Release oracle
16091 // is 0x05 = TX_4X8 (the `decode_token_recon_block` copy at
16092 // 0xc0d030, objdump-measured), and `av1_get_adjusted_tx_size` has no
16093 // TX_4X8 case. libaom HAS the transform, so the shape CHUNKS (the
16094 // `chroma422_rect32` arm below) into FOUR stacked TX_4X8 units per
16095 // plane (`tx_size_high_unit[TX_4X8] = 2`: blk_row 0, 2, 4, 6)
16096 // instead of refusing; no coefficient-table row is added, because
16097 // BLOCK_4X32 is not a table libaom has. 4:2:0 and 4:4:4 never land
16098 // here (their 8x32 strips read (4, 16) and (8, 32)), so the row is
16099 // 4:2:2-only.
16100 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8[..]),
16101 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
16102 // lane-av1-422p: the units' own set/scan -- the whole-rect read
16103 // below never sees this row, the `chroma422_rect32` arm chunks
16104 // first. Anything else is still a named-lane gap.
16105 (4, 32) if ss_x(fctx) == 1 && ss_y(fctx) == 0 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
16106 _ => unreachable!("decode_block_rect4 chroma shape set is closed: {chroma_w}x{chroma_h}"),
16107 };
16108 let luma_scan: &[u16] = if bw > bh { &SCAN_32X8 } else { &SCAN_8X32 };
16109 let (luma_levels, u_levels, v_levels) = if skip {
16110 (
16111 vec![0i32; bw * bh],
16112 vec![0i32; chroma_w * chroma_h],
16113 vec![0i32; chroma_w * chroma_h],
16114 )
16115 } else if chroma422_rect32 {
16116 // lane-av1-422p: the (4, 32) plane as FOUR TX_4X8 units per plane,
16117 // plane-major (every U unit, then every V) -- the walk the pinned
16118 // oracle's `decode_token_recon_block` makes for the BLOCK_INVALID
16119 // plane block: TX_4X8, so stepr = `tx_size_high_unit[TX_4X8]` = 2
16120 // 4-px rows and stepc = 1, unit rows at chroma y 0, 8, 16, 24.
16121 // Luma is the same single TX_8X32 rect the general arm reads.
16122 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16123 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
16124 let (luma_levels, luma_tx_type) = read_coeffs_rect(
16125 dec,
16126 &mut luma_coding,
16127 luma_scan,
16128 bw,
16129 bh,
16130 0,
16131 dc_sign_ctx(around[0].2),
16132 TxType::DctDct,
16133 0,
16134 )?;
16135 hit!(RECT4_COEFF_HITS);
16136 let luma_residual = dequant_and_inverse_typed_wh(
16137 &luma_levels,
16138 bw,
16139 bh,
16140 crate::decode::bit_depth(fctx),
16141 block_q_idx(fctx),
16142 plane_q_delta(0, fctx).0,
16143 plane_q_delta(0, fctx).1,
16144 luma_tx_type,
16145 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16146 );
16147 if let Some(b) = &palette_y_buf {
16148 set_palette_pred(b.clone(), fctx);
16149 }
16150 push_intra_rect(
16151 0,
16152 px,
16153 py,
16154 bw,
16155 bh,
16156 mode,
16157 angle_delta_y,
16158 reach,
16159 &luma_residual,
16160 None,
16161 filter_intra,
16162 smooth_neighbor,
16163 fctx,
16164 );
16165 // CfL parameters are computed ONCE per block over the strip's luma
16166 // (`are_parameters_computed`) and shared by all four units, as in
16167 // every other chunk arm.
16168 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16169 let mut unit_grids: Vec<((usize, usize), usize, Grid)> = Vec::new();
16170 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
16171 for unit_row in 0..4usize {
16172 let unit_mi = (mi_r + unit_row * 2, mi_c);
16173 let unit_reach = tu_reach_rect(
16174 bw,
16175 bh,
16176 0,
16177 unit_row * 8,
16178 8,
16179 8,
16180 reach,
16181 px,
16182 py,
16183 y.width,
16184 y.height,
16185 fctx,
16186 );
16187 if let Some((ub, vb)) = &palette_uv_bufs {
16188 let pbuf = if plane == 1 { ub } else { vb };
16189 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
16190 }
16191 // Each unit is read and recorded IMMEDIATELY: unit row 0's
16192 // `txb_skip_ctx` still sees the real above/left neighbour
16193 // states, a lower unit sees this block's own upper unit's
16194 // (libaom's per-unit `set_entropy_context`), and the lower
16195 // unit predicts off the upper one's reconstructed samples.
16196 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
16197 let unit_grid = read_rect_chroma_unit(
16198 dec,
16199 cdfs,
16200 TxbSet::ChromaRect8x4,
16201 &SCAN_4X8,
16202 4,
16203 8,
16204 plane,
16205 chroma_around[plane],
16206 uv_predict_mode,
16207 angle_delta_uv,
16208 unit_reach,
16209 buf,
16210 cpx,
16211 cpy + unit_row * 8,
16212 base_q_idx,
16213 // `get_txb_ctx_general`'s chroma branch
16214 // (txb_common.h): plane_bsize is BLOCK_INVALID (255)
16215 // here, `num_pels_log2_lookup[255]` = 255 (the +255
16216 // byte of the decodetxb copy at 0xc0de70,
16217 // objdump-measured) exceeds `BLOCK_4X8`'s 5, so the
16218 // ctx_offset is 10 -- the port's offset-7-first
16219 // `txb_skip_chroma_8` stores the offset-10 rows at
16220 // rows 3..6, hence +3.
16221 Some(3),
16222 alpha
16223 .zip(ac)
16224 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16225 smooth_neighbor_uv,
16226 fctx,
16227 )?;
16228 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
16229 unit_grids.push((unit_mi, plane, unit_grid));
16230 }
16231 }
16232 // The whole-block stamp rewrites the chroma cells ONE state wide,
16233 // which would erase the unit boundary the next block reads (class
16234 // `override-slot-on-one-arm`), so it carries zero chroma grids and
16235 // the per-unit writes replay after it. Its luma cells and side
16236 // spans are this arm's own bookkeeping.
16237 let zero_chroma = vec![0i32; chroma_w * chroma_h];
16238 neighbours.record_mi_rect(
16239 (mi_r, mi_c),
16240 bw,
16241 bh,
16242 &[&luma_levels[..], &zero_chroma[..], &zero_chroma[..]],
16243 );
16244 for (unit_mi, plane, grid) in &unit_grids {
16245 neighbours.record_mi_chroma(*unit_mi, 8, 8, *plane, grid);
16246 }
16247 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16248 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16249 record_strip_palette(
16250 neighbours,
16251 pal_at,
16252 bw,
16253 bh,
16254 pal_y_size,
16255 pal_y_colors,
16256 pal_uv_size,
16257 pal_uv_colors,
16258 );
16259 if bw > bh {
16260 hit!(RECT4_32_HORZ_HITS);
16261 } else {
16262 hit!(RECT4_32_VERT_HITS);
16263 }
16264 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16265 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16266 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16267 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16268 // transform size in both TXFM_CONTEXT bands. Without it the next block
16269 // reads the row's stale value.
16270 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16271 return Ok((mode, uv_predict_mode));
16272 } else {
16273 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16274 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
16275 let (luma_levels, luma_tx_type) = read_coeffs_rect(
16276 dec,
16277 &mut luma_coding,
16278 luma_scan,
16279 bw,
16280 bh,
16281 0,
16282 dc_sign_ctx(around[0].2),
16283 TxType::DctDct,
16284 0,
16285 )?;
16286 let mut planes = Vec::with_capacity(2);
16287 for plane in 1..3 {
16288 // `av1_get_tx_type` (`blockd.h:1278`): the mode-indexed type
16289 // stands only while it is a member of this tx size's set; a
16290 // 32x8/8x32 chroma transform (4:4:4) squares up to TX_32X32,
16291 // whose intra set is `EXT_TX_SET_DCTONLY` -- every ADST clamps
16292 // to DCT_DCT there, and ADST is undefined at widths above 16.
16293 let default_tx = if chroma_w.max(chroma_h) >= 32 {
16294 TxType::DctDct
16295 } else {
16296 default_intra_tx_type(uv_predict_mode as u8)
16297 };
16298 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
16299 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
16300 let (levels, tx_type) = read_chroma_coeffs_rect(
16301 dec,
16302 &mut coding,
16303 chroma_scan,
16304 chroma_w,
16305 chroma_h,
16306 skip_ctx,
16307 dc_sign_ctx(around[plane].2),
16308 default_tx,
16309 fctx,
16310 plane,
16311 )?;
16312 planes.push((levels, tx_type));
16313 }
16314 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
16315 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
16316 hit!(RECT4_COEFF_HITS);
16317 let luma_residual = dequant_and_inverse_typed_wh(
16318 &luma_levels,
16319 bw,
16320 bh,
16321 crate::decode::bit_depth(fctx),
16322 block_q_idx(fctx),
16323 plane_q_delta(0, fctx).0,
16324 plane_q_delta(0, fctx).1,
16325 luma_tx_type,
16326 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16327 );
16328 if let Some(b) = &palette_y_buf {
16329 set_palette_pred(b.clone(), fctx);
16330 }
16331 push_intra_rect(
16332 0,
16333 px,
16334 py,
16335 bw,
16336 bh,
16337 mode,
16338 angle_delta_y,
16339 reach,
16340 &luma_residual,
16341 None,
16342 filter_intra,
16343 smooth_neighbor,
16344 fctx,
16345 );
16346 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16347 for (plane, _buf, levels, tx_type) in [
16348 (1usize, &mut *u, &u_levels, u_tx_type),
16349 (2, &mut *v, &v_levels, v_tx_type),
16350 ] {
16351 let residual = dequant_and_inverse_typed_wh(
16352 levels,
16353 chroma_w,
16354 chroma_h,
16355 crate::decode::bit_depth(fctx),
16356 block_q_idx(fctx),
16357 plane_q_delta(plane, fctx).0,
16358 plane_q_delta(plane, fctx).1,
16359 tx_type,
16360 block_iqmatrix(fctx, plane, chroma_w, chroma_h, tx_type),
16361 );
16362 if let Some((ub, vb)) = &palette_uv_bufs {
16363 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
16364 }
16365 push_intra_rect(
16366 plane,
16367 cpx,
16368 cpy,
16369 chroma_w,
16370 chroma_h,
16371 uv_predict_mode,
16372 angle_delta_uv,
16373 reach,
16374 &residual,
16375 alpha
16376 .zip(ac)
16377 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16378 None,
16379 smooth_neighbor_uv,
16380 fctx,
16381 );
16382 }
16383 neighbours.record_mi_rect(
16384 (mi_r, mi_c),
16385 bw,
16386 bh,
16387 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16388 );
16389 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16390 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16391 record_strip_palette(
16392 neighbours,
16393 pal_at,
16394 bw,
16395 bh,
16396 pal_y_size,
16397 pal_y_colors,
16398 pal_uv_size,
16399 pal_uv_colors,
16400 );
16401 if bw > bh {
16402 hit!(RECT4_32_HORZ_HITS);
16403 } else {
16404 hit!(RECT4_32_VERT_HITS);
16405 }
16406 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16407 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16408 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16409 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16410 // transform size in both TXFM_CONTEXT bands. Without it the next block
16411 // reads the row's stale value.
16412 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16413 return Ok((mode, uv_predict_mode));
16414 };
16415 if let Some(b) = &palette_y_buf {
16416 set_palette_pred(b.clone(), fctx);
16417 }
16418 push_intra_rect(
16419 0,
16420 px,
16421 py,
16422 bw,
16423 bh,
16424 mode,
16425 angle_delta_y,
16426 reach,
16427 &luma_levels,
16428 None,
16429 filter_intra,
16430 smooth_neighbor,
16431 fctx,
16432 );
16433 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16434 if chroma422_rect32 {
16435 // lane-av1-422p: `predict_and_reconstruct_intra_block` (decodeframe.c
16436 // ~1000) predicts EVERY unit regardless of `skip_txfm`, so the skip
16437 // arm walks the same four TX_4X8 units per plane -- the lower unit
16438 // predicts off the upper one's predicted samples. No coefficients
16439 // are coded; the tail's whole-block zero stamp below is the state
16440 // libaom's `set_entropy_context` leaves.
16441 for (plane, _buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
16442 for unit_row in 0..4usize {
16443 let unit_reach = tu_reach_rect(
16444 bw,
16445 bh,
16446 0,
16447 unit_row * 8,
16448 8,
16449 8,
16450 reach,
16451 px,
16452 py,
16453 y.width,
16454 y.height,
16455 fctx,
16456 );
16457 if let Some((ub, vb)) = &palette_uv_bufs {
16458 let pbuf = if plane == 1 { ub } else { vb };
16459 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
16460 }
16461 push_intra_rect(
16462 plane,
16463 cpx,
16464 cpy + unit_row * 8,
16465 4,
16466 8,
16467 uv_predict_mode,
16468 angle_delta_uv,
16469 unit_reach,
16470 &ZERO_RESIDUAL[..4 * 8],
16471 alpha
16472 .zip(ac)
16473 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16474 None,
16475 smooth_neighbor_uv,
16476 fctx,
16477 );
16478 }
16479 }
16480 } else {
16481 if let Some((ub, _)) = &palette_uv_bufs {
16482 set_palette_pred(ub.clone(), fctx);
16483 }
16484 push_intra_rect(
16485 1,
16486 cpx,
16487 cpy,
16488 chroma_w,
16489 chroma_h,
16490 uv_predict_mode,
16491 angle_delta_uv,
16492 reach,
16493 &u_levels,
16494 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16495 None,
16496 smooth_neighbor_uv,
16497 fctx,
16498 );
16499 if let Some((_, vb)) = &palette_uv_bufs {
16500 set_palette_pred(vb.clone(), fctx);
16501 }
16502 push_intra_rect(
16503 2,
16504 cpx,
16505 cpy,
16506 chroma_w,
16507 chroma_h,
16508 uv_predict_mode,
16509 angle_delta_uv,
16510 reach,
16511 &v_levels,
16512 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16513 None,
16514 smooth_neighbor_uv,
16515 fctx,
16516 );
16517 }
16518 neighbours.record_mi_rect(
16519 (mi_r, mi_c),
16520 bw,
16521 bh,
16522 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16523 );
16524 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16525 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16526 record_strip_palette(
16527 neighbours,
16528 pal_at,
16529 bw,
16530 bh,
16531 pal_y_size,
16532 pal_y_colors,
16533 pal_uv_size,
16534 pal_uv_colors,
16535 );
16536 if bw > bh {
16537 hit!(RECT4_32_HORZ_HITS);
16538 } else {
16539 hit!(RECT4_32_VERT_HITS);
16540 }
16541 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16542 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16543 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16544 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16545 // transform size in both TXFM_CONTEXT bands. Without it the next block
16546 // reads the row's stale value.
16547 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16548 Ok((mode, uv_predict_mode))
16549}
16550
16551/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
16552/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
16553/// down, and the first shape here whose luma block is a single mi row (or
16554/// column).
16555///
16556/// What is new at this size is CHROMA. `is_chroma_reference`
16557/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
16558/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
16559/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
16560/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
16561/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
16562/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
16563/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
16564///
16565/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
16566/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
16567/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
16568/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
16569/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
16570/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
16571/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
16572/// shape's own CDF row.
16573///
16574/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
16575/// refuses by name rather than guess-decode.
16576#[allow(clippy::too_many_arguments)]
16577fn decode_rect4_16(
16578 dec: &mut SymbolDecoder,
16579 cdfs: &mut Cdfs,
16580 neighbours: &mut Neighbours,
16581 at16: (usize, usize),
16582 horz: bool,
16583 y: &mut PlaneBuf<'static>,
16584 u: &mut PlaneBuf<'static>,
16585 v: &mut PlaneBuf<'static>,
16586 enable_filter_intra: bool,
16587 allow_screen_content_tools: bool,
16588 base_q_idx: u8,
16589 tx_select: bool,
16590 reduced_tx_set: bool,
16591 fctx: &crate::decode::FrameCtx,
16592) -> Result<()> {
16593 let (r, c) = at16;
16594 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
16595 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
16596 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
16597 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
16598 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
16599 let mut prev: Option<((usize, usize), usize)> = None;
16600 let mut last_mode = DC_PRED;
16601 let mut last_uv_mode = DC_PRED;
16602 for i in 0..4usize {
16603 let lmi = if horz {
16604 (mi_row0 + i, mi_col0)
16605 } else {
16606 (mi_row0, mi_col0 + i)
16607 };
16608 // lane-av1-444: at 4:4:4 every strip is its own chroma reference
16609 // (no mi-parity test at ss 0/0, and the strip's own chroma block is
16610 // already >= 4x4) -- there is no 4:2:0 pair to close.
16611 // lane-av1-422o: the parity rule is per axis, straight out of
16612 // `is_chroma_reference`: a HORZ 16x4 strip (1 mi tall) keeps the
16613 // `ss_y == 0 -> every strip a reference` row rule, but a VERT 4x16
16614 // strip (1 mi wide) keeps the COLUMN clause `(mi_col & 1) || !(bw &
16615 // 1) || !ss_x`, which with bw == 1 mi reduces to `mi_col odd` for
16616 // every ss_x == 1 format -- the ODD strip closes the pair and reads
16617 // the chroma, exactly like 4:2:0. (VERT_4 partitions start on an
16618 // even mi_col, so `i % 2 == 1` is that clause.)
16619 let has_chroma = i % 2 == 1 || (horz && ss_y(fctx) == 0) || (!horz && ss_x(fctx) == 0);
16620 let (mode, uv, _tx) = decode_rect4_16_strip(
16621 dec,
16622 cdfs,
16623 neighbours,
16624 lmi,
16625 horz,
16626 has_chroma,
16627 prev,
16628 y,
16629 u,
16630 v,
16631 enable_filter_intra,
16632 allow_screen_content_tools,
16633 base_q_idx,
16634 tx_select,
16635 reduced_tx_set,
16636 fctx,
16637 )?;
16638 if let Some(m) = uv {
16639 last_uv_mode = m;
16640 }
16641 last_mode = mode;
16642 prev = Some((lmi, mode));
16643 }
16644 // The coarse 16-px cell holds one entry for the whole 16x16: the last
16645 // strip is what a block below (right) sees through it, the mi-exact maps
16646 // above answering everything finer.
16647 neighbours.above_mode[c] = last_mode;
16648 neighbours.left_mode[r] = last_mode;
16649 neighbours.above_uv_mode[c] = last_uv_mode;
16650 neighbours.left_uv_mode[r] = last_uv_mode;
16651 neighbours.above_side[c] = bw;
16652 neighbours.left_side[r] = bh;
16653 Ok(())
16654}
16655
16656/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
16657/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
16658/// block path can decode a SINGLE intra strip of a partition whose other
16659/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
16660/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
16661/// every strip publishes its own mi-exact mode). Returns
16662/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
16663/// Intrabc reconstruction for a rect strip that OWNS its chroma
16664/// (`bw/2 x bh/2` at the strip origin). 16x4/4x16 is not this shape -- that
16665/// pair goes through [`decode_rect4_16_intrabc`].
16666///
16667/// This is the same control flow as the unmerged lane's `decode_intrabc_rect`
16668/// (predict once, then one residual per transform unit on the INTER sets,
16669/// chroma inherits luma's `tx_type`), written against the helpers that exist
16670/// on this tree so a 2:1 strip no longer hides the 16x4 pair witness. The
16671/// merge with lane-av1-intrabc should keep one of the two bodies; the call
16672/// shape is the same.
16673#[allow(clippy::too_many_arguments)]
16674fn decode_intrabc_owned_rect(
16675 dec: &mut SymbolDecoder,
16676 cdfs: &mut Cdfs,
16677 neighbours: &mut Neighbours,
16678 (mi_r, mi_c): (usize, usize),
16679 (bw, bh): (usize, usize),
16680 skip: bool,
16681 (dv_row, dv_col): (i32, i32),
16682 y: &mut PlaneBuf<'static>,
16683 u: &mut PlaneBuf<'static>,
16684 v: &mut PlaneBuf<'static>,
16685 base_q_idx: u8,
16686 tx_select: bool,
16687 reduced_tx_set: bool,
16688 fctx: &crate::decode::FrameCtx,
16689) -> Result<()> {
16690 let _ = base_q_idx;
16691 let (px, py) = (mi_c * MI, mi_r * MI);
16692 let (cw, ch) = (bw / 2, bh / 2);
16693 let side = bw.max(bh);
16694 let cside = cw.max(ch);
16695 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
16696 let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get);
16697 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
16698 // `read_block_tx_size_rect` keys on this cell. A key frame forces it
16699 // false; the real bit is the caller's `tx_select`. Restored before return.
16700 fctx.tx_select_inter.with(|c| c.set(tx_select));
16701 let restore = ReducedTxRestore {
16702 fctx,
16703 saved_reduced,
16704 saved_tx,
16705 };
16706
16707 flush_recon(fctx, y, u, v);
16708 let pred_y = predict_intrabc_window(y, px, py, bw, bh, dv_col, dv_row, true, side, fctx);
16709 let pred_u = predict_intrabc_window(
16710 u,
16711 px / 2,
16712 py / 2,
16713 cw,
16714 ch,
16715 dv_col,
16716 dv_row,
16717 false,
16718 cside,
16719 fctx,
16720 );
16721 let pred_v = predict_intrabc_window(
16722 v,
16723 px / 2,
16724 py / 2,
16725 cw,
16726 ch,
16727 dv_col,
16728 dv_row,
16729 false,
16730 cside,
16731 fctx,
16732 );
16733
16734 let mi_cols = 2 * y.true_width.div_ceil(8);
16735 let mi_rows = 2 * y.true_height.div_ceil(8);
16736 let leaves = read_block_tx_size_rect(
16737 dec,
16738 cdfs,
16739 neighbours,
16740 (mi_r, mi_c),
16741 (bw, bh),
16742 (mi_cols, mi_rows),
16743 skip,
16744 fctx,
16745 )?;
16746 let mut luma_tx_type = TxType::DctDct;
16747 let luma_grid;
16748 let u_grid;
16749 let v_grid;
16750 if skip {
16751 // `reconstruct_mc_rect` indexes the residual at the square stride.
16752 // `bw * bh` underruns on a VERT strip (8x16: stride 16, 16 rows, index 136).
16753 push_mc_rect(
16754 0,
16755 px,
16756 py,
16757 side,
16758 bw,
16759 bh,
16760 Pred::Inline(&pred_y, side),
16761 &ZERO_RESIDUAL[..side * bh],
16762 fctx,
16763 );
16764 push_mc_rect(
16765 1,
16766 px / 2,
16767 py / 2,
16768 cside,
16769 cw,
16770 ch,
16771 Pred::Inline(&pred_u, cside),
16772 &ZERO_RESIDUAL[..cside * ch],
16773 fctx,
16774 );
16775 push_mc_rect(
16776 2,
16777 px / 2,
16778 py / 2,
16779 cside,
16780 cw,
16781 ch,
16782 Pred::Inline(&pred_v, cside),
16783 &ZERO_RESIDUAL[..cside * ch],
16784 fctx,
16785 );
16786 if let Some(ls) = leaves.as_ref() {
16787 // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`,
16788 // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its
16789 // whole entropy-band footprint. The non-skip arm below writes
16790 // those bands per transform unit and the tail's
16791 // `record_split_luma_rect_mi` writes chroma only, so without
16792 // this walk a skipped strip whose `leaves` resolved (every
16793 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
16794 // returns the 4x4 grid before it looks at `skip`) leaked the
16795 // PREVIOUS occupant's luma bands into the next block's
16796 // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped
16797 // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128
16798 // stream left a stale 7 in left[48] and mi(48,68)'s first
16799 // transform unit read `txb_skip_ctx` 3 where aomdec reads 1).
16800 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
16801 for &(row, col, tw, th) in ls {
16802 neighbours.record_mi_luma_rect(
16803 (mi_r + row, mi_c + col),
16804 tw,
16805 th,
16806 &ZERO_RESIDUAL[..tw * th],
16807 );
16808 }
16809 }
16810 luma_grid = Grid::Zero(side * side);
16811 u_grid = Grid::Zero(cside * cside);
16812 v_grid = Grid::Zero(cside * cside);
16813 } else if let Some(ls) = leaves.as_ref() {
16814 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
16815 let tu_mi = (mi_r + row, mi_c + col);
16816 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
16817 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
16818 let (g, tt) = if tw == th {
16819 read_inter_plane(
16820 dec,
16821 cdfs,
16822 inter_txbset_for(tw, reduced_tx_set),
16823 &default_scan(tw.min(32)),
16824 0,
16825 neighbours.around_mi(tu_mi, tw)[0],
16826 0,
16827 y,
16828 tu_px,
16829 tu_py,
16830 tw,
16831 base_q_idx,
16832 tu_pred,
16833 None,
16834 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
16835 fctx,
16836 )?
16837 } else {
16838 read_inter_plane_rect(
16839 dec,
16840 cdfs,
16841 rect_inter_luma_set(tw, th, fctx)?,
16842 (tw, th),
16843 side,
16844 0,
16845 neighbours.around_mi_rect(tu_mi, tw, th)[0],
16846 0,
16847 y,
16848 tu_px,
16849 tu_py,
16850 tu_pred,
16851 None,
16852 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
16853 fctx,
16854 )?
16855 };
16856 if idx == 0 {
16857 luma_tx_type = tt;
16858 }
16859 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
16860 if tw != th {
16861 neighbours.fill_lf_grid_leaf_luma(
16862 (tu_mi.0, tu_mi.1),
16863 tw / MI,
16864 th / MI,
16865 tw as u8,
16866 th as u8,
16867 );
16868 }
16869 }
16870 luma_grid = Grid::Zero(side * side);
16871 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16872 let (ug, _) = read_inter_plane_rect(
16873 dec,
16874 cdfs,
16875 rect_inter_chroma_set(cw, ch)?,
16876 (cw, ch),
16877 cside,
16878 1,
16879 around[1],
16880 0,
16881 u,
16882 px / 2,
16883 py / 2,
16884 Pred::Inline(&pred_u, cside),
16885 Some(luma_tx_type),
16886 None,
16887 fctx,
16888 )?;
16889 let (vg, _) = read_inter_plane_rect(
16890 dec,
16891 cdfs,
16892 rect_inter_chroma_set(cw, ch)?,
16893 (cw, ch),
16894 cside,
16895 2,
16896 around[2],
16897 0,
16898 v,
16899 px / 2,
16900 py / 2,
16901 Pred::Inline(&pred_v, cside),
16902 Some(luma_tx_type),
16903 None,
16904 fctx,
16905 )?;
16906 u_grid = ug;
16907 v_grid = vg;
16908 } else {
16909 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16910 let (g, tt) = read_inter_plane_rect(
16911 dec,
16912 cdfs,
16913 rect_inter_luma_set(bw, bh, fctx)?,
16914 (bw, bh),
16915 side,
16916 0,
16917 around[0],
16918 0,
16919 y,
16920 px,
16921 py,
16922 Pred::Inline(&pred_y, side),
16923 None,
16924 None,
16925 fctx,
16926 )?;
16927 luma_tx_type = tt;
16928 luma_grid = g;
16929 let (ug, _) = read_inter_plane_rect(
16930 dec,
16931 cdfs,
16932 rect_inter_chroma_set(cw, ch)?,
16933 (cw, ch),
16934 cside,
16935 1,
16936 around[1],
16937 0,
16938 u,
16939 px / 2,
16940 py / 2,
16941 Pred::Inline(&pred_u, cside),
16942 Some(luma_tx_type),
16943 None,
16944 fctx,
16945 )?;
16946 let (vg, _) = read_inter_plane_rect(
16947 dec,
16948 cdfs,
16949 rect_inter_chroma_set(cw, ch)?,
16950 (cw, ch),
16951 cside,
16952 2,
16953 around[2],
16954 0,
16955 v,
16956 px / 2,
16957 py / 2,
16958 Pred::Inline(&pred_v, cside),
16959 Some(luma_tx_type),
16960 None,
16961 fctx,
16962 )?;
16963 u_grid = ug;
16964 v_grid = vg;
16965 }
16966 drop(restore);
16967 if leaves.is_some() {
16968 neighbours.record_split_luma_rect_mi(
16969 (mi_r, mi_c),
16970 bw,
16971 bh,
16972 DC_PRED,
16973 DC_PRED,
16974 [&u_grid, &v_grid],
16975 );
16976 } else {
16977 neighbours.record_rect_mi(
16978 (mi_r, mi_c),
16979 bw,
16980 bh,
16981 DC_PRED,
16982 DC_PRED,
16983 &[&luma_grid, &u_grid, &v_grid],
16984 );
16985 }
16986 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
16987 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
16988 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
16989 neighbours.fill_lf_grid_rect(
16990 (mi_r, mi_c),
16991 bw / MI,
16992 bh / MI,
16993 bw.min(64) as u8,
16994 bh.min(64) as u8,
16995 0,
16996 fctx,
16997 );
16998 record_intrabc_mi_rect(
16999 mi_r,
17000 mi_c,
17001 bw / MI,
17002 bh / MI,
17003 Some((dv_row, dv_col)),
17004 neighbours,
17005 fctx,
17006 );
17007 let _ = luma_tx_type;
17008 Ok(())
17009}
17010
17011fn predict_intrabc_window(
17012 plane: &PlaneBuf<'_>,
17013 px: usize,
17014 py: usize,
17015 w: usize,
17016 h: usize,
17017 dv_col: i32,
17018 dv_row: i32,
17019 luma: bool,
17020 stride: usize,
17021 fctx: &crate::decode::FrameCtx,
17022) -> Vec<u16> {
17023 let mut dense = vec![0u16; w * h];
17024 mc::predict_with_filter(
17025 &plane.data,
17026 plane.width,
17027 plane.true_width,
17028 plane.true_height,
17029 mv_to_q4(px, dv_col, if luma { 0 } else { ss_x(fctx) }),
17030 mv_to_q4(py, dv_row, if luma { 0 } else { ss_y(fctx) }),
17031 w,
17032 h,
17033 mc::InterpFilterKind::Bilinear,
17034 &mut dense,
17035 fctx,
17036 );
17037 let mut laid = vec![0u16; stride * stride];
17038 for row in 0..h {
17039 laid[row * stride..][..w].copy_from_slice(&dense[row * w..][..w]);
17040 }
17041 laid
17042}
17043
17044struct ReducedTxRestore<'a> {
17045 fctx: &'a crate::decode::FrameCtx,
17046 saved_reduced: bool,
17047 saved_tx: bool,
17048}
17049impl Drop for ReducedTxRestore<'_> {
17050 fn drop(&mut self) {
17051 self.fctx
17052 .reduced_tx_set_inter
17053 .with(|c| c.set(self.saved_reduced));
17054 self.fctx.tx_select_inter.with(|c| c.set(self.saved_tx));
17055 }
17056}
17057
17058/// Reconstruction of one intrabc 16x4 / 4x16 strip (lane-av1-rect14).
17059///
17060/// A 1:4 strip is a PAIR. Both children share one chroma block, and only the
17061/// odd-mi member codes it (`is_chroma_reference`, `av1_common_int.h:1454`:
17062/// the bottom strip of a `HORZ_4`, the right strip of a `VERT_4`). The chroma
17063/// plane block is `ss_size_lookup[BLOCK_16X4][1][1] == BLOCK_8X4` (and
17064/// `BLOCK_4X8` for `VERT_4`) at the PAIR origin -- `setup_pred_plane`'s
17065/// `mi_row -= 1` when the block is one mi tall on an odd row. Luma is this
17066/// strip's own footprint, copied from this strip's DV. The block is
17067/// `is_inter_block`, so the residual uses the INTER sets and chroma inherits
17068/// the luma unit's coded `tx_type`.
17069///
17070/// Not [`decode_intrabc_rect`]: that helper (lane-av1-intrabc, not on this
17071/// tree) predicts chroma at `bw/2 x bh/2` of the strip itself. At 16x4 that
17072/// is an 8x2 half-pair at the odd strip -- wrong size, wrong origin, and it
17073/// would code chroma on every strip.
17074#[allow(clippy::too_many_arguments)]
17075fn decode_rect4_16_intrabc(
17076 dec: &mut SymbolDecoder,
17077 cdfs: &mut Cdfs,
17078 neighbours: &mut Neighbours,
17079 lmi: (usize, usize),
17080 horz: bool,
17081 has_chroma: bool,
17082 skip: bool,
17083 (dv_row, dv_col): (i32, i32),
17084 y: &mut PlaneBuf<'static>,
17085 u: &mut PlaneBuf<'static>,
17086 v: &mut PlaneBuf<'static>,
17087 base_q_idx: u8,
17088 tx_select: bool,
17089 reduced_tx_set: bool,
17090 fctx: &crate::decode::FrameCtx,
17091) -> Result<(usize, Option<usize>, (usize, usize))> {
17092 let _ = base_q_idx;
17093 hit!(RECT4_16_INTRABC_HITS);
17094 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
17095 let (mi_w, mi_h) = (bw / MI, bh / MI);
17096 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
17097 let side = bw.max(bh);
17098 // `rect_inter_luma_set` reads the frame cell. A key frame's tile decoder
17099 // publishes `reduced_tx_set` into it; set it here too so a caller that
17100 // passed the bit explicitly cannot disagree with the set we read.
17101 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
17102 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
17103 let restored = scopeguard_reduced(fctx, saved_reduced);
17104
17105 flush_recon(fctx, y, u, v);
17106 let mut pred_y_dense = vec![0u16; bw * bh];
17107 mc::predict_with_filter(
17108 &y.data,
17109 y.width,
17110 y.true_width,
17111 y.true_height,
17112 mv_to_q4(px, dv_col, 0),
17113 mv_to_q4(py, dv_row, 0),
17114 bw,
17115 bh,
17116 mc::InterpFilterKind::Bilinear,
17117 &mut pred_y_dense,
17118 fctx,
17119 );
17120 let mut pred_y = vec![0u16; side * side];
17121 for row in 0..bh {
17122 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
17123 }
17124
17125 // lane-av1444rect r2 (the class this lane named, second instance): the
17126 // pair geometry below is the 4:2:0 one and was applied at every `ss`. At
17127 // ss (0,0) `is_chroma_reference` (av1_common_int.h:1454) is
17128 // unconditionally true -- the strip is its own chroma reference, there is
17129 // no pair, and its chroma plane block IS the strip: 16x4 (HORZ_4) / 4x16
17130 // (VERT_4) at the strip's own origin, with its coefficient context read
17131 // over that same extent. The old constants instead predicted and coded an
17132 // 8x4 block at `(lmi - 1) * MI / 2`, a quarter of the position.
17133 //
17134 // MEASURED on a `testsrc2` 640x480 `--tune-content=screen --enable-intrabc=1
17135 // --enable-palette=1 --cq-level=60 --min-partition-size=4
17136 // --max-partition-size=64 --sb-size=64 --profile=1` stream (1016 B, 17
17137 // intrabc 16x4 strips at ss (0,0)): 455240 of 921600 samples wrong, the
17138 // entropy fork at read 11750 (`decodetxb.c:158`, the chroma `txb_skip`).
17139 // `--enable-intrabc=0` at the same settings is byte-exact, and the 4:2:0
17140 // twin of the same recipe is byte-exact.
17141 //
17142 // 4:2:0 and 4:2:2 keep every constant below verbatim -- the arm is gated on
17143 // the full ss (0,0), not on a per-axis shift, so `pw / 2` and the literal
17144 // halving are untouched for both.
17145 let own444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
17146 if ss_x(fctx) == 0 && ss_y(fctx) == 0 && has_chroma {
17147 hit!(INTRABC_RECT4_OWN_CHROMA444_HITS);
17148 }
17149 let (pw, ph) = if own444 {
17150 (bw, bh)
17151 } else if horz {
17152 (16usize, 8usize)
17153 } else {
17154 (8, 16)
17155 };
17156 let (cw, ch) = if own444 { (bw, bh) } else { (pw / 2, ph / 2) };
17157 let pair_mi = if has_chroma {
17158 if own444 {
17159 lmi
17160 } else if horz {
17161 (lmi.0 - 1, lmi.1)
17162 } else {
17163 (lmi.0, lmi.1 - 1)
17164 }
17165 } else {
17166 lmi
17167 };
17168 let (cpx, cpy) = if has_chroma {
17169 if own444 {
17170 (px, py)
17171 } else {
17172 (pair_mi.1 * MI / 2, pair_mi.0 * MI / 2)
17173 }
17174 } else {
17175 (0, 0)
17176 };
17177 let cside = cw.max(ch);
17178 let (pred_u, pred_v) = if has_chroma {
17179 let mut ud = vec![0u16; cw * ch];
17180 mc::predict_with_filter(
17181 &u.data,
17182 u.width,
17183 u.true_width,
17184 u.true_height,
17185 mv_to_q4(cpx, dv_col, ss_x(fctx)),
17186 mv_to_q4(cpy, dv_row, ss_y(fctx)),
17187 cw,
17188 ch,
17189 mc::InterpFilterKind::Bilinear,
17190 &mut ud,
17191 fctx,
17192 );
17193 let mut us = vec![0u16; cside * cside];
17194 for row in 0..ch {
17195 us[row * cside..][..cw].copy_from_slice(&ud[row * cw..][..cw]);
17196 }
17197 let mut vd = vec![0u16; cw * ch];
17198 mc::predict_with_filter(
17199 &v.data,
17200 v.width,
17201 v.true_width,
17202 v.true_height,
17203 mv_to_q4(cpx, dv_col, ss_x(fctx)),
17204 mv_to_q4(cpy, dv_row, ss_y(fctx)),
17205 cw,
17206 ch,
17207 mc::InterpFilterKind::Bilinear,
17208 &mut vd,
17209 fctx,
17210 );
17211 let mut vs = vec![0u16; cside * cside];
17212 for row in 0..ch {
17213 vs[row * cside..][..cw].copy_from_slice(&vd[row * cw..][..cw]);
17214 }
17215 (us, vs)
17216 } else {
17217 (Vec::new(), Vec::new())
17218 };
17219
17220 // Key-frame `tx_select` is the parameter. `tx_select_inter` is forced
17221 // false for a key frame, so `read_block_tx_size_rect` would skip the
17222 // symbol; read it here against the parameter the intra path already uses.
17223 // A skipped intrabc block predicts the whole footprint once and codes
17224 // no residual (`decode_token_recon_block`'s inter branch). Lossless
17225 // still forces TX_4X4 when the block is coded.
17226 let leaves = if skip || (!lossless(fctx) && !tx_select) {
17227 None
17228 } else if lossless(fctx) {
17229 let mut leaves = Vec::new();
17230 for row in 0..bh / MI {
17231 for col in 0..bw / MI {
17232 leaves.push((row, col, 4usize, 4usize));
17233 }
17234 }
17235 Some(leaves)
17236 } else {
17237 let ctx = txfm_partition_ctx_rect(
17238 neighbours.above_txfm[lmi.1],
17239 neighbours.left_txfm[lmi.0],
17240 side,
17241 bw,
17242 bh,
17243 );
17244 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17245 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17246 let (rng, _) = dec.debug_state();
17247 eprintln!(
17248 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
17249 lmi.0,
17250 lmi.1,
17251 u8::from(split)
17252 );
17253 }
17254 if !split {
17255 None
17256 } else {
17257 let (sub_w, sub_h) = sub_tx_size_map(bw, bh);
17258 let mi_cols = 2 * y.true_width.div_ceil(8);
17259 let mi_rows = 2 * y.true_height.div_ceil(8);
17260 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(lmi.1));
17261 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(lmi.0));
17262 let mut out = Vec::new();
17263 for row in (0..bh / MI).step_by(sub_h / MI) {
17264 for col in (0..bw / MI).step_by(sub_w / MI) {
17265 read_var_tx_size(
17266 dec,
17267 cdfs,
17268 neighbours,
17269 lmi,
17270 side,
17271 (max_w_mi, max_h_mi),
17272 (sub_w, sub_h),
17273 1,
17274 row,
17275 col,
17276 &mut out,
17277 );
17278 }
17279 }
17280 Some(out)
17281 }
17282 };
17283 let (tx_w, tx_h) = leaves
17284 .as_ref()
17285 .and_then(|ls| ls.first())
17286 .map_or((bw, bh), |l| (l.2, l.3));
17287
17288 let mut luma_tx_type = TxType::DctDct;
17289 let luma_grid;
17290 let mut u_grid = Grid::Zero(cw * ch);
17291 let mut v_grid = Grid::Zero(cw * ch);
17292 let chroma_stamped_per_unit;
17293
17294 if skip {
17295 push_mc_rect(
17296 0,
17297 px,
17298 py,
17299 side,
17300 bw,
17301 bh,
17302 Pred::Inline(&pred_y, side),
17303 &ZERO_RESIDUAL[..side * bh],
17304 fctx,
17305 );
17306 luma_grid = Grid::Zero(bw * bh);
17307 if has_chroma {
17308 push_mc_rect(
17309 1,
17310 cpx,
17311 cpy,
17312 cside,
17313 cw,
17314 ch,
17315 Pred::Inline(&pred_u, cside),
17316 &ZERO_RESIDUAL[..cside * ch],
17317 fctx,
17318 );
17319 push_mc_rect(
17320 2,
17321 cpx,
17322 cpy,
17323 cside,
17324 cw,
17325 ch,
17326 Pred::Inline(&pred_v, cside),
17327 &ZERO_RESIDUAL[..cside * ch],
17328 fctx,
17329 );
17330 }
17331 chroma_stamped_per_unit = false;
17332 } else if let Some(ls) = leaves.as_ref() {
17333 if lossless(fctx) {
17334 for &(row, col, _tw, _th) in ls {
17335 let tu_mi = (lmi.0 + row, lmi.1 + col);
17336 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17337 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17338 let (g, _) = read_inter_plane(
17339 dec,
17340 cdfs,
17341 if reduced_tx_set {
17342 TxbSet::Luma4Inter
17343 } else {
17344 TxbSet::Luma4InterSet1
17345 },
17346 &default_scan(4),
17347 0,
17348 neighbours.around_mi(tu_mi, 4)[0],
17349 0,
17350 y,
17351 tu_px,
17352 tu_py,
17353 4,
17354 base_q_idx,
17355 tu_pred,
17356 None,
17357 Some(neighbours.luma_skip_ctx(tu_mi, 1)),
17358 fctx,
17359 )?;
17360 neighbours.record_mi_luma_rect(tu_mi, 4, 4, &g);
17361 }
17362 } else {
17363 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
17364 let tu_mi = (lmi.0 + row, lmi.1 + col);
17365 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17366 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17367 let (g, tt) = if tw == th {
17368 read_inter_plane(
17369 dec,
17370 cdfs,
17371 inter_txbset_for(tw, reduced_tx_set),
17372 &default_scan(tw.min(32)),
17373 0,
17374 neighbours.around_mi(tu_mi, tw)[0],
17375 0,
17376 y,
17377 tu_px,
17378 tu_py,
17379 tw,
17380 base_q_idx,
17381 tu_pred,
17382 None,
17383 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
17384 fctx,
17385 )?
17386 } else {
17387 read_inter_plane_rect(
17388 dec,
17389 cdfs,
17390 rect_inter_luma_set(tw, th, fctx)?,
17391 (tw, th),
17392 side,
17393 0,
17394 neighbours.around_mi_rect(tu_mi, tw, th)[0],
17395 0,
17396 y,
17397 tu_px,
17398 tu_py,
17399 tu_pred,
17400 None,
17401 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
17402 fctx,
17403 )?
17404 };
17405 if idx == 0 {
17406 luma_tx_type = tt;
17407 }
17408 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
17409 }
17410 }
17411 luma_grid = Grid::Zero(bw * bh);
17412 chroma_stamped_per_unit = has_chroma && lossless(fctx);
17413 if has_chroma && lossless(fctx) {
17414 let (mut uo, mut vo) = (Vec::new(), Vec::new());
17415 read_inter_chroma_lossless(
17416 dec,
17417 cdfs,
17418 neighbours,
17419 u,
17420 v,
17421 Pred::Inline(&pred_u, cside),
17422 Pred::Inline(&pred_v, cside),
17423 pair_mi,
17424 (cpx, cpy),
17425 (0, 0),
17426 (cw, ch),
17427 (cw, ch),
17428 cside,
17429 0,
17430 base_q_idx,
17431 &mut uo,
17432 &mut vo,
17433 fctx,
17434 )?;
17435 u_grid = if uo.is_empty() {
17436 Grid::Zero(cw * ch)
17437 } else {
17438 Grid::Own(uo)
17439 };
17440 v_grid = if vo.is_empty() {
17441 Grid::Zero(cw * ch)
17442 } else {
17443 Grid::Own(vo)
17444 };
17445 } else if has_chroma {
17446 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
17447 let (ug, _) = read_inter_plane_rect(
17448 dec,
17449 cdfs,
17450 rect_inter_chroma_set(cw, ch)?,
17451 (cw, ch),
17452 cside,
17453 1,
17454 around[1],
17455 0,
17456 u,
17457 cpx,
17458 cpy,
17459 Pred::Inline(&pred_u, cside),
17460 Some(luma_tx_type),
17461 None,
17462 fctx,
17463 )?;
17464 u_grid = ug;
17465 let (vg, _) = read_inter_plane_rect(
17466 dec,
17467 cdfs,
17468 rect_inter_chroma_set(cw, ch)?,
17469 (cw, ch),
17470 cside,
17471 2,
17472 around[2],
17473 0,
17474 v,
17475 cpx,
17476 cpy,
17477 Pred::Inline(&pred_v, cside),
17478 Some(luma_tx_type),
17479 None,
17480 fctx,
17481 )?;
17482 v_grid = vg;
17483 }
17484 } else {
17485 let around = neighbours.around_mi_rect(lmi, bw, bh);
17486 let (g, tt) = read_inter_plane_rect(
17487 dec,
17488 cdfs,
17489 rect_inter_luma_set(bw, bh, fctx)?,
17490 (bw, bh),
17491 side,
17492 0,
17493 around[0],
17494 0,
17495 y,
17496 px,
17497 py,
17498 Pred::Inline(&pred_y, side),
17499 None,
17500 None,
17501 fctx,
17502 )?;
17503 luma_tx_type = tt;
17504 luma_grid = g;
17505 chroma_stamped_per_unit = false;
17506 if has_chroma {
17507 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
17508 let (ug, _) = read_inter_plane_rect(
17509 dec,
17510 cdfs,
17511 rect_inter_chroma_set(cw, ch)?,
17512 (cw, ch),
17513 cside,
17514 1,
17515 around[1],
17516 0,
17517 u,
17518 cpx,
17519 cpy,
17520 Pred::Inline(&pred_u, cside),
17521 Some(luma_tx_type),
17522 None,
17523 fctx,
17524 )?;
17525 u_grid = ug;
17526 let (vg, _) = read_inter_plane_rect(
17527 dec,
17528 cdfs,
17529 rect_inter_chroma_set(cw, ch)?,
17530 (cw, ch),
17531 cside,
17532 2,
17533 around[2],
17534 0,
17535 v,
17536 cpx,
17537 cpy,
17538 Pred::Inline(&pred_v, cside),
17539 Some(luma_tx_type),
17540 None,
17541 fctx,
17542 )?;
17543 v_grid = vg;
17544 }
17545 }
17546 drop(restored);
17547
17548 if leaves.is_none() {
17549 neighbours.record_mi_luma_rect(lmi, bw, bh, &luma_grid);
17550 }
17551 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, DC_PRED);
17552 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
17553 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
17554 for cell in 0..mi_w {
17555 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
17556 *slot = bw as u8;
17557 }
17558 }
17559 for cell in 0..mi_h {
17560 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
17561 *slot = bh as u8;
17562 }
17563 }
17564 let mut last_uv = None;
17565 if has_chroma {
17566 hit!(RECT4_16_CHROMA_HITS);
17567 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, DC_PRED);
17568 if !chroma_stamped_per_unit {
17569 let u_state = neighbour_state(&u_grid);
17570 let v_state = neighbour_state(&v_grid);
17571 let round_up_even = |n: usize| n.div_ceil(2) * 2;
17572 let bound_h = round_up_even(neighbours.mi_rows);
17573 let bound_w = round_up_even(neighbours.mi_cols);
17574 for cell in 0..(ph / MI) {
17575 if pair_mi.0 + cell < bound_h
17576 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
17577 {
17578 slot[1] = u_state;
17579 slot[2] = v_state;
17580 }
17581 }
17582 for cell in 0..(pw / MI) {
17583 if pair_mi.1 + cell < bound_w
17584 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
17585 {
17586 slot[1] = u_state;
17587 slot[2] = v_state;
17588 }
17589 }
17590 }
17591 last_uv = Some(DC_PRED);
17592 }
17593 if horz {
17594 hit!(RECT4_16_HORZ_HITS);
17595 } else {
17596 hit!(RECT4_16_VERT_HITS);
17597 }
17598 record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]);
17599 if leaves.is_none() {
17600 // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs`
17601 // with `skip && is_inter`, or the unsplit unit). A split tree already
17602 // published per leaf inside `read_var_tx_size`.
17603 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
17604 }
17605 record_intrabc_mi_rect(
17606 lmi.0,
17607 lmi.1,
17608 mi_w,
17609 mi_h,
17610 Some((dv_row, dv_col)),
17611 neighbours,
17612 fctx,
17613 );
17614 Ok((DC_PRED, last_uv, (tx_w, tx_h)))
17615}
17616
17617/// Restores `reduced_tx_set_inter` when the intrabc pair reader returns,
17618/// including through `?`.
17619struct ReducedRestore<'a> {
17620 fctx: &'a crate::decode::FrameCtx,
17621 saved: bool,
17622}
17623impl Drop for ReducedRestore<'_> {
17624 fn drop(&mut self) {
17625 self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved));
17626 }
17627}
17628fn scopeguard_reduced(fctx: &crate::decode::FrameCtx, saved: bool) -> ReducedRestore<'_> {
17629 ReducedRestore { fctx, saved }
17630}
17631
17632#[allow(clippy::too_many_arguments)]
17633fn decode_rect4_16_strip(
17634 dec: &mut SymbolDecoder,
17635 cdfs: &mut Cdfs,
17636 neighbours: &mut Neighbours,
17637 lmi: (usize, usize),
17638 horz: bool,
17639 has_chroma: bool,
17640 prev: Option<((usize, usize), usize)>,
17641 y: &mut PlaneBuf<'static>,
17642 u: &mut PlaneBuf<'static>,
17643 v: &mut PlaneBuf<'static>,
17644 enable_filter_intra: bool,
17645 allow_screen_content_tools: bool,
17646 base_q_idx: u8,
17647 tx_select: bool,
17648 reduced_tx_set: bool,
17649 fctx: &crate::decode::FrameCtx,
17650) -> Result<(usize, Option<usize>, (usize, usize))> {
17651 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
17652 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
17653 let (mi_w, mi_h) = (bw / MI, bh / MI);
17654 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
17655 let mut last_uv_mode: Option<usize> = None;
17656 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
17657 // aliases all four strips onto one entry, so the mi-exact map wins and
17658 // the previous strip stands in on the split axis.
17659 let mut above_mode = neighbours.above_mode[c];
17660 let mut left_mode = neighbours.left_mode[r];
17661 if let Some(((pr, pc), pmode)) = prev {
17662 if pc == lmi.1 && lmi.0 == pr + mi_h {
17663 above_mode = pmode;
17664 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
17665 left_mode = pmode;
17666 }
17667 }
17668 let (above_mode, left_mode) =
17669 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
17670 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
17671 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
17672 // off CDF row 0 and every cache hit off an empty cache.
17673 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
17674 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
17675 let (
17676 skip,
17677 mode,
17678 angle_delta_y,
17679 uv_mode,
17680 angle_delta_uv,
17681 alpha,
17682 filter_intra,
17683 palette_y,
17684 palette_uv,
17685 intrabc,
17686 ) = read_intra_mode_rect(
17687 dec,
17688 cdfs,
17689 above_mode,
17690 left_mode,
17691 true,
17692 has_chroma,
17693 bw,
17694 bh,
17695 enable_filter_intra,
17696 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
17697 allow_screen_content_tools,
17698 Some((palette_ctx, &palette_cache)),
17699 &palette_uv_cache,
17700 lmi.0,
17701 lmi.1,
17702 fctx,
17703 )?;
17704 if let Some(dv) = intrabc {
17705 return decode_rect4_16_intrabc(
17706 dec,
17707 cdfs,
17708 neighbours,
17709 lmi,
17710 horz,
17711 has_chroma,
17712 skip,
17713 dv,
17714 y,
17715 u,
17716 v,
17717 base_q_idx,
17718 tx_select,
17719 reduced_tx_set,
17720 fctx,
17721 );
17722 }
17723 if palette_y.is_some() || palette_uv.is_some() {
17724 hit!(RECT4_PALETTE_HITS);
17725 }
17726 // The colour-index map through the base colours IS the prediction.
17727 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
17728 // chroma transform this closing strip codes.
17729 let palette_y_buf: Option<Vec<u16>> = palette_y
17730 .as_ref()
17731 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
17732 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
17733 (
17734 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
17735 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
17736 )
17737 });
17738 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
17739 if smooth_neighbor {
17740 hit!(SMOOTH_LUMA_HITS);
17741 }
17742 if filter_intra.is_some() {
17743 hit!(FILTER_INTRA_RECT_HITS);
17744 }
17745 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
17746 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
17747 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
17748 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
17749 // lane-av1mixloss: the lossless-segment early return
17750 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a
17751 // lossless-segment strip codes no depth symbol here either (class
17752 // sweep of the sub8 leaf's fix).
17753 let depth = if tx_select && !lossless(fctx) {
17754 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
17755 // (`get_tx_size_context`, libaom `pred_common.h:342`).
17756 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
17757 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
17758 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17759 eprintln!(
17760 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
17761 lmi.0,
17762 lmi.1,
17763 dec.debug_state().0
17764 );
17765 }
17766 d
17767 } else {
17768 0
17769 };
17770 if depth != 0 {
17771 hit!(TX_DEPTH_HITS);
17772 hit!(RECT4_16_SPLIT_HITS);
17773 }
17774 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
17775 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
17776 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
17777 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
17778 if depth != 0 || lossless(fctx) {
17779 // [`decode_rect_split`]'s per-unit walk, inlined because the
17780 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
17781 // the strip (that function codes one chroma transform per block).
17782 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
17783 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
17784 // unit predicts off the units before it in raster order.
17785 let rect_unit = tx_w != tx_h;
17786 let zero_tu = vec![0i32; tx_w * tx_h];
17787 for tu_row in 0..bh / tx_h {
17788 for tu_col in 0..bw / tx_w {
17789 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
17790 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
17791 let tu_reach =
17792 Reach::of_tu(bw, bh, tu_col * tx_w, tu_row * tx_h, tx_w, tx_h, reach);
17793 if let Some(b) = &palette_y_buf {
17794 let tu_buf: Vec<u16> = (0..tx_h)
17795 .flat_map(|i| {
17796 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
17797 b[base..base + tx_w].iter().copied()
17798 })
17799 .collect();
17800 set_palette_pred(tu_buf, fctx);
17801 }
17802 if skip {
17803 push_intra_rect(
17804 0,
17805 tu_px,
17806 tu_py,
17807 tx_w,
17808 tx_h,
17809 mode,
17810 angle_delta_y,
17811 tu_reach,
17812 &zero_tu,
17813 None,
17814 filter_intra,
17815 smooth_neighbor,
17816 fctx,
17817 );
17818 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
17819 } else if rect_unit {
17820 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
17821 // 32 coded positions and the `TX_4X4` `tx_type` row:
17822 // exactly [`TxbSet::LumaRect4x8`].
17823 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
17824 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
17825 let set = if reduced_tx_set {
17826 TxbSet::LumaRect4x8
17827 } else {
17828 TxbSet::LumaRect4x8Set1
17829 };
17830 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
17831 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
17832 let (tu_grid, tu_tx_type) = read_coeffs_rect(
17833 dec,
17834 &mut coding,
17835 tu_scan,
17836 tx_w,
17837 tx_h,
17838 tu_skip_ctx,
17839 dc_sign_ctx(tu_around.2),
17840 TxType::DctDct,
17841 0,
17842 )?;
17843 let residual = dequant_and_inverse_typed_wh(
17844 &tu_grid,
17845 tx_w,
17846 tx_h,
17847 crate::decode::bit_depth(fctx),
17848 block_q_idx(fctx),
17849 plane_q_delta(0, fctx).0,
17850 plane_q_delta(0, fctx).1,
17851 tu_tx_type,
17852 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
17853 );
17854 push_intra_rect(
17855 0,
17856 tu_px,
17857 tu_py,
17858 tx_w,
17859 tx_h,
17860 mode,
17861 angle_delta_y,
17862 tu_reach,
17863 &residual,
17864 None,
17865 filter_intra,
17866 smooth_neighbor,
17867 fctx,
17868 );
17869 if tu_grid.iter().any(|&l| l != 0) {
17870 hit!(RECT4_16_COEFF_HITS);
17871 }
17872 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
17873 } else {
17874 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
17875 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
17876 let tu_grid = read_plane(
17877 dec,
17878 cdfs,
17879 txbset_for(tx_w, reduced_tx_set),
17880 default_scan(tx_w),
17881 0,
17882 tu_around,
17883 mode,
17884 mode,
17885 angle_delta_y,
17886 tu_reach,
17887 y,
17888 tu_px,
17889 tu_py,
17890 tx_w,
17891 tx_w,
17892 base_q_idx,
17893 None,
17894 filter_intra,
17895 Some(tu_skip_ctx),
17896 smooth_neighbor,
17897 fctx,
17898 )?;
17899 if tu_grid.iter().any(|&l| l != 0) {
17900 hit!(RECT4_16_COEFF_HITS);
17901 }
17902 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
17903 }
17904 }
17905 }
17906 } else {
17907 let levels = if skip {
17908 let zeros = Grid::Zero(bw * bh);
17909 if let Some(b) = &palette_y_buf {
17910 set_palette_pred(b.clone(), fctx);
17911 }
17912 push_intra_rect(
17913 0,
17914 px,
17915 py,
17916 bw,
17917 bh,
17918 mode,
17919 angle_delta_y,
17920 reach,
17921 &zeros,
17922 None,
17923 filter_intra,
17924 smooth_neighbor,
17925 fctx,
17926 );
17927 zeros
17928 } else {
17929 // The strip's luma TU *is* the strip (`plane_bsize ==
17930 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
17931 // `txb_skip_ctx` at 0.
17932 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
17933 let set = if reduced_tx_set {
17934 TxbSet::LumaRect16x4
17935 } else {
17936 TxbSet::LumaRect16x4Set1
17937 };
17938 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
17939 let (levels, tx_type) = read_coeffs_rect(
17940 dec,
17941 &mut coding,
17942 scan,
17943 bw,
17944 bh,
17945 0,
17946 dc_sign_ctx(around.2),
17947 TxType::DctDct,
17948 0,
17949 )?;
17950 let residual = dequant_and_inverse_typed_wh(
17951 &levels,
17952 bw,
17953 bh,
17954 crate::decode::bit_depth(fctx),
17955 block_q_idx(fctx),
17956 plane_q_delta(0, fctx).0,
17957 plane_q_delta(0, fctx).1,
17958 tx_type,
17959 block_iqmatrix(fctx, 0, bw, bh, tx_type),
17960 );
17961 if let Some(b) = &palette_y_buf {
17962 set_palette_pred(b.clone(), fctx);
17963 }
17964 push_intra_rect(
17965 0,
17966 px,
17967 py,
17968 bw,
17969 bh,
17970 mode,
17971 angle_delta_y,
17972 reach,
17973 &residual,
17974 None,
17975 filter_intra,
17976 smooth_neighbor,
17977 fctx,
17978 );
17979 hit!(RECT4_16_COEFF_HITS);
17980 levels
17981 };
17982 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
17983 }
17984 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
17985 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
17986 // `update_partition_context` writes `partition_context_lookup[
17987 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
17988 // the left (mirrored under VERT_4).
17989 for cell in 0..mi_w {
17990 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
17991 *slot = bw as u8;
17992 }
17993 }
17994 for cell in 0..mi_h {
17995 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
17996 *slot = bh as u8;
17997 }
17998 }
17999 if has_chroma {
18000 hit!(RECT4_16_CHROMA_HITS);
18001 // lane-av1-444: at 4:4:4 there is no pair -- every strip is its
18002 // own chroma reference and codes its own 16x4 / 4x16 chroma
18003 // block. (`set_mi_offsets`'s chroma snap is the zero offset at
18004 // ss 0/0, so the neighbour reads below anchor at the strip.)
18005 let (pair_mi, pw, ph) = if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
18006 (lmi, bw, bh)
18007 } else if ss_y(fctx) == 0 && horz {
18008 // lane-av1-422: chroma height is NOT subsampled, so a HORZ
18009 // 16x4 strip is its own chroma reference (`is_chroma_reference`
18010 // at ss(1,0): bh == 1 mi, so the row clause reduces to
18011 // `!ss_y`) and codes its own `ss_size_lookup[BLOCK_16X4][1][0]`
18012 // = BLOCK_8X4 chroma block -- a valid transform, no pair.
18013 // (lane-av1-422o: a VERTICAL 4x16 strip now falls through to
18014 // the pair merge below -- its own chroma block
18015 // `ss_size_lookup[BLOCK_4X16][1][0]` is BLOCK_INVALID, the
18016 // walk proved such leaves exist, and libaom codes the pair's
18017 // chroma from the closing strip; the chunk lives in the
18018 // `chroma422_pair16` arm below.)
18019 (lmi, bw, bh)
18020 } else if horz {
18021 ((lmi.0 - 1, lmi.1), 16, 8)
18022 } else {
18023 ((lmi.0, lmi.1 - 1), 8, 16)
18024 };
18025 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
18026 let (cpx, cpy) = (ppx >> ss_x(fctx), ppy >> ss_y(fctx));
18027 let (cw, ch) = (pw >> ss_x(fctx), ph >> ss_y(fctx));
18028 // lane-av1-422o: the 4:2:2 pair's chroma of a VERT 4x16 strip
18029 // pair: (4, 16) at ss(1,0). The bsize is still BLOCK_4X16, whose
18030 // `ss_size_lookup[..][1][0]` is BLOCK_INVALID, so libaom's
18031 // `av1_get_tx_size` reads `max_txsize_rect_lookup[255]` -- the
18032 // out-of-bounds byte is TX_4X8 in the pinned Release oracle, and
18033 // `av1_get_adjusted_tx_size` has no TX_4X8 case to adjust it.
18034 // `decode_token_recon_block` walks unit_width =
18035 // ROUND_POWER_OF_TWO(1, 1) = 1, unit_height = 4, with stepr =
18036 // tx_size_high_unit[TX_4X8] = 2: TWO TX_4X8 units per plane
18037 // (chroma rows 0..8 and 8..16), plane-major. Even the skip arm
18038 // walks per unit: `predict_and_reconstruct_intra_block` predicts
18039 // every unit regardless of `skip_txfm`.
18040 let chroma422_pair16 = (cw, ch) == (4, 16) && ss_x(fctx) == 1;
18041 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
18042 DC_PRED
18043 } else {
18044 uv_mode
18045 };
18046 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
18047 hit!(RECT4_16_CHROMA_DIR_HITS);
18048 }
18049 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
18050 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
18051 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
18052 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
18053 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
18054 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
18055 // the pair's top-left luma mi, never this leaf's odd row/column.
18056 // Reading `lmi` here named the leaf directly above (a non-chroma
18057 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
18058 // SMOOTH neighbour: filt_type 0 instead of 1 turned
18059 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
18060 // directional chroma strip, moving 4 samples by 1.
18061 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c, fctx);
18062 // lane-av1422warp: `smooth_uv_neighbour_unsnapped` now takes the
18063 // frame's own `ss_x` -- the unsnapped read is the pair-merge witness
18064 // counter's mirror of the snapping form, and the shipped read offsets
18065 // the above COLUMN by `+ss_x` (libaom's `chroma_above_mi`).
18066 //
18067 // lane-av1leftwit: this mirror is NOT evidence about the left read's
18068 // `+ss_y` term, whatever a report once said. It reads the leaf's own
18069 // (odd) mi row, which no decode call site does -- every one of them
18070 // uses the snapping form, whose base row is even -- and its result
18071 // feeds `RECT4_16_UV_PAIR_FILT_HITS` only. What it measures is real
18072 // and worth keeping (the pair's chroma-reference read against the
18073 // leaf's own row: 51/24/121/0/1 hits on the five fixtures censused),
18074 // so it stays; the decode path's own reach for the `+ss_y` term is
18075 // `uv_left_1mi_split_hits()`.
18076 if smooth_neighbor_uv
18077 != neighbours.smooth_uv_neighbour_unsnapped(
18078 lmi.0,
18079 lmi.1,
18080 r,
18081 c,
18082 ss_x(fctx),
18083 ss_y(fctx),
18084 false,
18085 )
18086 {
18087 hit!(RECT4_16_UV_PAIR_FILT_HITS);
18088 }
18089 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane
18090 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is
18091 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major
18092 // (`decode_token_recon_block`), not one `ChromaRect8x4`. Reading
18093 // the rect here consumed one symbol block too few and desynced
18094 // the next strip's `skip` (measured: lossless sb128 320x240,
18095 // mi(1,20) uv_mode matched, the following skip did not).
18096 let lossless_pair = lossless(fctx);
18097 let (u_levels, v_levels) = if lossless_pair {
18098 hit!(RECT4_16_LOSSLESS_CHROMA_HITS);
18099 if skip {
18100 for plane in 1..3usize {
18101 for rr in 0..ch / 4 {
18102 for cc in 0..cw / 4 {
18103 let (ox, oy) = (cc * 4, rr * 4);
18104 // The unit's origin and extent in LUMA pixels: `<< ss`
18105 // at 4:2:0 (8x8 luma for a 4x4 chroma unit), identity
18106 // at 4:4:4 -- the same form as the block-walk sibling
18107 // at decode.rs:35342. The hardcoded `ox * 2 / 8` is
18108 // only right at ss (1,1): at 4:4:4 it claims a 4x4
18109 // chroma unit is 8x8 luma, so `of_tu`'s
18110 // `col_off + tx_w < bw` test answers against a
18111 // footprint twice the real one and every unit past
18112 // the block's midpoint wrongly reports
18113 // `above_right = false` -- a directional chroma
18114 // strip then predicts from a neighbour libaom
18115 // never reads (measured: key frame 0, 4:4:4 lossless
18116 // 16x4 strip at (104,26), U 29 + V 34 samples wrong,
18117 // entropy bit-identical over 351109 EC_SYMR reads).
18118 let cu_reach = tu_reach(
18119 pw,
18120 ph,
18121 ox << ss_x(fctx),
18122 oy << ss_y(fctx),
18123 4 << ss_x(fctx),
18124 pair_reach,
18125 ppx,
18126 ppy,
18127 y.width,
18128 y.height,
18129 fctx,
18130 );
18131 if let Some((ub, vb)) = &palette_uv_bufs {
18132 let buf = if plane == 1 { ub } else { vb };
18133 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
18134 }
18135 push_intra(
18136 plane,
18137 cpx + ox,
18138 cpy + oy,
18139 4,
18140 uv_predict_mode,
18141 angle_delta_uv,
18142 cu_reach,
18143 &ZERO_RESIDUAL[..16],
18144 None,
18145 None,
18146 smooth_neighbor_uv,
18147 fctx,
18148 );
18149 let cu_mi = (
18150 pair_mi.0 + (oy << ss_y(fctx)) / MI,
18151 pair_mi.1 + (ox << ss_x(fctx)) / MI,
18152 );
18153 neighbours.record_mi_chroma(
18154 cu_mi,
18155 4 << ss_x(fctx),
18156 4 << ss_y(fctx),
18157 plane,
18158 &ZERO_RESIDUAL[..16],
18159 );
18160 }
18161 }
18162 }
18163 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
18164 } else {
18165 let scan4 = default_scan(4);
18166 // `get_txb_ctx`: offset 10 (our tables store it at +3)
18167 // when the plane block is larger than the transform.
18168 let offset = Some(3usize);
18169 let mut uo = vec![0i32; cw * ch];
18170 let mut vo = vec![0i32; cw * ch];
18171 for plane in 1..3usize {
18172 for rr in 0..ch / 4 {
18173 for cc in 0..cw / 4 {
18174 let (ox, oy) = (cc * 4, rr * 4);
18175 if cpx + ox >= u.true_width || cpy + oy >= u.true_height {
18176 continue;
18177 }
18178 // The unit's stamp is its own span: aom
18179 // `av1_set_entropy_contexts` (blockd.c:29)
18180 // memsets exactly `tx_size_wide_unit` x
18181 // `tx_size_high_unit` cells at the unit's own
18182 // `(aoff, loff)` -- for TX_4X4 ONE above cell
18183 // and ONE left cell. `(oy / 2, ox / 2)` +
18184 // `(8, 8)` is the 4:2:0 subsampled form (one
18185 // chroma cell = 8 luma px = 2 mi cells); at
18186 // 4:4:4 a unit is ONE mi cell, and the 2x2
18187 // smear let a 4-wide strip's later units
18188 // overwrite the NEXT COLUMN's above cell with
18189 // their own state -- a column aom never sees
18190 // this block write -- so the following block's
18191 // `all_zero` read the wrong `txb_skip` row
18192 // (frame-0 read #452, the llkf named gap).
18193 let cu_mi = (
18194 pair_mi.0 + (oy << ss_y(fctx)) / MI,
18195 pair_mi.1 + (ox << ss_x(fctx)) / MI,
18196 );
18197 // One luma-mi cell: the chroma entropy arrays
18198 // are subsampled, and our bands replicate that
18199 // one entry over the unit's two cells
18200 // (`read_intra_chroma_lossless`).
18201 let cu_around = neighbours.around_mi(cu_mi, MI);
18202 // Same ss-aware luma footprint as the skip arm
18203 // above -- `ox * 2 / 8` is the 4:2:0-only form and
18204 // mis-answers `of_tu` at 4:4:4 (see there).
18205 let cu_reach = tu_reach(
18206 pw,
18207 ph,
18208 ox << ss_x(fctx),
18209 oy << ss_y(fctx),
18210 4 << ss_x(fctx),
18211 pair_reach,
18212 ppx,
18213 ppy,
18214 y.width,
18215 y.height,
18216 fctx,
18217 );
18218 if let Some((ub, vb)) = &palette_uv_bufs {
18219 let buf = if plane == 1 { ub } else { vb };
18220 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
18221 }
18222 let buf: &mut PlaneBuf<'static> =
18223 if plane == 1 { &mut *u } else { &mut *v };
18224 let cu_grid = read_plane(
18225 dec,
18226 cdfs,
18227 TxbSet::Chroma4,
18228 &scan4,
18229 plane,
18230 cu_around[plane],
18231 mode,
18232 uv_predict_mode,
18233 angle_delta_uv,
18234 cu_reach,
18235 buf,
18236 cpx + ox,
18237 cpy + oy,
18238 4,
18239 4,
18240 base_q_idx,
18241 None,
18242 None,
18243 offset,
18244 smooth_neighbor_uv,
18245 fctx,
18246 )?;
18247 neighbours.record_mi_chroma(
18248 cu_mi,
18249 4 << ss_x(fctx),
18250 4 << ss_y(fctx),
18251 plane,
18252 &cu_grid,
18253 );
18254 hit!(CHROMA_SPLIT_TX_HITS);
18255 let dst = if plane == 1 { &mut uo } else { &mut vo };
18256 for row in 0..4 {
18257 let start = (oy + row) * cw + ox;
18258 dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]);
18259 }
18260 }
18261 }
18262 }
18263 (Grid::Own(uo), Grid::Own(vo))
18264 }
18265 } else if skip {
18266 let zeros = Grid::Zero(cw * ch);
18267 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
18268 // ~1000) predicts EVERY plane and only guards the residual on
18269 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
18270 // DC + alpha * luma-AC. Dropping the CfL term here left a
18271 // chroma-only bounded box on ReelC's key frames.
18272 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18273 if alpha.is_some() {
18274 hit!(CHROMA_SKIP_CFL_HITS);
18275 }
18276 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
18277 if chroma422_pair16 {
18278 // lane-av1-422o: two TX_4X8 units, each predicted on
18279 // its own edges (the lower one off the upper one's
18280 // samples); no coefficients are coded, and libaom's
18281 // `set_entropy_context` zeroed the block's own cells,
18282 // so the pair-wide zero stamp below stays correct.
18283 for unit_row in 0..2usize {
18284 let unit_reach = tu_reach_rect(
18285 pw,
18286 ph,
18287 0,
18288 unit_row * 8,
18289 8,
18290 8,
18291 pair_reach,
18292 ppx,
18293 ppy,
18294 y.width,
18295 y.height,
18296 fctx,
18297 );
18298 if let Some((ub, vb)) = &palette_uv_bufs {
18299 let pbuf = if plane == 1 { ub } else { vb };
18300 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
18301 }
18302 push_intra_rect(
18303 plane,
18304 cpx,
18305 cpy + unit_row * 8,
18306 4,
18307 8,
18308 uv_predict_mode,
18309 angle_delta_uv,
18310 unit_reach,
18311 &ZERO_RESIDUAL[..4 * 8],
18312 alpha
18313 .zip(ac)
18314 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18315 None,
18316 smooth_neighbor_uv,
18317 fctx,
18318 );
18319 }
18320 } else {
18321 if let Some((ub, vb)) = &palette_uv_bufs {
18322 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
18323 }
18324 push_intra_rect(
18325 plane,
18326 cpx,
18327 cpy,
18328 cw,
18329 ch,
18330 uv_predict_mode,
18331 angle_delta_uv,
18332 pair_reach,
18333 &zeros,
18334 alpha
18335 .zip(ac)
18336 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18337 None,
18338 smooth_neighbor_uv,
18339 fctx,
18340 );
18341 }
18342 }
18343 (zeros.clone(), zeros)
18344 } else if chroma422_pair16 {
18345 // lane-av1-422o: the pair's 4x16 chroma as TWO TX_4X8 units
18346 // per plane, plane-major (every U unit, then every V). Each
18347 // unit: the `ChromaRect8x4` tables (`get_txsize_entropy_ctx`
18348 // squares TX_4X8 up to the 8x8 class), `SCAN_4X8`, and a
18349 // `txb_skip_ctx` of above+left in the OFFSET-10 rows -- the
18350 // offset comes from `num_pels_log2_lookup[plane_bsize] >
18351 // num_pels_log2_lookup[BLOCK_4X8]` with plane_bsize =
18352 // BLOCK_INVALID (255), and the byte at that table's +255 in
18353 // the pinned Release oracle is 255 (`cmpb` against the
18354 // `0xc0db70` copy decodetxb.c links), i.e. the bigger-plane
18355 // arm: +3 on the offset-7-first chroma tables. No tx_type
18356 // symbol (only y plane's is transmitted); the unit's type is
18357 // `intra_mode_to_tx_type(UV mode)` kept by the all-16 ext-tx
18358 // set -- [`read_rect_chroma_unit`]'s own default. CfL params
18359 // are computed ONCE per block (`are_parameters_computed`)
18360 // over the pair's luma, shared by both units. Each unit is
18361 // predicted and recorded immediately, so the lower unit
18362 // reads the upper one's coefficient context.
18363 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18364 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
18365 for unit_row in 0..2usize {
18366 let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1);
18367 let unit_reach = tu_reach_rect(
18368 pw,
18369 ph,
18370 0,
18371 unit_row * 8,
18372 8,
18373 8,
18374 pair_reach,
18375 ppx,
18376 ppy,
18377 y.width,
18378 y.height,
18379 fctx,
18380 );
18381 if let Some((ub, vb)) = &palette_uv_bufs {
18382 let pbuf = if plane == 1 { ub } else { vb };
18383 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
18384 }
18385 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
18386 let unit_grid = read_rect_chroma_unit(
18387 dec,
18388 cdfs,
18389 TxbSet::ChromaRect8x4,
18390 &SCAN_4X8,
18391 4,
18392 8,
18393 plane,
18394 chroma_around[plane],
18395 uv_predict_mode,
18396 angle_delta_uv,
18397 unit_reach,
18398 buf,
18399 cpx,
18400 cpy + unit_row * 8,
18401 base_q_idx,
18402 // lane-av1-422q: the offset-10 rows -- the same
18403 // measured rule as the 4x32 arm (plane_bsize
18404 // BLOCK_INVALID for the pair's BLOCK_4X16 too;
18405 // num_pels_log2_lookup[255] = 0xff at the
18406 // 0xc0de70 copy -> +3 on the offset-7-first
18407 // chroma tables; see lanes/av1422q.report.md).
18408 Some(3),
18409 alpha
18410 .zip(ac)
18411 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18412 smooth_neighbor_uv,
18413 fctx,
18414 )?;
18415 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
18416 }
18417 }
18418 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
18419 } else {
18420 // lane-av1422ctxgather: 4:2:2's chroma above votes sample
18421 // every second luma-mi cell
18422 // ([`Neighbours::around_mi_422_chroma`]: at ss_x 1 one
18423 // chroma 4-px column spans two luma mi columns, and the
18424 // plain per-mi gather counts each column's whole-unit dc
18425 // sign twice). The left extent is unsubsampled at ss_y 0,
18426 // so its per-mi cells already line up one-to-one.
18427 let around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
18428 neighbours.around_mi_422_chroma(pair_mi, pw, ph)
18429 } else {
18430 neighbours.around_mi_rect(pair_mi, pw, ph)
18431 };
18432 // lane-av1-444: the strip's own 16x4 / 4x16 chroma at ss 0/0
18433 // (`TxbSet::Chroma8`, `get_txsize_entropy_ctx(TX_16X4)` =
18434 // the 8x8 set); 4:2:0 keeps the pair's 8x4 / 4x8.
18435 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (cw, ch) {
18436 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
18437 (4, 8) => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
18438 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
18439 // lane-av1-444: 4:4:4's own-strip vert chroma is (4,16)
18440 // -- one TX_4X16. (lane-av1-422o: the 4:2:2 pair's
18441 // (4,16) never reaches this row; `chroma422_pair16`
18442 // intercepts it above and chunks it into TX_4X8 units.)
18443 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
18444 // lane-av1-422: a 4:2:2 HORZ pair (16x8 luma) keeps the
18445 // pair's height: an 8x8 SQUARE chroma block, the same
18446 // `TxbSet::Chroma8` set any 8x8 chroma plane reads. The
18447 // 4:2:0 pair's chroma is 8x4 and 4:4:4's is 16x4, so this
18448 // row is unreachable there. It is also the witness arm:
18449 // a restored `/2 chroma height` lands on (8,4) and the
18450 // counter reads 0.
18451 (8, 8) => {
18452 hit!(CHROMA422_SQUARE_HITS);
18453 (TxbSet::Chroma8, default_scan(8))
18454 }
18455 // lane-av1-422o: with the `chroma422_pair16` arm above,
18456 // the (2,16) own-strip shape and the 4:4:4 shapes are the
18457 // only residents; anything else is a named-lane gap.
18458 _ => unreachable!("decode_rect4_16_strip chroma shape set is closed"),
18459 };
18460 let mut planes = Vec::with_capacity(2);
18461 for plane in 1..3 {
18462 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
18463 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
18464 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
18465 let (levels, tx_type) = read_chroma_coeffs_rect(
18466 dec,
18467 &mut coding,
18468 chroma_scan,
18469 cw,
18470 ch,
18471 skip_ctx,
18472 dc_sign_ctx(around[plane].2),
18473 default_tx,
18474 fctx,
18475 plane,
18476 )?;
18477 planes.push((levels, tx_type));
18478 }
18479 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
18480 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
18481 // CfL averages the luma of the WHOLE pair, the region this one
18482 // chroma transform covers.
18483 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
18484 for (plane, _buf, levels, tx_type) in [
18485 (1usize, &mut *u, &u_levels, u_tx_type),
18486 (2, &mut *v, &v_levels, v_tx_type),
18487 ] {
18488 let residual = dequant_and_inverse_typed_wh(
18489 levels,
18490 cw,
18491 ch,
18492 crate::decode::bit_depth(fctx),
18493 block_q_idx(fctx),
18494 plane_q_delta(plane, fctx).0,
18495 plane_q_delta(plane, fctx).1,
18496 tx_type,
18497 block_iqmatrix(fctx, plane, cw, ch, tx_type),
18498 );
18499 if let Some((ub, vb)) = &palette_uv_bufs {
18500 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
18501 }
18502 push_intra_rect(
18503 plane,
18504 cpx,
18505 cpy,
18506 cw,
18507 ch,
18508 uv_predict_mode,
18509 angle_delta_uv,
18510 pair_reach,
18511 &residual,
18512 alpha
18513 .zip(ac)
18514 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
18515 None,
18516 smooth_neighbor_uv,
18517 fctx,
18518 );
18519 }
18520 (u_levels, v_levels)
18521 };
18522 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
18523 // A lossless pair already stamped each TX_4X4 (`record_mi_chroma`).
18524 // The single-state rewrite below is the non-lossless TX_8X4/TX_4X8.
18525 // lane-av1-422o: the chunked pair's cells are stamped PER UNIT in
18526 // the arm above (libaom's coefficient contexts are per
18527 // 4x4-cell); a pair-wide state would erase the unit boundary the
18528 // next block reads.
18529 if !lossless_pair && !chroma422_pair16 {
18530 // The chroma planes' coefficient context, over the PAIR's mi span
18531 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
18532 // the luma one rounded up to its 4x4 unit).
18533 let u_state = neighbour_state(&u_levels);
18534 let v_state = neighbour_state(&v_levels);
18535 let round_up_even = |n: usize| n.div_ceil(2) * 2;
18536 let bound_h = round_up_even(neighbours.mi_rows);
18537 let bound_w = round_up_even(neighbours.mi_cols);
18538 for cell in 0..(ph / MI) {
18539 if pair_mi.0 + cell < bound_h
18540 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
18541 {
18542 slot[1] = u_state;
18543 slot[2] = v_state;
18544 }
18545 }
18546 for cell in 0..(pw / MI) {
18547 if pair_mi.1 + cell < bound_w
18548 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
18549 {
18550 slot[1] = u_state;
18551 slot[2] = v_state;
18552 }
18553 }
18554 }
18555 last_uv_mode = Some(uv_predict_mode);
18556 }
18557 if horz {
18558 hit!(RECT4_16_HORZ_HITS);
18559 } else {
18560 hit!(RECT4_16_VERT_HITS);
18561 }
18562 let (pal_y_size, pal_y_colors) = palette_y
18563 .as_ref()
18564 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
18565 let (pal_uv_size, pal_uv_colors) = palette_uv
18566 .as_ref()
18567 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
18568 record_strip_palette(
18569 neighbours,
18570 lmi,
18571 bw,
18572 bh,
18573 pal_y_size,
18574 pal_y_colors,
18575 pal_uv_size,
18576 pal_uv_colors,
18577 );
18578 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
18579 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
18580 // frame): the above row records `tx_size_wide` over the block's width and
18581 // the left column `tx_size_high` over its height. This 1:4 strip reader is
18582 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
18583 // and it published neither band -- so the block after a 64x16 strip read
18584 // the row's init value 64 as its left transform height and took
18585 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
18586 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
18587 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
18588 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
18589 Ok((mode, last_uv_mode, (tx_w, tx_h)))
18590}
18591
18592/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
18593/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
18594/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
18595/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
18596/// cap, so LUMA needs the same corner truncation [`decode_block`] already
18597/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
18598/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
18599/// this function's own charter/report), so both strips read a real 32x32
18600/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
18601/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
18602/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
18603/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
18604/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
18605/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
18606/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
18607/// that function, only the single-transform-unit (`tx_depth == 0`) case is
18608/// supported: a split transform refuses by name rather than guess-decode.
18609#[allow(clippy::too_many_arguments)]
18610fn decode_block_rect64(
18611 dec: &mut SymbolDecoder,
18612 cdfs: &mut Cdfs,
18613 neighbours: &mut Neighbours,
18614 at: (usize, usize),
18615 bw: usize,
18616 bh: usize,
18617 y: &mut PlaneBuf<'static>,
18618 u: &mut PlaneBuf<'static>,
18619 v: &mut PlaneBuf<'static>,
18620 enable_filter_intra: bool,
18621 allow_screen_content_tools: bool,
18622 base_q_idx: u8,
18623 tx_select: bool,
18624 reduced_tx_set: bool,
18625 fctx: &crate::decode::FrameCtx,
18626) -> Result<()> {
18627 let (r, c) = at;
18628 let (px, py) = (c * SUB, r * SUB);
18629 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
18630 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
18631 let palette_uv_cache = neighbours.palette_uv_cache(at);
18632 let (
18633 skip,
18634 mode,
18635 angle_delta_y,
18636 uv_mode,
18637 angle_delta_uv,
18638 alpha,
18639 filter_intra,
18640 palette_y,
18641 palette_uv,
18642 intrabc,
18643 ) = read_intra_mode_rect(
18644 dec,
18645 cdfs,
18646 nb_above_mode,
18647 nb_left_mode,
18648 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
18649 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
18650 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
18651 // correct), CFL must never be offered here -- passing `true`
18652 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
18653 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
18654 // from this block's very first symbol (lane-sbpart r3 bisect).
18655 false,
18656 true,
18657 bw,
18658 bh,
18659 enable_filter_intra,
18660 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
18661 allow_screen_content_tools,
18662 Some((palette_ctx, &palette_cache)),
18663 &palette_uv_cache,
18664 r * (SUB / MI),
18665 c * (SUB / MI),
18666 fctx,
18667 )?;
18668 if let Some((dv_row, dv_col)) = intrabc {
18669 return decode_intrabc_owned_rect(
18670 dec,
18671 cdfs,
18672 neighbours,
18673 (r * (SUB / MI), c * (SUB / MI)),
18674 (bw, bh),
18675 skip,
18676 (dv_row, dv_col),
18677 y,
18678 u,
18679 v,
18680 base_q_idx,
18681 tx_select,
18682 reduced_tx_set,
18683 fctx,
18684 );
18685 }
18686 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
18687 // lane-t900 r34: a non-skip palette block on a superblock-level strip
18688 // -- counted so its gate cannot go vacuous (this was a refusal until
18689 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
18690 // decodes_pixel_exact`).
18691 hit!(PALETTE_SB_STRIP_HITS);
18692 }
18693 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
18694 if smooth_neighbor {
18695 hit!(SMOOTH_LUMA_HITS);
18696 }
18697 let smooth_neighbor_uv =
18698 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
18699 if filter_intra.is_some() {
18700 // `filter_intra_size_class_rect` already returns `None` for both
18701 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
18702 // 32 on both axes), so this symbol is never read at this level --
18703 // kept only as the same defensive refusal [`decode_block_rect`] has.
18704 return Err(unsupported(
18705 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
18706 av1_filter_intra_allowed_bsize caps at 32x32)",
18707 ));
18708 }
18709 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
18710 DC_PRED
18711 } else {
18712 uv_mode
18713 };
18714 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
18715 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
18716 // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes
18717 // no depth symbol here either (class sweep of the sub8 leaf's fix).
18718 let depth = if tx_select && !lossless(fctx) {
18719 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
18720 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
18721 // intra-only frame publishes them from every block too
18722 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
18723 // 1920x792 128-superblock stream,
18724 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
18725 // `tx_size_cat2` row 1 where libaom reads row 2.
18726 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
18727 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
18728 // counts `sub_tx_size_map` steps from the block's own max rect
18729 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
18730 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
18731 // steps, so this level's category is 3 (the same one a 64x64 square
18732 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
18733 // here was a wrong-table read of a real symbol.
18734 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
18735 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18736 eprintln!(
18737 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
18738 dec.debug_state().0
18739 );
18740 }
18741 d
18742 } else {
18743 0
18744 };
18745 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
18746 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
18747 publish_txfm_bands_if_in_inter(
18748 neighbours,
18749 (mi_r, mi_c),
18750 depth_to_tx_wh(bw, bh, depth, fctx),
18751 (bw, bh),
18752 fctx,
18753 );
18754 if depth != 0 || lossless(fctx) {
18755 hit!(TX_DEPTH_HITS);
18756 // lane-rectsplit r1/r4: the superblock-level strip splits its
18757 // transform through the very same per-unit path as its 32x32-level
18758 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
18759 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
18760 // measured the old square formula mis-tiling exactly that strip).
18761 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
18762 if bw.max(bh) / bw.min(bh) == 4 {
18763 let which = if depth == 1 {
18764 &RECT4_SPLIT_DEPTH1_HITS
18765 } else {
18766 &RECT4_SPLIT_DEPTH2_HITS
18767 };
18768 hit_do! { which.with(|c| c.set(c.get() + 1)); }
18769 }
18770 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
18771 eprintln!(
18772 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
18773 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
18774 angle_y={angle_delta_y}"
18775 );
18776 }
18777 let modes = RectStripModes {
18778 skip,
18779 mode,
18780 angle_delta_y,
18781 uv_predict_mode,
18782 angle_delta_uv,
18783 alpha,
18784 filter_intra,
18785 smooth_neighbor,
18786 smooth_neighbor_uv,
18787 palette_y: palette_y
18788 .as_ref()
18789 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
18790 palette_uv: palette_uv.as_ref().map(|p| {
18791 (
18792 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
18793 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
18794 )
18795 }),
18796 };
18797 if palette_y.is_some() || palette_uv.is_some() {
18798 hit!(PALETTE_SPLIT_TX_HITS);
18799 }
18800 decode_rect_split(
18801 dec,
18802 cdfs,
18803 neighbours,
18804 (mi_r, mi_c),
18805 bw,
18806 bh,
18807 tx_w,
18808 tx_h,
18809 &modes,
18810 y,
18811 u,
18812 v,
18813 base_q_idx,
18814 reduced_tx_set,
18815 fctx,
18816 )?;
18817 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
18818 // (lane-palette2 r10): this return skips the fn's own tail, so a
18819 // split-tx superblock strip would otherwise leave the above/left
18820 // palette arrays holding a dead block's colours.
18821 let (py_size, py_colors) = palette_y
18822 .as_ref()
18823 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
18824 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
18825 let (puv_size, puv_colors) = palette_uv
18826 .as_ref()
18827 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
18828 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
18829 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
18830 // return skips the fn's own tail, so a SPLIT superblock-level strip
18831 // published no TXFM_CONTEXT band and the next block read the row's init
18832 // value 64 as its left transform height. Measured on the 10-bit
18833 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
18834 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
18835 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
18836 // bands carry the SPLIT unit's size, not the block's.
18837 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
18838 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
18839 hit!(RECT_PARTITION_HITS);
18840 return Ok(());
18841 }
18842 let (tx_w, tx_h) = (bw, bh);
18843 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
18844 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
18845 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
18846 if let Some(ref pyv) = palette_y {
18847 let buf: Vec<u16> = pyv
18848 .map
18849 .iter()
18850 .map(|&idx| pyv.colors[idx as usize])
18851 .collect();
18852 set_palette_pred(buf, fctx);
18853 }
18854 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
18855 (
18856 puv.map
18857 .iter()
18858 .map(|&idx| puv.u_colors[idx as usize])
18859 .collect(),
18860 puv.map
18861 .iter()
18862 .map(|&idx| puv.v_colors[idx as usize])
18863 .collect(),
18864 )
18865 });
18866 if skip {
18867 push_intra_rect(
18868 0,
18869 px,
18870 py,
18871 bw,
18872 bh,
18873 mode,
18874 angle_delta_y,
18875 reach,
18876 &ZERO_RESIDUAL[..bw * bh],
18877 None,
18878 filter_intra,
18879 smooth_neighbor,
18880 fctx,
18881 );
18882 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
18883 if let Some((ub, _)) = &palette_uv_bufs {
18884 set_palette_pred(ub.clone(), fctx);
18885 }
18886 push_intra_rect(
18887 1,
18888 cpx,
18889 cpy,
18890 chroma_w,
18891 chroma_h,
18892 uv_predict_mode,
18893 angle_delta_uv,
18894 reach,
18895 &ZERO_RESIDUAL[..chroma_w * chroma_h],
18896 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
18897 None,
18898 smooth_neighbor_uv,
18899 fctx,
18900 );
18901 if let Some((_, vb)) = &palette_uv_bufs {
18902 set_palette_pred(vb.clone(), fctx);
18903 }
18904 push_intra_rect(
18905 2,
18906 cpx,
18907 cpy,
18908 chroma_w,
18909 chroma_h,
18910 uv_predict_mode,
18911 angle_delta_uv,
18912 reach,
18913 &ZERO_RESIDUAL[..chroma_w * chroma_h],
18914 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
18915 None,
18916 smooth_neighbor_uv,
18917 fctx,
18918 );
18919 neighbours.record_rect(
18920 at,
18921 bw,
18922 bh,
18923 mode,
18924 uv_predict_mode,
18925 &[
18926 &ZERO_RESIDUAL[..bw * bh],
18927 &ZERO_RESIDUAL[..chroma_w * chroma_h],
18928 &ZERO_RESIDUAL[..chroma_w * chroma_h],
18929 ],
18930 );
18931 } else {
18932 let around = neighbours.around_rect(at, bw, bh);
18933 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
18934 // (see this function's own doc comment). A 64-length axis codes only
18935 // its low 32 coefficients, so the corner is `min(bw, 32)` x
18936 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
18937 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
18938 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
18939 let scan32 = default_scan(TX32);
18940 if coeff_trace_on() {
18941 let (rng, _) = dec.debug_state();
18942 eprintln!(
18943 "EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}"
18944 );
18945 }
18946 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
18947 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
18948 read_coeffs(
18949 dec,
18950 &mut luma_coding,
18951 &scan32,
18952 0,
18953 dc_sign_ctx(around[0].2),
18954 TxType::DctDct,
18955 Some((bw, bh)),
18956 )?
18957 } else {
18958 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
18959 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
18960 // (`scan.c`) gives both the very same `default_scan_32x16` /
18961 // `default_scan_16x32` the 2:1 sizes use ("Half of the
18962 // coefficients of tx64 at higher frequencies are set to zeros. So
18963 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
18964 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
18965 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
18966 // 512-position eob group) -- BOTH identical to TX_32X16, so the
18967 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
18968 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
18969 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
18970 // what `base_ctx_rect` computes at (32, 16).
18971 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
18972 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
18973 read_coeffs_rect(
18974 dec,
18975 &mut luma_coding,
18976 luma_scan,
18977 luma_cw,
18978 luma_ch,
18979 0,
18980 dc_sign_ctx(around[0].2),
18981 TxType::DctDct,
18982 0,
18983 )?
18984 };
18985 if coeff_trace_on() {
18986 let (rng, _) = dec.debug_state();
18987 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
18988 }
18989 let mut luma_levels = vec![0i32; bw * bh];
18990 for row in 0..luma_ch {
18991 luma_levels[row * bw..][..luma_cw]
18992 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
18993 }
18994 {
18995 let cur = block_q_idx(fctx);
18996 if cur != i32::from(base_q_idx) {
18997 hit!(RECT64_QIDX_DRIFT_HITS);
18998 }
18999 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19000 eprintln!(
19001 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
19002 );
19003 }
19004 }
19005 let luma_residual = dequant_and_inverse_typed_wh(
19006 &luma_levels,
19007 bw,
19008 bh,
19009 crate::decode::bit_depth(fctx),
19010 block_q_idx(fctx),
19011 plane_q_delta(0, fctx).0,
19012 plane_q_delta(0, fctx).1,
19013 luma_tx_type,
19014 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
19015 );
19016 push_intra_rect(
19017 0,
19018 px,
19019 py,
19020 bw,
19021 bh,
19022 mode,
19023 angle_delta_y,
19024 reach,
19025 &luma_residual,
19026 None,
19027 filter_intra,
19028 smooth_neighbor,
19029 fctx,
19030 );
19031 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
19032 let leftcol: Vec<u16> = if px > 0 {
19033 (py..py + bh)
19034 .map(|row| y.data[row * y.width + px - 1])
19035 .collect()
19036 } else {
19037 vec![]
19038 };
19039 eprintln!(
19040 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
19041 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
19042 luma_corner.iter().any(|&v| v != 0),
19043 &y.data[py * y.width + px..][..bw],
19044 leftcol,
19045 );
19046 }
19047 // CHROMA. At 4:2:0 the plane block is already one adjusted UV
19048 // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma
19049 // is larger than that, so it is tiled into 32-capped units.
19050 let _ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
19051 let (uw, uh) = (chroma_w.min(32), chroma_h.min(32));
19052 let (nw, nh) = (chroma_w / uw, chroma_h / uh);
19053 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (uw, uh) {
19054 (32, 32) => (TxbSet::Chroma32, default_scan(32)),
19055 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
19056 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
19057 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8),
19058 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
19059 _ => {
19060 return Err(unsupported(
19061 "a 64-axis strip whose chroma unit has no coefficient table",
19062 ));
19063 }
19064 };
19065 let bigger = nw * nh > 1;
19066 let mut u_levels = vec![0i32; chroma_w * chroma_h];
19067 let mut v_levels = vec![0i32; chroma_w * chroma_h];
19068 // The tiled units below stamp their own coefficient context
19069 // immediately, then the whole-strip `record_rect` rewrite paints
19070 // every chroma cell with ONE whole-strip state and the per-unit DC
19071 // signs and levels are lost (class `override-slot-on-one-arm`, same
19072 // shape as `decode_rect_split`'s chroma_tiled clobber). Collected
19073 // here and replayed after that record, the c8 `mu_chroma_units` way.
19074 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
19075 for plane_idx in 1..=2 {
19076 for cu_row in 0..nh {
19077 for cu_col in 0..nw {
19078 let cu_around = if nw == 1 && nh == 1 {
19079 around
19080 } else {
19081 let lsx = uw << ss_x(fctx);
19082 let lsy = uh << ss_y(fctx);
19083 let cu_mi = (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI));
19084 neighbours.around_mi_rect(cu_mi, lsx, lsy)
19085 };
19086 let lsx = uw << ss_x(fctx);
19087 let lsy = uh << ss_y(fctx);
19088 let cfl = alpha.map(|(au, av)| {
19089 let a = if plane_idx == 1 { au } else { av };
19090 (
19091 a,
19092 cfl_src_rect(px + cu_col * lsx, py + cu_row * lsy, lsx, lsy),
19093 )
19094 });
19095 let levels = if uw == uh {
19096 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
19097 if let Some((ub, vb)) = &palette_uv_bufs {
19098 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
19099 }
19100 read_plane(
19101 dec,
19102 cdfs,
19103 chroma_set,
19104 chroma_scan,
19105 plane_idx,
19106 cu_around[plane_idx],
19107 mode,
19108 uv_predict_mode,
19109 angle_delta_uv,
19110 reach,
19111 plane,
19112 cpx + cu_col * uw,
19113 cpy + cu_row * uh,
19114 uw,
19115 uw,
19116 base_q_idx,
19117 cfl,
19118 None,
19119 bigger.then_some(3),
19120 smooth_neighbor_uv,
19121 fctx,
19122 )?
19123 } else {
19124 let skip_ctx = usize::from(cu_around[plane_idx].0)
19125 + usize::from(cu_around[plane_idx].1)
19126 + usize::from(bigger) * 3;
19127 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
19128 let (levels, tx_type) = read_chroma_coeffs_rect(
19129 dec,
19130 &mut coding,
19131 chroma_scan,
19132 uw,
19133 uh,
19134 skip_ctx,
19135 dc_sign_ctx(cu_around[plane_idx].2),
19136 TxType::DctDct,
19137 fctx,
19138 plane_idx,
19139 )?;
19140 let residual = dequant_and_inverse_typed_wh(
19141 &levels,
19142 uw,
19143 uh,
19144 crate::decode::bit_depth(fctx),
19145 block_q_idx(fctx),
19146 plane_q_delta(plane_idx, fctx).0,
19147 plane_q_delta(plane_idx, fctx).1,
19148 tx_type,
19149 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
19150 );
19151 if let Some((ub, vb)) = &palette_uv_bufs {
19152 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
19153 }
19154 push_intra_rect(
19155 plane_idx,
19156 cpx + cu_col * uw,
19157 cpy + cu_row * uh,
19158 uw,
19159 uh,
19160 uv_predict_mode,
19161 angle_delta_uv,
19162 reach,
19163 &residual,
19164 cfl,
19165 None,
19166 smooth_neighbor_uv,
19167 fctx,
19168 );
19169 levels
19170 };
19171 let dst = if plane_idx == 1 {
19172 &mut u_levels
19173 } else {
19174 &mut v_levels
19175 };
19176 for row in 0..uh {
19177 let d = (cu_row * uh + row) * chroma_w + cu_col * uw;
19178 dst[d..d + uw].copy_from_slice(&levels[row * uw..][..uw]);
19179 }
19180 if bigger {
19181 neighbours.record_mi_chroma(
19182 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
19183 lsx,
19184 lsy,
19185 plane_idx,
19186 &levels,
19187 );
19188 tiled_chroma_units.push((
19189 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
19190 plane_idx,
19191 levels.clone(),
19192 lsx,
19193 lsy,
19194 ));
19195 }
19196 }
19197 }
19198 }
19199 neighbours.record_rect(
19200 at,
19201 bw,
19202 bh,
19203 mode,
19204 uv_predict_mode,
19205 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
19206 );
19207 // The per-unit re-stamp: `record_rect` above wrote the whole strip's
19208 // chroma cells from the assembled grids' one whole-strip state,
19209 // overwriting exactly the stamps the tiled loop just made.
19210 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
19211 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
19212 }
19213 hit!(RECT_COEFF_HITS);
19214 }
19215 let (py_size, py_colors) = palette_y
19216 .as_ref()
19217 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
19218 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
19219 let (puv_size, puv_colors) = palette_uv
19220 .as_ref()
19221 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
19222 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
19223 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
19224 neighbours.fill_lf_grid_rect(
19225 (mi_r, mi_c),
19226 bw / MI,
19227 bh / MI,
19228 tx_w as u8,
19229 tx_h as u8,
19230 0,
19231 fctx,
19232 );
19233 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
19234 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
19235 // frame): the above row records `tx_size_wide` over the block's width and
19236 // the left column `tx_size_high` over its height. This 1:4 strip reader is
19237 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
19238 // and it published neither band -- so the block after a 64x16 strip read
19239 // the row's init value 64 as its left transform height and took
19240 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
19241 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
19242 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
19243 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
19244 hit!(SB_RECT_HITS);
19245 match (bw, bh) {
19246 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
19247 (16, 64) => hit!(SB_RECT4_VERT_HITS),
19248 _ => {}
19249 }
19250 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19251 let (rng, _) = dec.debug_state();
19252 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
19253 }
19254 Ok(())
19255}
19256
19257/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
19258/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
19259/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
19260/// it lands away from zero, for gate tests to prove a real stream fired one.
19261fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
19262 let symbol = dec.symbol(cdf);
19263 if symbol != ANGLE_DELTA_ZERO {
19264 hit!(ANGLE_DELTA_HITS);
19265 }
19266 symbol as i32 - ANGLE_DELTA_ZERO as i32
19267}
19268
19269#[allow(clippy::too_many_arguments)]
19270fn read_intra_mode(
19271 dec: &mut SymbolDecoder,
19272 cdfs: &mut Cdfs,
19273 above_mode: usize,
19274 left_mode: usize,
19275 cfl: bool,
19276 side: usize,
19277 enable_filter_intra: bool,
19278 skip_ctx: usize,
19279 allow_screen_content_tools: bool,
19280 allow_intrabc: bool,
19281 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
19282 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
19283 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
19284 // `None` at the excluded call sites (the 8x8-leaf path), which still read
19285 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
19286 // decoder reads either way -- but refuse by name the moment it fires,
19287 // exactly the old behaviour.
19288 palette: Option<(usize, &[u16])>,
19289 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
19290 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
19291 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
19292 // `use_palette_y`, not a neighbour lookup).
19293 palette_uv_cache: &[u16],
19294 mi_r: usize,
19295 mi_c: usize,
19296 fctx: &crate::decode::FrameCtx,
19297) -> Result<(
19298 bool,
19299 usize,
19300 i32,
19301 usize,
19302 i32,
19303 Option<(i32, i32)>,
19304 Option<usize>,
19305 Option<PaletteY>,
19306 Option<PaletteUv>,
19307)> {
19308 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
19309 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
19310 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
19311 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
19312 // line against the instrumented aomdec, not just `tell()`.
19313 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
19314 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
19315 if ec_istep {
19316 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
19317 // (decodemv.c:818), printed at the same point: before the first
19318 // mode-info symbol of the block, so a cross-decoder range ladder can
19319 // be keyed on the BLOCK, not just on the symbol sequence.
19320 eprintln!(
19321 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}",
19322 dec.debug_state().0
19323 );
19324 }
19325 macro_rules! istep {
19326 ($name:literal, $val:expr) => {
19327 if ec_istep {
19328 let (rng, _) = dec.debug_state();
19329 eprintln!(
19330 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
19331 $name, $val
19332 );
19333 }
19334 };
19335 }
19336 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
19337 // point every square caller routes through (see `read_intra_mode_rect`).
19338 let cfl = if cfl && side > 32 {
19339 hit!(NOCFL_UV_MODE_HITS);
19340 false
19341 } else {
19342 cfl
19343 };
19344 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
19345 // `skip` when `SegIdPreSkip`, and after it otherwise.
19346 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
19347 if seg_id_pre_skip(fctx) {
19348 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
19349 }
19350 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
19351 if trace {
19352 eprintln!(
19353 "TRACE skip value={} rng={}",
19354 skip as i32,
19355 dec.debug_state().0
19356 );
19357 }
19358 istep!("skip", skip as i32);
19359 if !seg_id_pre_skip(fctx) {
19360 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
19361 }
19362 // spec order (see the comment below on `read_intrabc_info`): `skip`,
19363 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
19364 maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
19365 istep!("cdef", 0);
19366 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
19367 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
19368 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
19369 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
19370 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
19371 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
19372 istep!("dq", 0);
19373 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
19374 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
19375 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
19376 // intra frame whose header set `allow_intrabc`. Actual intra block copy
19377 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
19378 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
19379 // draws the line at consuming this one flag symbol and refusing by name
19380 // when it fires, so the arithmetic decoder still resyncs for a stream
19381 // that merely allows (but never uses) intrabc.
19382 if allow_intrabc {
19383 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
19384 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
19385 eprintln!(
19386 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
19387 u8::from(use_intrabc),
19388 dec.debug_state().0
19389 );
19390 }
19391 if trace {
19392 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
19393 }
19394 if use_intrabc {
19395 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);
19396 if trace {
19397 eprintln!("TRACE intrabc dv={dv:?}");
19398 }
19399 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
19400 hit!(INTRABC_HITS);
19401 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
19402 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
19403 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
19404 // `DC_PRED` (which is also what the neighbour mode contexts and
19405 // the loop filter then see).
19406 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
19407 }
19408 }
19409 let above_ctx = INTRA_MODE_CTX[above_mode];
19410 let left_ctx = INTRA_MODE_CTX[left_mode];
19411 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
19412 if trace {
19413 eprintln!(
19414 "TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
19415 dec.debug_state().0
19416 );
19417 }
19418 istep!("mode", mode as i32);
19419 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
19420 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
19421 if trace {
19422 eprintln!(
19423 "TRACE angle_delta value={}",
19424 delta + ANGLE_DELTA_ZERO as i32
19425 );
19426 }
19427 delta
19428 } else {
19429 0
19430 };
19431 istep!("angle_y", angle_delta_y);
19432 // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette
19433 // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref`
19434 // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader
19435 // gates its chroma symbols on.
19436 let has_chroma = !mono(fctx);
19437 let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx);
19438 let uv_mode = if !has_chroma {
19439 DC_PRED
19440 } else if cfl {
19441 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
19442 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
19443 } else {
19444 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
19445 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
19446 };
19447 if trace {
19448 eprintln!(
19449 "TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}",
19450 dec.debug_state().0
19451 );
19452 }
19453 istep!("uv_mode", uv_mode as i32);
19454 let alpha = if cfl && uv_mode == UV_CFL_PRED {
19455 Some(read_cfl_alphas(dec, cdfs))
19456 } else {
19457 None
19458 };
19459 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
19460 // from this lane's directional chroma: a corner block with neither
19461 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
19462 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
19463 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
19464 // bug in that fallback this lane's own scope does not cover. Keep it
19465 // refused here rather than ship a silently-wrong decode.
19466 if (9..=12).contains(&uv_mode) {
19467 hit!(SMOOTH_UV_HITS);
19468 }
19469 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
19470 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
19471 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
19472 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
19473 // the `else` branch below and never reads one either way.
19474 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
19475 hit!(DIRECTIONAL_UV_HITS);
19476 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
19477 } else {
19478 0
19479 };
19480 istep!("angle_uv", angle_delta_uv);
19481 if angle_delta_uv != 0 {
19482 hit!(UV_ANGLE_DELTA_HITS);
19483 }
19484 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
19485 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
19486 // gated by `av1_allow_palette` (blockd.h -- size bound only,
19487 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
19488 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
19489 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
19490 // read the same CDF row whenever every neighbour really is non-palette).
19491 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
19492 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
19493 // neighbour lookup at all), so it is exact even at the excluded call
19494 // sites once Y decodes real syntax there too.
19495 //
19496 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
19497 // inline from `read_palette_mode_info` -- it runs later, from
19498 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
19499 // after the WHOLE mode-info read for the block, including UV palette
19500 // mode_info (`read_palette_mode_info`'s own second half, right below)
19501 // and `read_filter_intra_mode_info`. So this branch now only reads
19502 // mode/size/colours for both planes (deferring the two colour-index-map
19503 // decodes to after `filter_intra`, below) -- r6's range trace pinned
19504 // this exact ordering bug (`compare-range-not-tell`: ranges matched
19505 // bit-for-bit through the Y colours, diverged only at the old inline
19506 // `decode_color_index_map` call).
19507 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
19508 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
19509 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) {
19510 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
19511 if mode == DC_PRED {
19512 if trace {
19513 let (rng, _) = dec.debug_state();
19514 eprintln!(
19515 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
19516 );
19517 }
19518 }
19519 let use_palette_y =
19520 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
19521 if mode == DC_PRED && trace {
19522 let (rng, _) = dec.debug_state();
19523 eprintln!(
19524 "TRACE palette_y_mode value={} rng={rng}",
19525 use_palette_y as i32
19526 );
19527 }
19528 if use_palette_y {
19529 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
19530 if trace {
19531 let (rng, _) = dec.debug_state();
19532 eprintln!("TRACE palette_y_size n={n} rng={rng}");
19533 }
19534 let colors = read_palette_colors_y(dec, n, cache, fctx);
19535 if trace {
19536 let (rng, _) = dec.debug_state();
19537 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
19538 }
19539 palette_y_pending = Some((n, colors));
19540 }
19541 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
19542 // unconditionally at this bit position whenever `uv_mode ==
19543 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
19544 // scope always reconstructs chroma alongside luma (`decode_block`
19545 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
19546 // is always true here and does not need threading in.
19547 //
19548 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
19549 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a
19550 // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size`
19551 // symbol even at this chroma-owning square block.
19552 let palette_uv_mode_ctx = usize::from(use_palette_y);
19553 if has_chroma
19554 && uv_mode == DC_PRED
19555 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
19556 {
19557 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
19558 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
19559 palette_uv_pending = Some((n, u_colors, v_colors));
19560 }
19561 }
19562 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
19563 // `use_filter_intra` symbol this decoder never read at all until
19564 // lane-av1real r10 -- silently skipping it left every bit past a
19565 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
19566 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
19567 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
19568 // symbol's bits were never consumed).
19569 let mut filter_intra = None;
19570 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
19571 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
19572 // `use_filter_intra` symbol for a Y-palette block, and reading one here
19573 // desynced every screen-content stream from the first palette block on
19574 // (it surfaced as a bogus "partition below 8x8" refusal further down the
19575 // tile).
19576 if mode == DC_PRED
19577 && enable_filter_intra
19578 && palette_y_pending.is_none()
19579 && let Some(class) = filter_intra_size_class(side)
19580 {
19581 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
19582 if trace {
19583 eprintln!(
19584 "TRACE use_filter_intra side={side} rng={} value={}",
19585 dec.debug_state().0,
19586 use_filter_intra as i32
19587 );
19588 }
19589 istep!("use_filter_intra", use_filter_intra as i32);
19590 if use_filter_intra {
19591 hit!(FILTER_INTRA_HITS);
19592 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
19593 if trace {
19594 eprintln!("TRACE filter_intra_mode value={fi_mode}");
19595 }
19596 istep!("filter_intra_mode", fi_mode as i32);
19597 filter_intra = Some(fi_mode);
19598 }
19599 }
19600 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
19601 // shared U/V map) -- the same order libaom's own loop visits them in.
19602 let palette_y = palette_y_pending.map(|(n, colors)| {
19603 let map = decode_color_index_map(
19604 dec,
19605 cdfs,
19606 n,
19607 side,
19608 palette_onscreen(mi_r, mi_c, side, side, fctx),
19609 false,
19610 );
19611 hit!(PALETTE_HITS);
19612 if trace {
19613 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
19614 }
19615 PaletteY {
19616 size: n,
19617 colors,
19618 map,
19619 }
19620 });
19621 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
19622 let on = palette_onscreen_uv(
19623 (side, side),
19624 palette_onscreen(mi_r, mi_c, side, side, fctx),
19625 (side >> ss_x(fctx), side >> ss_y(fctx)),
19626 (ss_x(fctx), ss_y(fctx)),
19627 );
19628 // lane-av1-422d: the chroma map's extent is the PLANE BLOCK
19629 // `(side >> ss_x) x (side >> ss_y)` -- 4x8 at ss (1,0), not the
19630 // square call's `(side >> ss_x)`-squared (4x4), which left a
19631 // 16-entry map for a 32-sample unit and panicked the reconstruct.
19632 let map = decode_color_index_map_wh(
19633 dec,
19634 cdfs,
19635 n,
19636 side >> ss_x(fctx),
19637 side >> ss_y(fctx),
19638 on,
19639 true,
19640 );
19641 hit!(PALETTE_UV_HITS);
19642 if trace {
19643 eprintln!(
19644 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
19645 &u_colors[..n],
19646 &v_colors[..n]
19647 );
19648 }
19649 PaletteUv {
19650 size: n,
19651 u_colors,
19652 v_colors,
19653 map,
19654 }
19655 });
19656 Ok((
19657 skip,
19658 mode,
19659 angle_delta_y,
19660 uv_mode,
19661 angle_delta_uv,
19662 alpha,
19663 filter_intra,
19664 palette_y,
19665 palette_uv,
19666 ))
19667}
19668
19669/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
19670/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
19671/// intra modes.
19672const UV_CFL_PRED: usize = 13;
19673
19674/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
19675/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
19676/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
19677/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
19678/// joint sign the same way. Returns each plane's final signed `alpha_q3`
19679/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
19680fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
19681 hit!(CFL_BLOCK_HITS);
19682 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
19683 let sign_u = ((joint_sign + 1) * 11) >> 5;
19684 let sign_v = (joint_sign + 1) - 3 * sign_u;
19685 let alpha_u = if sign_u == 0 {
19686 0
19687 } else {
19688 let ctx_u = (joint_sign + 1 - 3) as usize;
19689 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
19690 if sign_u == 2 { mag } else { -mag }
19691 };
19692 let alpha_v = if sign_v == 0 {
19693 0
19694 } else {
19695 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
19696 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
19697 if sign_v == 2 { mag } else { -mag }
19698 };
19699 (alpha_u, alpha_v)
19700}
19701
19702/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
19703/// the reconstructed luma samples under a `side`-square block, subsampled
19704/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
19705/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
19706/// to give the AC values [`cfl_scaled`] scales by alpha.
19707fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
19708 cfl_ac_q3_at(px, py, side, side, |lx, ly| {
19709 i32::from(y.data[ly * y.width + lx])
19710 })
19711}
19712
19713/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
19714/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
19715/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
19716/// reconstruction through THIS function rather than a second transcription of
19717/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
19718/// CfL AC at the frame's subsampling. 4:2:0 keeps the 2x2 average; 4:4:4
19719/// copies each luma sample shifted to Q3 (`cfl_luma_subsampling_444_lbd`).
19720fn cfl_ac_ss(
19721 y: &PlaneBuf<'_>,
19722 px: usize,
19723 py: usize,
19724 bw: usize,
19725 bh: usize,
19726 ss_x: usize,
19727 ss_y: usize,
19728) -> Vec<i32> {
19729 if ss_x == 0 && ss_y == 0 {
19730 let mut ac = vec![0i32; bw * bh];
19731 let mut sum = 0i32;
19732 for row in 0..bh {
19733 for col in 0..bw {
19734 let q3 = i32::from(y.data[(py + row) * y.width + px + col]) << 3;
19735 ac[row * bw + col] = q3;
19736 sum += q3;
19737 }
19738 }
19739 let num_pel = (bw * bh) as i32;
19740 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
19741 ac.iter_mut().for_each(|v| *v -= avg);
19742 ac
19743 } else if ss_x == 1 && ss_y == 0 {
19744 // lane-av1-422: `cfl_luma_subsampling_422_lbd_c` -- each chroma sample
19745 // averages the HORIZONTAL luma pair above it, at full chroma height
19746 // (`(a + b) >> 1` in Q3 is `(a + b) << 2`). A rect luma strip's chroma
19747 // is square here, and the 4:2:0 rect/square helpers below would halve
19748 // the height it must keep.
19749 let (cw, ch) = (bw >> 1, bh);
19750 let mut ac = vec![0i32; cw * ch];
19751 let mut sum = 0i32;
19752 for row in 0..ch {
19753 for col in 0..cw {
19754 let (lx, ly) = (px + col * 2, py + row);
19755 let q3 = (i32::from(y.data[ly * y.width + lx])
19756 + i32::from(y.data[ly * y.width + lx + 1]))
19757 << 2;
19758 ac[row * cw + col] = q3;
19759 sum += q3;
19760 }
19761 }
19762 let num_pel = (cw * ch) as i32;
19763 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
19764 ac.iter_mut().for_each(|v| *v -= avg);
19765 ac
19766 } else if bw == bh {
19767 cfl_ac_q3(y, px, py, bw)
19768 } else {
19769 cfl_ac_q3_rect(y, px, py, bw, bh)
19770 }
19771}
19772
19773pub(crate) fn cfl_ac_q3_at(
19774 px: usize,
19775 py: usize,
19776 bw: usize,
19777 bh: usize,
19778 sample: impl Fn(usize, usize) -> i32,
19779) -> Vec<i32> {
19780 let (cw, ch) = (bw / 2, bh / 2);
19781 let mut ac = vec![0i32; cw * ch];
19782 let mut sum = 0i32;
19783 for cy in 0..ch {
19784 for cx in 0..cw {
19785 let (lx, ly) = (px + cx * 2, py + cy * 2);
19786 let q3 =
19787 (sample(lx, ly) + sample(lx + 1, ly) + sample(lx, ly + 1) + sample(lx + 1, ly + 1))
19788 << 1;
19789 ac[cy * cw + cx] = q3;
19790 sum += q3;
19791 }
19792 }
19793 let num_pel = (cw * ch) as i32;
19794 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
19795 ac.iter_mut().for_each(|v| *v -= avg);
19796 ac
19797}
19798
19799/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
19800/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
19801/// ties away from zero on the shifted-out sign).
19802pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
19803 let v = alpha_q3 * ac_q3;
19804 if v >= 0 {
19805 (v + 32) >> 6
19806 } else {
19807 -((-v + 32) >> 6)
19808 }
19809}
19810
19811/// One plane's reconstruction buffer, `width * height` samples, and the
19812/// prediction/residual reads and writes into it — the decode-side twin of
19813/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
19814/// (own-edge and reach clamps both), passing what it gathers straight to
19815/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
19816/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
19817/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
19818/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
19819/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
19820/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
19821/// lane-mc64 r1: the decode-order index the stage dumps below key their file
19822/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
19823/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
19824/// without this every frame overwrote `.f0` and a per-frame bisection silently
19825/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
19826#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
19827fn stage_dump_idx() -> usize {
19828 PREFILT_PICTURE_IDX
19829 .load(std::sync::atomic::Ordering::SeqCst)
19830 .saturating_sub(1)
19831}
19832
19833fn dump_stage16(
19834 var: &str,
19835 y: &PlaneBuf<'_>,
19836 u: &PlaneBuf<'_>,
19837 v: &PlaneBuf<'_>,
19838 fw: usize,
19839 fh: usize,
19840) {
19841 use std::io::Write;
19842 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
19843 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
19844 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
19845 // not be read out at all.
19846 if let Ok(path) = crate::envflags::var(var)
19847 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
19848 {
19849 for (p, w, h) in [
19850 (y, fw, fh),
19851 (u, fw.div_ceil(2), fh.div_ceil(2)),
19852 (v, fw.div_ceil(2), fh.div_ceil(2)),
19853 ] {
19854 for row in 0..h {
19855 let mut bytes = Vec::with_capacity(w * 2);
19856 for &s in &p.data[row * p.width..][..w] {
19857 bytes.extend_from_slice(&s.to_le_bytes());
19858 }
19859 let _ = f.write_all(&bytes);
19860 }
19861 }
19862 }
19863}
19864
19865/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
19866/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
19867/// every frame overwrote the previous one and only the LAST frame survived,
19868/// which silently defeats any per-frame filter-stage bisection.
19869fn dump_stage_idx(var: &str) -> usize {
19870 use std::collections::HashMap;
19871 use std::sync::{Mutex, OnceLock};
19872 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
19873 let mut m = IDX
19874 .get_or_init(|| Mutex::new(HashMap::new()))
19875 .lock()
19876 .unwrap();
19877 let e = m.entry(var.to_string()).or_insert(0);
19878 let i = *e;
19879 *e += 1;
19880 i
19881}
19882
19883fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
19884 use std::io::Write;
19885 if let Ok(path) = crate::envflags::var(var)
19886 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
19887 {
19888 for p in [y, u, v] {
19889 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
19890 let _ = f.write_all(&narrow);
19891 }
19892 }
19893}
19894
19895/// `EC_AV1_PREFILT_WIDE_DUMP=<prefix>` -> `<prefix>.f<N>`, the pre-loop-filter
19896/// reconstruction cropped to each plane's mi-ALIGNED true extent, byte for
19897/// byte the shape aomdec's own rung 7 writes (`y_width`/`y_height`,
19898/// `uv_width`/`uv_height`), so the two can be diffed directly.
19899///
19900/// lane-av1444edge: this used to be an inline block in the KEY-frame tile path
19901/// only, with a FUNCTION-LOCAL `static IDX2` as its counter. Both facts were
19902/// measurement traps, and the second one is why the first went unnoticed:
19903/// the inter-frame path (`decode_inter_frame_tile_with_cdfs`) had no wide
19904/// prefilter dump at all, so every 4:4:4 lossy divergence localized to an
19905/// inter frame had no pre-filter rung to compare against and got attributed to
19906/// reconstruction when the oracle could not see it. The `static` also restarted
19907/// per monomorphisation, so every frame after the first overwrote `.f0` -- a
19908/// per-frame bisection silently compared the LAST decoded frame. The counter
19909/// is now the shared per-var [`dump_stage_idx`] map, and the call also sits on
19910/// the inter path (skipped when the filter pipeline is active, which has
19911/// already deblocked by the time the tile tail runs -- same condition
19912/// `capture_filter_replay` guards itself with).
19913fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
19914 let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") else {
19915 return;
19916 };
19917 use std::io::Write;
19918 let idx = dump_stage_idx("EC_AV1_PREFILT_WIDE_DUMP");
19919 let crop = |plane: &PlaneBuf<'_>| -> Vec<u8> {
19920 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
19921 for row in 0..plane.true_height {
19922 out.extend(
19923 plane.data[row * plane.width..][..plane.true_width]
19924 .iter()
19925 .map(|&s| s as u8),
19926 );
19927 }
19928 out
19929 };
19930 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
19931 let _ = f.write_all(&crop(y));
19932 let _ = f.write_all(&crop(u));
19933 let _ = f.write_all(&crop(v));
19934 }
19935}
19936
19937/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
19938/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
19939/// at most 4095), so a decode that hashes identically under the flag proves
19940/// the output does not depend on the plane buffer's initial content.
19941const PLANE_SENTINEL: u16 = 0xDEAD;
19942
19943/// A frame plane's own backing store, `n` samples, UNINITIALISED.
19944///
19945/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
19946/// by the tile walk's reconstruction before anything reads it, so the
19947/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
19948/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
19949/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
19950/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
19951/// ways (see the lane report) and the two agree, which is the proof that no
19952/// unwritten sample reaches the output.
19953fn fresh_plane(n: usize) -> Vec<u16> {
19954 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
19955 return vec![PLANE_SENTINEL; n];
19956 }
19957 let mut v: Vec<u16> = Vec::with_capacity(n);
19958 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
19959 // capacity was just reserved, so the vector owns `n` initialised-or-not
19960 // `u16` slots. Every one is written by reconstruction before it is read
19961 // (proven by the sentinel gate above).
19962 #[allow(unsafe_code)]
19963 unsafe {
19964 v.set_len(n);
19965 }
19966 v
19967}
19968
19969#[derive(Clone)]
19970struct PlaneBuf<'a> {
19971 data: std::borrow::Cow<'a, [u16]>,
19972 width: usize,
19973 height: usize,
19974 /// The frame's true, decodable extent in this plane's own units — past
19975 /// this, samples are the padded coding surface's invented tail, never a
19976 /// real decoder's edge or reach reads.
19977 true_width: usize,
19978 true_height: usize,
19979 /// This plane's own tile's top-left pixel origin (spec: intra prediction
19980 /// never reaches across a tile boundary even though an earlier-decoded
19981 /// tile's real pixels sit right there in the shared buffer) — set via
19982 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
19983 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
19984 /// is threaded (the two-tile column-split stage 1 fixture's tile always
19985 /// ends at the frame's own right/bottom edge); a non-last tile's own
19986 /// right/bottom reach bound is still open, tracked in the report.
19987 tile_x0: usize,
19988 tile_y0: usize,
19989 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
19990 /// (exclusive) -- a non-last tile column/row's own reach must stop at
19991 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
19992 /// full padded extent) for the single-tile/last-tile case, matching the
19993 /// old unclipped behaviour exactly.
19994 tile_x1: usize,
19995 tile_y1: usize,
19996}
19997
19998/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
19999/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
20000/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
20001/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
20002/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
20003/// `ALTREF2`/`ALTREF`).
20004
20005impl PlaneBuf<'_> {
20006 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
20007 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
20008 /// are already in this plane's own units (luma pixels for `y`, chroma
20009 /// pixels — halved — for `u`/`v`).
20010 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
20011 self.tile_x0 = x0;
20012 self.tile_y0 = y0;
20013 self.tile_x1 = x1;
20014 self.tile_y1 = y1;
20015 }
20016
20017 fn edges(
20018 &self,
20019 x: usize,
20020 y: usize,
20021 side: usize,
20022 reach: Reach,
20023 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
20024 let own_across = x + side.min(self.true_width.saturating_sub(x));
20025 let across = if reach.above_right {
20026 own_across + side.min(self.true_width.saturating_sub(own_across))
20027 } else {
20028 own_across
20029 }
20030 .min(self.width)
20031 .min(self.tile_x1);
20032 let own_down = y + side.min(self.true_height.saturating_sub(y));
20033 let down = if reach.below_left {
20034 own_down + side.min(self.true_height.saturating_sub(own_down))
20035 } else {
20036 own_down
20037 }
20038 .min(self.height)
20039 .min(self.tile_y1);
20040 let above = (y > self.tile_y0 && across > x)
20041 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
20042 let left = (x > self.tile_x0 && down > y).then(|| {
20043 (y..down)
20044 .map(|row| self.data[row * self.width + x - 1])
20045 .collect::<Vec<_>>()
20046 });
20047 let corner =
20048 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
20049 (above, left, corner)
20050 }
20051
20052 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
20053 /// the above/left reach each extend by their OWN axis (`bw` across,
20054 /// `bh` down), not one shared `side`.
20055 fn edges_rect(
20056 &self,
20057 x: usize,
20058 y: usize,
20059 bw: usize,
20060 bh: usize,
20061 reach: Reach,
20062 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
20063 let own_across = x + bw.min(self.true_width.saturating_sub(x));
20064 let across = if reach.above_right {
20065 own_across + bw.min(self.true_width.saturating_sub(own_across))
20066 } else {
20067 own_across
20068 }
20069 .min(self.width)
20070 .min(self.tile_x1);
20071 let own_down = y + bh.min(self.true_height.saturating_sub(y));
20072 let down = if reach.below_left {
20073 own_down + bh.min(self.true_height.saturating_sub(own_down))
20074 } else {
20075 own_down
20076 }
20077 .min(self.height)
20078 .min(self.tile_y1);
20079 let above = (y > self.tile_y0 && across > x)
20080 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
20081 let left = (x > self.tile_x0 && down > y).then(|| {
20082 (y..down)
20083 .map(|row| self.data[row * self.width + x - 1])
20084 .collect::<Vec<_>>()
20085 });
20086 let corner =
20087 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
20088 if matches!((bw, bh), (16, 8) | (8, 16)) {
20089 hit!(RECT_STRIP_PRED_HITS);
20090 if across > own_across || down > own_down {
20091 hit!(RECT_STRIP_REACH_HITS);
20092 }
20093 }
20094 (above, left, corner)
20095 }
20096
20097 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
20098 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
20099 /// already-rect-capable `(bw, bh)` pair.
20100 #[allow(clippy::too_many_arguments)]
20101 #[track_caller]
20102 fn reconstruct_rect(
20103 &mut self,
20104 x: usize,
20105 y: usize,
20106 bw: usize,
20107 bh: usize,
20108 mode: usize,
20109 angle_delta: i32,
20110 reach: Reach,
20111 residual: &[i32],
20112 cfl: Option<(i32, &[i32])>,
20113 filter_intra: Option<usize>,
20114 smooth_neighbor: bool,
20115 // lane-wave1 step (i): the palette/intrabc prediction override, taken
20116 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
20117 // than by this replay.
20118 pred: Option<Vec<u16>>,
20119 fctx: &crate::decode::FrameCtx,
20120 ) {
20121 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
20122 // (lane-palette2 r4): a palette block's prediction is the
20123 // reconstructed colour-index map, needing no edge pixels at all.
20124 let prediction = if let Some(buf) = pred {
20125 buf
20126 } else {
20127 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
20128 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
20129 eprintln!(
20130 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
20131 above.as_ref().map(|a| (a.len(), a[0])),
20132 left.as_ref().map(|l| l.len()),
20133 left.as_ref().map(|l| l[0]),
20134 self.tile_x0,
20135 self.tile_y0,
20136 self.true_width,
20137 self.true_height
20138 );
20139 }
20140 let mut prediction = vec![0u16; bw * bh];
20141 if let Some(fi_mode) = filter_intra {
20142 crate::intra::predict_filter_intra(
20143 fi_mode,
20144 above.as_deref(),
20145 left.as_deref(),
20146 corner,
20147 bw,
20148 bh,
20149 &mut prediction,
20150 fctx,
20151 );
20152 } else {
20153 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
20154 predict(
20155 mode as u8,
20156 angle_delta,
20157 above.as_deref(),
20158 left.as_deref(),
20159 corner,
20160 bw,
20161 bh,
20162 enable_edge_filter,
20163 smooth_neighbor,
20164 &mut prediction,
20165 fctx,
20166 );
20167 }
20168 prediction
20169 };
20170 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
20171 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
20172 if crate::envflags::env_flag!("EC_PRED") {
20173 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
20174 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
20175 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
20176 eprintln!(
20177 "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
20178 std::panic::Location::caller(),
20179 i32::from(smooth_neighbor)
20180 );
20181 }
20182 let residual = dense_residual(residual, bw * bh);
20183 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
20184 let res0: Vec<i32> = residual[..bw.min(8)].to_vec();
20185 let pred0: Vec<u16> = prediction[..bw.min(8)].to_vec();
20186 eprintln!(
20187 "DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}"
20188 );
20189 }
20190 for row in 0..bh {
20191 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
20192 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
20193 // whose padded width is not superblock aligned hangs past it.
20194 if y + row >= self.height {
20195 break;
20196 }
20197 for col in 0..bw {
20198 if x + col >= self.width {
20199 break;
20200 }
20201 let idx = row * bw + col;
20202 let mut base = i32::from(prediction[idx]);
20203 if let Some((alpha_q3, ac_q3)) = cfl {
20204 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
20205 }
20206 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
20207 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
20208 }
20209 }
20210 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
20211 // -- a block whose prediction matches the oracle's but whose written
20212 // samples do not is either a residual defect or a later overwrite, and
20213 // only this print separates the two.
20214 if crate::envflags::env_flag!("EC_PRED") {
20215 let row0: Vec<u16> = (0..bw.min(8))
20216 .map(|c| self.data[y * self.width + x + c])
20217 .collect();
20218 let col0: Vec<u16> = (0..bh.min(8))
20219 .map(|r| self.data[(y + r) * self.width + x])
20220 .collect();
20221 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
20222 }
20223 }
20224
20225 /// Predicts under `mode` then adds `residual` (side*side, raster),
20226 /// writing the clamped reconstruction back into the plane at `(x, y)`.
20227 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
20228 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
20229 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
20230 /// order (cfl.c).
20231 #[track_caller]
20232 fn reconstruct(
20233 &mut self,
20234 x: usize,
20235 y: usize,
20236 side: usize,
20237 mode: usize,
20238 angle_delta: i32,
20239 reach: Reach,
20240 residual: &[i32],
20241 cfl: Option<(i32, &[i32])>,
20242 filter_intra: Option<usize>,
20243 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
20244 // libaom `get_filt_type`): true when the block's above OR left
20245 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
20246 // Callers pass their own plane's neighbour-mode check
20247 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
20248 // callers until a smooth/paeth `uv_mode` can reach this call at all
20249 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
20250 // keeps `false` exact for chroma without this fn needing to know why.
20251 smooth_neighbor: bool,
20252 // lane-wave1 step (i): the palette/intrabc prediction override, taken
20253 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
20254 // than by this replay.
20255 pred: Option<Vec<u16>>,
20256 fctx: &crate::decode::FrameCtx,
20257 ) {
20258 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
20259 // takes priority over `predict()`/`predict_filter_intra` entirely --
20260 // palette prediction needs no edge pixels at all.
20261 let prediction = if let Some(buf) = pred {
20262 buf
20263 } else {
20264 let (above, left, corner) = self.edges(x, y, side, reach);
20265 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
20266 eprintln!(
20267 "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}",
20268 above.as_deref(),
20269 left.as_deref(),
20270 );
20271 }
20272 let mut prediction = vec![0u16; side * side];
20273 if let Some(fi_mode) = filter_intra {
20274 crate::intra::predict_filter_intra(
20275 fi_mode,
20276 above.as_deref(),
20277 left.as_deref(),
20278 corner,
20279 side,
20280 side,
20281 &mut prediction,
20282 fctx,
20283 );
20284 } else {
20285 // `enable_intra_edge_filter` is the sequence header's own flag
20286 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
20287 // call, never per-block) -- threading it through every
20288 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
20289 // dozen sites for a value that never changes mid-decode, so it
20290 // rides a thread-local instead (this decoder is single-threaded
20291 // per stream).
20292 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
20293 predict(
20294 mode as u8,
20295 angle_delta,
20296 above.as_deref(),
20297 left.as_deref(),
20298 corner,
20299 side,
20300 side,
20301 enable_edge_filter,
20302 smooth_neighbor,
20303 &mut prediction,
20304 fctx,
20305 );
20306 }
20307 prediction
20308 };
20309 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
20310 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
20311 if crate::envflags::env_flag!("EC_PRED") {
20312 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
20313 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
20314 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
20315 eprintln!(
20316 "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
20317 std::panic::Location::caller(),
20318 i32::from(smooth_neighbor)
20319 );
20320 }
20321 let residual = dense_residual(residual, side * side);
20322 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
20323 let res0: Vec<i32> = residual[..side.min(8)].to_vec();
20324 let pred0: Vec<u16> = prediction[..side.min(8)].to_vec();
20325 eprintln!(
20326 "DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}",
20327 cfl.is_some()
20328 );
20329 }
20330 for row in 0..side {
20331 // lane-sb128c r8: libaom's frame buffer is superblock
20332 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
20333 // transform unit of a 128x64 block at the BOTTOM frame edge
20334 // can hang past the last padded row (1920x792: a unit at
20335 // y=768 wants 832 rows of an 800-row buffer, which panicked
20336 // the film's key frames). Those samples are outside the
20337 // frame: never output, and no block below ever references
20338 // them.
20339 if y + row >= self.height {
20340 break;
20341 }
20342 for col in 0..side {
20343 if x + col >= self.width {
20344 break;
20345 }
20346 let idx = row * side + col;
20347 let mut base = i32::from(prediction[idx]);
20348 if let Some((alpha_q3, ac_q3)) = cfl {
20349 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
20350 }
20351 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
20352 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
20353 }
20354 }
20355 }
20356}
20357
20358/// Reads one plane's transform block, reconstructs it into `plane` at
20359/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
20360#[allow(clippy::too_many_arguments)]
20361
20362fn read_plane(
20363 dec: &mut SymbolDecoder,
20364 cdfs: &mut Cdfs,
20365 set: TxbSet,
20366 scan: &[u16],
20367 plane_idx: usize,
20368 around: (bool, bool, i32),
20369 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
20370 // it for every plane's `txb` lookup (it is what an intra transform type's
20371 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
20372 tx_mode: usize,
20373 predict_mode: usize,
20374 angle_delta: i32,
20375 reach: Reach,
20376 // lane-wave1 step (i): unread -- this reader records its write
20377 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
20378 // stays in the signature so every call site still proves the plane is
20379 // exclusively held while its coefficients are parsed.
20380 _plane: &mut PlaneBuf<'static>,
20381 x: usize,
20382 y: usize,
20383 side: usize,
20384 tx_side: usize,
20385 base_q_idx: u8,
20386 cfl: Option<(i32, CflSrc)>,
20387 filter_intra: Option<usize>,
20388 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
20389 // smaller than its own block (spec `get_txb_ctx_general`'s
20390 // `plane_bsize != tx_size` branch), carrying the already-looked-up
20391 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
20392 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
20393 // formula below.
20394 luma_skip_ctx: Option<usize>,
20395 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
20396 smooth_neighbor: bool,
20397 fctx: &crate::decode::FrameCtx,
20398) -> Result<Grid> {
20399 // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's
20400 // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`)
20401 // never reaches a chroma plane -- no u/v coefficient symbol is coded and
20402 // no chroma write is recorded. Return the all-zero grid the caller's
20403 // neighbour bookkeeping reads, without consuming a bit.
20404 if plane_idx > 0 && mono(fctx) {
20405 return Ok(Grid::Zero(side * side));
20406 }
20407 // lane-av1readcensus: the units read from here on are this plane's.
20408 set_census_plane(plane_idx);
20409 let skip_ctx = if plane_idx == 0 {
20410 luma_skip_ctx.unwrap_or(0)
20411 } else {
20412 // libaom `get_txb_ctx`: a chroma unit's context is
20413 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
20414 // plane block is bigger than the transform. Our chroma tables hold the
20415 // offset-7 rows first, so the caller adds 3 for the bigger-block case
20416 // (every chroma unit of a plane block above TX_4X4 -- lane-sb128b r3,
20417 // and lane-av1h5 measured the 4:4:4 lossless 128 root's TX_4X4 chroma
20418 // units reading the offset-10 rows too, against aomdec's `EC_DBGCTX`).
20419 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
20420 };
20421 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
20422 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
20423 // not by the block's ordinary `mode` (which is always DC_PRED whenever
20424 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
20425 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
20426 // filter-intra in AV1).
20427 let tx_mode = if plane_idx == 0 {
20428 fi_tx_row(tx_mode, filter_intra)
20429 } else {
20430 tx_mode
20431 };
20432 let mut coding = cdfs.txb(set, tx_mode);
20433 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
20434 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
20435 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
20436 // plane of a lossless block (the residual then goes through the WHT, so
20437 // the type only picks the scan, which is the default one).
20438 if lossless(fctx) {
20439 coding.tx_type = None;
20440 }
20441 // Luma's `default_tx_type` is only a fallback for the sizes whose
20442 // `TxbSet` carries no symbol at all (32-point and up), which the spec
20443 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
20444 // *never* its own coded symbol (`coding.tx_type` is always `None` for
20445 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
20446 // the plane's own predicted mode (`default_intra_tx_type`) -- except
20447 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
20448 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
20449 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
20450 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
20451 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
20452 // narrows there — only `Chroma32` and up do).
20453 let default_tx_type = if plane_idx == 0 || side >= 32 {
20454 TxType::DctDct
20455 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
20456 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
20457 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
20458 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
20459 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
20460 // [`read_inter_plane`]'s own `side < 32` guard).
20461 inherited
20462 } else {
20463 default_intra_tx_type(predict_mode as u8)
20464 };
20465 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
20466 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
20467 let default_tx_type = if lossless(fctx) {
20468 TxType::DctDct
20469 } else {
20470 default_tx_type
20471 };
20472 let (grid, tx_type) = read_coeffs(
20473 dec,
20474 &mut coding,
20475 scan,
20476 skip_ctx,
20477 dc_sign_ctx(around.2),
20478 default_tx_type,
20479 None,
20480 )?;
20481 note_chroma_class1(plane_idx, tx_type);
20482 if plane_idx == 0 {
20483 fctx.luma_tx_type.with(|c| c.set(tx_type));
20484 }
20485 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
20486 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
20487 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
20488 // guard also assumes.
20489 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
20490 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
20491 // keyed by that true size, not the coded corner's -- so the corner
20492 // goes into the top-left of a `side`-sized grid, not the reverse.
20493 let levels = extend_corner(grid, tx_side, tx_side, side, side);
20494 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
20495 let tx = TxParams {
20496 w: side,
20497 h: side,
20498 bit_depth: bit_depth(fctx),
20499 q_idx: block_q_idx(fctx),
20500 dc_delta,
20501 ac_delta,
20502 tx_type,
20503 qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type),
20504 stride: 0,
20505 lossless: lossless(fctx),
20506 };
20507 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20508 let residual = tx.run(&levels);
20509 eprintln!(
20510 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}",
20511 &*levels,
20512 );
20513 }
20514 push_intra_tx(
20515 plane_idx,
20516 x,
20517 y,
20518 side,
20519 side,
20520 false,
20521 predict_mode,
20522 angle_delta,
20523 reach,
20524 tx,
20525 &levels,
20526 cfl,
20527 filter_intra,
20528 smooth_neighbor,
20529 fctx,
20530 );
20531 // `record`'s neighbour state only reads whether *the coded grid* (not the
20532 // residual) has nonzero entries, so the levels this function already
20533 // built are what it wants back -- both arms of the old `tx_side == side`
20534 // branch returned exactly that, one of them through a full `to_vec` copy
20535 // of the grid per intra transform unit (lane-coefbuf).
20536 Ok(levels)
20537}
20538
20539/// [`push_intra`] when the unit is square, [`push_intra_rect`] when it is a
20540/// rect (lane-av1-422f): a 4:2:2 square-block chroma unit is the plane
20541/// block's own rect shape, and the `rect` flag selects
20542/// [`PlaneBuf::reconstruct_rect`]'s two-dimensional loop.
20543#[allow(clippy::too_many_arguments)]
20544fn push_intra_unit(
20545 plane: usize,
20546 x: usize,
20547 y: usize,
20548 w: usize,
20549 h: usize,
20550 mode: usize,
20551 angle_delta: i32,
20552 reach: Reach,
20553 residual: &[i32],
20554 cfl: Option<(i32, CflSrc)>,
20555 filter_intra: Option<usize>,
20556 smooth_neighbor: bool,
20557 fctx: &crate::decode::FrameCtx,
20558) {
20559 if w == h {
20560 push_intra(
20561 plane,
20562 x,
20563 y,
20564 w,
20565 mode,
20566 angle_delta,
20567 reach,
20568 residual,
20569 cfl,
20570 filter_intra,
20571 smooth_neighbor,
20572 fctx,
20573 );
20574 } else {
20575 push_intra_rect(
20576 plane,
20577 x,
20578 y,
20579 w,
20580 h,
20581 mode,
20582 angle_delta,
20583 reach,
20584 residual,
20585 cfl,
20586 filter_intra,
20587 smooth_neighbor,
20588 fctx,
20589 );
20590 }
20591}
20592
20593/// ONE RECT chroma transform unit of a square block's uv plane
20594/// (lane-av1-422f) -- a 4:2:2 frame's plane block is `(side/2, side)` and
20595/// `av1_get_max_uv_txsize` fills it with a single rect unit below side 64
20596/// (TX_4X8 / TX_8X16 / TX_16X32), which the square-shaped [`read_plane`]
20597/// cannot express. Same shape as [`leaf8_chroma422_unit`]'s proven read: the
20598/// [`TxbSet`] whose entropy class the unit squares up to, the unit-shaped
20599/// scan, `txb_skip_ctx` = above + left in the offset-7 rows (the unit covers
20600/// the plane block exactly, so no `+3` bigger-plane term -- that one lives in
20601/// the square multi-unit walks' `chroma_ctx_offset`), and the plane's
20602/// predicted mode supplies the mode-derived default `tx_type` unless an armed
20603/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own -- except at an
20604/// entropy class of 32x32 and up, where the spec forces `DCT_DCT`
20605/// ([`read_plane`]'s `side >= 32` clamp).
20606#[allow(clippy::too_many_arguments)]
20607fn read_rect_chroma_unit(
20608 dec: &mut SymbolDecoder,
20609 cdfs: &mut Cdfs,
20610 set: TxbSet,
20611 scan: &[u16],
20612 w: usize,
20613 h: usize,
20614 plane_idx: usize,
20615 around: (bool, bool, i32),
20616 uv_predict_mode: usize,
20617 angle_delta_uv: i32,
20618 reach: Reach,
20619 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
20620 // the plane exclusively while the unit's coefficients are parsed.
20621 _plane: &mut PlaneBuf<'static>,
20622 x: usize,
20623 y: usize,
20624 // Signature parity with [`read_plane`]; the dequant reads its q index
20625 // off `block_q_idx(fctx)` like every other reader here.
20626 _base_q_idx: u8,
20627 // lane-av1-422p: `get_txb_ctx_general`'s chroma branch
20628 // (txb_common.h) reads `txb_skip_ctx = above + left + ctx_offset`,
20629 // where `ctx_offset` is 10 when the plane block is bigger than the
20630 // transform and 7 otherwise. The port stores the offset-7 rows at
20631 // `txb_skip_chroma_8` rows 0..3 and the offset-10 rows at rows 3..6
20632 // (lane-av1-422b), so a unit SMALLER than its plane block passes
20633 // `Some(3)` to reach the offset-10 rows. Every unit that IS the whole
20634 // plane block stays `None` -- 4:2:2 plane blocks never shrink to a
20635 // rect unit except in the chunk arms.
20636 chroma_skip_offset: Option<usize>,
20637 cfl: Option<(i32, CflSrc)>,
20638 smooth_neighbor_uv: bool,
20639 fctx: &crate::decode::FrameCtx,
20640) -> Result<Grid> {
20641 if ss_x(fctx) == 1 && ss_y(fctx) == 0 && w != h {
20642 hit!(CHROMA422_RECT_HITS);
20643 }
20644 let default_tx = if w.max(h) >= 32 {
20645 TxType::DctDct
20646 } else {
20647 fctx.intrabc_chroma_tx
20648 .with(std::cell::Cell::get)
20649 .unwrap_or_else(|| default_intra_tx_type(uv_predict_mode as u8))
20650 };
20651 let mut coding = cdfs.txb(set, uv_predict_mode);
20652 let (levels, tx_type) = read_coeffs_rect(
20653 dec,
20654 &mut coding,
20655 scan,
20656 w,
20657 h,
20658 usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0),
20659 dc_sign_ctx(around.2),
20660 default_tx,
20661 plane_idx,
20662 )?;
20663 let residual = dequant_and_inverse_typed_wh(
20664 &levels,
20665 w,
20666 h,
20667 crate::decode::bit_depth(fctx),
20668 block_q_idx(fctx),
20669 plane_q_delta(plane_idx, fctx).0,
20670 plane_q_delta(plane_idx, fctx).1,
20671 tx_type,
20672 block_iqmatrix(fctx, plane_idx, w, h, tx_type),
20673 );
20674 push_intra_rect(
20675 plane_idx,
20676 x,
20677 y,
20678 w,
20679 h,
20680 uv_predict_mode,
20681 angle_delta_uv,
20682 reach,
20683 &residual,
20684 cfl,
20685 None,
20686 smooth_neighbor_uv,
20687 fctx,
20688 );
20689 Ok(levels)
20690}
20691
20692/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
20693/// three planes, reconstructing them into `y`/`u`/`v` and updating
20694/// `neighbours`.
20695#[allow(clippy::too_many_arguments)]
20696fn decode_block(
20697 dec: &mut SymbolDecoder,
20698 cdfs: &mut Cdfs,
20699 neighbours: &mut Neighbours,
20700 at: (usize, usize),
20701 side: usize,
20702 luma_set: TxbSet,
20703 chroma_set: TxbSet,
20704 luma_tx: usize,
20705 chroma_tx: usize,
20706 scans: (&[u16], &[u16]),
20707 cfl: bool,
20708 y: &mut PlaneBuf<'static>,
20709 u: &mut PlaneBuf<'static>,
20710 v: &mut PlaneBuf<'static>,
20711 base_q_idx: u8,
20712 enable_filter_intra: bool,
20713 allow_screen_content_tools: bool,
20714 allow_intrabc: bool,
20715 scan32: &[u16],
20716 scan16: &[u16],
20717 scan8: &[u16],
20718 scan4: &[u16],
20719 tx_select: bool,
20720 reduced_tx_set: bool,
20721 fctx: &crate::decode::FrameCtx,
20722) -> Result<()> {
20723 let (r, c) = at;
20724 let (px, py) = (c * SUB, r * SUB);
20725 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
20726 let palette_uv_cache = neighbours.palette_uv_cache(at);
20727 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
20728 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
20729 let (
20730 skip,
20731 mode,
20732 angle_delta_y,
20733 uv_mode,
20734 angle_delta_uv,
20735 alpha,
20736 filter_intra,
20737 palette_y,
20738 palette_uv,
20739 ) = read_intra_mode(
20740 dec,
20741 cdfs,
20742 nb_above_mode,
20743 nb_left_mode,
20744 cfl,
20745 side,
20746 enable_filter_intra,
20747 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
20748 allow_screen_content_tools,
20749 allow_intrabc,
20750 Some((palette_ctx, &palette_cache)),
20751 &palette_uv_cache,
20752 r * (SUB / MI),
20753 c * (SUB / MI),
20754 fctx,
20755 )?;
20756 if at_tile_left && palette_y.is_some() {
20757 hit!(PALETTE_TILE_LEFT_HITS);
20758 }
20759 // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane
20760 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
20761 // tables/scans are replaced by the 4x4 ones and the block always takes the
20762 // multi-transform-unit path below. lane-av1mixloss: this rewrite used to
20763 // sit at the TOP of the function -- before `read_intra_mode`, which is
20764 // where the block's own `segment_id` is read -- so a mixed frame resolved
20765 // every block's geometry against the PREVIOUS block's segment (a lossless
20766 // neighbour forced 4x4 units on a lossy block; a lossy one handed the
20767 // lossless TxParams an 8x8 grid). libaom's order is the opposite one:
20768 // `decode_mbmi_block` (segment id included) runs before any tx-size rule.
20769 // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this
20770 // rewrite (which sat above `read_intra_mode`) rides along here -- same
20771 // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own
20772 // segment like the lossless arm above it.
20773 let (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx_h, scans) = if lossless(fctx) {
20774 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, 4, (scan4, scan4))
20775 } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
20776 let tx = if side >= 64 { 32 } else { side };
20777 let (set, scan): (TxbSet, &[u16]) = match tx {
20778 32 => (TxbSet::Chroma32, scan32),
20779 16 => (TxbSet::Chroma16, scan16),
20780 8 => (TxbSet::Chroma8, scan8),
20781 _ => (TxbSet::Chroma4, scan4),
20782 };
20783 (luma_set, set, luma_tx, tx, tx, (scans.0, scan))
20784 } else if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
20785 // lane-av1-422f: the uv plane block is the (side/2, side) rect
20786 // (`ss_size_lookup[..][1][0]`), and `av1_get_max_uv_txsize` is
20787 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[plane_bsize])` --
20788 // the RECT that fills the plane block, NOT the square transform of
20789 // the smaller side (the oracle reads ONE TX_8X16 for a 16x16 block's
20790 // 8x16 plane where the old model read two 8x8 units): 4 -> TX_4X4
20791 // (the 2x4 plane rounds up to BLOCK_4X4), 8 -> TX_4X8, 16 ->
20792 // TX_8X16, 32 -> TX_16X32 (one unit per plane, the whole plane
20793 // block), 64 -> TX_32X64 adjusts to TX_32X32 and 128 -> TX_64X64
20794 // adjusts to TX_32X32 (square units, a 1x2 / 2x4 grid).
20795 // `chroma_tx` is the unit WIDTH, `chroma_tx_h` its HEIGHT; the
20796 // chroma walks below read one (chroma_tx, chroma_tx_h) unit per grid
20797 // cell and key their rect reads on `chroma_tx != chroma_tx_h`.
20798 let (tx_w, tx_h) = match side {
20799 4 => (4, 4),
20800 8 => (4, 8),
20801 16 => (8, 16),
20802 32 => (16, 32),
20803 // 64 and 128: TX_32X64 / TX_64X64 adjust down to TX_32X32.
20804 _ => (32, 32),
20805 };
20806 let (set, scan): (TxbSet, &[u16]) = match side {
20807 4 => (TxbSet::Chroma4, scan4),
20808 8 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
20809 16 => (TxbSet::ChromaRect16x8, &SCAN_8X16[..]),
20810 32 => (TxbSet::ChromaRect32x16, &SCAN_16X32[..]),
20811 _ => (TxbSet::Chroma32, scan32),
20812 };
20813 (luma_set, set, luma_tx, tx_w, tx_h, (scans.0, scan))
20814 } else {
20815 (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx, scans)
20816 };
20817 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
20818 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
20819 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
20820 // actual chroma-from-luma correlation, same as this decoder always did.
20821 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
20822 DC_PRED
20823 } else {
20824 uv_mode
20825 };
20826 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
20827 if smooth_neighbor {
20828 hit!(SMOOTH_LUMA_HITS);
20829 }
20830 let smooth_neighbor_uv =
20831 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
20832 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20833 eprintln!(
20834 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
20835 angle_delta_uv={angle_delta_uv}"
20836 );
20837 }
20838 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
20839 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
20840 // block, skipped or not. `logical_tx` is what the loop filter's edge
20841 // lookup and the next block's own `get_tx_size_context` want (the *nominal*
20842 // transform size -- 64 even for the 64x64 corner-scanned case, spec
20843 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
20844 // which only differs from it at that one corner case.
20845 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
20846 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
20847 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
20848 // intrabc block reads NO tx-size symbol at all -- it takes
20849 // `maxRectTxSize` -- while every ordinary skipped intra block does read
20850 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
20851 // the tile from that block on (class `equal-range-means-unread`).
20852 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
20853 // tree instead (`read_var_tx_size`), the same syntax the inter block path
20854 // has always read -- libaom's `parse_decode_block` dispatches on
20855 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
20856 // intrabc block as inter.
20857 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
20858 // libaom `parse_decode_block`'s var-tx tree condition carries
20859 // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc
20860 // block inside a LOSSLESS segment of a mixed frame reads NO
20861 // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line
20862 // hands back TX_4X4. Invisible while every lossless frame was also
20863 // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which
20864 // is why the mixed frame is the first stream to reach it.
20865 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx);
20866 let intrabc_leaves = if intrabc_vartx {
20867 let max_tx = side.min(64);
20868 // `max_block_wide`/`max_block_high`: the frame's own mi grid
20869 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
20870 // right/bottom edge reads no split symbol for the units outside it.
20871 let mi_cols = 2 * y.true_width.div_ceil(8);
20872 let mi_rows = 2 * y.true_height.div_ceil(8);
20873 let side_mi = side / MI;
20874 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
20875 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
20876 let mut leaves = Vec::new();
20877 for row in (0..side_mi).step_by(max_tx / MI) {
20878 for col in (0..side_mi).step_by(max_tx / MI) {
20879 read_var_tx_size(
20880 dec,
20881 cdfs,
20882 neighbours,
20883 (mi_r, mi_c),
20884 side,
20885 (max_w_mi, max_h_mi),
20886 (max_tx, max_tx),
20887 0,
20888 row,
20889 col,
20890 &mut leaves,
20891 );
20892 }
20893 }
20894 hit!(INTRABC_VARTX_HITS);
20895 // lane-t900 r33 census: the t900 recipes resolved every tree UNIFORM.
20896 // lane-av1-ibcvtx: a tree that resolved to mixed leaf sizes is no
20897 // longer refused -- the luma reconstruct below walks the tree's own
20898 // leaf list per leaf (libaom `decode_token_recon_block`, whose token
20899 // loop reconstructs whatever `read_tx_size_vartx` resolved, per
20900 // transform unit), so mixed sizes reconstruct at their own stride.
20901 // The counter marks the shape so a gate can prove a witness actually
20902 // carries a mixed tree and not merely another uniform one.
20903 let uniform = leaves.first().is_some_and(|f| {
20904 leaves
20905 .iter()
20906 .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)
20907 });
20908 if !uniform {
20909 hit!(INTRABC_VARTX_MIXED_LEAVES_HITS);
20910 if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") {
20911 eprintln!(
20912 "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \
20913 dv={intrabc_dv:?} leaves={leaves:?}"
20914 );
20915 }
20916 }
20917 Some(leaves)
20918 } else {
20919 None
20920 };
20921 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves.as_ref().map(|l| l[0].2) {
20922 (tx, if tx == 64 { 32 } else { tx })
20923 } else if tx_select && !intrabc_skip_tx {
20924 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx);
20925 (resolved, if resolved == 64 { 32 } else { resolved })
20926 } else {
20927 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
20928 // TX_64X64, so a 128x128 block is always FOUR luma transform units
20929 // even with `tx_select` off -- the TU loop below, never the
20930 // single-unit path.
20931 (lossless_tx(side.min(64), fctx), luma_tx)
20932 };
20933 if tx_select && logical_tx < side && uv_mode != DC_PRED {
20934 hit!(SQ_CHROMA_TX_HITS);
20935 }
20936 let luma_set = if tx_select {
20937 txbset_for(logical_tx, reduced_tx_set)
20938 } else {
20939 luma_set
20940 };
20941 let luma_set = if intrabc_dv.is_some() {
20942 inter_txbset_for(logical_tx, reduced_tx_set)
20943 } else {
20944 luma_set
20945 };
20946 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
20947 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
20948 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
20949 let chroma_side = side >> ss_x(fctx);
20950 // lane-av1-422b: chroma extent per axis, `side` at ss_y 0 (4:2:2/4:4:4),
20951 // `side / 2` at 4:2:0.
20952 let chroma_height = side >> ss_y(fctx);
20953 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
20954 // frame's own pre-loop-filter reconstruction (all loop filters are off
20955 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
20956 // block vector, with the BILINEAR kernel libaom forces for intrabc --
20957 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
20958 // odd, which is exactly what the bilinear taps then interpolate.
20959 flush_recon(fctx, y, u, v);
20960 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
20961 let mut yb = vec![0u16; side * side];
20962 mc::predict_with_filter(
20963 &y.data,
20964 y.width,
20965 y.true_width,
20966 y.true_height,
20967 mv_to_q4(px, dv_col, 0),
20968 mv_to_q4(py, dv_row, 0),
20969 side,
20970 side,
20971 mc::InterpFilterKind::Bilinear,
20972 &mut yb,
20973 fctx,
20974 );
20975 let mut ub = vec![0u16; chroma_side * chroma_height];
20976 mc::predict_with_filter(
20977 &u.data,
20978 u.width,
20979 u.true_width,
20980 u.true_height,
20981 mv_to_q4(cpx, dv_col, ss_x(fctx)),
20982 mv_to_q4(cpy, dv_row, ss_y(fctx)),
20983 chroma_side,
20984 chroma_height,
20985 mc::InterpFilterKind::Bilinear,
20986 &mut ub,
20987 fctx,
20988 );
20989 let mut vb = vec![0u16; chroma_side * chroma_height];
20990 mc::predict_with_filter(
20991 &v.data,
20992 v.width,
20993 v.true_width,
20994 v.true_height,
20995 mv_to_q4(cpx, dv_col, ss_x(fctx)),
20996 mv_to_q4(cpy, dv_row, ss_y(fctx)),
20997 chroma_side,
20998 chroma_height,
20999 mc::InterpFilterKind::Bilinear,
21000 &mut vb,
21001 fctx,
21002 );
21003 (yb, ub, vb)
21004 });
21005 // A palette-Y block's own prediction is the reconstructed colour-index
21006 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
21007 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
21008 // parameter through this function's dozen `y.reconstruct`/`read_plane`
21009 // sites. A split luma transform (`tx_select && logical_tx != side`)
21010 // would need the map sliced per-TU -- untested against a real
21011 // `--enable-palette=1` stream this round, so refuse by name rather than
21012 // guess at the slicing (charter's own named-acceptable fallback).
21013 let palette_y_buf: Option<Vec<u16>> = palette_y
21014 .as_ref()
21015 .map(|py| py.map.iter().map(|&idx| py.colors[idx as usize]).collect());
21016 // lane-t900 r32: the intrabc luma prediction rides the very same
21017 // whole-block override slot, so the multi-TU loop below windows it per
21018 // transform unit exactly like a palette map -- setting it once up front
21019 // handed the whole `side`x`side` buffer to the FIRST unit and left every
21020 // later one predicting off block edges (the var-tx tree above is what
21021 // first makes `logical_tx < side` reachable for an intrabc block).
21022 let palette_y_buf = match &intrabc_bufs {
21023 Some((yb, _, _)) => Some(yb.clone()),
21024 None => palette_y_buf,
21025 };
21026 // With one luma transform unit the whole `side`x`side` map is the
21027 // prediction; with several (`logical_tx != side`) each unit takes its own
21028 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
21029 // below (lane-palette2 r7) -- setting the full-block buffer here would be
21030 // taken by the FIRST unit and indexed at the wrong stride.
21031 // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call
21032 // (the `else` arm below -- a palette/intrabc block never takes the per-unit
21033 // `split_tx_skip` walk), so its map must be armed here even when the
21034 // transform is split. Gating the arm on `logical_tx == side` alone left a
21035 // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC
21036 // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen
21037 // key frame; class override-slot-on-one-arm). Neither prediction is
21038 // edge-derived, so the whole-block buffer at the block's own stride is
21039 // exactly what that single call wants.
21040 // Counted on the SHAPE, not on the arm below, so a gate can tell a stream
21041 // that reaches this block apart from one that never does (class
21042 // gate-blind-to-feature).
21043 if palette_y_buf.is_some() && skip && logical_tx < side {
21044 hit!(SKIP_SPLIT_TX_OVERRIDE_HITS);
21045 }
21046 if let Some(buf) = &palette_y_buf
21047 && (logical_tx == side || skip)
21048 {
21049 set_palette_pred(buf.clone(), fctx);
21050 }
21051 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
21052 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
21053 // plane's own `reconstruct`/`read_plane` call below (never both planes at
21054 // once), since Y's own set-then-take already emptied the slot by the time
21055 // either of these run.
21056 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
21057 (
21058 puv.map
21059 .iter()
21060 .map(|&idx| puv.u_colors[idx as usize])
21061 .collect(),
21062 puv.map
21063 .iter()
21064 .map(|&idx| puv.v_colors[idx as usize])
21065 .collect(),
21066 )
21067 });
21068 // The chroma half of the intrabc prediction rides the same per-plane
21069 // override slot the UV-palette buffers do (set fresh before each plane's
21070 // own `reconstruct`/`read_plane` call below).
21071 let palette_uv_bufs = match &intrabc_bufs {
21072 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
21073 None => palette_uv_bufs,
21074 };
21075 if skip {
21076 // A skipped block codes no residual syntax at all (spec 5.11.34):
21077 // straight prediction, on every plane.
21078 //
21079 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
21080 // is skipped (only an INTER skip forces the largest transform), and
21081 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
21082 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
21083 // already written left/above of it inside this same block. Predicting
21084 // the whole `side`x`side` at once gives a different (uniformly off by
21085 // ~1) answer, which is exactly the residue this lane was chasing.
21086 // The palette/intrabc override path keeps the single-call shape (its
21087 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
21088 // untested for skip and unreachable in these streams).
21089 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
21090 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
21091 // per-unit prediction is keyed on the transform being smaller than
21092 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
21093 // narrower meaning (a READ split tx depth).
21094 let split_tx_skip = logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
21095 if split_tx_skip {
21096 if tx_select {
21097 hit!(SKIP_SPLIT_TX_HITS);
21098 }
21099 let n_axis = side / logical_tx;
21100 for tu_row in 0..n_axis {
21101 for tu_col in 0..n_axis {
21102 let tu_px = px + tu_col * logical_tx;
21103 let tu_py = py + tu_row * logical_tx;
21104 if tu_px >= y.true_width || tu_py >= y.true_height {
21105 continue;
21106 }
21107 let tu_reach = tu_reach(
21108 side,
21109 side,
21110 tu_col * logical_tx,
21111 tu_row * logical_tx,
21112 logical_tx,
21113 reach,
21114 px,
21115 py,
21116 y.width,
21117 y.height,
21118 fctx,
21119 );
21120 push_intra(
21121 0,
21122 tu_px,
21123 tu_py,
21124 logical_tx,
21125 mode,
21126 angle_delta_y,
21127 tu_reach,
21128 &ZERO_RESIDUAL[..logical_tx * logical_tx],
21129 None,
21130 filter_intra,
21131 smooth_neighbor,
21132 fctx,
21133 );
21134 }
21135 }
21136 } else {
21137 push_intra(
21138 0,
21139 px,
21140 py,
21141 side,
21142 mode,
21143 angle_delta_y,
21144 reach,
21145 &ZERO_RESIDUAL[..side * side],
21146 None,
21147 filter_intra,
21148 smooth_neighbor,
21149 fctx,
21150 );
21151 }
21152 let ac = alpha.map(|_| cfl_src(px, py, side));
21153 // lane-av1-422b: the chroma unit grid is `cn_cols` x `cn_rows` --
21154 // square at 4:2:0/4:4:4, at 4:2:2 `(side/2)/tx` units wide by
21155 // `side/tx` tall (the plane block is (side/2, side)). A unit's LUMA
21156 // anchor follows the per-axis shifts: `chroma_tx << ss_x` wide,
21157 // `chroma_tx_h << ss_y` tall (lane-av1-422f: the unit itself is the
21158 // (chroma_tx, chroma_tx_h) rect, so a 4:2:2 frame below side 64
21159 // reads ONE unit per plane, the whole plane block).
21160 let cn_cols = (chroma_side / chroma_tx).max(1);
21161 let cn_rows = (chroma_height / chroma_tx_h).max(1);
21162 let luma_span_x = chroma_tx << ss_x(fctx);
21163 let luma_span_y = chroma_tx_h << ss_y(fctx);
21164 for cu_row in 0..cn_rows {
21165 for cu_col in 0..cn_cols {
21166 let cu_r = if cn_rows == 1 && cn_cols == 1 {
21167 reach
21168 } else {
21169 tu_reach_rect(
21170 side,
21171 side,
21172 cu_col * luma_span_x,
21173 cu_row * luma_span_y,
21174 luma_span_x,
21175 luma_span_y,
21176 reach,
21177 px,
21178 py,
21179 y.width,
21180 y.height,
21181 fctx,
21182 )
21183 };
21184 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
21185 if let Some((ub, _)) = &palette_uv_bufs {
21186 set_palette_pred(ub.clone(), fctx);
21187 }
21188 push_intra_unit(
21189 1,
21190 cu_x,
21191 cu_y,
21192 chroma_tx,
21193 chroma_tx_h,
21194 uv_predict_mode,
21195 angle_delta_uv,
21196 cu_r,
21197 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
21198 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21199 None,
21200 smooth_neighbor_uv,
21201 fctx,
21202 );
21203 if let Some((_, vb)) = &palette_uv_bufs {
21204 set_palette_pred(vb.clone(), fctx);
21205 }
21206 push_intra_unit(
21207 2,
21208 cu_x,
21209 cu_y,
21210 chroma_tx,
21211 chroma_tx_h,
21212 uv_predict_mode,
21213 angle_delta_uv,
21214 cu_r,
21215 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
21216 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21217 None,
21218 smooth_neighbor_uv,
21219 fctx,
21220 );
21221 }
21222 }
21223 let luma_grid = vec![0i32; side * side];
21224 let u_grid = vec![0i32; chroma_side * chroma_side];
21225 let v_grid = vec![0i32; chroma_side * chroma_side];
21226 neighbours.record(
21227 at,
21228 side,
21229 mode,
21230 uv_predict_mode,
21231 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
21232 );
21233 } else if logical_tx == side {
21234 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
21235 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
21236 // that arm was redundant -- and wrong at 128, where
21237 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
21238 // block is four units whether or not `tx_select` is on.
21239 // A single luma transform unit -- the old path, unchanged (including
21240 // the 64x64 corner case, `logical_tx == side == 64` with
21241 // `coeff_tx_side == 32`).
21242 let around = neighbours.around(at, side);
21243 let luma_grid = read_plane(
21244 dec,
21245 cdfs,
21246 luma_set,
21247 luma_scan,
21248 0,
21249 around[0],
21250 mode,
21251 mode,
21252 angle_delta_y,
21253 reach,
21254 y,
21255 px,
21256 py,
21257 side,
21258 coeff_tx_side,
21259 base_q_idx,
21260 None,
21261 filter_intra,
21262 None,
21263 smooth_neighbor,
21264 fctx,
21265 )?;
21266 let ac = alpha.map(|_| cfl_src(px, py, side));
21267 // Armed for exactly this block's two chroma reads (see
21268 // [`INTRABC_CHROMA_TX`]); the luma call above just set
21269 // [`LUMA_TX_TYPE`] to the type it coded.
21270 if intrabc_dv.is_some() {
21271 fctx.intrabc_chroma_tx
21272 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
21273 }
21274 // lane-av1-444: this arm is one luma TU (`logical_tx == side`), including
21275 // the 64x64 case whose coefficient grid is 32. At 4:4:4 the chroma plane
21276 // is the same size as luma and `av1_get_max_uv_txsize` caps it at
21277 // TX_32X32, so a 64x64 block codes four chroma units, plane-major
21278 // (every U, then every V) — the same loop the multi-TU arm runs.
21279 // At 4:2:0 `chroma_side == chroma_tx`, so it stays one read.
21280 // lane-av1-422b: 4:2:2 never collapses to one read above a 4x4 luma
21281 // block -- the unit grid is `(side/2)/tx` wide by `side/tx` tall.
21282 // lane-av1-422f: `chroma_tx` is the unit WIDTH and `chroma_tx_h` its
21283 // HEIGHT, so below side 64 a 4:2:2 frame's grid is 1x1 and the one
21284 // unit is the plane block's own rect.
21285 let cn_cols = (chroma_side / chroma_tx).max(1);
21286 let cn_rows = (chroma_height / chroma_tx_h).max(1);
21287 let luma_span_x = chroma_tx << ss_x(fctx);
21288 let luma_span_y = chroma_tx_h << ss_y(fctx);
21289 let (u_grid, v_grid, chroma_units) = if cn_rows == 1 && cn_cols == 1 {
21290 if chroma_tx == chroma_tx_h {
21291 if let Some((ub, _)) = &palette_uv_bufs {
21292 set_palette_pred(ub.clone(), fctx);
21293 }
21294 let u_grid = read_plane(
21295 dec,
21296 cdfs,
21297 chroma_set,
21298 scans.1,
21299 1,
21300 around[1],
21301 mode,
21302 uv_predict_mode,
21303 angle_delta_uv,
21304 reach,
21305 u,
21306 cpx,
21307 cpy,
21308 chroma_side,
21309 chroma_tx,
21310 base_q_idx,
21311 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21312 None,
21313 None,
21314 smooth_neighbor_uv,
21315 fctx,
21316 )?;
21317 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21318 eprintln!(
21319 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
21320 &u.data[cpy * u.width + cpx..][..chroma_side]
21321 );
21322 }
21323 if let Some((_, vb)) = &palette_uv_bufs {
21324 set_palette_pred(vb.clone(), fctx);
21325 }
21326 let v_grid = read_plane(
21327 dec,
21328 cdfs,
21329 chroma_set,
21330 scans.1,
21331 2,
21332 around[2],
21333 mode,
21334 uv_predict_mode,
21335 angle_delta_uv,
21336 reach,
21337 v,
21338 cpx,
21339 cpy,
21340 chroma_side,
21341 chroma_tx,
21342 base_q_idx,
21343 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21344 None,
21345 None,
21346 smooth_neighbor_uv,
21347 fctx,
21348 )?;
21349 (u_grid, v_grid, Vec::new())
21350 } else {
21351 // lane-av1-422f: the one unit is a RECT filling the plane
21352 // block -- the square-shaped [`read_plane`] cannot express
21353 // it, so both planes go through [`read_rect_chroma_unit`]
21354 // (U, then V, the same order the square arm reads). The
21355 // chroma context reads per chroma 4-px cell (see
21356 // [`Neighbours::around_mi_422_chroma`]).
21357 let chroma_around = neighbours.around_mi_422_chroma((mi_r, mi_c), side, side);
21358 if let Some((ub, _)) = &palette_uv_bufs {
21359 set_palette_pred(ub.clone(), fctx);
21360 }
21361 let u_grid = read_rect_chroma_unit(
21362 dec,
21363 cdfs,
21364 chroma_set,
21365 scans.1,
21366 chroma_tx,
21367 chroma_tx_h,
21368 1,
21369 chroma_around[1],
21370 uv_predict_mode,
21371 angle_delta_uv,
21372 reach,
21373 u,
21374 cpx,
21375 cpy,
21376 base_q_idx,
21377 None,
21378 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
21379 smooth_neighbor_uv,
21380 fctx,
21381 )?;
21382 if let Some((_, vb)) = &palette_uv_bufs {
21383 set_palette_pred(vb.clone(), fctx);
21384 }
21385 let v_grid = read_rect_chroma_unit(
21386 dec,
21387 cdfs,
21388 chroma_set,
21389 scans.1,
21390 chroma_tx,
21391 chroma_tx_h,
21392 2,
21393 chroma_around[2],
21394 uv_predict_mode,
21395 angle_delta_uv,
21396 reach,
21397 v,
21398 cpx,
21399 cpy,
21400 base_q_idx,
21401 None,
21402 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
21403 smooth_neighbor_uv,
21404 fctx,
21405 )?;
21406 (u_grid, v_grid, Vec::new())
21407 }
21408 } else {
21409 let chroma_ctx_offset = Some(3);
21410 let mut u_pass: Vec<Grid> = Vec::new();
21411 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
21412 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
21413 for plane_pass in 1..=2usize {
21414 let mut pass_idx = 0usize;
21415 for cu_row in 0..cn_rows {
21416 for cu_col in 0..cn_cols {
21417 let cu_mi = (
21418 mi_r + cu_row * (luma_span_y / MI),
21419 mi_c + cu_col * (luma_span_x / MI),
21420 );
21421 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21422 // lane-av1-422f: chroma-only loop; per-chroma-cell
21423 // above votes (see [`Neighbours::around_mi_422_chroma`]).
21424 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
21425 } else {
21426 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
21427 };
21428 let cu_reach = tu_reach_rect(
21429 side,
21430 side,
21431 cu_col * luma_span_x,
21432 cu_row * luma_span_y,
21433 luma_span_x,
21434 luma_span_y,
21435 reach,
21436 px,
21437 py,
21438 y.width,
21439 y.height,
21440 fctx,
21441 );
21442 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
21443 if let Some((ub, vb)) = &palette_uv_bufs {
21444 let pbuf = if plane_pass == 1 { ub } else { vb };
21445 set_palette_pred(
21446 palette_window(
21447 pbuf,
21448 chroma_side,
21449 cu_col * chroma_tx,
21450 cu_row * chroma_tx_h,
21451 chroma_tx,
21452 chroma_tx_h,
21453 ),
21454 fctx,
21455 );
21456 }
21457 let buf: &mut PlaneBuf<'static> =
21458 if plane_pass == 1 { &mut *u } else { &mut *v };
21459 let cu_grid = read_plane(
21460 dec,
21461 cdfs,
21462 chroma_set,
21463 scans.1,
21464 plane_pass,
21465 cu_around[plane_pass],
21466 mode,
21467 uv_predict_mode,
21468 angle_delta_uv,
21469 cu_reach,
21470 buf,
21471 cu_x,
21472 cu_y,
21473 chroma_tx,
21474 chroma_tx,
21475 base_q_idx,
21476 alpha
21477 .zip(ac)
21478 .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)),
21479 None,
21480 chroma_ctx_offset,
21481 smooth_neighbor_uv,
21482 fctx,
21483 )?;
21484 hit!(CHROMA_SPLIT_TX_HITS);
21485 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21486 hit!(CHROMA422_SQUARE_HITS);
21487 }
21488 // Immediately, so the next unit of this block reads this
21489 // one's coefficient context. `record` below stamps one
21490 // chroma state across the whole block; the replay after
21491 // it puts the per-unit state back.
21492 neighbours.record_mi_chroma(
21493 cu_mi,
21494 luma_span_x,
21495 luma_span_y,
21496 plane_pass,
21497 &cu_grid,
21498 );
21499 if plane_pass == 1 {
21500 u_pass.push(cu_grid);
21501 } else {
21502 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
21503 units.push((
21504 cu_mi,
21505 luma_span_x,
21506 luma_span_y,
21507 u_grid.clone(),
21508 cu_grid.clone(),
21509 ));
21510 last_grids = [u_grid, cu_grid];
21511 }
21512 pass_idx += 1;
21513 }
21514 }
21515 }
21516 (last_grids[0].clone(), last_grids[1].clone(), units)
21517 };
21518 fctx.intrabc_chroma_tx.with(|c| c.set(None));
21519 neighbours.record(
21520 at,
21521 side,
21522 mode,
21523 uv_predict_mode,
21524 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
21525 );
21526 for (cu_mi, sw, sh, u_unit, v_unit) in &chroma_units {
21527 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_unit);
21528 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_unit);
21529 }
21530 } else {
21531 // Several luma transform units, raster order (spec
21532 // `transform_block`'s loop): the block's resolved transform is
21533 // genuinely smaller than its own side, so each tile of it predicts
21534 // and codes independently, its own context read fresh off whatever
21535 // the earlier tiles in this same block already wrote -- the same
21536 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
21537 let n_axis = side / logical_tx;
21538 // lane-av1-422f: unit width/height per axis, like walk 2 above --
21539 // a 4:2:2 frame below side 64 reads ONE rect unit per plane per
21540 // chunk, the whole plane block.
21541 let cn_cols = (chroma_side / chroma_tx).max(1);
21542 let cn_rows = (chroma_height / chroma_tx_h).max(1);
21543 let luma_span_x = chroma_tx << ss_x(fctx);
21544 let luma_span_y = chroma_tx_h << ss_y(fctx);
21545 // libaom's transform-block loop is over 64x64 luma "mu" chunks
21546 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
21547 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
21548 // before moving to the next one. Below 128 a block is a single chunk,
21549 // so this is byte-for-byte the all-luma-then-all-chroma order that has
21550 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
21551 // and reading all four luma units first desyncs the tile at the second
21552 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
21553 let nchunk = (side / 64).max(1);
21554 // `cn > 1` means the uv plane block is larger than the uv transform,
21555 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
21556 let chroma_ctx_offset = if cn_rows * cn_cols > 1 { Some(3) } else { None };
21557 let tpc = (n_axis / nchunk).max(1);
21558 let cpc_rows = (cn_rows / nchunk).max(1);
21559 let cpc_cols = (cn_cols / nchunk).max(1);
21560 // The block's luma transform units, raster order inside each mu
21561 // chunk. lane-av1-ibcvtx: an intrabc block's units are the var-tx
21562 // tree's own leaf list -- mixed sizes included, exactly what libaom's
21563 // `decode_token_recon_block` token loop reconstructs (one
21564 // `av1_read_coeffs_txb` + inverse transform per resolved unit) --
21565 // while every other block's list is the uniform `logical_tx` grid
21566 // this loop has always walked, generated here in the same order.
21567 let mut chunk_tus: Vec<Vec<(usize, usize, usize)>> = vec![Vec::new(); nchunk * nchunk];
21568 if let Some(leaves) = &intrabc_leaves {
21569 for &(lr, lc, tw, _th) in leaves {
21570 let (off_y, off_x) = (lr * MI, lc * MI);
21571 chunk_tus[(off_y / 64) * nchunk + (off_x / 64)].push((off_y, off_x, tw));
21572 }
21573 } else {
21574 for tu_row in 0..n_axis {
21575 for tu_col in 0..n_axis {
21576 chunk_tus[(tu_row / tpc) * nchunk + (tu_col / tpc)].push((
21577 tu_row * logical_tx,
21578 tu_col * logical_tx,
21579 logical_tx,
21580 ));
21581 }
21582 }
21583 }
21584 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
21585 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
21586 for ch_row in 0..nchunk {
21587 for ch_col in 0..nchunk {
21588 // lane-av1-ibcvtx: the chunk's chroma units inherit the CHROMA tx
21589 // type of the co-located luma position (`av1_get_tx_type`,
21590 // blockd.h:1278: a non-Y plane of an inter-classified block -- and
21591 // intrabc is one -- reads `tx_type_map`, i.e. the coded type of the
21592 // luma unit covering it). Inside a mu chunk that is the chunk's
21593 // FIRST luma unit in raster order (the chunk origin is always the
21594 // first leaf's own origin). Captured right after that unit's read;
21595 // the single-TU arm below does the same for a whole-block unit.
21596 let mut first_leaf_tx: Option<TxType> = None;
21597 for &(tu_off_y, tu_off_x, tu_tx) in &chunk_tus[ch_row * nchunk + ch_col] {
21598 let tu_mi = (mi_r + tu_off_y / MI, mi_c + tu_off_x / MI);
21599 let tu_px = px + tu_off_x;
21600 let tu_py = py + tu_off_y;
21601 // Same libaom clip as `decode_rect_split`'s loop above; a
21602 // square block only hangs off the frame when the frame's mi
21603 // dimensions are odd at the block's own level.
21604 if tu_px >= y.true_width || tu_py >= y.true_height {
21605 continue;
21606 }
21607 let tu_around = neighbours.around_mi(tu_mi, tu_tx)[0];
21608 // A transform unit inside a block is NOT a block at that
21609 // position (lane-palette2 r12): `Reach::of` granted the
21610 // top-right 8x8 unit of a 16x16 D203 block bottom-left
21611 // pixels libaom refuses outright (`col_off > 0`), which is
21612 // the diagonal wedge seed 46 reconstructed wrong.
21613 let tu_reach = tu_reach(
21614 side, side, tu_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height,
21615 fctx,
21616 );
21617 // This transform unit's own bsize (`tu_tx`) is smaller
21618 // than the block it sits in (`side`), so `txb_skip_ctx` is
21619 // the neighbour-magnitude table, not the lone-TU 0 (spec
21620 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
21621 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tu_tx / MI);
21622 // An intrabc unit's CDF set and scan follow the unit's OWN
21623 // resolved size (`get_txsize_entropy_ctx` /
21624 // `av1_get_scan` per `av1_read_coeffs_txb` call); the
21625 // uniform grid's precomputed pair already matches because
21626 // `tu_tx == logical_tx` there.
21627 let (tu_set, tu_scan) = if intrabc_dv.is_some() {
21628 (
21629 inter_txbset_for(tu_tx, reduced_tx_set),
21630 scan_for(
21631 if tu_tx == 64 { 32 } else { tu_tx },
21632 scan32,
21633 scan16,
21634 scan8,
21635 scan4,
21636 ),
21637 )
21638 } else {
21639 (luma_set, luma_scan)
21640 };
21641 if let Some(buf) = &palette_y_buf {
21642 hit!(PALETTE_SPLIT_TX_HITS);
21643 let mut window = vec![0u16; tu_tx * tu_tx];
21644 for row in 0..tu_tx {
21645 let src = (tu_off_y + row) * side + tu_off_x;
21646 window[row * tu_tx..][..tu_tx].copy_from_slice(&buf[src..][..tu_tx]);
21647 }
21648 set_palette_pred(window, fctx);
21649 }
21650 let tu_grid = read_plane(
21651 dec,
21652 cdfs,
21653 tu_set,
21654 tu_scan,
21655 0,
21656 tu_around,
21657 mode,
21658 mode,
21659 angle_delta_y,
21660 tu_reach,
21661 y,
21662 tu_px,
21663 tu_py,
21664 tu_tx,
21665 // The unit's own COEFFICIENT grid, half its side at
21666 // TX_64X64 (a 64-point transform codes nothing past 32);
21667 // identical to `tu_tx` at every smaller size
21668 // (lane-sb128b r1).
21669 if tu_tx == 64 { 32 } else { tu_tx },
21670 base_q_idx,
21671 None,
21672 filter_intra,
21673 Some(tu_skip_ctx),
21674 smooth_neighbor,
21675 fctx,
21676 )?;
21677 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21678 eprintln!(
21679 "TRACE tu_bitpos mi=({},{}) tell={}",
21680 tu_mi.0,
21681 tu_mi.1,
21682 dec.debug_bitpos()
21683 );
21684 }
21685 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);
21686 if first_leaf_tx.is_none() {
21687 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
21688 }
21689 }
21690 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
21691 // this still runs after every luma unit of the block.
21692 let ac = alpha.map(|_| cfl_src(px, py, side));
21693 // lane-av1-ibcvtx: an intrabc block's chroma rides the luma's coded
21694 // tx type (see `first_leaf_tx` above) -- the same arm the single-TU
21695 // branch sets before its own chroma reads.
21696 if intrabc_dv.is_some() {
21697 if let Some(t) = first_leaf_tx {
21698 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
21699 }
21700 }
21701 // The block's uv plane block is `chroma_side` across but its uv
21702 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
21703 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
21704 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
21705 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
21706 // FOUR units (lane-sb128b r2) -- one per mu chunk.
21707 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
21708 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
21709 // the chunk, then every V unit. At one unit per plane per chunk --
21710 // every non-lossless case this decoder reaches -- that is the same
21711 // symbol order as the interleaved pair this loop used to read; a
21712 // lossless frame's 4x4 chroma units are the case where it differs
21713 // (lane-lossless2).
21714 let mut u_pass: Vec<Grid> = Vec::new();
21715 for plane_pass in 1..=2usize {
21716 let mut pass_idx = 0usize;
21717 for cu_row in ch_row * cpc_rows..(ch_row + 1) * cpc_rows {
21718 for cu_col in ch_col * cpc_cols..(ch_col + 1) * cpc_cols {
21719 // libaom `decode_reconstruct_tx`'s frame-edge clip
21720 // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col
21721 // >= max_blocks_wide` returns before ANY symbol is read): a
21722 // transform unit whose 4x4 origin sits outside the frame's mi
21723 // grid is not coded at all. The luma loop above carries the
21724 // same clip; its absence here read `txb_skip` (+coeffs) for
21725 // chroma units libaom never wrote -- the lossless 64x64 block
21726 // at mi(48,0) of a 320x240 frame overhangs the bottom edge by
21727 // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not
21728 // eight (lane-av1-loss64; 48 chroma units per plane in
21729 // aomdec's EC_COEFF census vs the 64 this loop read).
21730 // `max_block_wide/high` (av1_common_int.h:1565): the plane
21731 // block's pixel span (4:2:0 halves the luma span, clamped to
21732 // 4 by `set_plane_n4`) plus the negative overhang
21733 // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4
21734 // units.
21735 let span_mi = side / MI;
21736 let over_w_mi = (2 * y.true_width.div_ceil(8)) as i32
21737 - mi_c as i32
21738 - span_mi as i32;
21739 let over_h_mi = (2 * y.true_height.div_ceil(8)) as i32
21740 - mi_r as i32
21741 - span_mi as i32;
21742 // `max_block_wide/high` in chroma pixels: the plane block's
21743 // own span (`side` at 4:4:4, `side / 2` at 4:2:0 -- the old
21744 // hardcoded `span_mi * 2` clipped three quarters of a 4:4:4
21745 // block's coded units and desynced the tile) plus the
21746 // negative overhang (`mb_to_*_edge >> (3 + ss)`), whose
21747 // chroma-px scale is `MI >> ss` per mi.
21748 let plane_px = (((span_mi * MI) >> ss_x(fctx)).max(4)) as i32;
21749 let over_w_px = over_w_mi.min(0) * (MI >> ss_x(fctx)) as i32;
21750 let over_h_px = over_h_mi.min(0) * (MI >> ss_y(fctx)) as i32;
21751 let max_units_w = ((plane_px + over_w_px) >> 2).max(0) as usize;
21752 // lane-av1-422f: the shared halved formula in the `else` counts
21753 // the plane span in 4-px units through the 2-px-per-mi
21754 // subsampled height, which a 4:2:2 plane does not have (ss_y
21755 // 0) -- its span is the full luma mi count, so a keyed
21756 // formula clips the same units libaom's `max_block_high`
21757 // does. 4:2:0 and 4:4:4 keep the proven shared rows (at 4:2:0
21758 // `MI >> ss_y` is 2, the same `2 * over_h_mi.min(0)` the
21759 // pre-ss form spelled).
21760 let max_units_h = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21761 (span_mi as i32 + over_h_mi.min(0)).max(0) as usize
21762 } else {
21763 ((plane_px + over_h_px) >> 2).max(0) as usize
21764 };
21765 let (unit_w, unit_h) = (chroma_tx / 4, chroma_tx_h / 4);
21766 if cu_col * unit_w >= max_units_w || cu_row * unit_h >= max_units_h {
21767 hit!(CHROMA_EDGE_TU_CLIP_HITS);
21768 continue;
21769 }
21770 // The chroma context arrays are indexed in LUMA mi, so this
21771 // unit's anchor is its own luma quadrant (lane-av1-422b: the
21772 // quadrant spans `chroma_tx << ss_x` luma px wide by
21773 // `chroma_tx_h << ss_y` tall -- at 4:2:2 below side 64 the
21774 // one unit's quadrant is the whole block).
21775 let cu_mi = (
21776 mi_r + cu_row * (luma_span_y / MI),
21777 mi_c + cu_col * (luma_span_x / MI),
21778 );
21779 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21780 // lane-av1-422f: chroma-only loop; per-chroma-cell above
21781 // votes (see [`Neighbours::around_mi_422_chroma`]).
21782 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
21783 } else {
21784 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
21785 };
21786 let cu_reach = if cn_rows == 1 && cn_cols == 1 {
21787 reach
21788 } else {
21789 tu_reach_rect(
21790 side,
21791 side,
21792 cu_col * luma_span_x,
21793 cu_row * luma_span_y,
21794 luma_span_x,
21795 luma_span_y,
21796 reach,
21797 px,
21798 py,
21799 y.width,
21800 y.height,
21801 fctx,
21802 )
21803 };
21804 let (cu_x, cu_y) =
21805 (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
21806 if let Some((ub, vb)) = &palette_uv_bufs {
21807 let pbuf = if plane_pass == 1 { ub } else { vb };
21808 set_palette_pred(
21809 palette_window(
21810 pbuf,
21811 chroma_side,
21812 cu_col * chroma_tx,
21813 cu_row * chroma_tx_h,
21814 chroma_tx,
21815 chroma_tx_h,
21816 ),
21817 fctx,
21818 );
21819 }
21820 let buf: &mut PlaneBuf<'static> =
21821 if plane_pass == 1 { &mut *u } else { &mut *v };
21822 let cu_grid = if chroma_tx == chroma_tx_h {
21823 read_plane(
21824 dec,
21825 cdfs,
21826 chroma_set,
21827 scans.1,
21828 plane_pass,
21829 cu_around[plane_pass],
21830 mode,
21831 uv_predict_mode,
21832 angle_delta_uv,
21833 cu_reach,
21834 buf,
21835 cu_x,
21836 cu_y,
21837 chroma_tx,
21838 chroma_tx,
21839 base_q_idx,
21840 alpha.zip(ac).map(|((au, av), ac)| {
21841 (if plane_pass == 1 { au } else { av }, ac)
21842 }),
21843 None,
21844 chroma_ctx_offset,
21845 smooth_neighbor_uv,
21846 fctx,
21847 )?
21848 } else {
21849 // lane-av1-422f: the whole plane block as one rect unit;
21850 // `chroma_ctx_offset` is `None` there (the unit covers
21851 // the plane block, so the offset-7 skip rows are right).
21852 read_rect_chroma_unit(
21853 dec,
21854 cdfs,
21855 chroma_set,
21856 scans.1,
21857 chroma_tx,
21858 chroma_tx_h,
21859 plane_pass,
21860 cu_around[plane_pass],
21861 uv_predict_mode,
21862 angle_delta_uv,
21863 cu_reach,
21864 buf,
21865 cu_x,
21866 cu_y,
21867 base_q_idx,
21868 None,
21869 alpha.zip(ac).map(|((au, av), ac)| {
21870 (if plane_pass == 1 { au } else { av }, ac)
21871 }),
21872 smooth_neighbor_uv,
21873 fctx,
21874 )?
21875 };
21876 if cn_rows * cn_cols > 1 {
21877 hit!(CHROMA_SPLIT_TX_HITS);
21878 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21879 hit!(CHROMA422_SQUARE_HITS);
21880 }
21881 // Immediately, so the NEXT unit of this same block reads
21882 // this one's coefficient context (libaom's chroma
21883 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
21884 // 1 from this left neighbour -- measured against aomdec).
21885 // The same writes are replayed after `record_split_luma`
21886 // below, which would otherwise clobber them whole-block.
21887 neighbours.record_mi_chroma(
21888 cu_mi,
21889 luma_span_x,
21890 luma_span_y,
21891 plane_pass,
21892 &cu_grid,
21893 );
21894 }
21895 if plane_pass == 1 {
21896 u_pass.push(cu_grid);
21897 } else {
21898 let u_grid =
21899 std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
21900 if cn_rows * cn_cols > 1 {
21901 units.push((
21902 cu_mi,
21903 luma_span_x,
21904 luma_span_y,
21905 u_grid.clone(),
21906 cu_grid.clone(),
21907 ));
21908 }
21909 last_grids = [u_grid, cu_grid];
21910 }
21911 pass_idx += 1;
21912 }
21913 }
21914 }
21915 }
21916 if intrabc_dv.is_some() {
21917 fctx.intrabc_chroma_tx.with(|c| c.set(None));
21918 }
21919 }
21920 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
21921 // context write; at `cn > 1` the per-unit writes above are what the
21922 // next block reads, so they run after this (last writer wins).
21923 neighbours.record_split_luma(
21924 at,
21925 side,
21926 mode,
21927 uv_predict_mode,
21928 [&last_grids[0], &last_grids[1]],
21929 );
21930 for (cu_mi, sw, sh, u_grid, v_grid) in &units {
21931 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_grid);
21932 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_grid);
21933 }
21934 }
21935 // Unconditional, `size == 0` for a non-palette block: clears any stale
21936 // neighbour palette state the same way [`Neighbours::record`] always
21937 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
21938 // (the split-luma-TU branch above always refuses before reaching here
21939 // when `palette_y` is `Some`, so it is never live for that branch).
21940 let (py_size, py_colors) = palette_y
21941 .as_ref()
21942 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
21943 neighbours.record_palette_y(at, side, py_size, py_colors);
21944 let (puv_size, puv_colors) = palette_uv
21945 .as_ref()
21946 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
21947 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
21948 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
21949 neighbours.fill_lf_grid(
21950 (r * (SUB / MI), c * (SUB / MI)),
21951 side / MI,
21952 logical_tx as u8,
21953 0,
21954 fctx,
21955 );
21956 // lane-t900 r32 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size,
21957 // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY
21958 // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM
21959 // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express
21960 // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED
21961 // intrabc block publish its BLOCK size instead, intrabc being the only
21962 // "inter" block an intra-only frame codes (`blockd.h:373`). So this call
21963 // stays the authority wherever one can appear; with `allow_intrabc` unset
21964 // it writes exactly what the grid already did.
21965 if allow_intrabc {
21966 set_txfm_ctxs(
21967 neighbours,
21968 (mi_r, mi_c),
21969 logical_tx,
21970 side / MI,
21971 side / MI,
21972 skip && intrabc_dv.is_some(),
21973 );
21974 }
21975 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, neighbours, fctx);
21976 Ok(())
21977}
21978
21979thread_local! {
21980 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
21981 /// root's HORZ arm, and 64x128 ones at its VERT arm.
21982 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21983 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21984 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
21985 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
21986 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
21987 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
21988 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
21989 /// inter frame) -- (128x64, 64x128).
21990 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
21991 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
21992 /// handed back var-tx leaves, so the per-transform-unit luma publication
21993 /// loop never ran and the block has to clear its own luma coefficient
21994 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
21995 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
21996 /// non-vacuous.
21997 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21998 /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded
21999 /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the
22000 /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this
22001 /// shape non-vacuous -- a stream that never codes one reads 0.
22002 pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22003 /// lane-av1-128rectspan: chroma transform units of a 128-root HORZ/VERT
22004 /// intra block re-stamped by the end-of-block replay
22005 /// (`record_split_luma_rect` clobbers the per-unit contexts the chroma
22006 /// walk published, so every unit replays its own state after it). A
22007 /// non-skip 128x64/64x128 block codes `nch_x * cn * 2 + nch_y * cn_h * 2`
22008 /// of them, so this reads 0 on any stream that never codes one -- the
22009 /// non-vacuity anchor for the replay's own gate.
22010 pub(crate) static SB128RECT_CHROMA_REPLAY_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22011 /// ... and the number of non-skip 128-root rect BLOCKS whose replay
22012 /// height differs from the unit's own LUMA-MI height -- the signature of the
22013 /// width passed to both axes (`luma_span` where the in-loop stamp used
22014 /// `luma_span_h`). Zero on every stream this decoder admits: both
22015 /// supported chroma formats have `ss_x == ss_y` (4:2:0 and 4:4:4), and
22016 /// 4:2:2 -- the one format whose two spans differ -- is refused by name
22017 /// at the sequence header (`stream::decode_frame`), so the arm is
22018 /// defensive until that format is ported. The counter turns a future
22019 /// 4:2:2 admission (or any hardcoded span) into a named red gate instead
22020 /// of silent mi-state corruption.
22021 pub(crate) static SB128RECT_REPLAY_SPAN_MISMATCH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22022}
22023
22024/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
22025pub fn skip_vartx_luma_reset_hits() -> usize {
22026 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
22027}
22028
22029/// [`INTRA128_LOSSLESS_HITS`], for a gate's own before/after delta.
22030pub(crate) fn intra128_lossless_hits() -> usize {
22031 INTRA128_LOSSLESS_HITS.with(std::cell::Cell::get)
22032}
22033
22034/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
22035pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
22036 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
22037}
22038
22039/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
22040/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
22041pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
22042 (
22043 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
22044 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
22045 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
22046 )
22047}
22048
22049/// [`SB128RECT_CHROMA_REPLAY_HITS`] (chroma units re-stamped by
22050/// `decode_block_128rect`'s end-of-block replay) and
22051/// [`SB128RECT_REPLAY_SPAN_MISMATCH_HITS`] (replays whose stamped height was
22052/// not the unit's own), for a gate's own before/after delta.
22053pub(crate) fn sb128rect_chroma_replay_hits() -> (usize, usize) {
22054 (
22055 SB128RECT_CHROMA_REPLAY_HITS.with(std::cell::Cell::get),
22056 SB128RECT_REPLAY_SPAN_MISMATCH_HITS.with(std::cell::Cell::get),
22057 )
22058}
22059
22060/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
22061/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
22062/// `decode_inter_block`'s own rect path).
22063///
22064/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
22065/// transform unit, with the 128-specific geometry:
22066/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
22067/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
22068/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
22069/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
22070/// same CDF a 64x64 square block reads).
22071/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
22072/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
22073/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
22074/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
22075/// a chunk before moving to the next (the interleave lane-sb128b r3
22076/// measured at the 128x128 NONE root).
22077/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
22078/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
22079/// No CfL, no filter intra (both cap at 32x32) and no palette
22080/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
22081/// reader's own size gates already say so, and the guard below is defensive.
22082///
22083/// lane-lossless128: on a LOSSLESS frame every one of those sizes collapses to
22084/// TX_4X4 -- `read_tx_mode` returns `ONLY_4X4` before the frame codes a tx-size
22085/// symbol and `read_tx_size` returns `TX_4X4` before it looks at anything
22086/// (`decodeframe.c:141`, `:1183`) -- so the block is tiled into 4x4 luma units
22087/// and (because a lossless frame forces `TX_4X4` on CHROMA too) 4x4 chroma
22088/// units, plane-major inside each 64x64 mu chunk exactly as
22089/// `decode_token_recon_block` codes them. Reading the 64-point geometry there
22090/// reconstructs into a `side`-sized plane with a 16-sample residual (the panic
22091/// this lane closed); the geometry and the unit walks below are normalized on
22092/// `lossless_frame`.
22093#[allow(clippy::too_many_arguments)]
22094fn decode_block_128rect(
22095 dec: &mut SymbolDecoder,
22096 cdfs: &mut Cdfs,
22097 neighbours: &mut Neighbours,
22098 at: (usize, usize),
22099 bw: usize,
22100 bh: usize,
22101 y: &mut PlaneBuf<'static>,
22102 u: &mut PlaneBuf<'static>,
22103 v: &mut PlaneBuf<'static>,
22104 base_q_idx: u8,
22105 enable_filter_intra: bool,
22106 allow_screen_content_tools: bool,
22107 tx_select: bool,
22108 reduced_tx_set: bool,
22109 fctx: &crate::decode::FrameCtx,
22110) -> Result<()> {
22111 let (r, c) = at;
22112 let (px, py) = (c * SUB, r * SUB);
22113 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
22114 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
22115 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
22116 let palette_uv_cache = neighbours.palette_uv_cache(at);
22117 let (
22118 skip,
22119 mode,
22120 angle_delta_y,
22121 uv_mode,
22122 angle_delta_uv,
22123 alpha,
22124 filter_intra,
22125 palette_y,
22126 palette_uv,
22127 intrabc,
22128 ) = read_intra_mode_rect(
22129 dec,
22130 cdfs,
22131 nb_above_mode,
22132 nb_left_mode,
22133 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
22134 // 13-symbol no-CFL CDF here, never the 14-symbol one.
22135 false,
22136 true,
22137 bw,
22138 bh,
22139 enable_filter_intra,
22140 neighbours.skip_txfm_ctx(mi_r, mi_c),
22141 allow_screen_content_tools,
22142 Some((palette_ctx, &palette_cache)),
22143 &palette_uv_cache,
22144 mi_r,
22145 mi_c,
22146 fctx,
22147 )?;
22148 if let Some((dv_row, dv_col)) = intrabc {
22149 // lane-av1-ibcrect: the reconstruction is ported -- an intrabc block
22150 // is is_inter_block, so libaom predicts the whole 128x64/64x128 strip
22151 // from this frame's own reconstruction and runs the INTER residual
22152 // walk (`decode_token_recon_block`'s else arm) over it.
22153 return decode_intrabc_128rect(
22154 dec,
22155 cdfs,
22156 neighbours,
22157 (mi_r, mi_c),
22158 (bw, bh),
22159 skip,
22160 (dv_row, dv_col),
22161 y,
22162 u,
22163 v,
22164 base_q_idx,
22165 fctx,
22166 );
22167 }
22168 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
22169 return Err(unsupported(
22170 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
22171 their size gates caps at 64x64 or below, so none of these symbols exists there)",
22172 ));
22173 }
22174 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
22175 DC_PRED
22176 } else {
22177 uv_mode
22178 };
22179 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
22180 if smooth_neighbor {
22181 hit!(SMOOTH_LUMA_HITS);
22182 }
22183 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
22184 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
22185 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
22186 // lane-lossless128: a LOSSLESS frame codes no tx-size symbol at all --
22187 // libaom's `read_tx_mode` returns `ONLY_4X4` for a `coded_lossless` frame
22188 // before the symbol is even considered (`decodeframe.c:141`) and
22189 // `read_tx_size` returns `TX_4X4` before it looks at anything
22190 // (`decodeframe.c:1183`). So `tx_select` is off, every plane is walked as
22191 // TX_4X4 transform units, and no `tx_size_cat3` symbol may be consumed.
22192 let lossless_frame = lossless(fctx);
22193 let in_inter = fctx
22194 .intra_in_inter_mode
22195 .with(std::cell::Cell::get)
22196 .is_some();
22197 let depth = if tx_select && !lossless_frame {
22198 // lane-inter128intra r1: `get_tx_size_context` compares the bands
22199 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --
22200 // TX_64X64 for every 128-axis block, hence the `min(64)`.
22201 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
22202 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
22203 } else {
22204 0
22205 };
22206 if depth != 0 {
22207 hit!(TX_DEPTH_HITS);
22208 }
22209 hit_do! {
22210 INTRA_SB128_DEPTH_HITS.with(|c| {
22211 let mut h = c.get();
22212 h[depth.min(2)] += 1;
22213 c.set(h);
22214 });
22215 }
22216 let logical_tx = if lossless_frame { 4 } else { 64 >> depth };
22217 if lossless_frame {
22218 hit!(INTRA128_LOSSLESS_HITS);
22219 }
22220 // A 64-point transform codes nothing past its low 32 coefficients.
22221 let coeff_tx_side = logical_tx.min(32);
22222 let luma_set = if lossless_frame {
22223 TxbSet::Luma4
22224 } else {
22225 txbset_for(logical_tx, reduced_tx_set)
22226 };
22227 let luma_scan = default_scan(coeff_tx_side);
22228 // `av1_get_max_uv_txsize` caps at TX_32X32 normally; a lossless frame
22229 // forces every plane to TX_4X4 (its own `Chroma4` set and 4x4 scan).
22230 let chroma_tx = if lossless_frame { 4 } else { 32 };
22231 let chroma_set = if lossless_frame {
22232 TxbSet::Chroma4
22233 } else {
22234 TxbSet::Chroma32
22235 };
22236 let chroma_scan = default_scan(chroma_tx);
22237 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
22238 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
22239 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
22240 let (nch_x, nch_y) = (bw / 64, bh / 64);
22241 // The frame's own mi grid (`av1_calc_mi_size`, 8-px aligned): libaom's
22242 // `decode_token_recon_block` clips each vector's walk to
22243 // `max_block_wide/high`, so a chroma unit whose top-left is off the frame
22244 // codes nothing.
22245 let mi_cols = 2 * y.true_width.div_ceil(8);
22246 let mi_rows = 2 * y.true_height.div_ceil(8);
22247 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
22248 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
22249 // Non-lossless: per mu chunk, `(64 >> ss) / chroma_tx` chroma units per
22250 // axis -- one 32x32 at 4:2:0, two stacked on the tall axis at 4:2:2
22251 // (lane-av1-422bigblock: the chunk's chroma plane block is 32x64 there),
22252 // four at 4:4:4 (lane-av1-444sb's own finding on this same walk).
22253 debug_assert!(
22254 lossless_frame
22255 || (chroma_w / chroma_tx, chroma_h / chroma_tx)
22256 == (
22257 nch_x * ((64 >> ss_x(fctx)) / chroma_tx),
22258 nch_y * ((64 >> ss_y(fctx)) / chroma_tx)
22259 )
22260 );
22261 let tpc = 64 / logical_tx;
22262 let zero_tu = vec![0i32; logical_tx * logical_tx];
22263 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
22264 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
22265 let mut units: Vec<(usize, (usize, usize), Grid)> = Vec::new();
22266 // The chroma context arrays are indexed in LUMA mi; every chroma unit of
22267 // every chunk shares this luma span (2 chroma pixels per luma unit).
22268 let luma_span = chroma_tx << ss_x(fctx);
22269 let luma_span_h = chroma_tx << ss_y(fctx);
22270 for ch_row in 0..nch_y {
22271 for ch_col in 0..nch_x {
22272 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
22273 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
22274 let tu_mi = (
22275 mi_r + tu_row * (logical_tx / MI),
22276 mi_c + tu_col * (logical_tx / MI),
22277 );
22278 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
22279 // libaom clips the transform loop to
22280 // `max_blocks_wide/high`: a unit whose top-left sample is
22281 // outside the frame is never coded.
22282 if tu_px >= y.true_width || tu_py >= y.true_height {
22283 continue;
22284 }
22285 // Edge availability of a unit INSIDE a block, with the
22286 // 128 geometry -- `has_top_right` is false for a block
22287 // whose largest side is > 64, which [`Reach::of_rect`]
22288 // already answered for the block and [`tu_reach`] carries
22289 // down to the units on its own top row.
22290 let tu_r = tu_reach(
22291 bw,
22292 bh,
22293 tu_col * logical_tx,
22294 tu_row * logical_tx,
22295 logical_tx,
22296 reach,
22297 px,
22298 py,
22299 y.width,
22300 y.height,
22301 fctx,
22302 );
22303 if skip {
22304 push_intra(
22305 0,
22306 tu_px,
22307 tu_py,
22308 logical_tx,
22309 mode,
22310 angle_delta_y,
22311 tu_r,
22312 &zero_tu,
22313 None,
22314 None,
22315 smooth_neighbor,
22316 fctx,
22317 );
22318 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
22319 continue;
22320 }
22321 // The unit is smaller than its block, so `txb_skip_ctx`
22322 // is the neighbour-magnitude table, never the lone-TU 0.
22323 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
22324 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
22325 let tu_grid = read_plane(
22326 dec,
22327 cdfs,
22328 luma_set,
22329 &luma_scan,
22330 0,
22331 tu_around,
22332 mode,
22333 mode,
22334 angle_delta_y,
22335 tu_r,
22336 y,
22337 tu_px,
22338 tu_py,
22339 logical_tx,
22340 coeff_tx_side,
22341 base_q_idx,
22342 None,
22343 None,
22344 Some(tu_skip_ctx),
22345 smooth_neighbor,
22346 fctx,
22347 )?;
22348 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
22349 }
22350 }
22351 // Transform units per axis inside this mu chunk's chroma span:
22352 // a 64x64 luma chunk covers `64 >> ss` chroma pixels per axis,
22353 // so it holds `(64 >> ss) / chroma_tx` units -- one 32x32 at
22354 // 4:2:0, four at 4:4:4 (lane-av1-444sb), TWO STACKED TX_32X32 on
22355 // the tall axis at 4:2:2 (lane-av1-422bigblock: the chunk's
22356 // chroma plane block is 32x64 there, so the two axes' counts
22357 // part ways -- 1 x 2); 8x8 TX_4X4 units when lossless.
22358 let cn = ((64 >> ss_x(fctx)) / chroma_tx).max(1);
22359 let cn_h = ((64 >> ss_y(fctx)) / chroma_tx).max(1);
22360 // libaom's per-chunk `unit_width/height` (plane-mi units of the
22361 // luma mi grid): `min(mu_blocks + col, max_blocks) >> ss`.
22362 let unit_w = ((ch_col + 1) * 16).min(max_w_mi) >> ss_x(fctx);
22363 let unit_h = ((ch_row + 1) * 16).min(max_h_mi) >> ss_y(fctx);
22364 let stepc = (chroma_tx / 4).max(1);
22365 // `decode_token_recon_block` codes a mu chunk PLANE-MAJOR: every U
22366 // unit of the chunk, then every V unit. At one unit per plane per
22367 // chunk (every non-lossless 128-axis block) that is the same
22368 // symbol order the interleaved pair used to read; a lossless
22369 // frame's 4x4 chroma units are where it becomes observable.
22370 for plane_pass in 1..=2usize {
22371 for ci_row in 0..cn_h {
22372 for ci_col in 0..cn {
22373 // The clamp strides are the CHUNK's chroma mi extent
22374 // per axis: 16 luma mi >> the axis's own ss.
22375 if ch_col * (16 >> ss_x(fctx)) + ci_col * stepc >= unit_w
22376 || ch_row * (16 >> ss_y(fctx)) + ci_row * stepc >= unit_h
22377 {
22378 continue;
22379 }
22380 let cu_x = cpx + ch_col * (64 >> ss_x(fctx)) + ci_col * chroma_tx;
22381 let cu_y = cpy + ch_row * (64 >> ss_y(fctx)) + ci_row * chroma_tx;
22382 let cu_mi = (
22383 mi_r + ch_row * 16 + ci_row * ((chroma_tx << ss_y(fctx)) / 4),
22384 mi_c + ch_col * 16 + ci_col * ((chroma_tx << ss_x(fctx)) / 4),
22385 );
22386 let cu_r = tu_reach_rect(
22387 bw,
22388 bh,
22389 ch_col * 64 + ci_col * luma_span,
22390 ch_row * 64 + ci_row * luma_span_h,
22391 luma_span,
22392 luma_span_h,
22393 reach,
22394 px,
22395 py,
22396 y.width,
22397 y.height,
22398 fctx,
22399 );
22400 if skip {
22401 push_intra(
22402 plane_pass,
22403 cu_x,
22404 cu_y,
22405 chroma_tx,
22406 uv_predict_mode,
22407 angle_delta_uv,
22408 cu_r,
22409 &zero_cu,
22410 None,
22411 None,
22412 smooth_neighbor_uv,
22413 fctx,
22414 );
22415 continue;
22416 }
22417 let cu_around = neighbours.around_mi_rect(cu_mi, luma_span, luma_span_h);
22418 let buf: &mut PlaneBuf<'static> =
22419 if plane_pass == 1 { &mut *u } else { &mut *v };
22420 let grid = read_plane(
22421 dec,
22422 cdfs,
22423 chroma_set,
22424 &chroma_scan,
22425 plane_pass,
22426 cu_around[plane_pass],
22427 mode,
22428 uv_predict_mode,
22429 angle_delta_uv,
22430 cu_r,
22431 buf,
22432 cu_x,
22433 cu_y,
22434 chroma_tx,
22435 chroma_tx,
22436 base_q_idx,
22437 None,
22438 None,
22439 Some(3),
22440 smooth_neighbor_uv,
22441 fctx,
22442 )?;
22443 last_grids[plane_pass - 1] = grid.clone();
22444 // Immediately, so the NEXT unit of this same block
22445 // reads this one's coefficient context; replayed after
22446 // `record_split_luma_rect` below, which would otherwise
22447 // clobber them whole-block.
22448 neighbours.record_mi_chroma(
22449 cu_mi,
22450 luma_span,
22451 luma_span_h,
22452 plane_pass,
22453 &grid,
22454 );
22455 units.push((plane_pass, cu_mi, grid));
22456 }
22457 }
22458 }
22459 if !skip {
22460 hit!(CHROMA_SPLIT_TX_HITS);
22461 }
22462 }
22463 }
22464 if skip {
22465 neighbours.record_rect(
22466 at,
22467 bw,
22468 bh,
22469 mode,
22470 uv_predict_mode,
22471 &[
22472 &ZERO_RESIDUAL[..bw * bh],
22473 &ZERO_RESIDUAL[..chroma_w * chroma_h],
22474 &ZERO_RESIDUAL[..chroma_w * chroma_h],
22475 ],
22476 );
22477 } else {
22478 neighbours.record_split_luma_rect(
22479 at,
22480 bw,
22481 bh,
22482 mode,
22483 uv_predict_mode,
22484 [&last_grids[0], &last_grids[1]],
22485 );
22486 // lane-av1-128rectspan: the replay must re-stamp each unit over the
22487 // SAME cells the walk above stamped it over -- `record_mi_chroma`'s
22488 // height drives `left[]` and its width `above[]`, and the walk used
22489 // the per-axis `luma_span_h`. Passing the width on both axes doubled
22490 // the `left[]` run wherever the two differ (4:2:2), reaching 8 mi
22491 // rows below the block on the last unit of a 128x64/64x128 strip and
22492 // smearing a neighbour chunk's unit over its neighbour's rows.
22493 //
22494 // DEFENSIVE at the decoder's current capability set: both admitted
22495 // chroma formats have `ss_x == ss_y` (4:2:0 ss (1,1), 4:4:4 ss
22496 // (0,0)), so the two spans are equal and this line is a no-op on
22497 // every stream `decode_stream` accepts; 4:2:2 (ss (1,0)) -- the one
22498 // format where they differ -- is refused by name at the sequence
22499 // header, so the arm is unreachable there. It stays per-axis because
22500 // the walk it replays is per-axis, and a 4:2:2 port must not have to
22501 // re-derive this. `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` names the
22502 // day that changes.
22503 if luma_span != luma_span_h {
22504 hit!(SB128RECT_REPLAY_SPAN_MISMATCH_HITS);
22505 }
22506 for (plane, cu_mi, grid) in &units {
22507 neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span_h, *plane, grid);
22508 hit!(SB128RECT_CHROMA_REPLAY_HITS);
22509 }
22510 }
22511 // No palette exists at this size; the unconditional stamp clears any
22512 // stale neighbour palette state, as every other block path does.
22513 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
22514 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
22515 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
22516 neighbours.fill_lf_grid_rect(
22517 (mi_r, mi_c),
22518 bw / MI,
22519 bh / MI,
22520 logical_tx as u8,
22521 logical_tx as u8,
22522 0,
22523 fctx,
22524 );
22525 if in_inter || allow_intrabc_frame(fctx) {
22526 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
22527 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
22528 // inter frame, intra ones included: an intra block stamps its
22529 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
22530 // A key frame reads those bands only when it allows intrabc
22531 // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom
22532 // stamps here too -- lane-av1-intrabc r3.
22533 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (logical_tx, logical_tx), (bw, bh));
22534 }
22535 if in_inter {
22536 hit_do! {
22537 INTRA128_IN_INTER_HITS.with(|c| {
22538 let mut h = c.get();
22539 h[usize::from(bw < bh)] += 1;
22540 c.set(h);
22541 });
22542 }
22543 } else if bw > bh {
22544 hit!(INTRA_SB128_HORZ_HITS);
22545 } else {
22546 hit!(INTRA_SB128_VERT_HITS);
22547 }
22548 Ok(())
22549}
22550
22551/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
22552/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
22553/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
22554/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
22555/// just-decoded mode, not the enclosing slot's stale one, is the true
22556/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
22557/// units, which is what its coefficient context (finer than [`SUB`]) is read
22558/// at. Returns the mode this leaf decoded, for the caller's own
22559/// `prev_leaf`/final mode-writeback bookkeeping.
22560#[allow(clippy::too_many_arguments)]
22561/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
22562/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
22563/// `above_mode[col]`, and its true above neighbour is the mi directly above
22564/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
22565/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
22566/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
22567/// (bottom-right) into both, as this path did, is right only when all four
22568/// leaves happen to share a mode. `done` may be short at the true frame edge
22569/// (the straddle caller filters positions off the frame), so each side falls
22570/// back to the last leaf actually decoded.
22571fn write_back_split_modes(
22572 neighbours: &mut Neighbours,
22573 done: &[((usize, usize), usize)],
22574 parent_mi: (usize, usize),
22575 slot: (usize, usize),
22576) {
22577 let (sr, sc) = slot;
22578 let Some(&(_, last)) = done.last() else {
22579 return;
22580 };
22581 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
22582 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
22583 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
22584}
22585
22586fn decode_leaf8(
22587 dec: &mut SymbolDecoder,
22588 cdfs: &mut Cdfs,
22589 neighbours: &mut Neighbours,
22590 outer_at: (usize, usize),
22591 leaf_mi: (usize, usize),
22592 scans: (&[u16], &[u16]),
22593 prev_leaf: Option<((usize, usize), usize)>,
22594 y: &mut PlaneBuf<'static>,
22595 u: &mut PlaneBuf<'static>,
22596 v: &mut PlaneBuf<'static>,
22597 base_q_idx: u8,
22598 enable_filter_intra: bool,
22599 allow_screen_content_tools: bool,
22600 allow_intrabc: bool,
22601 tx_select: bool,
22602 reduced_tx_set: bool,
22603 fctx: &crate::decode::FrameCtx,
22604) -> Result<usize> {
22605 let (r, c) = outer_at;
22606 // lane-modectx r1: the group's own availability-correct fallback pair, not
22607 // the raw coarse bands (which leak across a tile edge -- see
22608 // `modes_above_left`).
22609 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
22610 if let Some(((pr, pc), pmode)) = prev_leaf {
22611 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
22612 above_mode = pmode;
22613 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
22614 left_mode = pmode;
22615 }
22616 }
22617 // The mi-exact neighbour wins over both the coarse 16x16 slot and
22618 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
22619 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
22620 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
22621 // lane-rectsplitx r2 swept this arm into
22622 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
22623 // "no neighbour" at a tile edge, where the coarse cell holds the block
22624 // above/left of it inside the same 16x16.
22625 let (above_mode, left_mode) =
22626 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
22627 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
22628 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
22629 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
22630 // this leaf's `smooth_neighbor` is built from -- passing `false` here
22631 // filtered a directional chroma block's edge at the wrong strength
22632 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
22633 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
22634 // with the coarse [`SUB`] slot as the fallback when no block recorded
22635 // that exact mi cell.
22636 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
22637 if smooth_neighbor {
22638 hit!(SMOOTH_LUMA_HITS);
22639 }
22640 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
22641 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
22642 // `decode_block` caller at 16x16 and up.
22643 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
22644 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
22645 // `read_palette_mode_info`), at its REAL mi position -- passing
22646 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
22647 // moment a real 8x8 palette block fired, which is where every 8-bit
22648 // `--tune-content=screen --min-partition-size=8` stream stopped.
22649 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
22650 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
22651 let (
22652 skip,
22653 mode,
22654 angle_delta_y,
22655 uv_mode,
22656 angle_delta_uv,
22657 alpha,
22658 filter_intra,
22659 palette_y,
22660 palette_uv,
22661 ) = read_intra_mode(
22662 dec,
22663 cdfs,
22664 above_mode,
22665 left_mode,
22666 true,
22667 8,
22668 enable_filter_intra,
22669 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
22670 allow_screen_content_tools,
22671 allow_intrabc,
22672 Some((palette_ctx, &palette_cache)),
22673 &palette_uv_cache,
22674 leaf_mi.0,
22675 leaf_mi.1,
22676 fctx,
22677 )?;
22678 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
22679 // `read_intra_mode` and then decoded the block as if it were ordinary
22680 // intra. libaom's `is_inter_block` counts an intrabc block
22681 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
22682 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
22683 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
22684 // same value with a different interval, so the tile desynced at the very
22685 // next symbol (class `wrong-alphabet-same-value`). Everything below
22686 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
22687 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
22688 if intrabc_dv.is_some() {
22689 hit!(LEAF8_INTRABC_HITS);
22690 }
22691 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
22692 // index map, mapped through the base colours, IS the block's prediction --
22693 // carried to the next `reconstruct`/`read_plane` through the same
22694 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
22695 let palette_y_buf: Option<Vec<u16>> = palette_y
22696 .as_ref()
22697 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
22698 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
22699 (
22700 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
22701 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
22702 )
22703 });
22704 let (pal_y_size, pal_y_colors) = palette_y
22705 .as_ref()
22706 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
22707 let (pal_uv_size, pal_uv_colors) = palette_uv
22708 .as_ref()
22709 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
22710 if palette_y.is_some() || palette_uv.is_some() {
22711 hit!(PALETTE_LEAF8_HITS);
22712 }
22713 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
22714 DC_PRED
22715 } else {
22716 uv_mode
22717 };
22718 neighbours.above_uv_mode[c] = uv_predict_mode;
22719 neighbours.left_uv_mode[r] = uv_predict_mode;
22720 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
22721 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
22722 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
22723 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
22724 // transform units, same raster-order per-TU pattern `decode_block`'s
22725 // multi-TU branch runs).
22726 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
22727 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
22728 // intrabc block, so a SKIPPED one takes the largest transform and an
22729 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
22730 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
22731 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
22732 // `parse_decode_block`'s tree condition carries
22733 // `!xd->lossless[mbmi->segment_id]` (see [`decode_block`]'s own copy):
22734 // a lossless segment's intrabc leaf reads no tree, TX_4X4 via
22735 // `read_tx_size`'s first line (lane-av1mixloss).
22736 let resolved = if tx_select && intrabc_dv.is_some() && !skip && !lossless(fctx) {
22737 let mut leaves = Vec::new();
22738 let mi_cols = 2 * y.true_width.div_ceil(8);
22739 let mi_rows = 2 * y.true_height.div_ceil(8);
22740 read_var_tx_size(
22741 dec,
22742 cdfs,
22743 neighbours,
22744 leaf_mi,
22745 8,
22746 (
22747 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
22748 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
22749 ),
22750 (8, 8),
22751 0,
22752 0,
22753 0,
22754 &mut leaves,
22755 );
22756 hit!(INTRABC_VARTX_HITS);
22757 leaves.first().map_or(8, |l| l.2)
22758 } else if tx_select && intrabc_dv.is_none() {
22759 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, fctx)
22760 } else {
22761 // lane-lossless: TX_4X4 on a lossless frame, no symbol
22762 // (libaom `read_tx_size`).
22763 lossless_tx(8, fctx)
22764 };
22765 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
22766 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
22767 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
22768 // 4:4:4: this 8x8 block's chroma plane block is 8x8 (same scan as luma,
22769 // `scans.0`). 4:2:0 stays the 4x4 unit this leaf was written for.
22770 // lane-av1-422d: 4:2:2 (ss 1/0) halves only the width, so the plane block
22771 // is 4x8 -- ONE rect transform unit per plane (`av1_get_max_uv_txsize(
22772 // BLOCK_8X8)` at ss (1,0) is `max_txsize_rect_lookup[BLOCK_4X8]` ==
22773 // TX_4X8): one txb_skip + one scan per plane in the
22774 // [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the
22775 // shape, read through [`leaf8_chroma422_unit`] in each arm below. The
22776 // `(csz, cset, cscan)` selection keeps serving the square arms (444's
22777 // 8x8, 420's 4x4); the rect arms branch on [`chroma_422`] instead.
22778 let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
22779 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
22780 let (csz, cset, cscan) = if chroma_444 {
22781 (8usize, TxbSet::Chroma8, scans.0)
22782 } else {
22783 (4usize, TxbSet::Chroma4, scans.1)
22784 };
22785 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
22786 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
22787 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
22788 // the full-pel block vector, with the BILINEAR kernel libaom forces.
22789 flush_recon(fctx, y, u, v);
22790 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
22791 let mut yb = vec![0u16; 8 * 8];
22792 mc::predict_with_filter(
22793 &y.data,
22794 y.width,
22795 y.true_width,
22796 y.true_height,
22797 mv_to_q4(px, dv_col, 0),
22798 mv_to_q4(py, dv_row, 0),
22799 8,
22800 8,
22801 mc::InterpFilterKind::Bilinear,
22802 &mut yb,
22803 fctx,
22804 );
22805 // The chroma extent is THIS frame's subsampled size of the 8x8 luma
22806 // leaf (`get_plane_block_size`): 4x4 at 4:2:0, 4x8 at 4:2:2, 8x8 at
22807 // 4:4:4. The literal 4x4 this replaces hardcoded the 4:2:0 halving --
22808 // at 4:4:4 the 16-sample override fed this leaf's own 8x8 chroma
22809 // reconstruct, which indexed `prediction[16]` of a 16-sample buffer
22810 // (len 16, index 16 at `PlaneBuf::reconstruct`), and at 4:2:2 it
22811 // covered half the leaf's 4x8 chroma plane block (lane-av1-422d's
22812 // `if chroma_422 { (4, 8) }` arm, which the ss-derived form subsumes:
22813 // `8 >> ss_x` is 4 and `8 >> ss_y` is 8 there). The same buffers
22814 // are windowed at stride 8 by `read_intra_chroma_lossless` (the TX4
22815 // 4:4:4-lossless arm) and consumed whole by the TX8 and skip arms,
22816 // so all three heal with this one sizing.
22817 let (cw, ch) = (8 >> ss_x(fctx), 8 >> ss_y(fctx));
22818 let mut ub = vec![0u16; cw * ch];
22819 mc::predict_with_filter(
22820 &u.data,
22821 u.width,
22822 u.true_width,
22823 u.true_height,
22824 mv_to_q4(cpx, dv_col, ss_x(fctx)),
22825 mv_to_q4(cpy, dv_row, ss_y(fctx)),
22826 cw,
22827 ch,
22828 mc::InterpFilterKind::Bilinear,
22829 &mut ub,
22830 fctx,
22831 );
22832 let mut vb = vec![0u16; cw * ch];
22833 mc::predict_with_filter(
22834 &v.data,
22835 v.width,
22836 v.true_width,
22837 v.true_height,
22838 mv_to_q4(cpx, dv_col, ss_x(fctx)),
22839 mv_to_q4(cpy, dv_row, ss_y(fctx)),
22840 cw,
22841 ch,
22842 mc::InterpFilterKind::Bilinear,
22843 &mut vb,
22844 fctx,
22845 );
22846 (yb, ub, vb)
22847 });
22848 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
22849 // `decode_block` uses: set fresh right before each plane's own
22850 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
22851 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
22852 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
22853 // first shape that reaches that loop with an override set).
22854 let palette_y_buf = match &intrabc_bufs {
22855 Some((yb, _, _)) => Some(yb.clone()),
22856 None => palette_y_buf,
22857 };
22858 // lane-av1intrapred: the chroma twin of the `palette_y_buf` wrap above --
22859 // `decode_block` does the same for its own `palette_uv_bufs`
22860 // (decode.rs's single-TU and multi-TU chroma reads). Without it, an
22861 // intrabc leaf whose var-tx tree split to TX_4X4 reached the TX4 arm's
22862 // chroma reads with the override unset: the unit predicted INTRA from
22863 // the UV mode (intrabc's is DC) instead of copying the frame at the DV,
22864 // R5 first differing pixel U(184,4), block mi (2,92).
22865 let palette_uv_bufs = match &intrabc_bufs {
22866 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
22867 None => palette_uv_bufs,
22868 };
22869 let (luma_grid, u_grid, v_grid);
22870 if skip {
22871 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
22872 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
22873 // transform units, each off the units already written left/above of
22874 // it inside this same leaf -- an intra block's transform size is read
22875 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
22876 // A palette block's prediction is the whole-block index map, never
22877 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
22878 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
22879 // even when `tx_depth` resolved to TX_4X4.
22880 if resolved == 4 && palette_y_buf.is_none() {
22881 hit!(SKIP_SPLIT_TX_HITS);
22882 for tu_row in 0..2 {
22883 for tu_col in 0..2 {
22884 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
22885 if tu_px >= y.true_width || tu_py >= y.true_height {
22886 continue;
22887 }
22888 let tu_reach = tu_reach(
22889 8,
22890 8,
22891 tu_col * 4,
22892 tu_row * 4,
22893 4,
22894 reach,
22895 px,
22896 py,
22897 y.width,
22898 y.height,
22899 fctx,
22900 );
22901 push_intra(
22902 0,
22903 tu_px,
22904 tu_py,
22905 4,
22906 mode,
22907 angle_delta_y,
22908 tu_reach,
22909 &ZERO_RESIDUAL[..16],
22910 None,
22911 filter_intra,
22912 smooth_neighbor,
22913 fctx,
22914 );
22915 }
22916 }
22917 } else {
22918 if let Some(buf) = &palette_y_buf {
22919 set_palette_pred(buf.clone(), fctx);
22920 }
22921 push_intra(
22922 0,
22923 px,
22924 py,
22925 8,
22926 mode,
22927 angle_delta_y,
22928 reach,
22929 &ZERO_RESIDUAL[..64],
22930 None,
22931 filter_intra,
22932 smooth_neighbor,
22933 fctx,
22934 );
22935 }
22936 let ac = alpha.map(|_| cfl_src(px, py, 8));
22937 // Three skip-arm shapes, dispatched on THIS frame's subsampling.
22938 // lane-av1-422d: at 4:2:2 a skipped leaf still predicts its 4x8 rect
22939 // unit per plane (CfL keeps its contribution, [`decode_block`]'s own
22940 // skip-arm rule); no coefficient symbol exists, so the entropy
22941 // context never enters the rect read.
22942 if chroma_422 {
22943 u_grid = leaf8_chroma422_unit(
22944 dec,
22945 cdfs,
22946 (false, false, 0),
22947 uv_predict_mode,
22948 angle_delta_uv,
22949 reach,
22950 1,
22951 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22952 true,
22953 intrabc_bufs
22954 .as_ref()
22955 .map(|(_, ub, _)| ub.clone())
22956 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
22957 u,
22958 cpx,
22959 cpy,
22960 smooth_neighbor_uv,
22961 fctx,
22962 )?;
22963 v_grid = leaf8_chroma422_unit(
22964 dec,
22965 cdfs,
22966 (false, false, 0),
22967 uv_predict_mode,
22968 angle_delta_uv,
22969 reach,
22970 2,
22971 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22972 true,
22973 intrabc_bufs
22974 .as_ref()
22975 .map(|(_, _, vb)| vb.clone())
22976 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
22977 v,
22978 cpx,
22979 cpy,
22980 smooth_neighbor_uv,
22981 fctx,
22982 )?;
22983 luma_grid = Grid::Zero(64);
22984 } else {
22985 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster of
22986 // TX_4X4 units (`av1_get_tx_size`: lossless forces TX_4X4 on EVERY
22987 // plane), so a skipped leaf predicts per unit -- each from its own
22988 // edges -- like the luma `SKIP_SPLIT_TX` loop above. CfL never fires
22989 // here (`is_cfl_allowed` at lossless needs plane_bsize == 4x4; this
22990 // chroma plane block is 8x8), and intrabc/palette keep the
22991 // whole-plane-block prediction they already run. The guard also
22992 // requires `chroma_444`, so it can never reach the 4:2:2 arm above.
22993 let chroma_units_444 =
22994 chroma_444 && lossless(fctx) && intrabc_bufs.is_none() && palette_uv_bufs.is_none();
22995 if let Some((_, ub, _)) = &intrabc_bufs {
22996 set_palette_pred(ub.clone(), fctx);
22997 } else if let Some((ub, _)) = &palette_uv_bufs {
22998 set_palette_pred(ub.clone(), fctx);
22999 }
23000 if chroma_units_444 {
23001 for cu_row in 0..2 {
23002 for cu_col in 0..2 {
23003 let cu_reach = tu_reach(
23004 8,
23005 8,
23006 cu_col * 4,
23007 cu_row * 4,
23008 4,
23009 reach,
23010 px,
23011 py,
23012 y.width,
23013 y.height,
23014 fctx,
23015 );
23016 push_intra(
23017 1,
23018 cpx + cu_col * 4,
23019 cpy + cu_row * 4,
23020 4,
23021 uv_predict_mode,
23022 angle_delta_uv,
23023 cu_reach,
23024 &ZERO_RESIDUAL[..16],
23025 None,
23026 None,
23027 smooth_neighbor_uv,
23028 fctx,
23029 );
23030 }
23031 }
23032 } else {
23033 push_intra(
23034 1,
23035 cpx,
23036 cpy,
23037 csz,
23038 uv_predict_mode,
23039 angle_delta_uv,
23040 reach,
23041 &ZERO_RESIDUAL[..csz * csz],
23042 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23043 None,
23044 smooth_neighbor_uv,
23045 fctx,
23046 );
23047 }
23048 if let Some((_, _, vb)) = &intrabc_bufs {
23049 set_palette_pred(vb.clone(), fctx);
23050 } else if let Some((_, vb)) = &palette_uv_bufs {
23051 set_palette_pred(vb.clone(), fctx);
23052 }
23053 if chroma_units_444 {
23054 for cu_row in 0..2 {
23055 for cu_col in 0..2 {
23056 let cu_reach = tu_reach(
23057 8,
23058 8,
23059 cu_col * 4,
23060 cu_row * 4,
23061 4,
23062 reach,
23063 px,
23064 py,
23065 y.width,
23066 y.height,
23067 fctx,
23068 );
23069 push_intra(
23070 2,
23071 cpx + cu_col * 4,
23072 cpy + cu_row * 4,
23073 4,
23074 uv_predict_mode,
23075 angle_delta_uv,
23076 cu_reach,
23077 &ZERO_RESIDUAL[..16],
23078 None,
23079 None,
23080 smooth_neighbor_uv,
23081 fctx,
23082 );
23083 }
23084 }
23085 } else {
23086 push_intra(
23087 2,
23088 cpx,
23089 cpy,
23090 csz,
23091 uv_predict_mode,
23092 angle_delta_uv,
23093 reach,
23094 &ZERO_RESIDUAL[..csz * csz],
23095 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23096 None,
23097 smooth_neighbor_uv,
23098 fctx,
23099 );
23100 }
23101 luma_grid = Grid::Zero(64);
23102 u_grid = Grid::Zero(csz * csz);
23103 v_grid = Grid::Zero(csz * csz);
23104 }
23105 } else if resolved != 4 {
23106 let around = neighbours.around_mi(leaf_mi, 8);
23107 // lane-av1-422h: the 4:2:2 chroma rect unit's `get_txb_ctx_general`
23108 // reads its above votes over CHROMA 4-px cells -- at ss_x 1 one chroma
23109 // cell spans TWO luma mi columns, so the per-luma-mi sum counts each
23110 // above chroma column twice and `dc_sign_ctx`'s signum flips whenever
23111 // the doubled sum crosses zero (the same class
23112 // [`Neighbours::around_mi_422_chroma`] fixes for the rect readers;
23113 // measured at mi(2,24) plane 2: ours dc_sign row 0, oracle row 2).
23114 // The left extent is unsubsquared at ss_y 0 and stays one-to-one.
23115 let chroma_around = if chroma_422 {
23116 neighbours.around_mi_422_chroma(leaf_mi, 8, 8)
23117 } else {
23118 around
23119 };
23120 if let Some(buf) = &palette_y_buf {
23121 set_palette_pred(buf.clone(), fctx);
23122 }
23123 luma_grid = read_plane(
23124 dec,
23125 cdfs,
23126 if intrabc_dv.is_some() {
23127 inter_txbset_for(8, reduced_tx_set)
23128 } else if reduced_tx_set {
23129 TxbSet::Luma8
23130 } else {
23131 TxbSet::Luma8Set1
23132 },
23133 scans.0,
23134 0,
23135 around[0],
23136 mode,
23137 mode,
23138 angle_delta_y,
23139 reach,
23140 y,
23141 px,
23142 py,
23143 8,
23144 TX8,
23145 base_q_idx,
23146 None,
23147 filter_intra,
23148 None,
23149 smooth_neighbor,
23150 fctx,
23151 )?;
23152 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
23153 // an intrabc block's chroma tx_type is the colocated LUMA transform's
23154 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
23155 if intrabc_dv.is_some() {
23156 fctx.intrabc_chroma_tx
23157 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
23158 }
23159 let ac = alpha.map(|_| cfl_src(px, py, 8));
23160 if chroma_422 {
23161 // lane-av1-422d: ONE 4x8 rect unit per plane (`av1_get_max_uv_txsize`
23162 // at ss (1,0) == TX_4X8), covering the plane block exactly, off the
23163 // leaf's own 8x8-span entropy context (`chroma_tiled`'s convention).
23164 u_grid = leaf8_chroma422_unit(
23165 dec,
23166 cdfs,
23167 chroma_around[1],
23168 uv_predict_mode,
23169 angle_delta_uv,
23170 reach,
23171 1,
23172 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23173 false,
23174 intrabc_bufs
23175 .as_ref()
23176 .map(|(_, ub, _)| ub.clone())
23177 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23178 u,
23179 cpx,
23180 cpy,
23181 smooth_neighbor_uv,
23182 fctx,
23183 )?;
23184 v_grid = leaf8_chroma422_unit(
23185 dec,
23186 cdfs,
23187 chroma_around[2],
23188 uv_predict_mode,
23189 angle_delta_uv,
23190 reach,
23191 2,
23192 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23193 false,
23194 intrabc_bufs
23195 .as_ref()
23196 .map(|(_, _, vb)| vb.clone())
23197 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23198 v,
23199 cpx,
23200 cpy,
23201 smooth_neighbor_uv,
23202 fctx,
23203 )?;
23204 } else {
23205 if let Some((_, ub, _)) = &intrabc_bufs {
23206 set_palette_pred(ub.clone(), fctx);
23207 } else if let Some((ub, _)) = &palette_uv_bufs {
23208 set_palette_pred(ub.clone(), fctx);
23209 }
23210 u_grid = read_plane(
23211 dec,
23212 cdfs,
23213 cset,
23214 cscan,
23215 1,
23216 around[1],
23217 mode,
23218 uv_predict_mode,
23219 angle_delta_uv,
23220 reach,
23221 u,
23222 cpx,
23223 cpy,
23224 csz,
23225 csz,
23226 base_q_idx,
23227 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23228 None,
23229 None,
23230 smooth_neighbor_uv,
23231 fctx,
23232 )?;
23233 if let Some((_, _, vb)) = &intrabc_bufs {
23234 set_palette_pred(vb.clone(), fctx);
23235 } else if let Some((_, vb)) = &palette_uv_bufs {
23236 set_palette_pred(vb.clone(), fctx);
23237 }
23238 v_grid = read_plane(
23239 dec,
23240 cdfs,
23241 cset,
23242 cscan,
23243 2,
23244 around[2],
23245 mode,
23246 uv_predict_mode,
23247 angle_delta_uv,
23248 reach,
23249 v,
23250 cpx,
23251 cpy,
23252 csz,
23253 csz,
23254 base_q_idx,
23255 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23256 None,
23257 None,
23258 smooth_neighbor_uv,
23259 fctx,
23260 )?;
23261 }
23262 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
23263 // two chroma reads (`decode_block`'s own tail does the same) -- left
23264 // set, every later chroma block would inherit this luma tx_type,
23265 // which picks the scan and the inverse transform.
23266 fctx.intrabc_chroma_tx.with(|c| c.set(None));
23267 } else {
23268 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
23269 // grid of 4x4 transform units, each predicted from the leaf's own
23270 // 8x8 `mode` and reading its own fresh context off the earlier
23271 // units in this same leaf (the same per-TU pattern `decode_block`'s
23272 // multi-TU branch runs at bigger blocks).
23273 let mut first_leaf_tx: Option<TxType> = None;
23274 for tu_row in 0..2 {
23275 for tu_col in 0..2 {
23276 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
23277 let tu_px = px + tu_col * 4;
23278 let tu_py = py + tu_row * 4;
23279 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
23280 if crate::encode::Reach::in_vert_ab() {
23281 hit!(VERT_AB_TX4_HITS);
23282 }
23283 let tu_reach = tu_reach(
23284 8,
23285 8,
23286 tu_col * 4,
23287 tu_row * 4,
23288 4,
23289 reach,
23290 px,
23291 py,
23292 y.width,
23293 y.height,
23294 fctx,
23295 );
23296 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
23297 // Each 4x4 unit predicts from its own window of the block's
23298 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
23299 // 16x16 and up) -- the whole-block buffer would be taken by
23300 // the FIRST unit and indexed at the wrong stride.
23301 if let Some(buf) = &palette_y_buf {
23302 hit!(PALETTE_SPLIT_TX_HITS);
23303 let mut window = vec![0u16; 16];
23304 for row in 0..4 {
23305 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
23306 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
23307 }
23308 set_palette_pred(window, fctx);
23309 }
23310 let tu_grid = read_plane(
23311 dec,
23312 cdfs,
23313 if intrabc_dv.is_some() {
23314 inter_txbset_for(4, reduced_tx_set)
23315 } else if reduced_tx_set {
23316 TxbSet::Luma4
23317 } else {
23318 TxbSet::Luma4Set1
23319 },
23320 scans.1,
23321 0,
23322 tu_around,
23323 mode,
23324 mode,
23325 angle_delta_y,
23326 tu_reach,
23327 y,
23328 tu_px,
23329 tu_py,
23330 4,
23331 4,
23332 base_q_idx,
23333 None,
23334 filter_intra,
23335 Some(tu_skip_ctx),
23336 smooth_neighbor,
23337 fctx,
23338 )?;
23339 if crate::envflags::env_flag!("EC_AV1_TRACE") {
23340 eprintln!(
23341 "TRACE tu_bitpos mi=({},{}) tell={}",
23342 tu_mi.0,
23343 tu_mi.1,
23344 dec.debug_bitpos()
23345 );
23346 }
23347 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
23348 // The FIRST (top-left, co-located with this group's chroma)
23349 // TU's coded tx_type is what the group's chroma inherits --
23350 // the same capture [`decode_block`]'s multi-TU branch makes
23351 // for `first_leaf_tx` (libaom `av1_get_tx_type`, blockd.h:
23352 // an inter-classified block's `PLANE_TYPE_UV` reads
23353 // `tx_type_map`, and intrabc is inter-classified).
23354 if first_leaf_tx.is_none() {
23355 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
23356 }
23357 }
23358 }
23359 // lane-av1intrapred: an intrabc leaf whose var-tx tree split to
23360 // TX_4X4 never armed [`INTRABC_CHROMA_TX`], so its chroma reads fell
23361 // back to `default_intra_tx_type(DC_PRED)` = `DCT_DCT` and took the
23362 // 2D scan, the 2D eob row and the 2D nz contexts where libaom takes
23363 // the inherited luma type's (R5's first fork: mi (36,66), luma
23364 // (0,0) coded `H_ADST` off the 16-symbol inter set, chroma U then
23365 // decoded its `eob` from the wrong CDF row). Same arm the
23366 // `resolved != 4` branch above runs for its whole-leaf unit.
23367 if intrabc_dv.is_some() {
23368 if let Some(t) = first_leaf_tx {
23369 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
23370 }
23371 }
23372 let ac = alpha.map(|_| cfl_src(px, py, 8));
23373 // lane-av1-422h: same ss_x-1 dc-vote sampling as the whole-leaf arm
23374 // above -- the doubled above sum crosses zero at mi(2,24) plane 2.
23375 let chroma_around = if chroma_422 {
23376 neighbours.around_mi_422_chroma(leaf_mi, 8, 8)
23377 } else {
23378 neighbours.around_mi(leaf_mi, 8)
23379 };
23380 // lane-av1intrapred: the non-vacuity counter -- armed slot consulted
23381 // by this arm's chroma reads means the frame-copy + inherited-type
23382 // route ran; zero at gate time means the fixture stopped reaching it.
23383 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
23384 hit!(INTRABC_TX4_CHROMA_COPY_HITS);
23385 }
23386 if chroma_422 {
23387 // lane-av1-422d: the chroma unit does NOT follow the luma var-tx
23388 // split -- `uv_txsize` is `av1_get_max_uv_txsize` of the block,
23389 // still the one 4x8 rect unit per plane at ss (1,0).
23390 u_grid = leaf8_chroma422_unit(
23391 dec,
23392 cdfs,
23393 chroma_around[1],
23394 uv_predict_mode,
23395 angle_delta_uv,
23396 reach,
23397 1,
23398 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23399 false,
23400 intrabc_bufs
23401 .as_ref()
23402 .map(|(_, ub, _)| ub.clone())
23403 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23404 u,
23405 cpx,
23406 cpy,
23407 smooth_neighbor_uv,
23408 fctx,
23409 )?;
23410 v_grid = leaf8_chroma422_unit(
23411 dec,
23412 cdfs,
23413 chroma_around[2],
23414 uv_predict_mode,
23415 angle_delta_uv,
23416 reach,
23417 2,
23418 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23419 false,
23420 intrabc_bufs
23421 .as_ref()
23422 .map(|(_, _, vb)| vb.clone())
23423 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23424 v,
23425 cpx,
23426 cpy,
23427 smooth_neighbor_uv,
23428 fctx,
23429 )?;
23430 } else if chroma_444 && lossless(fctx) {
23431 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster
23432 // of TX_4X4 units per plane, PLANE-MAJOR (`av1_get_tx_size`:
23433 // lossless forces TX_4X4 on EVERY plane) -- the same walk
23434 // `read_intra_chroma_lossless` runs for whole blocks. Reading one
23435 // TX_8X8 unit here panicked before: the lossless inverse is the
23436 // 4x4-only WHT (`TxParams::run`'s own `(w, h) == (4, 4)`
23437 // invariant), and the unit count desyncs the tile either way.
23438 // Per-unit `record_mi_chroma` calls stamp the neighbour bands
23439 // inside, which is why the tail's whole-leaf chroma stamp below
23440 // is skipped for this shape.
23441 let (mut uo, mut vo) = (Vec::new(), Vec::new());
23442 read_intra_chroma_lossless(
23443 dec,
23444 cdfs,
23445 neighbours,
23446 u,
23447 v,
23448 leaf_mi,
23449 (px, py),
23450 (cpx, cpy),
23451 8,
23452 (8, 8),
23453 (0, 0),
23454 (8, 8),
23455 8,
23456 reach,
23457 (y.width, y.height),
23458 mode,
23459 uv_predict_mode,
23460 angle_delta_uv,
23461 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
23462 smooth_neighbor_uv,
23463 base_q_idx,
23464 &mut uo,
23465 &mut vo,
23466 fctx,
23467 )?;
23468 u_grid = if uo.is_empty() {
23469 Grid::Zero(64)
23470 } else {
23471 Grid::Own(uo)
23472 };
23473 v_grid = if vo.is_empty() {
23474 Grid::Zero(64)
23475 } else {
23476 Grid::Own(vo)
23477 };
23478 } else {
23479 if let Some((ub, _)) = &palette_uv_bufs {
23480 set_palette_pred(ub.clone(), fctx);
23481 }
23482 u_grid = read_plane(
23483 dec,
23484 cdfs,
23485 cset,
23486 cscan,
23487 1,
23488 chroma_around[1],
23489 mode,
23490 uv_predict_mode,
23491 angle_delta_uv,
23492 reach,
23493 u,
23494 cpx,
23495 cpy,
23496 csz,
23497 csz,
23498 base_q_idx,
23499 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23500 None,
23501 None,
23502 smooth_neighbor_uv,
23503 fctx,
23504 )?;
23505 if let Some((_, vb)) = &palette_uv_bufs {
23506 set_palette_pred(vb.clone(), fctx);
23507 }
23508 v_grid = read_plane(
23509 dec,
23510 cdfs,
23511 cset,
23512 cscan,
23513 2,
23514 chroma_around[2],
23515 mode,
23516 uv_predict_mode,
23517 angle_delta_uv,
23518 reach,
23519 v,
23520 cpx,
23521 cpy,
23522 csz,
23523 csz,
23524 base_q_idx,
23525 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23526 None,
23527 None,
23528 smooth_neighbor_uv,
23529 fctx,
23530 )?;
23531 }
23532 // The two chroma reads above are the only consulters of this leaf's
23533 // armed [`INTRABC_CHROMA_TX`]; leaving it set would make the NEXT
23534 // leaf's chroma inherit this leaf's luma type instead of its own
23535 // derivation (class armed-slot-leak-into-next-leaf, seen live: the
23536 // regular-intra leaf after an intrabc TX4 leaf took the intrabc
23537 // luma's `V_ADST` for its chroma eob row).
23538 if intrabc_dv.is_some() {
23539 fctx.intrabc_chroma_tx.with(|c| c.set(None));
23540 }
23541 // `record_split_luma` expects a `record`-style `(r, c)` position in
23542 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
23543 // already in mi units, so calling it here double-scaled the
23544 // position. Plane 0 is already correct per-TU from the
23545 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
23546 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
23547 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
23548 // leaf's own 8x8 side over `MI`).
23549 let side_mi = 2;
23550 for cell in 0..side_mi {
23551 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
23552 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
23553 }
23554 let round_up_even = |n: usize| n.div_ceil(2) * 2;
23555 let bound_h = round_up_even(neighbours.mi_rows);
23556 let bound_w = round_up_even(neighbours.mi_cols);
23557 let u_state = neighbour_state(&u_grid);
23558 let v_state = neighbour_state(&v_grid);
23559 // The 4:4:4 lossless walk above already stamped these bands PER UNIT
23560 // (its raster-order last writer per cell is exactly libaom's
23561 // per-entry last update); this whole-leaf aggregate would clobber
23562 // four distinct unit states with one, so it runs only for the shapes
23563 // whose chroma really is one unit.
23564 if !(chroma_444 && lossless(fctx)) {
23565 for cell in 0..side_mi {
23566 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
23567 neighbours.left[leaf_mi.0 + cell][1] = u_state;
23568 neighbours.left[leaf_mi.0 + cell][2] = v_state;
23569 }
23570 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
23571 neighbours.above[leaf_mi.1 + cell][1] = u_state;
23572 neighbours.above[leaf_mi.1 + cell][2] = v_state;
23573 }
23574 }
23575 }
23576 // This leaf's own palette state into the mi-granular above/left bands
23577 // (sizes 0 when it used none, which is what clears a previous block's
23578 // palette out of the next block's ctx and colour cache).
23579 {
23580 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
23581 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
23582 }
23583 neighbours.fill_skip_grid(leaf_mi, 2, skip);
23584 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
23585 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
23586 // own copy; only an intrabc var-tx read consumes these bands on the intra
23587 // path, so the write is armed by `allow_intrabc`.
23588 if allow_intrabc {
23589 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
23590 }
23591 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
23592 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
23593 return Ok(mode);
23594 }
23595 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
23596 // This leaf's own palette state into the mi-granular above/left bands
23597 // (sizes 0 when it used none, which is what clears a previous block's
23598 // palette out of the next block's ctx and colour cache).
23599 {
23600 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
23601 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
23602 }
23603 hit!(INTER8_SKIP_BAND_HITS);
23604 neighbours.fill_skip_grid(leaf_mi, 2, skip);
23605 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
23606 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
23607 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
23608 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
23609 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
23610 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
23611 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
23612 // wrong CDF row, so the msac range diverged mid-frame with no refusal
23613 // (class `wrong-alphabet-same-value`; the ReelB key frame at
23614 // -ss 900, first bad luma sample row 186 col 1803).
23615 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
23616 // lane-t900 r32 / lane-av1txbands: `set_txfm_ctxs` for an 8x8 leaf -- see
23617 // `decode_block`'s own copy for why this stays beside
23618 // [`Neighbours::fill_lf_grid_rect`]'s publish (the skipped-intrabc
23619 // BLOCK-size term).
23620 if allow_intrabc {
23621 set_txfm_ctxs(
23622 neighbours,
23623 leaf_mi,
23624 resolved,
23625 2,
23626 2,
23627 skip && intrabc_dv.is_some(),
23628 );
23629 }
23630 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
23631 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
23632 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
23633 // publish its own cells exactly like `decode_block` does.
23634 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
23635 Ok(mode)
23636}
23637
23638/// lane-av1-422d: ONE 4:2:2 chroma transform unit of an 8x8 leaf
23639/// ([`decode_leaf8`]). At ss (1,0) the plane block is 4x8 and
23640/// `av1_get_max_uv_txsize(BLOCK_8X8)` resolves to
23641/// `max_txsize_rect_lookup[BLOCK_4X8]` == TX_4X8, so the WHOLE plane block is
23642/// a single rect unit -- one txb_skip + one scan per plane in the
23643/// [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the
23644/// shape. Mirrors [`sub8_leaf_chroma444`]'s rect arm at the leaf's halved
23645/// position: the entropy context is the leaf's own 8x8 luma-span
23646/// above/left state (the `chroma_tiled` arm's convention; no `+3`
23647/// plane-block-bigger term -- the unit covers the plane block exactly), the
23648/// CFL source is the leaf's whole 8x8 luma block, and the plane's predicted
23649/// mode supplies the mode-derived default `tx_type` unless an armed
23650/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own (the caller
23651/// arms and disarms it, exactly as it does around its square reads).
23652#[allow(clippy::too_many_arguments)]
23653fn leaf8_chroma422_unit(
23654 dec: &mut SymbolDecoder,
23655 cdfs: &mut Cdfs,
23656 around: (bool, bool, i32),
23657 uv_predict_mode: usize,
23658 angle_delta_uv: i32,
23659 reach: Reach,
23660 plane_idx: usize,
23661 cfl: Option<(i32, CflSrc)>,
23662 skip: bool,
23663 // The prediction override the square arms feed through
23664 // `set_palette_pred`: an intrabc leaf's frame copy at the DV takes
23665 // priority over a palette block's colour-index map.
23666 pred_override: Option<Vec<u16>>,
23667 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
23668 // the plane exclusively while the unit's coefficients are parsed.
23669 _plane: &mut PlaneBuf<'static>,
23670 cpx: usize,
23671 cpy: usize,
23672 smooth_neighbor_uv: bool,
23673 fctx: &crate::decode::FrameCtx,
23674) -> Result<Grid> {
23675 // The unit's prediction runs whether or not a residual follows it -- a
23676 // skipped leaf still predicts (the CfL contribution survives a skip),
23677 // and a skipped intrabc leaf still copies the frame at its DV.
23678 if let Some(buf) = pred_override {
23679 set_palette_pred(buf, fctx);
23680 }
23681 if skip {
23682 push_intra_rect(
23683 plane_idx,
23684 cpx,
23685 cpy,
23686 4,
23687 8,
23688 uv_predict_mode,
23689 angle_delta_uv,
23690 reach,
23691 &ZERO_RESIDUAL[..4 * 8],
23692 cfl,
23693 None,
23694 smooth_neighbor_uv,
23695 fctx,
23696 );
23697 return Ok(Grid::Zero(4 * 8));
23698 }
23699 let default_tx = fctx
23700 .intrabc_chroma_tx
23701 .with(std::cell::Cell::get)
23702 .unwrap_or_else(|| default_intra_tx_type(uv_predict_mode as u8));
23703 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
23704 let (levels, tx_type) = read_coeffs_rect(
23705 dec,
23706 &mut coding,
23707 &SCAN_4X8,
23708 4,
23709 8,
23710 usize::from(around.0) + usize::from(around.1),
23711 dc_sign_ctx(around.2),
23712 default_tx,
23713 plane_idx,
23714 )?;
23715 let residual = dequant_and_inverse_typed_wh(
23716 &levels,
23717 4,
23718 8,
23719 crate::decode::bit_depth(fctx),
23720 block_q_idx(fctx),
23721 plane_q_delta(plane_idx, fctx).0,
23722 plane_q_delta(plane_idx, fctx).1,
23723 tx_type,
23724 block_iqmatrix(fctx, plane_idx, 4, 8, tx_type),
23725 );
23726 push_intra_rect(
23727 plane_idx,
23728 cpx,
23729 cpy,
23730 4,
23731 8,
23732 uv_predict_mode,
23733 angle_delta_uv,
23734 reach,
23735 &residual,
23736 cfl,
23737 None,
23738 smooth_neighbor_uv,
23739 fctx,
23740 );
23741 Ok(levels)
23742}
23743
23744/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
23745/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
23746/// bottom, where no partition symbol is read at all -- `decode_block` runs
23747/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
23748/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
23749/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
23750/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
23751/// of the 2x2 4x4 group carries chroma syntax at all.
23752#[allow(clippy::too_many_arguments)]
23753fn read_intra_mode_sub8(
23754 dec: &mut SymbolDecoder,
23755 cdfs: &mut Cdfs,
23756 above_mode: usize,
23757 left_mode: usize,
23758 has_chroma: bool,
23759 enable_filter_intra: bool,
23760 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
23761 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
23762 // from the wrong row is the same VALUE with a different interval, so it
23763 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
23764 fi_class: usize,
23765 skip_ctx: usize,
23766 allow_intrabc: bool,
23767 mi_r: usize,
23768 mi_c: usize,
23769 // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4`
23770 // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf
23771 // left the second mi column at segment 0, which reads back as a
23772 // neighbour's `cdf_index`/prediction two blocks later.
23773 seg_w_mi: usize,
23774 seg_h_mi: usize,
23775 fctx: &crate::decode::FrameCtx,
23776) -> Result<(
23777 bool,
23778 usize,
23779 i32,
23780 Option<(usize, i32, Option<(i32, i32)>)>,
23781 Option<usize>,
23782 Option<(i32, i32)>,
23783)> {
23784 // lane-av1mono: a monochrome leaf codes no chroma mode (libaom
23785 // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`.
23786 let has_chroma = has_chroma && !mono(fctx);
23787 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
23788 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
23789 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
23790 if ec_istep {
23791 eprintln!(
23792 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}",
23793 dec.debug_state().0
23794 );
23795 }
23796 // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder
23797 // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block.
23798 macro_rules! istep {
23799 ($name:literal, $val:expr) => {
23800 if ec_istep {
23801 eprintln!(
23802 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}",
23803 $name,
23804 $val,
23805 dec.debug_state().0
23806 );
23807 }
23808 };
23809 }
23810 // lane-seg2: same `intra_segment_id` placement as the square and rect
23811 // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id`
23812 // like any other block, over its own 1x1 mi footprint. Dropping it here
23813 // both ate a symbol (the tile desynced at the frame's first sub-8x8
23814 // split) and left `cur_segment_id` on the previous block, so the leaf
23815 // dequantized with a neighbour's `SEG_LVL_ALT_Q`.
23816 if seg_id_pre_skip(fctx) {
23817 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
23818 }
23819 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
23820 if trace {
23821 eprintln!(
23822 "TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}",
23823 skip as i32,
23824 dec.debug_state().0
23825 );
23826 }
23827 istep!("skip", skip as i32);
23828 if !seg_id_pre_skip(fctx) {
23829 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
23830 }
23831 maybe_read_cdef_idx(dec, mi_r, mi_c, (2, 2), skip, fctx);
23832 istep!("cdef", 0);
23833 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
23834 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
23835 istep!("dq", 0);
23836 if allow_intrabc {
23837 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
23838 if ec_istep {
23839 eprintln!(
23840 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
23841 u8::from(use_intrabc),
23842 dec.debug_state().0
23843 );
23844 }
23845 if use_intrabc {
23846 // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block
23847 // vector right after the flag and RETURNS -- no y/uv mode, angle
23848 // delta, palette, CfL or filter-intra syntax follows, and the
23849 // block is reconstructed by the INTER path (libaom's
23850 // `is_inter_block` counts an intrabc block), so the caller takes
23851 // the frame-copy prediction + inter residual.
23852 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (seg_w_mi, seg_h_mi), fctx);
23853 // lane-av1txr: the DV travels back in the RETURN value -- it is
23854 // NOT published through `FrameCtx::intrabc_dv`. That slot is the
23855 // SQUARE paths' handoff (`decode_block`/`decode_leaf8` arm it,
23856 // then `take()` it in the same call), so a sub-8x8 leaf that
23857 // armed it left the vector standing for the NEXT >=8x8 block:
23858 // `warped.obu`'s (38,60) 8x8 intra block took it as its own
23859 // intrabc and read an inter var-tx `txfm_split` where libaom read
23860 // an intra `tx_depth` (class `stale-slot-handoff`).
23861 hit!(INTRABC_HITS);
23862 return Ok((skip, DC_PRED, 0, None, None, Some(dv)));
23863 }
23864 }
23865 let above_ctx = INTRA_MODE_CTX[above_mode];
23866 let left_ctx = INTRA_MODE_CTX[left_mode];
23867 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
23868 istep!("mode", mode);
23869 if trace {
23870 eprintln!(
23871 "TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
23872 dec.debug_state().0
23873 );
23874 }
23875 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
23876 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
23877 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
23878 // symbol. Reading one consumed a symbol the encoder never wrote and
23879 // desynced the tile at the very next element.
23880 let angle_delta_y = 0;
23881 let chroma = if has_chroma {
23882 // `is_cfl_allowed` (blockd.h): at lossless CfL needs the CHROMA plane
23883 // block to be a single TX_4X4 (`cfl_allowed_px`). True for this leaf
23884 // at 4:2:0 (the group's plane block is 4x4) and for a 4:4:4
23885 // `BLOCK_4X4` split leaf, but FALSE for a 4:4:4 `BLOCK_8X4`/`BLOCK_4X8`
23886 // rect leaf, whose plane block is the rect itself -- that shape reads
23887 // the 13-symbol `uv_mode_no_cfl` CDF, and reading the CFL alphabet
23888 // there desynced the tile at the rect leaf's own uv_mode symbol (measured:
23889 // ours consumed the 14-symbol interval where the oracle read 13, first
23890 // divergence at the rect leaf mi (8,16) of `ll444.obu`; class
23891 // `wrong-alphabet-same-value`, lane-av1-llsub8).
23892 let uv_mode = if cfl_allowed_px(seg_w_mi * MI, seg_h_mi * MI, fctx) {
23893 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
23894 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
23895 } else {
23896 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
23897 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
23898 };
23899 if trace {
23900 eprintln!(
23901 "TRACE sub8 uv_mode value={uv_mode} rng={}",
23902 dec.debug_state().0
23903 );
23904 }
23905 if (9..=12).contains(&uv_mode) {
23906 hit!(SMOOTH_UV_HITS);
23907 }
23908 let alpha = if uv_mode == UV_CFL_PRED {
23909 Some(read_cfl_alphas(dec, cdfs))
23910 } else {
23911 None
23912 };
23913 if (V_PRED..=D67_PRED).contains(&uv_mode) {
23914 hit!(DIRECTIONAL_UV_HITS);
23915 }
23916 // See the luma comment above: no angle delta below 8x8.
23917 let angle_delta_uv = 0;
23918 Some((uv_mode, angle_delta_uv, alpha))
23919 } else {
23920 None
23921 };
23922 let mut filter_intra = None;
23923 if mode == DC_PRED && enable_filter_intra {
23924 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
23925 if trace {
23926 eprintln!(
23927 "TRACE sub8 use_filter_intra value={}",
23928 use_filter_intra as i32
23929 );
23930 }
23931 if use_filter_intra {
23932 hit!(FILTER_INTRA_HITS);
23933 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
23934 filter_intra = Some(fi_mode);
23935 }
23936 }
23937 Ok((skip, mode, angle_delta_y, chroma, filter_intra, None))
23938}
23939/// 4:4:4 sub-8x8 key-frame leaf chroma (lane-av1-444). At subsampling 0/0
23940/// `is_chroma_reference` (av1_common_int.h:1459) is unconditional, so EVERY
23941/// 4x4 / 4x8 / 8x4 leaf codes its own full-resolution chroma unit right
23942/// after its own luma (`read_intra_mode_sub8` already read this leaf's own
23943/// `uv_mode`), not the one shared 4x4 unit [`decode_leaf_split4`] /
23944/// [`decode_leaf_rect8`]'s group tails decode at 4:2:0. Mirrors those tails
23945/// arm for arm at leaf scale: a skipped leaf keeps its CfL contribution, an
23946/// intrabc leaf predicts a frame copy at its DV with the luma `tx_type`
23947/// inherited through [`INTRABC_CHROMA_TX`] (the caller arms it right after
23948/// the luma read) -- and a SKIPPED intrabc leaf is still the DV copy, never
23949/// an intra prediction (lane-av1-ibcskip2: libaom's
23950/// `av1_build_inter_predictors_sb` runs for an intrabc block regardless of
23951/// `skip`). The chroma position, reach and entropy-context span are
23952/// the leaf's own (ss 0/0); the 4x8/8x4 unit reads the same
23953/// `ChromaRect8x4` tables [`decode_rect_split`] proves for that shape.
23954/// Records the leaf's own `uv_mode` map entry and chroma above/left state,
23955/// and returns the (u, v) grids for the caller's coarse slots.
23956#[allow(clippy::too_many_arguments)]
23957fn sub8_leaf_chroma444(
23958 dec: &mut SymbolDecoder,
23959 cdfs: &mut Cdfs,
23960 neighbours: &mut Neighbours,
23961 lmi: (usize, usize),
23962 bw: usize,
23963 bh: usize,
23964 uv_mode: usize,
23965 alpha: Option<(i32, i32)>,
23966 skip: bool,
23967 intrabc_dv: Option<(i32, i32)>,
23968 y: &PlaneBuf<'static>,
23969 u: &mut PlaneBuf<'static>,
23970 v: &mut PlaneBuf<'static>,
23971 scan4: &[u16],
23972 base_q_idx: u8,
23973 smooth_neighbor_uv: bool,
23974 fctx: &crate::decode::FrameCtx,
23975) -> Result<(Grid, Grid, usize, usize)> {
23976 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
23977 DC_PRED
23978 } else {
23979 uv_mode
23980 };
23981 let (w_mi, h_mi) = (bw / MI, bh / MI);
23982 neighbours.record_uv_mode_mi(lmi.0, lmi.1, w_mi, h_mi, uv_predict_mode);
23983 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
23984 let square = (bw, bh) == (4, 4);
23985 // `Reach::of_rect` has no 4x4 table (`rect_reach_tables` starts at 4x8);
23986 // the square unit takes the leaf's own `Reach::of`, as its luma does.
23987 let reach = if square {
23988 Reach::of(4, px, py, y.width, y.height, fctx)
23989 } else {
23990 Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx)
23991 };
23992 let grids = if let Some(dv) = intrabc_dv.filter(|_| skip) {
23993 // lane-av1-ibcskip2: a SKIPPED intrabc leaf still predicts the frame
23994 // copy at its DV -- libaom's `av1_build_inter_predictors_sb` runs for
23995 // an intrabc block regardless of `skip` (only the residual read is
23996 // dropped), so the reconstruction is the bare DV copy. The intra push
23997 // in the next arm is the NON-intrabc route; predicting DC there
23998 // decoded flat cells where this fixture's oracle copies frame bytes
23999 // (class skipped-intrabc-predicts-intra,
24000 // lanes/av1ibcskip2.report.md). Same armed-palette-slot route the
24001 // leaf's own luma skip arm uses (`decode_leaf_split4` /
24002 // `decode_leaf_rect8`); the caller already flushed the recon queue
24003 // before its luma DV copy, so the source samples are current.
24004 let mut ub = vec![0u16; bw * bh];
24005 mc::predict_with_filter(
24006 &u.data,
24007 u.width,
24008 u.true_width,
24009 u.true_height,
24010 mv_to_q4(px, dv.1, 0),
24011 mv_to_q4(py, dv.0, 0),
24012 bw,
24013 bh,
24014 mc::InterpFilterKind::Bilinear,
24015 &mut ub,
24016 fctx,
24017 );
24018 let mut vb = vec![0u16; bw * bh];
24019 mc::predict_with_filter(
24020 &v.data,
24021 v.width,
24022 v.true_width,
24023 v.true_height,
24024 mv_to_q4(px, dv.1, 0),
24025 mv_to_q4(py, dv.0, 0),
24026 bw,
24027 bh,
24028 mc::InterpFilterKind::Bilinear,
24029 &mut vb,
24030 fctx,
24031 );
24032 hit!(SKIPPED_INTRABC_DV_COPY_HITS);
24033 let zeros = &ZERO_RESIDUAL[..bw * bh];
24034 if square {
24035 set_palette_pred(ub, fctx);
24036 push_intra(
24037 1,
24038 px,
24039 py,
24040 4,
24041 DC_PRED,
24042 0,
24043 reach,
24044 zeros,
24045 None,
24046 None,
24047 smooth_neighbor_uv,
24048 fctx,
24049 );
24050 set_palette_pred(vb, fctx);
24051 push_intra(
24052 2,
24053 px,
24054 py,
24055 4,
24056 DC_PRED,
24057 0,
24058 reach,
24059 zeros,
24060 None,
24061 None,
24062 smooth_neighbor_uv,
24063 fctx,
24064 );
24065 } else {
24066 set_palette_pred(ub, fctx);
24067 push_intra_rect(
24068 1,
24069 px,
24070 py,
24071 bw,
24072 bh,
24073 DC_PRED,
24074 0,
24075 reach,
24076 zeros,
24077 None,
24078 None,
24079 smooth_neighbor_uv,
24080 fctx,
24081 );
24082 set_palette_pred(vb, fctx);
24083 push_intra_rect(
24084 2,
24085 px,
24086 py,
24087 bw,
24088 bh,
24089 DC_PRED,
24090 0,
24091 reach,
24092 zeros,
24093 None,
24094 None,
24095 smooth_neighbor_uv,
24096 fctx,
24097 );
24098 }
24099 // The same arm-without-clear route the 4:2:0 tails count: a skipped
24100 // leaf reads no coefficient, so the inherited chroma `tx_type` is
24101 // dropped unconsumed.
24102 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
24103 fctx.intrabc_chroma_tx.with(|c| c.set(None));
24104 (Grid::Zero(bw * bh), Grid::Zero(bw * bh), 4, 4)
24105 } else if skip {
24106 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
24107 if square {
24108 push_intra(
24109 1,
24110 px,
24111 py,
24112 4,
24113 uv_predict_mode,
24114 0,
24115 reach,
24116 &ZERO_RESIDUAL[..16],
24117 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
24118 None,
24119 smooth_neighbor_uv,
24120 fctx,
24121 );
24122 push_intra(
24123 2,
24124 px,
24125 py,
24126 4,
24127 uv_predict_mode,
24128 0,
24129 reach,
24130 &ZERO_RESIDUAL[..16],
24131 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
24132 None,
24133 smooth_neighbor_uv,
24134 fctx,
24135 );
24136 } else {
24137 push_intra_rect(
24138 1,
24139 px,
24140 py,
24141 bw,
24142 bh,
24143 uv_predict_mode,
24144 0,
24145 reach,
24146 &ZERO_RESIDUAL[..bw * bh],
24147 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
24148 None,
24149 smooth_neighbor_uv,
24150 fctx,
24151 );
24152 push_intra_rect(
24153 2,
24154 px,
24155 py,
24156 bw,
24157 bh,
24158 uv_predict_mode,
24159 0,
24160 reach,
24161 &ZERO_RESIDUAL[..bw * bh],
24162 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
24163 None,
24164 smooth_neighbor_uv,
24165 fctx,
24166 );
24167 }
24168 // The same arm-without-clear route the 4:2:0 tails count: a skipped
24169 // leaf reads no coefficient, so an armed intrabc slot is dropped.
24170 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
24171 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
24172 fctx.intrabc_chroma_tx.with(|c| c.set(None));
24173 }
24174 (Grid::Zero(bw * bh), Grid::Zero(bw * bh), 4, 4)
24175 } else if let Some(dv) = intrabc_dv {
24176 // Frame copy at the DV; the residual still reads the ordinary chroma
24177 // tables with the inherited luma `tx_type` (see the 4:2:0 tails).
24178 let mut ub = vec![0u16; bw * bh];
24179 mc::predict_with_filter(
24180 &u.data,
24181 u.width,
24182 u.true_width,
24183 u.true_height,
24184 mv_to_q4(px, dv.1, 0),
24185 mv_to_q4(py, dv.0, 0),
24186 bw,
24187 bh,
24188 mc::InterpFilterKind::Bilinear,
24189 &mut ub,
24190 fctx,
24191 );
24192 let mut vb = vec![0u16; bw * bh];
24193 mc::predict_with_filter(
24194 &v.data,
24195 v.width,
24196 v.true_width,
24197 v.true_height,
24198 mv_to_q4(px, dv.1, 0),
24199 mv_to_q4(py, dv.0, 0),
24200 bw,
24201 bh,
24202 mc::InterpFilterKind::Bilinear,
24203 &mut vb,
24204 fctx,
24205 );
24206 let around = neighbours.around_mi_rect(lmi, bw, bh);
24207 let pair = if square {
24208 set_palette_pred(ub, fctx);
24209 let ug = read_plane(
24210 dec,
24211 cdfs,
24212 TxbSet::Chroma4,
24213 scan4,
24214 1,
24215 around[1],
24216 DC_PRED,
24217 DC_PRED,
24218 0,
24219 reach,
24220 u,
24221 px,
24222 py,
24223 4,
24224 TX4,
24225 base_q_idx,
24226 None,
24227 None,
24228 None,
24229 smooth_neighbor_uv,
24230 fctx,
24231 )?;
24232 set_palette_pred(vb, fctx);
24233 let vg = read_plane(
24234 dec,
24235 cdfs,
24236 TxbSet::Chroma4,
24237 scan4,
24238 2,
24239 around[2],
24240 DC_PRED,
24241 DC_PRED,
24242 0,
24243 reach,
24244 v,
24245 px,
24246 py,
24247 4,
24248 TX4,
24249 base_q_idx,
24250 None,
24251 None,
24252 None,
24253 smooth_neighbor_uv,
24254 fctx,
24255 )?;
24256 (ug, vg, 4, 4)
24257 } else {
24258 // lane-av1-ibc444rect: the unskipped lossless chroma walk this
24259 // lane fixes (one rect unit -> per-4x4 Chroma4 units).
24260 if lossless(fctx) {
24261 hit!(INTRABC_RECT8_LOSSLESS_CHROMA_HITS);
24262 }
24263 if lossless(fctx) {
24264 // lane-av1-ibc444rect: at lossless `read_tx_size` forces
24265 // TX_4X4 on EVERY plane (`av1_get_tx_size`'s lossless
24266 // first line), so this rect leaf's chroma is (bw/4)*(bh/4)
24267 // TX_4X4 units at their own 4x4 origins -- not the single
24268 // `ChromaRect8x4` rect unit the non-lossless arm below reads
24269 // (`av1_get_max_uv_txsize(BLOCK_8X4)`'s rect, unreachable at
24270 // lossless). Same walk the leaf's own non-intrabc lossless
24271 // arm runs (lane-av1-llsub8's fix), plane-major per libaom
24272 // `decode_token_recon_block`, with the intra predictor
24273 // swapped for the CURRENT frame at the DV; CFL is never
24274 // allowed at lossless and no alpha rides an intrabc leaf.
24275 let mut out_u = Grid::Own(vec![0i32; bw * bh]);
24276 let mut out_v = Grid::Own(vec![0i32; bw * bh]);
24277 for (plane_idx, buf) in [(1usize, u), (2usize, v)] {
24278 for ur in 0..bh / 4usize {
24279 for uc in 0..bw / 4usize {
24280 let (umi_r, umi_c) = (lmi.0 + ur, lmi.1 + uc);
24281 let (upx, upy) = (px + uc * 4, py + ur * 4);
24282 let mut pb = vec![0u16; 16];
24283 mc::predict_with_filter(
24284 &buf.data,
24285 buf.width,
24286 buf.true_width,
24287 buf.true_height,
24288 mv_to_q4(upx, dv.1, 0),
24289 mv_to_q4(upy, dv.0, 0),
24290 4,
24291 4,
24292 mc::InterpFilterKind::Bilinear,
24293 &mut pb,
24294 fctx,
24295 );
24296 set_palette_pred(pb, fctx);
24297 let unit_around = neighbours.around_mi_rect((umi_r, umi_c), 4, 4);
24298 // lane-av1loss444kf: libaom asks
24299 // `has_top_right`/`has_bottom_left` with the
24300 // LEAF's bsize, this unit's `(col_off, row_off)`
24301 // and `tx_size` -- not as a standalone BLOCK_4X4
24302 // at the unit's own position. A 4x8 leaf's FIRST
24303 // unit has its bottom-left pixels inside the
24304 // block's own second row (already reconstructed),
24305 // which `has_bottom_left`'s
24306 // `row_off + count < plane_bh_unit` early-out
24307 // answers TRUE; the 4x4 table answered false, so
24308 // `PlaneBuf::edges` replicated the last left
24309 // sample and the unit predicted from a fabricated
24310 // edge (the 4:4:4 lossless key frame's 49-sample
24311 // chroma damage at (196,200)-(204,200)). The
24312 // 4:2:2 twin of this arm was fixed the same way
24313 // (lane-av1-422kf2); this is its 4:4:4 twin.
24314 let unit_reach = Reach::of_tu(bw, bh, uc * 4, ur * 4, 4, 4, reach);
24315 if !square
24316 && unit_reach != Reach::of(4, upx, upy, y.width, y.height, fctx)
24317 {
24318 hit!(SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS);
24319 }
24320 let grid = read_plane(
24321 dec,
24322 cdfs,
24323 TxbSet::Chroma4,
24324 scan4,
24325 plane_idx,
24326 unit_around[plane_idx],
24327 DC_PRED,
24328 DC_PRED,
24329 0,
24330 unit_reach,
24331 buf,
24332 upx,
24333 upy,
24334 4,
24335 TX4,
24336 base_q_idx,
24337 None,
24338 None,
24339 Some(3),
24340 smooth_neighbor_uv,
24341 fctx,
24342 )?;
24343 let cell = grid_unit_state(&grid, 4, 0, 0, 4, 4);
24344 if umi_r < neighbours.mi_rows {
24345 neighbours.left[umi_r][plane_idx] = cell;
24346 }
24347 if umi_c < neighbours.mi_cols {
24348 neighbours.above[umi_c][plane_idx] = cell;
24349 }
24350 let out = if plane_idx == 1 {
24351 &mut out_u
24352 } else {
24353 &mut out_v
24354 };
24355 if let Grid::Own(v) = out {
24356 for r in 0..4usize {
24357 v[(ur * 4 + r) * bw + uc * 4..][..4]
24358 .copy_from_slice(&grid[r * 4..][..4]);
24359 }
24360 }
24361 }
24362 }
24363 }
24364 (out_u, out_v, 4, 4)
24365 } else {
24366 let scan: &[u16] = if bw > bh { &SCAN_8X4 } else { &SCAN_4X8 };
24367 let default_tx = fctx
24368 .intrabc_chroma_tx
24369 .with(std::cell::Cell::get)
24370 .unwrap_or(TxType::DctDct);
24371 let mut out = (Grid::Zero(bw * bh), Grid::Zero(bw * bh), bw, bh);
24372 for (plane_idx, buf) in [(1usize, ub), (2usize, vb)] {
24373 let skip_ctx =
24374 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
24375 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, DC_PRED);
24376 let (levels, tx_type) = read_coeffs_rect(
24377 dec,
24378 &mut coding,
24379 scan,
24380 bw,
24381 bh,
24382 skip_ctx,
24383 dc_sign_ctx(around[plane_idx].2),
24384 default_tx,
24385 plane_idx,
24386 )?;
24387 let residual = dequant_and_inverse_typed_wh(
24388 &levels,
24389 bw,
24390 bh,
24391 crate::decode::bit_depth(fctx),
24392 block_q_idx(fctx),
24393 plane_q_delta(plane_idx, fctx).0,
24394 plane_q_delta(plane_idx, fctx).1,
24395 tx_type,
24396 block_iqmatrix(fctx, plane_idx, bw, bh, tx_type),
24397 );
24398 set_palette_pred(buf, fctx);
24399 push_intra_rect(
24400 plane_idx,
24401 px,
24402 py,
24403 bw,
24404 bh,
24405 DC_PRED,
24406 0,
24407 reach,
24408 &residual,
24409 None,
24410 None,
24411 smooth_neighbor_uv,
24412 fctx,
24413 );
24414 if plane_idx == 1 {
24415 out.0 = levels;
24416 } else {
24417 out.1 = levels;
24418 }
24419 }
24420 out
24421 }
24422 };
24423 fctx.intrabc_chroma_tx.with(|c| c.set(None));
24424 pair
24425 } else {
24426 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
24427 let around = neighbours.around_mi_rect(lmi, bw, bh);
24428 if square {
24429 let ug = read_plane(
24430 dec,
24431 cdfs,
24432 TxbSet::Chroma4,
24433 scan4,
24434 1,
24435 around[1],
24436 uv_mode,
24437 uv_predict_mode,
24438 0,
24439 reach,
24440 u,
24441 px,
24442 py,
24443 4,
24444 TX4,
24445 base_q_idx,
24446 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
24447 None,
24448 None,
24449 smooth_neighbor_uv,
24450 fctx,
24451 )?;
24452 let vg = read_plane(
24453 dec,
24454 cdfs,
24455 TxbSet::Chroma4,
24456 scan4,
24457 2,
24458 around[2],
24459 uv_mode,
24460 uv_predict_mode,
24461 0,
24462 reach,
24463 v,
24464 px,
24465 py,
24466 4,
24467 TX4,
24468 base_q_idx,
24469 alpha.zip(ac).map(|((_

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