forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

decode.rs24680 lines, 2.3 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// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
2279// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
2280// shapes whose `use_filter_intra` symbol had no CDF class before this round.
2281// A gate asserting the wider counter would be satisfied by a 32x16 strip and
2282// prove nothing about the new shapes.
2283thread_local! {
2284 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
2285 const { std::cell::Cell::new(0) };
2286}
2287
2288/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
2289#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2290pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
2291 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
2292}
2293
2294// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
2295// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
2296// counter would be satisfied by a 16x8 strip and prove nothing here.
2297thread_local! {
2298 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
2299 const { std::cell::Cell::new(0) };
2300}
2301
2302/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
2303#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2304pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
2305 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
2306}
2307
2308// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
2309// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
2310// call on the current thread -- the same before/after counter pattern as
2311// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
2312// `eob_pt`/1D-neighbour context path rather than every block coincidentally
2313// landing on `DCT_DCT`.
2314thread_local! {
2315 static TX_CLASS1_HITS: std::cell::Cell<usize> =
2316 const { std::cell::Cell::new(0) };
2317}
2318
2319// How many `uv_mode` reads resolved to a directional chroma mode (neither
2320// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
2321// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
2322// actually exercised chroma's own directional predictor.
2323thread_local! {
2324 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
2325 const { std::cell::Cell::new(0) };
2326}
2327
2328/// Current value of [`DIRECTIONAL_UV_HITS`].
2329#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2330pub(crate) fn directional_uv_hits() -> usize {
2331 DIRECTIONAL_UV_HITS.with(|c| c.get())
2332}
2333
2334// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
2335// something other than [`ANGLE_DELTA_ZERO`], across every call in the
2336// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
2337// proving a stream actually exercised a nonzero angle delta.
2338thread_local! {
2339 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
2340 const { std::cell::Cell::new(0) };
2341}
2342
2343// How many [`read_single_ref`] reads resolved to a reference other than
2344// `LAST_FRAME`, across every call on the current thread -- the same before/after
2345// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
2346// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
2347// only other supported one so far) rather than every block coincidentally
2348// resolving `LAST_FRAME`.
2349thread_local! {
2350 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
2351 const { std::cell::Cell::new(0) };
2352}
2353
2354/// Current value of [`NON_LAST_REF_HITS`].
2355#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2356pub(crate) fn non_last_ref_hits() -> usize {
2357 NON_LAST_REF_HITS.with(|c| c.get())
2358}
2359
2360// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
2361// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
2362// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
2363// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
2364// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
2365// `GOLDEN_FRAME` draw it did not ask for.
2366thread_local! {
2367 static LAST2_HITS: std::cell::Cell<usize> =
2368 const { std::cell::Cell::new(0) };
2369}
2370thread_local! {
2371 static LAST3_HITS: std::cell::Cell<usize> =
2372 const { std::cell::Cell::new(0) };
2373}
2374thread_local! {
2375 static GOLDEN_HITS: std::cell::Cell<usize> =
2376 const { std::cell::Cell::new(0) };
2377}
2378thread_local! {
2379 static BWDREF_HITS: std::cell::Cell<usize> =
2380 const { std::cell::Cell::new(0) };
2381}
2382thread_local! {
2383 static ALTREF2_HITS: std::cell::Cell<usize> =
2384 const { std::cell::Cell::new(0) };
2385}
2386thread_local! {
2387 static ALTREF_HITS: std::cell::Cell<usize> =
2388 const { std::cell::Cell::new(0) };
2389}
2390
2391// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
2392// -- proves a `reference_select` stream actually reached a block that picked
2393// compound, not just that the header bit was set. Every such block is
2394// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
2395// so this only ever counts attempted reads, never a completed decode.
2396thread_local! {
2397 static COMP_MODE_HITS: std::cell::Cell<usize> =
2398 const { std::cell::Cell::new(0) };
2399}
2400
2401/// Current value of [`COMP_MODE_HITS`].
2402#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2403pub(crate) fn comp_mode_hits() -> usize {
2404 COMP_MODE_HITS.with(|c| c.get())
2405}
2406
2407// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
2408// use for, across every call on the current thread -- the same before/after
2409// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
2410// exercised palette reconstruction rather than only reading and refusing the
2411// `palette_y_mode` symbol.
2412thread_local! {
2413 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2414}
2415
2416/// Current value of [`PALETTE_HITS`].
2417#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2418pub(crate) fn palette_hits() -> usize {
2419 PALETTE_HITS.with(|c| c.get())
2420}
2421
2422// lane-tiles r12: of those, how many sat at their own TILE's left column --
2423// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
2424// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
2425// palette gate that never hits one proves nothing about the tile guard.
2426thread_local! {
2427 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2428}
2429
2430/// Current value of [`PALETTE_TILE_LEFT_HITS`].
2431#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2432pub(crate) fn palette_tile_left_hits() -> usize {
2433 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
2434}
2435
2436// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
2437// palette use -- proves a stream actually reconstructed UV palette pixels,
2438// not just read and refused the `palette_uv_mode` symbol.
2439thread_local! {
2440 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2441}
2442
2443/// Current value of [`PALETTE_UV_HITS`].
2444#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2445pub(crate) fn palette_uv_hits() -> usize {
2446 PALETTE_UV_HITS.with(|c| c.get())
2447}
2448
2449// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
2450// decoded a real palette-Y use -- proves the rect strip's own palette syntax
2451// (not just the square path's) actually fired.
2452thread_local! {
2453 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2454}
2455
2456/// Current value of [`PALETTE_RECT_HITS`].
2457#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2458pub(crate) fn palette_rect_hits() -> usize {
2459 PALETTE_RECT_HITS.with(|c| c.get())
2460}
2461
2462// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
2463// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
2464// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
2465// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
2466// RD, almost always refused-on-use because the block doesn't end up USING a
2467// palette -- see r5's report). This is the site the removed refusal
2468// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
2469// fired here whether or not the block picked a palette, so this is the
2470// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
2471// never observes.
2472thread_local! {
2473 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2474}
2475
2476/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
2477#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2478pub(crate) fn rect_screen_content_hits() -> usize {
2479 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
2480}
2481
2482// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
2483// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
2484// windowing actually ran, not just that the whole-block path stayed exact.
2485// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
2486// first actually incremented in r7, when the refusal it guarded was lifted.
2487thread_local! {
2488 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2489}
2490
2491thread_local! {
2492 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
2493 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
2494 /// (16x8/8x16), the two shapes the lifted refusals named.
2495 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2496}
2497
2498/// Current value of [`RECT4_PALETTE_HITS`].
2499#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2500pub(crate) fn rect4_palette_hits() -> usize {
2501 RECT4_PALETTE_HITS.with(|c| c.get())
2502}
2503
2504/// Current value of [`PALETTE_SPLIT_TX_HITS`].
2505#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2506pub(crate) fn palette_split_tx_hits() -> usize {
2507 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
2508}
2509
2510thread_local! {
2511 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
2512 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
2513 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
2514 /// `--min-partition-size=8` puts them on this leaf path.
2515 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2516}
2517
2518/// Current value of [`PALETTE_LEAF8_HITS`].
2519#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2520pub(crate) fn palette_leaf8_hits() -> usize {
2521 PALETTE_LEAF8_HITS.with(|c| c.get())
2522}
2523
2524/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
2525#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2526pub(crate) fn reset_palette_leaf8_hits() {
2527 PALETTE_LEAF8_HITS.with(|c| c.set(0));
2528}
2529
2530thread_local! {
2531 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
2532 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
2533 /// block that also carries a real, corner-cropped luma transform.
2534 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2535}
2536
2537/// Current value of [`PALETTE_SB_STRIP_HITS`].
2538#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2539pub(crate) fn palette_sb_strip_hits() -> usize {
2540 PALETTE_SB_STRIP_HITS.with(|c| c.get())
2541}
2542
2543/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
2544#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2545pub(crate) fn reset_palette_sb_strip_hits() {
2546 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
2547}
2548
2549// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
2550// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
2551// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
2552// capability rather than the key frame's, which every screen stream also
2553// carries.
2554thread_local! {
2555 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2556 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2557}
2558
2559// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
2560// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
2561// shared counter too, so only this one proves a gate really reached the leaf
2562// where the refusal used to sit.
2563thread_local! {
2564 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
2565 const { std::cell::Cell::new((0, 0)) };
2566}
2567
2568/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
2569pub(crate) fn inter8_palette_hits() -> (usize, usize) {
2570 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
2571}
2572
2573/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
2574pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
2575 (
2576 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
2577 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
2578 )
2579}
2580
2581// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
2582// and which are therefore predicted one transform unit at a time (a skipped
2583// block codes no coefficients, so nothing else in the stream witnesses this
2584// path -- only the pixels do).
2585thread_local! {
2586 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2587}
2588
2589/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
2590pub fn skip_split_tx_hits() -> usize {
2591 SKIP_SPLIT_TX_HITS.with(|c| c.get())
2592}
2593
2594// lane-svt1: SKIPPED square blocks carrying a palette/intrabc prediction whose
2595// `tx_depth` split the luma transform -- the arm that predicted DC off the
2596// block edges before the fix. Like [`SKIP_SPLIT_TX_HITS`] only the pixels
2597// witness this path, so a gate that wants it needs the counter.
2598thread_local! {
2599 static SKIP_SPLIT_TX_OVERRIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2600}
2601
2602/// Current value of [`SKIP_SPLIT_TX_OVERRIDE_HITS`] (blocks).
2603pub fn skip_split_tx_override_hits() -> usize {
2604 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.get())
2605}
2606
2607/// Zeroes [`SKIP_SPLIT_TX_OVERRIDE_HITS`] before a gate's own decode attempt.
2608pub fn reset_skip_split_tx_override_hits() {
2609 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.set(0));
2610}
2611
2612// lane-svtinter: palette colour-index maps whose block is cut by the frame's
2613// bottom/right mi edge, so spec 5.11.50's `onscreenWidth`/`onscreenHeight`
2614// really are smaller than the block and FEWER symbols are read than the
2615// block has cells (class map-read-past-frame-edge).
2616thread_local! {
2617 static PALETTE_ONSCREEN_CUT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2618}
2619
2620/// Current value of [`PALETTE_ONSCREEN_CUT_HITS`] (colour-index maps).
2621pub fn palette_onscreen_cut_hits() -> usize {
2622 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.get())
2623}
2624
2625/// Zeroes [`PALETTE_ONSCREEN_CUT_HITS`] before a gate's own decode attempt.
2626pub fn reset_palette_onscreen_cut_hits() {
2627 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.set(0));
2628}
2629
2630/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
2631pub fn reset_skip_split_tx_hits() {
2632 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
2633}
2634
2635// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
2636// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
2637// the gate's proof that the lifted path actually ran, per size.
2638thread_local! {
2639 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
2640 const { std::cell::Cell::new([0; 4]) };
2641}
2642
2643/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
2644#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2645pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
2646 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2647}
2648
2649/// A just-decoded palette-Y block's own predicted pixels
2650/// (`side*side`, row-major, `colors[map[i]]`), consumed by
2651/// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
2652/// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
2653/// per-block override through `read_plane`'s two dozen call sites is the
2654/// alternative this avoids). Always empty again once that call consumes
2655/// it (`.take()`), so a non-palette block's own `reconstruct` call never
2656/// sees stale state.
2657
2658/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
2659/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
2660/// site whose reconstruct never runs would be picked up by the NEXT block's
2661/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
2662/// lane-lossless2: one transform unit's window on a block-sized palette
2663/// prediction buffer. A unit reads its prediction at ITS OWN stride, so
2664/// handing it the whole-block buffer makes every unit reconstruct the block's
2665/// top-left corner (the luma split-transform paths already window; the chroma
2666/// ones did not, which is invisible until a lossless frame codes a palette
2667/// block as 4x4 chroma units).
2668fn palette_window(
2669 buf: &[u16],
2670 stride: usize,
2671 ox: usize,
2672 oy: usize,
2673 w: usize,
2674 h: usize,
2675) -> Vec<u16> {
2676 (0..h)
2677 .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied())
2678 .collect()
2679}
2680
2681/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
2682#[track_caller]
2683fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
2684 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2685 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
2686 eprintln!(
2687 "PALSET len={} stale={stale} at {}",
2688 buf.len(),
2689 std::panic::Location::caller()
2690 );
2691 }
2692 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
2693}
2694
2695#[track_caller]
2696fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
2697 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
2698 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2699 eprintln!(
2700 "PALTAKE len={:?} at {}",
2701 got.as_ref().map(Vec::len),
2702 std::panic::Location::caller()
2703 );
2704 }
2705 got
2706}
2707
2708/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
2709/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
2710/// pixels, because at parse time this block's own luma is still queued.
2711#[derive(Clone, Copy, Debug)]
2712pub(crate) struct CflSrc {
2713 px: usize,
2714 py: usize,
2715 bw: usize,
2716 bh: usize,
2717}
2718
2719fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
2720 CflSrc {
2721 px,
2722 py,
2723 bw: side,
2724 bh: side,
2725 }
2726}
2727
2728fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
2729 CflSrc { px, py, bw, bh }
2730}
2731
2732/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
2733/// instead of executed. Each variant is the resolved argument tuple of the
2734/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
2735/// order performs exactly the same writes in exactly the same order --
2736/// entropy parsing no longer touches the frame's own planes (except the two
2737/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
2738/// the replay on a superblock-row wavefront worker.
2739/// The dequantization + inverse transform of one transform unit, kept as its
2740/// INPUTS so that a recorded write carries the work instead of its result
2741/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
2742/// recon worker, not on the parsing thread. `stride == 0` means the dense
2743/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
2744/// `reconstruct_mc_rect` reads both of its buffers at.
2745#[derive(Clone, Copy)]
2746pub(crate) struct TxParams {
2747 pub(crate) w: usize,
2748 pub(crate) h: usize,
2749 pub(crate) bit_depth: u8,
2750 pub(crate) q_idx: i32,
2751 pub(crate) dc_delta: i32,
2752 pub(crate) ac_delta: i32,
2753 pub(crate) tx_type: TxType,
2754 /// lane-av1-qmatrix: this unit's inverse quantisation matrix, selected
2755 /// on the parse thread by [`block_iqmatrix`] and captured here so the
2756 /// recon worker scales identically without touching frame state.
2757 pub(crate) qm: Option<crate::qm::Iqm>,
2758 pub(crate) stride: usize,
2759 /// lane-lossless: this transform unit belongs to a lossless BLOCK (its
2760 /// segment's `xd->lossless[segment_id]` bit), so the residual comes off
2761 /// the 4x4 Walsh-Hadamard
2762 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
2763 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
2764 pub(crate) lossless: bool,
2765}
2766
2767/// lane-av1mixloss: Walsh-Hadamard transform units actually reconstructed.
2768/// The mixed-lossless witness's proof the per-segment lossless path really
2769/// ran on a frame that is NOT `CodedLossless`. Atomic because the wavefront
2770/// workers run this on their own threads.
2771static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2772
2773/// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after
2774/// delta around one decode.
2775#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2776pub(crate) fn lossless_wht_units() -> usize {
2777 LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
2778}
2779
2780impl TxParams {
2781 /// The one copy of the produce-the-residual code: the inline path calls it
2782 /// on the parse thread, the wavefront worker calls it on its own, so both
2783 /// are the same function on the same inputs and byte-identical.
2784 fn run(self, grid: &[i32]) -> Vec<i32> {
2785 let residual = if self.lossless {
2786 LOSSLESS_WHT_UNITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2787 debug_assert_eq!((self.w, self.h), (4, 4));
2788 debug_assert_eq!(self.tx_type, TxType::DctDct);
2789 crate::transform::dequant_and_inverse_wht4x4(
2790 grid,
2791 self.bit_depth,
2792 self.q_idx,
2793 self.dc_delta,
2794 self.ac_delta,
2795 )
2796 } else {
2797 dequant_and_inverse_typed_wh(
2798 grid,
2799 self.w,
2800 self.h,
2801 self.bit_depth,
2802 self.q_idx,
2803 self.dc_delta,
2804 self.ac_delta,
2805 self.tx_type,
2806 self.qm,
2807 )
2808 };
2809 // An all-zero grid transforms to the empty marker, and a strided copy
2810 // of zeros is still zeros: the marker passes straight through.
2811 if residual.is_empty() {
2812 return residual;
2813 }
2814 if self.stride == 0 {
2815 return residual;
2816 }
2817 // lane-av1-422sub8rect: `h` rows of `stride` -- a rect unit whose
2818 // height exceeds its (narrow) prediction stride needs the full
2819 // stride * h; every square caller has h == stride and is unchanged.
2820 let mut strided = vec![0i32; self.stride * self.h];
2821 for row in 0..self.h {
2822 strided[row * self.stride..][..self.w]
2823 .copy_from_slice(&residual[row * self.w..][..self.w]);
2824 }
2825 strided
2826 }
2827}
2828
2829/// A recorded write's residual: already transformed, or the coefficients and
2830/// [`TxParams`] the worker transforms itself.
2831pub(crate) enum Residual {
2832 /// An already-transformed residual in the arena, `(offset, len)`; a zero
2833 /// `len` is the all-zero marker [`dense_residual`] expands.
2834 Done(u32, u32),
2835 /// The coefficients live in the pushing tile's arena
2836 /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
2837 /// len)` in it.
2838 Coeffs(TxParams, u32, u32),
2839}
2840
2841impl Residual {
2842 /// The record for a transform unit whose coefficient grid is all zero:
2843 /// the empty marker, so neither the grid nor the residual is cloned and
2844 /// the worker never runs the transform (60% of the 4K segment's units).
2845 fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2846 if is_zero_grid(grid) {
2847 return Self::Done(0, 0);
2848 }
2849 Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
2850 }
2851
2852 /// A residual the parse thread already transformed, kept in the arena
2853 /// instead of its own `Vec`.
2854 fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2855 // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself,
2856 // which is exactly the all-zero marker -- one pointer compare instead
2857 // of copying up to 64 KB of zeros into the arena per block.
2858 if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) {
2859 return Self::Done(0, 0);
2860 }
2861 Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
2862 }
2863
2864 /// The residual to reconstruct with; `scratch` is where a transform run
2865 /// on this thread lands, so the caller owns that buffer.
2866 fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
2867 match self {
2868 Self::Done(off, len) => &arena[off as usize..][..len as usize],
2869 Self::Coeffs(p, off, len) => {
2870 *scratch = p.run(&arena[off as usize..][..len as usize]);
2871 scratch
2872 }
2873 }
2874 }
2875}
2876
2877/// Appends to the tile's coefficient arena, returning the offset the record
2878/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
2879fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
2880 fctx.coeff_arena.with(|a| {
2881 let mut a = a.borrow_mut();
2882 let off = a.len();
2883 a.extend_from_slice(v);
2884 off as u32
2885 })
2886}
2887
2888/// [`push_coeffs`] for a recorded prediction.
2889fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
2890 fctx.pred_arena.with(|a| {
2891 let mut a = a.borrow_mut();
2892 let off = a.len();
2893 a.extend_from_slice(v);
2894 off as u32
2895 })
2896}
2897
2898/// An all-zero residual, for the transform units that code no coefficient:
2899/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
2900/// and the reconstruction loops below read this instead of a per-unit
2901/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
2902/// (a 128-wide inter block's prediction stride).
2903pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
2904
2905/// lane-blockscratch: one plane's coefficient levels as the block-tail
2906/// neighbour writes want them. A plane that coded nothing (a skipped block, a
2907/// strip with no chroma, luma under a var-tx split whose units already wrote
2908/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
2909/// zeroing up to 64 KB of its own per block.
2910#[derive(Clone)]
2911enum Grid {
2912 Zero(usize),
2913 Own(Vec<i32>),
2914}
2915
2916/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
2917/// unit that writes into it. Only a block wider or taller than 64 px codes its
2918/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
2919/// collectors per block and then drop them untouched.
2920fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
2921 if v.is_empty() {
2922 *v = vec![0i32; n];
2923 }
2924 v
2925}
2926
2927impl std::ops::Deref for Grid {
2928 type Target = [i32];
2929 fn deref(&self) -> &[i32] {
2930 match self {
2931 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
2932 Grid::Own(v) => v,
2933 }
2934 }
2935}
2936
2937/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
2938/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
2939/// transform units that code no coefficient without the scan (lane-coefgrid).
2940pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
2941 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
2942}
2943
2944/// `residual`, or `n` zeros when it is the empty all-zero marker.
2945fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
2946 if residual.is_empty() {
2947 &ZERO_RESIDUAL[..n]
2948 } else {
2949 residual
2950 }
2951}
2952
2953/// Where a recorded motion-compensated write reads its prediction from.
2954///
2955/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
2956/// the parse thread's single biggest reconstruction cost, so at
2957/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
2958/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
2959/// runs it into its own three-plane slot, and every transform unit of that
2960/// block then reads its window out of that slot ([`Pred::Cur`]).
2961#[derive(Clone, Copy)]
2962pub(crate) enum Pred<'a> {
2963 /// A prediction the parse thread already built, at its own stride
2964 /// (`stride == 0` means "the reader's own `stride` argument").
2965 Inline(&'a [u16], usize),
2966 /// The current block's deferred prediction: plane, its stride, and this
2967 /// unit's offset into it.
2968 Cur {
2969 plane: usize,
2970 stride: usize,
2971 off: usize,
2972 },
2973}
2974
2975impl<'a> Pred<'a> {
2976 /// The same prediction read at an explicit stride.
2977 fn view(self, stride: usize) -> Self {
2978 match self {
2979 Self::Inline(b, _) => Self::Inline(b, stride),
2980 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
2981 }
2982 }
2983 /// The materialised buffer and the stride to read it at (`stride` is the
2984 /// reader's own when this prediction was built dense); `None` for a
2985 /// deferred prediction, which only a recorded op can carry.
2986 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
2987 match self {
2988 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
2989 Self::Cur { .. } => None,
2990 }
2991 }
2992 /// This prediction's window starting `n` samples in.
2993 fn offset(self, n: usize) -> Self {
2994 match self {
2995 Self::Inline(b, s) => Self::Inline(&b[n..], s),
2996 Self::Cur { plane, stride, off } => Self::Cur {
2997 plane,
2998 stride,
2999 off: off + n,
3000 },
3001 }
3002 }
3003}
3004
3005/// [`Pred`], resolved into what a recorded op carries.
3006pub(crate) enum PredSrc {
3007 /// A prediction window in the tile's prediction arena, `(offset, len)`.
3008 Owned(u32, u32),
3009 /// A window of the block prediction: its plane, its offset, and the
3010 /// stride it is read at -- which is the block's, not necessarily the
3011 /// op's (a transform unit's residual stays dense, so the worker takes
3012 /// its window out of the block prediction itself).
3013 Cur {
3014 plane: usize,
3015 off: usize,
3016 src: usize,
3017 },
3018}
3019
3020/// One block's whole-block prediction build, deferred to a recon worker.
3021///
3022/// The closure borrows the tile's reference pictures and its own frame-level
3023/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
3024/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
3025/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
3026pub(crate) struct PredBuild(
3027 Box<
3028 dyn FnOnce(
3029 &mut PlaneBuf<'static>,
3030 &mut PlaneBuf<'static>,
3031 &mut PlaneBuf<'static>,
3032 &crate::decode::FrameCtx,
3033 // lane-blockmem: the previous block's three prediction buffers,
3034 // refilled in place -- the build used to return three fresh
3035 // `Vec`s per block and drop these.
3036 &mut [Vec<u16>; 3],
3037 ),
3038 >,
3039);
3040
3041// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
3042// pictures and frame tables, and the closure runs on exactly one worker.
3043#[allow(unsafe_code)]
3044unsafe impl Send for PredBuild {}
3045
3046/// `true` when this tile's writes are recorded for the wavefront instead of
3047/// performed at the push site, i.e. when a prediction may be deferred.
3048fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
3049 fctx.recon_planes.with(std::cell::Cell::get).is_none()
3050}
3051
3052/// The previous block's prediction buffer, cleared and zero-filled to `n`
3053/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
3054/// without the per-block allocation and free.
3055fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
3056 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
3057 // than resized element by element -- which is every block on the inline
3058 // path, where there is no previous buffer to reuse.
3059 if v.capacity() < n {
3060 return vec![0u16; n];
3061 }
3062 v.clear();
3063 v.resize(n, 0);
3064 v
3065}
3066
3067/// Records one block's prediction build for the worker that reconstructs it.
3068#[allow(unsafe_code)]
3069fn push_pred<'a>(
3070 fctx: &crate::decode::FrameCtx,
3071 f: impl FnOnce(
3072 &mut PlaneBuf<'static>,
3073 &mut PlaneBuf<'static>,
3074 &mut PlaneBuf<'static>,
3075 &crate::decode::FrameCtx,
3076 &mut [Vec<u16>; 3],
3077 ) + 'a,
3078) {
3079 type Dyn<'x> = dyn FnOnce(
3080 &mut PlaneBuf<'static>,
3081 &mut PlaneBuf<'static>,
3082 &mut PlaneBuf<'static>,
3083 &crate::decode::FrameCtx,
3084 &mut [Vec<u16>; 3],
3085 ) + 'x;
3086 let boxed: Box<Dyn<'a>> = Box::new(f);
3087 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
3088 // before the borrows the closure holds go out of scope.
3089 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
3090 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
3091}
3092
3093/// One superblock's recorded writes plus the two arenas they index -- the
3094/// unit a wavefront worker takes off the queue (lane-recoparse).
3095pub(crate) struct ReconJob {
3096 ops: Vec<ReconOp>,
3097 coeffs: Vec<i32>,
3098 preds: Vec<u16>,
3099}
3100
3101pub(crate) enum ReconOp {
3102 /// lane-wave4: build this block's prediction into the worker's slot.
3103 Pred(PredBuild),
3104 Intra {
3105 plane: usize,
3106 x: usize,
3107 y: usize,
3108 bw: usize,
3109 bh: usize,
3110 /// `true` when the parse site called `reconstruct_rect` (whose
3111 /// `edges_rect` differs from `edges` even at `bw == bh`).
3112 rect: bool,
3113 mode: usize,
3114 angle_delta: i32,
3115 reach: Reach,
3116 residual: Residual,
3117 cfl: Option<(i32, CflSrc)>,
3118 filter_intra: Option<usize>,
3119 smooth_neighbor: bool,
3120 /// The palette/intrabc prediction override, taken off
3121 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
3122 /// from that slot by the replay.
3123 pred: Option<Vec<u16>>,
3124 },
3125 Mc {
3126 plane: usize,
3127 x: usize,
3128 y: usize,
3129 stride: usize,
3130 w: usize,
3131 h: usize,
3132 prediction: PredSrc,
3133 residual: Residual,
3134 },
3135}
3136
3137/// The three planes of the tile currently being decoded, as raw pointers.
3138///
3139/// corner-cut: at one reconstruction thread a recorded write must cost
3140/// nothing -- deferring it to the end of the superblock is +1.2%
3141/// instructions and +4.5% wall on 4K, because the residual is written at
3142/// parse and read back cache-cold at replay. So the recorded op is performed
3143/// at the push site instead, through the pointers the tile decoder registers
3144/// once ([`ReconInline`]), which is the same thread, the same order and the
3145/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
3146/// stack still holds aliases them, exactly the [`crate::par::Shared`]
3147/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
3148/// threading the three planes down every `read_plane`/`read_inter_plane`
3149/// call site (~40) so the push site owns the borrow it writes through.
3150#[derive(Clone, Copy)]
3151pub(crate) struct ReconPlanes(
3152 *mut PlaneBuf<'static>,
3153 *mut PlaneBuf<'static>,
3154 *mut PlaneBuf<'static>,
3155);
3156
3157// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
3158// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
3159// value travelling is `None`; the pointers never leave the tile decoder's
3160// own thread.
3161#[allow(unsafe_code)]
3162unsafe impl Send for ReconPlanes {}
3163// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
3164// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
3165// contract, one superblock per band instead of one row band.
3166#[allow(unsafe_code)]
3167unsafe impl Sync for ReconPlanes {}
3168
3169/// Registers the tile's planes for inline reconstruction and unregisters them
3170/// on every exit from the tile decoder, including the `?` ones -- a stale
3171/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
3172/// tile.
3173pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
3174
3175#[allow(unsafe_code)]
3176impl<'a> ReconInline<'a> {
3177 /// Installs the guard for this tile when reconstruction is inline
3178 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
3179 /// to the queue instead, for the wavefront workers to replay.
3180 fn install(
3181 fctx: &'a crate::decode::FrameCtx,
3182 y: &mut PlaneBuf<'static>,
3183 u: &mut PlaneBuf<'static>,
3184 v: &mut PlaneBuf<'static>,
3185 ) -> Option<Self> {
3186 if crate::par::recon_threads() != 1 {
3187 return None;
3188 }
3189 // SAFETY: the planes are locals of the tile decoder and outlive the
3190 // guard, which is dropped on every exit from it (including `?`); see
3191 // [`ReconPlanes`] for the aliasing trade-off.
3192 let planes = ReconPlanes(
3193 std::ptr::from_mut(y),
3194 std::ptr::from_mut(u),
3195 std::ptr::from_mut(v),
3196 );
3197 fctx.recon_planes.with(|c| c.set(Some(planes)));
3198 Some(Self(fctx))
3199 }
3200}
3201
3202impl Drop for ReconInline<'_> {
3203 fn drop(&mut self) {
3204 self.0.recon_planes.with(|c| c.set(None));
3205 }
3206}
3207
3208#[allow(unsafe_code)]
3209fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
3210 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
3211 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
3212 // the parse site would have performed itself before lane-wave1.
3213 // The inline path never records coefficients (the transform runs at
3214 // the push site), so the arena is not read here.
3215 unsafe {
3216 exec_op(
3217 op,
3218 &mut *y,
3219 &mut *u,
3220 &mut *v,
3221 &mut Default::default(),
3222 &[],
3223 &[],
3224 fctx,
3225 )
3226 };
3227 return;
3228 }
3229 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
3230}
3231
3232/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
3233/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
3234///
3235/// The parser keeps parsing and never touches the planes; each superblock's
3236/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
3237/// `(row, column)` inside the tile (128x128 superblocks are one job for all
3238/// four of their 64x64 visits, since a 128 block writes across quadrants).
3239/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
3240/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
3241/// every pixel an intra predictor can read (its edges reach one block right
3242/// along the row above and one block down the column to the left, both
3243/// inside those two neighbours) and every CfL AC read (this block's own
3244/// luma, written by this same job). Jobs are handed out in raster order, so
3245/// the oldest outstanding one always has its dependencies met: no deadlock.
3246///
3247/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
3248/// `thread_local!` and miss every worker, which is why the default is 1.
3249pub(crate) struct WaveState {
3250 q: std::sync::Mutex<WaveQueue>,
3251 cv: std::sync::Condvar,
3252 planes: ReconPlanes,
3253 /// The [`FrameCtx`] fields reconstruction reads (`sample_max` is
3254 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
3255 bit_depth: u8,
3256 enable_edge_filter: bool,
3257 /// lane-av1wavefront: the sequence's chroma subsampling. The replay-side
3258 /// readers -- the deferred chroma builds' `mv_to_q4(.., ss_x(fctx))`
3259 /// positions and `exec_intra`'s CfL AC signal -- must see the FRAME's
3260 /// pair, not [`FrameCtx::new`]'s 4:2:0 default: on a 4:4:4 stream the
3261 /// default halved every worker's chroma reference position and lost the
3262 /// chroma planes (the 444_sb128rect witness, U 17504 / V 3 at PREFILT on
3263 /// frame 1) while every 4:2:0 gate stream stayed accidentally exact.
3264 subsampling: (u8, u8),
3265 last_col: usize,
3266}
3267
3268struct WaveQueue {
3269 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
3270 /// row's front job can ever be runnable -- a job waits on its own left
3271 /// neighbour -- so a worker takes the lowest row whose front job's
3272 /// dependencies are met. Popping the raster-oldest job instead (what
3273 /// this replaced) put every worker on the SAME row, where the wavefront
3274 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
3275 rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
3276 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
3277 /// walking it.
3278 queued: usize,
3279 /// Per superblock row, the last column reconstructed (-1 = none yet).
3280 done: Vec<isize>,
3281 /// Per superblock row, the last column PARSED (submitted, whether or not
3282 /// it recorded any write) and the last column actually pushed as a job
3283 /// (-1 = none). A row is fully reconstructed once it has been parsed to
3284 /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
3285 /// reads that to release the row's filters (see [`wave_rows_complete`]).
3286 last_sub: Vec<isize>,
3287 last_push: Vec<isize>,
3288 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
3289 active: usize,
3290 closed: bool,
3291 /// lane-sballoc: the three per-superblock buffers a finished job hands
3292 /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no
3293 /// first-touch page faults) instead of the `Vec::with_capacity` it used
3294 /// to make per superblock -- 3 allocations and 3 frees per superblock,
3295 /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives
3296 /// inside the queue's own mutex, which both sides already take.
3297 free: Vec<JobBufs>,
3298 free_cap: usize,
3299}
3300
3301/// One recycled set of [`ReconJob`] buffers (lane-sballoc).
3302type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>);
3303
3304impl WaveQueue {
3305 /// The lowest-row queued job whose wavefront dependencies are satisfied,
3306 /// or `None` (with the blocking condition counted when instrumented).
3307 fn take_runnable(&mut self, last_col: usize, stats: bool) -> Option<(usize, usize, ReconJob)> {
3308 let mut blocked: Option<bool> = None;
3309 for r in 0..self.rows.len() {
3310 let Some(front) = self.rows[r].front() else {
3311 continue;
3312 };
3313 let c = front.0;
3314 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
3315 let left = c == 0 || self.done[r] >= c as isize - 1;
3316 if above && left {
3317 let (c, job) = self.rows[r].pop_front().expect("front checked above");
3318 self.queued -= 1;
3319 return Some((r, c, job));
3320 }
3321 if blocked.is_none() {
3322 blocked = Some(above);
3323 }
3324 }
3325 if stats {
3326 match blocked {
3327 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
3328 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
3329 None => 0,
3330 };
3331 }
3332 None
3333 }
3334}
3335
3336/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
3337/// worker's time goes (busy replaying, waiting for a dependency, idle on an
3338/// empty queue), how far ahead the parse thread is, and how often the two
3339/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
3340/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
3341/// whole run.
3342const WS_SLOTS: usize = 16;
3343use std::sync::atomic::AtomicU64;
3344use std::sync::atomic::Ordering::Relaxed;
3345static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3346static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3347static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3348static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3349static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
3350static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
3351/// Parse-thread time between two submits, i.e. everything parse still does
3352/// itself (symbol decode plus the predictions not deferred).
3353static WS_PARSE: AtomicU64 = AtomicU64::new(0);
3354/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
3355/// (the intrabc/interintra reads) and at the tile's end.
3356static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
3357static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
3358static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
3359static WS_TILES: AtomicU64 = AtomicU64::new(0);
3360
3361fn wave_stats() -> bool {
3362 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
3363 match ON.load(Relaxed) {
3364 0 => {
3365 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
3366 .map(|v| v.trim() == "1")
3367 .unwrap_or(false);
3368 ON.store(1 + u8::from(on), Relaxed);
3369 on
3370 }
3371 n => n == 2,
3372 }
3373}
3374
3375fn wave_stats_dump() {
3376 let ms = |n: u64| n as f64 / 1e6;
3377 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
3378 for i in 0..WS_SLOTS {
3379 let jobs = WS_JOBS[i].load(Relaxed);
3380 if jobs == 0 {
3381 continue;
3382 }
3383 s += &format!(
3384 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
3385 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
3386 ms(WS_BUSY[i].load(Relaxed)),
3387 ms(WS_WAIT[i].load(Relaxed)),
3388 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
3389 );
3390 }
3391 s += &format!(
3392 " | pipe={}/{}",
3393 PIPE_FRAMES.load(Relaxed),
3394 PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
3395 );
3396 s += &format!(
3397 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
3398 ms(WS_PARSE.load(Relaxed)),
3399 ms(WS_BARRIER.load(Relaxed)),
3400 WS_BARRIERS.load(Relaxed),
3401 ms(WS_DRAIN.load(Relaxed)),
3402 WS_BLOCK_ABOVE.load(Relaxed),
3403 WS_BLOCK_LEFT.load(Relaxed),
3404 );
3405 eprintln!("{s}");
3406}
3407
3408#[allow(unsafe_code)]
3409fn wave_worker(st: &WaveState, idx: usize) {
3410 let fctx = FrameCtx::new();
3411 fctx.bit_depth.set(st.bit_depth);
3412 fctx.enable_edge_filter.set(st.enable_edge_filter);
3413 let (sx, sy) = st.subsampling;
3414 fctx.subsampling_x.set(sx);
3415 fctx.subsampling_y.set(sy);
3416 let stats = wave_stats();
3417 let slot = idx.min(WS_SLOTS - 1);
3418 loop {
3419 let t0 = std::time::Instant::now();
3420 let mut q = st.q.lock().unwrap();
3421 let (r, c, job) = loop {
3422 if let Some(job) = q.take_runnable(st.last_col, stats) {
3423 break job;
3424 }
3425 if q.closed && q.queued == 0 {
3426 return;
3427 }
3428 q = st.cv.wait(q).unwrap();
3429 };
3430 q.active += 1;
3431 drop(q);
3432 if stats {
3433 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3434 WS_JOBS[slot].fetch_add(1, Relaxed);
3435 WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
3436 }
3437 let t1 = std::time::Instant::now();
3438 let ReconPlanes(y, u, v) = st.planes;
3439 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
3440 // every superblock that could have written or be reading them is
3441 // complete by the wavefront rule above.
3442 let mut cur: [Vec<u16>; 3] = Default::default();
3443 let ReconJob {
3444 mut ops,
3445 mut coeffs,
3446 mut preds,
3447 } = job;
3448 unsafe {
3449 for op in ops.drain(..) {
3450 exec_op(
3451 op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx,
3452 );
3453 }
3454 }
3455 if stats {
3456 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
3457 }
3458 coeffs.clear();
3459 preds.clear();
3460 let mut q = st.q.lock().unwrap();
3461 // lane-sballoc: hand the three buffers back for the next submit.
3462 if q.free.len() < q.free_cap {
3463 q.free.push((ops, coeffs, preds));
3464 }
3465 q.done[r] = c as isize;
3466 q.active -= 1;
3467 st.cv.notify_all();
3468 }
3469}
3470
3471/// Installs the wavefront for one tile and joins its workers on every exit
3472/// from the tile decoder, including the `?` ones -- the jobs hold raw
3473/// pointers into the tile's planes, so no worker may outlive them.
3474/// (lane-pool1: the workers come from this thread's persistent pool, so a
3475/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
3476/// with fresh scratch.)
3477pub(crate) struct WaveGuard<'a>(
3478 &'a crate::decode::FrameCtx,
3479 Option<crate::par::Batch<'static>>,
3480);
3481
3482#[allow(unsafe_code)]
3483impl<'a> WaveGuard<'a> {
3484 fn install(
3485 fctx: &'a crate::decode::FrameCtx,
3486 y: &mut PlaneBuf<'static>,
3487 u: &mut PlaneBuf<'static>,
3488 v: &mut PlaneBuf<'static>,
3489 rows: usize,
3490 cols: usize,
3491 ) -> Option<Self> {
3492 let threads = crate::par::recon_threads();
3493 if threads == 1 || rows == 0 || cols == 0 {
3494 return None;
3495 }
3496 let st = std::sync::Arc::new(WaveState {
3497 q: std::sync::Mutex::new(WaveQueue {
3498 rows: (0..rows)
3499 .map(|_| std::collections::VecDeque::new())
3500 .collect(),
3501 queued: 0,
3502 done: vec![-1; rows],
3503 last_sub: vec![-1; rows],
3504 last_push: vec![-1; rows],
3505 active: 0,
3506 closed: false,
3507 free: Vec::new(),
3508 free_cap: threads + 2,
3509 }),
3510 cv: std::sync::Condvar::new(),
3511 // SAFETY: the planes are locals of the tile decoder and outlive
3512 // this guard, which joins every worker in `drop`.
3513 planes: ReconPlanes(
3514 std::ptr::from_mut(y),
3515 std::ptr::from_mut(u),
3516 std::ptr::from_mut(v),
3517 ),
3518 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
3519 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
3520 subsampling: (
3521 fctx.subsampling_x.with(std::cell::Cell::get),
3522 fctx.subsampling_y.with(std::cell::Cell::get),
3523 ),
3524 last_col: cols - 1,
3525 });
3526 let batch = crate::par::Batch::new("ec-av1-recon");
3527 for idx in 0..threads {
3528 let st = std::sync::Arc::clone(&st);
3529 batch.submit(move || wave_worker(&st, idx));
3530 }
3531 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
3532 fctx.wave_mark
3533 .with(|c| c.set(Some(std::time::Instant::now())));
3534 Some(Self(fctx, Some(batch)))
3535 }
3536}
3537
3538impl Drop for WaveGuard<'_> {
3539 fn drop(&mut self) {
3540 let st = self.0.wave.with(|w| w.borrow_mut().take());
3541 if let Some(st) = st {
3542 st.q.lock().unwrap().closed = true;
3543 st.cv.notify_all();
3544 }
3545 let t0 = std::time::Instant::now();
3546 // Dropping the batch waits every worker out, as the joins did.
3547 drop(self.1.take());
3548 if wave_stats() {
3549 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3550 WS_TILES.fetch_add(1, Relaxed);
3551 wave_stats_dump();
3552 }
3553 }
3554}
3555
3556/// An empty buffer for the next superblock: the recycled one when it is at
3557/// least as big as the superblock just parsed, else a fresh sized one
3558/// (lane-sballoc; `v` is always empty).
3559fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> {
3560 if v.capacity() < cap {
3561 v.reserve_exact(cap - v.len());
3562 }
3563 v
3564}
3565
3566/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
3567/// when there is no wavefront (one reconstruction thread), in which case the
3568/// caller replays them itself.
3569fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
3570 let st = fctx.wave.with(|w| w.borrow().clone());
3571 let Some(st) = st else { return false };
3572 // lane-blockmem: the op list is replaced sized for the next superblock,
3573 // exactly as the two arenas below are -- taking it left a zero-capacity
3574 // `Vec` that regrew (and memmoved every recorded op) from nothing on
3575 // every superblock.
3576 // lane-sballoc: the replacement comes from the finished jobs' free list
3577 // when there is one (warm capacity, already faulted in); only the first
3578 // superblocks of a tile allocate.
3579 let mut q = st.q.lock().unwrap();
3580 let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default();
3581 let ops = fctx.recon_ops.with(|c| {
3582 let mut c = c.borrow_mut();
3583 let cap = c.len();
3584 std::mem::replace(&mut *c, reuse(sops, cap))
3585 });
3586 // The job owns its coefficients: the arena is replaced by an empty one
3587 // sized for the next superblock, so parse never regrows from nothing and
3588 // the worker frees this buffer once, instead of once per unit.
3589 let coeffs = fctx.coeff_arena.with(|c| {
3590 let mut c = c.borrow_mut();
3591 let cap = c.len();
3592 std::mem::replace(&mut *c, reuse(scoeffs, cap))
3593 });
3594 let preds = fctx.pred_arena.with(|c| {
3595 let mut c = c.borrow_mut();
3596 let cap = c.len();
3597 std::mem::replace(&mut *c, reuse(spreds, cap))
3598 });
3599 {
3600 if (c as isize) > q.last_sub[r] {
3601 q.last_sub[r] = c as isize;
3602 }
3603 if !ops.is_empty() {
3604 q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
3605 q.queued += 1;
3606 q.last_push[r] = c as isize;
3607 }
3608 drop(q);
3609 st.cv.notify_all();
3610 }
3611 if wave_stats() {
3612 let now = std::time::Instant::now();
3613 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
3614 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
3615 }
3616 }
3617 true
3618}
3619
3620/// Waits until every submitted job is reconstructed, so the parser may read
3621/// the planes itself (the intrabc source fetch and the interintra intra
3622/// predictor -- see [`flush_recon`]).
3623fn wave_barrier(fctx: &crate::decode::FrameCtx) {
3624 let st = fctx.wave.with(|w| w.borrow().clone());
3625 let Some(st) = st else { return };
3626 let stats = wave_stats();
3627 let t0 = std::time::Instant::now();
3628 let mut q = st.q.lock().unwrap();
3629 while q.queued > 0 || q.active > 0 {
3630 q = st.cv.wait(q).unwrap();
3631 }
3632 drop(q);
3633 if stats {
3634 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3635 WS_BARRIERS.fetch_add(1, Relaxed);
3636 }
3637}
3638
3639/// Performs an intra write at its push site when the tile registered its
3640/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
3641/// caller must record it for the wavefront workers instead.
3642#[allow(unsafe_code)]
3643#[allow(clippy::too_many_arguments)]
3644fn inline_intra(
3645 plane: usize,
3646 x: usize,
3647 oy: usize,
3648 bw: usize,
3649 bh: usize,
3650 rect: bool,
3651 mode: usize,
3652 angle_delta: i32,
3653 reach: Reach,
3654 residual: &[i32],
3655 cfl: Option<(i32, CflSrc)>,
3656 filter_intra: Option<usize>,
3657 smooth_neighbor: bool,
3658 fctx: &crate::decode::FrameCtx,
3659) -> bool {
3660 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3661 return false;
3662 };
3663 let pred = take_palette_pred(fctx);
3664 // SAFETY: see [`ReconPlanes`].
3665 unsafe {
3666 exec_intra(
3667 &mut *y,
3668 &mut *u,
3669 &mut *v,
3670 plane,
3671 x,
3672 oy,
3673 bw,
3674 bh,
3675 rect,
3676 mode,
3677 angle_delta,
3678 reach,
3679 residual,
3680 cfl,
3681 filter_intra,
3682 smooth_neighbor,
3683 pred,
3684 fctx,
3685 );
3686 }
3687 true
3688}
3689
3690/// [`inline_intra`] for a motion-compensated write.
3691#[allow(unsafe_code)]
3692#[allow(clippy::too_many_arguments)]
3693fn inline_mc(
3694 plane: usize,
3695 x: usize,
3696 oy: usize,
3697 stride: usize,
3698 w: usize,
3699 h: usize,
3700 prediction: &[u16],
3701 residual: &[i32],
3702 fctx: &crate::decode::FrameCtx,
3703) -> bool {
3704 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3705 return false;
3706 };
3707 // SAFETY: see [`ReconPlanes`].
3708 unsafe {
3709 exec_mc(
3710 &mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx,
3711 );
3712 }
3713 true
3714}
3715
3716/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
3717#[allow(clippy::too_many_arguments)]
3718fn push_intra(
3719 plane: usize,
3720 x: usize,
3721 y: usize,
3722 side: usize,
3723 mode: usize,
3724 angle_delta: i32,
3725 reach: Reach,
3726 residual: &[i32],
3727 cfl: Option<(i32, CflSrc)>,
3728 filter_intra: Option<usize>,
3729 smooth_neighbor: bool,
3730 fctx: &crate::decode::FrameCtx,
3731) {
3732 if inline_intra(
3733 plane,
3734 x,
3735 y,
3736 side,
3737 side,
3738 false,
3739 mode,
3740 angle_delta,
3741 reach,
3742 residual,
3743 cfl,
3744 filter_intra,
3745 smooth_neighbor,
3746 fctx,
3747 ) {
3748 return;
3749 }
3750 let pred = take_palette_pred(fctx);
3751 push_op(
3752 fctx,
3753 ReconOp::Intra {
3754 plane,
3755 x,
3756 y,
3757 bw: side,
3758 bh: side,
3759 rect: false,
3760 mode,
3761 angle_delta,
3762 reach,
3763 residual: Residual::done(residual, fctx),
3764 cfl,
3765 filter_intra,
3766 smooth_neighbor,
3767 pred,
3768 },
3769 );
3770}
3771
3772/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
3773#[allow(clippy::too_many_arguments)]
3774fn push_intra_rect(
3775 plane: usize,
3776 x: usize,
3777 y: usize,
3778 bw: usize,
3779 bh: usize,
3780 mode: usize,
3781 angle_delta: i32,
3782 reach: Reach,
3783 residual: &[i32],
3784 cfl: Option<(i32, CflSrc)>,
3785 filter_intra: Option<usize>,
3786 smooth_neighbor: bool,
3787 fctx: &crate::decode::FrameCtx,
3788) {
3789 if inline_intra(
3790 plane,
3791 x,
3792 y,
3793 bw,
3794 bh,
3795 true,
3796 mode,
3797 angle_delta,
3798 reach,
3799 residual,
3800 cfl,
3801 filter_intra,
3802 smooth_neighbor,
3803 fctx,
3804 ) {
3805 return;
3806 }
3807 let pred = take_palette_pred(fctx);
3808 push_op(
3809 fctx,
3810 ReconOp::Intra {
3811 plane,
3812 x,
3813 y,
3814 bw,
3815 bh,
3816 rect: true,
3817 mode,
3818 angle_delta,
3819 reach,
3820 residual: Residual::done(residual, fctx),
3821 cfl,
3822 filter_intra,
3823 smooth_neighbor,
3824 pred,
3825 },
3826 );
3827}
3828
3829/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
3830fn push_mc(
3831 plane: usize,
3832 x: usize,
3833 y: usize,
3834 side: usize,
3835 prediction: Pred<'_>,
3836 residual: &[i32],
3837 fctx: &crate::decode::FrameCtx,
3838) {
3839 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
3840}
3841
3842/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
3843#[allow(clippy::too_many_arguments)]
3844fn push_mc_rect(
3845 plane: usize,
3846 x: usize,
3847 y: usize,
3848 stride: usize,
3849 w: usize,
3850 h: usize,
3851 prediction: Pred<'_>,
3852 residual: &[i32],
3853 fctx: &crate::decode::FrameCtx,
3854) {
3855 let (src, stride) = match prediction.inline(stride) {
3856 Some(v) => v,
3857 None => {
3858 let Pred::Cur {
3859 plane: sp,
3860 stride: ss,
3861 off,
3862 } = prediction
3863 else {
3864 unreachable!()
3865 };
3866 push_op(
3867 fctx,
3868 ReconOp::Mc {
3869 plane,
3870 x,
3871 y,
3872 stride: ss,
3873 w,
3874 h,
3875 prediction: PredSrc::Cur {
3876 plane: sp,
3877 off,
3878 src: ss,
3879 },
3880 residual: Residual::done(residual, fctx),
3881 },
3882 );
3883 return;
3884 }
3885 };
3886 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
3887 return;
3888 }
3889 push_op(
3890 fctx,
3891 ReconOp::Mc {
3892 plane,
3893 x,
3894 y,
3895 stride,
3896 w,
3897 h,
3898 // The whole window `reconstruct_mc_rect` reads at `stride`, not
3899 // `w * h`: the record keeps exactly what `src.to_vec()` carried.
3900 prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
3901 residual: Residual::done(residual, fctx),
3902 },
3903 );
3904}
3905
3906/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
3907/// thread the transform runs here, exactly as before; on the wavefront it
3908/// travels with the op and runs on the worker (lane-wave3).
3909#[allow(clippy::too_many_arguments)]
3910fn push_intra_tx(
3911 plane: usize,
3912 x: usize,
3913 y: usize,
3914 bw: usize,
3915 bh: usize,
3916 rect: bool,
3917 mode: usize,
3918 angle_delta: i32,
3919 reach: Reach,
3920 tx: TxParams,
3921 grid: &[i32],
3922 cfl: Option<(i32, CflSrc)>,
3923 filter_intra: Option<usize>,
3924 smooth_neighbor: bool,
3925 fctx: &crate::decode::FrameCtx,
3926) {
3927 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3928 inline_intra(
3929 plane,
3930 x,
3931 y,
3932 bw,
3933 bh,
3934 rect,
3935 mode,
3936 angle_delta,
3937 reach,
3938 &tx.run(grid),
3939 cfl,
3940 filter_intra,
3941 smooth_neighbor,
3942 fctx,
3943 );
3944 return;
3945 }
3946 let pred = take_palette_pred(fctx);
3947 push_op(
3948 fctx,
3949 ReconOp::Intra {
3950 plane,
3951 x,
3952 y,
3953 bw,
3954 bh,
3955 rect,
3956 mode,
3957 angle_delta,
3958 reach,
3959 residual: Residual::coeffs(tx, grid, fctx),
3960 cfl,
3961 filter_intra,
3962 smooth_neighbor,
3963 pred,
3964 },
3965 );
3966}
3967
3968/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
3969#[allow(clippy::too_many_arguments)]
3970fn push_mc_rect_tx(
3971 plane: usize,
3972 x: usize,
3973 y: usize,
3974 stride: usize,
3975 w: usize,
3976 h: usize,
3977 prediction: Pred<'_>,
3978 tx: TxParams,
3979 grid: &[i32],
3980 fctx: &crate::decode::FrameCtx,
3981) {
3982 // lane-wave4: a deferred prediction is not there to be windowed -- the
3983 // op carries its offset into the block's prediction instead, and the
3984 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
3985 // both buffers at one stride).
3986 let (prediction, stride) = match prediction.inline(stride) {
3987 Some(v) => v,
3988 None => {
3989 let Pred::Cur {
3990 plane: sp,
3991 stride: ss,
3992 off,
3993 } = prediction
3994 else {
3995 unreachable!()
3996 };
3997 let mut tx = tx;
3998 tx.stride = 0;
3999 push_op(
4000 fctx,
4001 ReconOp::Mc {
4002 plane,
4003 x,
4004 y,
4005 stride: w,
4006 w,
4007 h,
4008 prediction: PredSrc::Cur {
4009 plane: sp,
4010 off,
4011 src: ss,
4012 },
4013 residual: Residual::coeffs(tx, grid, fctx),
4014 },
4015 );
4016 return;
4017 }
4018 };
4019 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
4020 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
4021 // stride, so a prediction handed over at the block's stride (a var-tx
4022 // unit's window, lane-wave4) has to be densified for a dense residual
4023 // -- which is exactly what the recorded path below does.
4024 let residual = tx.run(grid);
4025 let res_stride = if tx.stride == 0 { w } else { tx.stride };
4026 let window;
4027 let prediction = if stride == res_stride {
4028 prediction
4029 } else {
4030 debug_assert_eq!(res_stride, w);
4031 let mut win = Vec::with_capacity(w * h);
4032 for row in 0..h {
4033 win.extend_from_slice(&prediction[row * stride..][..w]);
4034 }
4035 window = win;
4036 &window[..]
4037 };
4038 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
4039 return;
4040 }
4041 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
4042 // two buffers at `stride`, so the record carries that window densely
4043 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
4044 // copied 64*64 samples on the PARSING thread before. The residual is then
4045 // produced dense too (`TxParams::stride = 0`), which is the same numbers
4046 // in the same places at stride `w`.
4047 let off = fctx.pred_arena.with(|a| {
4048 let mut a = a.borrow_mut();
4049 let off = a.len();
4050 for row in 0..h {
4051 a.extend_from_slice(&prediction[row * stride..][..w]);
4052 }
4053 off as u32
4054 });
4055 let mut tx = tx;
4056 tx.stride = 0;
4057 push_op(
4058 fctx,
4059 ReconOp::Mc {
4060 plane,
4061 x,
4062 y,
4063 stride: w,
4064 w,
4065 h,
4066 prediction: PredSrc::Owned(off, (w * h) as u32),
4067 residual: Residual::coeffs(tx, grid, fctx),
4068 },
4069 );
4070}
4071
4072/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
4073/// and empties the queue (lane-wave1 step (i)).
4074///
4075/// Called at the top of each superblock visit and at the end of each tile, so
4076/// a whole superblock's parsing runs with no plane access at all; the two
4077/// parse-time pixel READS that survive -- the intrabc source fetch and the
4078/// interintra intra predictor -- flush ahead of themselves instead, which
4079/// keeps them byte-exact and names exactly what step (ii) still has to move.
4080fn flush_recon(
4081 fctx: &crate::decode::FrameCtx,
4082 y: &mut PlaneBuf<'static>,
4083 u: &mut PlaneBuf<'static>,
4084 v: &mut PlaneBuf<'static>,
4085) {
4086 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
4087 // writes in place, not just this superblock's queue.
4088 wave_barrier(fctx);
4089 let mut ops = fctx
4090 .recon_spare
4091 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4092 fctx.recon_ops
4093 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
4094 let mut coeffs = fctx
4095 .coeff_spare
4096 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4097 fctx.coeff_arena
4098 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
4099 let mut preds = fctx
4100 .pred_spare
4101 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4102 fctx.pred_arena
4103 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
4104 let mut cur: [Vec<u16>; 3] = Default::default();
4105 for op in ops.drain(..) {
4106 exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
4107 }
4108 coeffs.clear();
4109 preds.clear();
4110 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
4111 fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
4112 fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
4113}
4114
4115/// Performs one recorded write: the body [`flush_recon`] replays, and the
4116/// body [`push_op`] runs immediately when reconstruction is inline.
4117fn exec_op(
4118 op: ReconOp,
4119 y: &mut PlaneBuf<'static>,
4120 u: &mut PlaneBuf<'static>,
4121 v: &mut PlaneBuf<'static>,
4122 cur: &mut [Vec<u16>; 3],
4123 coeffs: &[i32],
4124 preds: &[u16],
4125 fctx: &crate::decode::FrameCtx,
4126) {
4127 // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel
4128 // write, leaving the entropy parse and the per-mi neighbour bookkeeping
4129 // alone. It makes the encoder's own streams garbage, so it is a
4130 // MEASUREMENT rung only -- what it measures is how much of the encoder's
4131 // first decode of its own tiles (`par::S_FIRST`) is reconstruction and
4132 // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile
4133 // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that
4134 // stage and the parse plus the neighbour grids are the other 94%. That
4135 // is why handing the decoder the encoder's own reconstruction cannot
4136 // shrink the stage: only publishing the per-mi neighbour state the
4137 // filters read (and so never parsing at all) can.
4138 if crate::envflags::env_flag!("EC_AV1_NORECON") {
4139 return;
4140 }
4141 let mut scratch = Vec::new();
4142 match op {
4143 ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur),
4144 ReconOp::Intra {
4145 plane,
4146 x,
4147 y: oy,
4148 bw,
4149 bh,
4150 rect,
4151 mode,
4152 angle_delta,
4153 reach,
4154 residual,
4155 cfl,
4156 filter_intra,
4157 smooth_neighbor,
4158 pred,
4159 } => exec_intra(
4160 y,
4161 u,
4162 v,
4163 plane,
4164 x,
4165 oy,
4166 bw,
4167 bh,
4168 rect,
4169 mode,
4170 angle_delta,
4171 reach,
4172 residual.resolve(coeffs, &mut scratch),
4173 cfl,
4174 filter_intra,
4175 smooth_neighbor,
4176 pred,
4177 fctx,
4178 ),
4179 ReconOp::Mc {
4180 plane,
4181 x,
4182 y: oy,
4183 stride,
4184 w,
4185 h,
4186 prediction,
4187 residual,
4188 } => {
4189 let residual = residual.resolve(coeffs, &mut scratch);
4190 match prediction {
4191 PredSrc::Owned(off, len) => {
4192 let p = &preds[off as usize..][..len as usize];
4193 exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
4194 }
4195 PredSrc::Cur {
4196 plane: sp,
4197 off,
4198 src,
4199 } => {
4200 let block = std::mem::take(&mut cur[sp]);
4201 if src == stride {
4202 exec_mc(
4203 y,
4204 u,
4205 v,
4206 plane,
4207 x,
4208 oy,
4209 stride,
4210 w,
4211 h,
4212 &block[off..],
4213 residual,
4214 fctx,
4215 );
4216 } else {
4217 // A transform unit's residual is dense, so its window
4218 // of the block prediction is taken out dense too --
4219 // the copy the parsing thread used to make, made here.
4220 let mut window = Vec::with_capacity(w * h);
4221 for row in 0..h {
4222 window.extend_from_slice(&block[off + row * src..][..w]);
4223 }
4224 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
4225 }
4226 cur[sp] = block;
4227 }
4228 }
4229 }
4230 }
4231}
4232
4233/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
4234/// path ([`push_op`]'s registered planes) reaches it without ever building
4235/// the record -- which is what keeps one reconstruction thread at the cost of
4236/// the pre-lane-wave1 decoder.
4237#[allow(clippy::too_many_arguments)]
4238fn exec_intra(
4239 y: &mut PlaneBuf<'static>,
4240 u: &mut PlaneBuf<'static>,
4241 v: &mut PlaneBuf<'static>,
4242 plane: usize,
4243 x: usize,
4244 oy: usize,
4245 bw: usize,
4246 bh: usize,
4247 rect: bool,
4248 mode: usize,
4249 angle_delta: i32,
4250 reach: Reach,
4251 residual: &[i32],
4252 cfl: Option<(i32, CflSrc)>,
4253 filter_intra: Option<usize>,
4254 smooth_neighbor: bool,
4255 pred: Option<Vec<u16>>,
4256 fctx: &crate::decode::FrameCtx,
4257) {
4258 // The CfL AC signal is read HERE, off the luma that has already been
4259 // written for this block -- at parse time it would have been the previous
4260 // frame's samples.
4261 let ac = cfl.map(|(alpha, src)| {
4262 let sig = cfl_ac_ss(&*y, src.px, src.py, src.bw, src.bh, ss_x(fctx), ss_y(fctx));
4263 (alpha, sig)
4264 });
4265 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
4266 let target: &mut PlaneBuf<'static> = match plane {
4267 0 => &mut *y,
4268 1 => &mut *u,
4269 _ => &mut *v,
4270 };
4271 if rect {
4272 target.reconstruct_rect(
4273 x,
4274 oy,
4275 bw,
4276 bh,
4277 mode,
4278 angle_delta,
4279 reach,
4280 residual,
4281 cfl,
4282 filter_intra,
4283 smooth_neighbor,
4284 pred,
4285 fctx,
4286 );
4287 } else {
4288 target.reconstruct(
4289 x,
4290 oy,
4291 bw,
4292 mode,
4293 angle_delta,
4294 reach,
4295 residual,
4296 cfl,
4297 filter_intra,
4298 smooth_neighbor,
4299 pred,
4300 fctx,
4301 );
4302 }
4303}
4304
4305/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
4306#[allow(clippy::too_many_arguments)]
4307fn exec_mc(
4308 y: &mut PlaneBuf<'static>,
4309 u: &mut PlaneBuf<'static>,
4310 v: &mut PlaneBuf<'static>,
4311 plane: usize,
4312 x: usize,
4313 oy: usize,
4314 stride: usize,
4315 w: usize,
4316 h: usize,
4317 prediction: &[u16],
4318 residual: &[i32],
4319 fctx: &crate::decode::FrameCtx,
4320) {
4321 let target: &mut PlaneBuf<'static> = match plane {
4322 0 => &mut *y,
4323 1 => &mut *u,
4324 _ => &mut *v,
4325 };
4326 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
4327}
4328
4329thread_local! {
4330 /// The current frame's `mi` grid, kept only while a frame header set
4331 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
4332 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
4333 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
4334 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
4335 /// does not allow intrabc (so nothing is paid for it).
4336 ///
4337 /// corner-cut: only [`decode_block`] (the square path) records into it,
4338 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
4339 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
4340 /// be wrong there; upgrade = record from the rect/leaf paths too.
4341 /// The block vector [`read_intra_mode`] just decoded, handed to
4342 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
4343 /// which the alternative -- a tenth tuple member through every caller --
4344 /// already avoids). Always `.take()`n by the block that reads it.
4345 /// How many blocks read `use_intrabc == 1` and took the DV path -- the
4346 /// gate's hit counter. Bumped on the READ, before the rect-strip refusal
4347 /// returns too, so it counts reads, not reconstructions (a refused block
4348 /// is never reconstructed).
4349 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4350}
4351// The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
4352// an intrabc block's chroma reads can inherit it (see
4353// [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
4354// through that one arming site.
4355// libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
4356// branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
4357// satisfies (`blockd.h:373`) -- and takes the *colocated luma
4358// transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
4359// `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
4360// intrabc block's two chroma [`read_plane`] calls; the type decides the
4361// `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
4362// -- getting it wrong desyncs the chroma coefficients, it is not a
4363// reconstruction-only detail.
4364
4365/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
4366/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
4367/// needs no separate plumbing to reach the rect-strip mode reader.
4368fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
4369 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
4370}
4371
4372thread_local! {
4373 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
4374 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
4375 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
4376 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4377}
4378
4379/// Current value of [`RECT_INTRABC_READS`].
4380pub(crate) fn rect_intrabc_reads() -> usize {
4381 RECT_INTRABC_READS.with(|c| c.get())
4382}
4383
4384/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
4385#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4386pub(crate) fn reset_rect_intrabc_reads() {
4387 RECT_INTRABC_READS.with(|c| c.set(0));
4388}
4389
4390thread_local! {
4391 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
4392 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
4393 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4394}
4395
4396thread_local! {
4397 /// Chroma reads of an intrabc TX4-split leaf that consulted an ARMED
4398 /// [`INTRABC_CHROMA_TX`] slot -- proof that the arm's frame-copy +
4399 /// inherited-type route actually ran (lane-av1intrapred r2's non-vacuity
4400 /// counter: zero means the gate's fixture no longer reaches the route).
4401 static INTRABC_TX4_CHROMA_COPY_HITS: std::cell::Cell<usize> =
4402 const { std::cell::Cell::new(0) };
4403}
4404
4405/// Current value of [`INTRABC_TX4_CHROMA_COPY_HITS`].
4406#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4407pub(crate) fn intrabc_tx4_chroma_copy_hits() -> usize {
4408 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.get())
4409}
4410
4411/// Zeroes [`INTRABC_TX4_CHROMA_COPY_HITS`] (gate tests call this before a decode).
4412#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4413pub(crate) fn reset_intrabc_tx4_chroma_copy_hits() {
4414 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.set(0));
4415}
4416
4417/// Current value of [`LEAF8_INTRABC_HITS`].
4418pub(crate) fn leaf8_intrabc_hits() -> usize {
4419 LEAF8_INTRABC_HITS.with(|c| c.get())
4420}
4421
4422/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
4423#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4424pub(crate) fn reset_leaf8_intrabc_hits() {
4425 LEAF8_INTRABC_HITS.with(|c| c.set(0));
4426}
4427
4428/// Current value of [`INTRABC_HITS`].
4429#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4430pub(crate) fn intrabc_hits() -> usize {
4431 INTRABC_HITS.with(|c| c.get())
4432}
4433
4434thread_local! {
4435 /// An intrabc block that IS a sub-8x8 group's CHROMA REFERENCE and is
4436 /// SKIPPED: the route that arms [`INTRABC_CHROMA_TX`] and then reads no
4437 /// chroma coefficient at all, so the slot used to stay armed into the NEXT
4438 /// block's chroma read. Both group shapes (4x4 split, 4x8/8x4 rect) count
4439 /// here. A non-zero value is what makes the disarm below load-bearing.
4440 static SKIPPED_INTRABC_CHROMA_ARM_HITS: std::cell::Cell<usize> =
4441 const { std::cell::Cell::new(0) };
4442}
4443
4444/// Current value of [`SKIPPED_INTRABC_CHROMA_ARM_HITS`].
4445#[allow(dead_code)] // read only from the `#[cfg(test)]` gates and the probe
4446pub(crate) fn skipped_intrabc_chroma_arm_hits() -> usize {
4447 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.get())
4448}
4449
4450/// Zeroes [`SKIPPED_INTRABC_CHROMA_ARM_HITS`] (gate tests call this before a
4451/// decode).
4452#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4453pub(crate) fn reset_skipped_intrabc_chroma_arm_hits() {
4454 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.set(0));
4455}
4456
4457thread_local! {
4458 /// lane-av1-ibcskip2: a sub-8x8 4:4:4 leaf that is BOTH intrabc AND
4459 /// `skip` -- the arm whose chroma is the bare frame copy at the DV
4460 /// (libaom `av1_build_inter_predictors_sb` runs regardless of `skip`).
4461 /// Before the fix this route predicted intra-DC and every one of this
4462 /// fixture's 150 such cells differed from the oracle on both chroma
4463 /// planes.
4464 static SKIPPED_INTRABC_DV_COPY_HITS: std::cell::Cell<usize> =
4465 const { std::cell::Cell::new(0) };
4466}
4467
4468/// Current value of [`SKIPPED_INTRABC_DV_COPY_HITS`].
4469#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4470pub(crate) fn skipped_intrabc_dv_copy_hits() -> usize {
4471 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.get())
4472}
4473
4474/// Zeroes [`SKIPPED_INTRABC_DV_COPY_HITS`] (gate tests call this before a
4475/// decode).
4476#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4477pub(crate) fn reset_skipped_intrabc_dv_copy_hits() {
4478 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.set(0));
4479}
4480
4481/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
4482#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4483pub(crate) fn reset_intrabc_hits() {
4484 INTRABC_HITS.with(|c| c.set(0));
4485}
4486
4487thread_local! {
4488 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
4489 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
4490 /// that replaced the refusal "an intrabc block under TxMode::Select".
4491 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4492 /// lane-av1-ibcvtx: intrabc var-tx trees that resolved to MIXED leaf
4493 /// sizes (not one square size across every leaf) -- the engagement
4494 /// counter proving a witness actually exercises the per-leaf reconstruct.
4495 static INTRABC_VARTX_MIXED_LEAVES_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4496 /// lane-av1txr: as above for a `BLOCK_4X8`/`BLOCK_8X4` intrabc leaf --
4497 /// libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`, so these leaves
4498 /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no
4499 /// symbol here desynced `warped.obu` at the very next block.
4500 static RECT_INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4501 /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction
4502 /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip
4503 /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never
4504 /// this one).
4505 static INTRABC_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4506 /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT).
4507 static INTRABC_RECT_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4508 /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction
4509 /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read),
4510 /// split by the strip's orientation -- `bw > bh` is a HORZ strip,
4511 /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED
4512 /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS`
4513 /// counts neither orientation nor the skip flag, so an arm that flipped
4514 /// to an all-skip stream (no residual reader at all) would stay green.
4515 static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> =
4516 const { std::cell::Cell::new([0, 0]) };
4517 /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`]
4518 /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split
4519 /// by orientation. The r5 panic (residual stride `bw * bh` underrunning
4520 /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was
4521 /// invisible to every gate because they only counted CODED strips.
4522 static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> =
4523 const { std::cell::Cell::new([0, 0]) };
4524}
4525
4526/// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed,
4527/// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`].
4528#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4529pub fn intrabc_rect_coded_hits() -> [usize; 2] {
4530 INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get)
4531}
4532
4533/// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks
4534/// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`].
4535#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4536pub fn intrabc_rect_skipped_hits() -> [usize; 2] {
4537 INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get)
4538}
4539
4540/// Current value of [`INTRABC_RECT_HITS`].
4541#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4542pub fn intrabc_rect_hits() -> usize {
4543 INTRABC_RECT_HITS.with(|c| c.get())
4544}
4545
4546/// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`].
4547#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4548pub(crate) fn reset_intrabc_rect_hits() {
4549 INTRABC_RECT_HITS.with(|c| c.set(0));
4550 INTRABC_RECT_VARTX_HITS.with(|c| c.set(0));
4551 INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0]));
4552 INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0]));
4553}
4554
4555/// Current value of [`INTRABC_RECT_VARTX_HITS`].
4556#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4557pub fn intrabc_rect_vartx_hits() -> usize {
4558 INTRABC_RECT_VARTX_HITS.with(|c| c.get())
4559}
4560
4561thread_local! {
4562 /// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip
4563 /// (BLOCK_128X64 / BLOCK_64X128) whose reconstruction
4564 /// [`decode_intrabc_128rect`] ran -- the shape the named refusal used to
4565 /// guard (`decode_block_128rect`). A refused block bumps
4566 /// [`INTRABC_HITS`] but never this one.
4567 static INTRABC_128RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4568 /// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc
4569 /// strip's mu-chunk walk read, one per `read_inter_plane` chroma call.
4570 /// At 4:2:0 a 64x64 mu chunk's chroma plane block is 32x32, so one
4571 /// TX_32X32 per plane per chunk; at 4:2:2 it is 32x64 and holds TWO
4572 /// STACKED units per plane. The square-cut `chunk_chroma = cside * 64 /
4573 /// side` model walked the 4:2:0 count on every axis, so this counter is
4574 /// the reach/arm witness for the per-axis walk.
4575 static INTRABC_128RECT_CHROMA_CHUNK_HITS: std::cell::Cell<usize> =
4576 const { std::cell::Cell::new(0) };
4577 /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as
4578 /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the
4579 /// per-axis walk used. A 4:2:2 run and a 4:2:0 run of the same block
4580 /// differ here (32|64 vs 32|32), which is what the de-square-cut fixes.
4581 static INTRABC_128RECT_CHUNK_SHAPE: std::cell::Cell<usize> =
4582 const { std::cell::Cell::new(0) };
4583}
4584
4585/// Current value of [`INTRABC_128RECT_HITS`].
4586#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4587pub fn intrabc_128rect_hits() -> usize {
4588 INTRABC_128RECT_HITS.with(|c| c.get())
4589}
4590
4591/// Zeroes [`INTRABC_128RECT_HITS`].
4592#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4593pub(crate) fn reset_intrabc_128rect_hits() {
4594 INTRABC_128RECT_HITS.with(|c| c.set(0));
4595}
4596
4597/// Current value of [`INTRABC_128RECT_CHROMA_CHUNK_HITS`].
4598#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4599pub fn intrabc_128rect_chroma_chunk_hits() -> usize {
4600 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.get())
4601}
4602
4603/// Current value of [`INTRABC_128RECT_CHUNK_SHAPE`].
4604#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4605pub fn intrabc_128rect_chunk_shape() -> usize {
4606 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.get())
4607}
4608
4609/// Zeroes [`INTRABC_128RECT_CHROMA_CHUNK_HITS`] and
4610/// [`INTRABC_128RECT_CHUNK_SHAPE`].
4611#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4612pub(crate) fn reset_intrabc_128rect_chroma_chunk_hits() {
4613 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(0));
4614 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.set(0));
4615}
4616
4617/// Current value of [`INTRABC_VARTX_HITS`].
4618pub fn intrabc_vartx_hits() -> usize {
4619 INTRABC_VARTX_HITS.with(|c| c.get())
4620}
4621
4622/// Current value of [`INTRABC_VARTX_MIXED_LEAVES_HITS`].
4623pub fn intrabc_vartx_mixed_leaves_hits() -> usize {
4624 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.get())
4625}
4626
4627/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
4628#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4629pub(crate) fn reset_intrabc_vartx_hits() {
4630 INTRABC_VARTX_HITS.with(|c| c.set(0));
4631}
4632
4633/// Zeroes [`INTRABC_VARTX_MIXED_LEAVES_HITS`] (gate tests call this before a
4634/// decode).
4635#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4636pub(crate) fn reset_intrabc_vartx_mixed_leaves_hits() {
4637 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.set(0));
4638}
4639
4640/// Current value of [`RECT_INTRABC_VARTX_HITS`].
4641#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4642pub fn rect_intrabc_vartx_hits() -> usize {
4643 RECT_INTRABC_VARTX_HITS.with(|c| c.get())
4644}
4645
4646/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
4647/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
4648/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
4649/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
4650fn record_intrabc_mi(
4651 mi_r: usize,
4652 mi_c: usize,
4653 n4: usize,
4654 dv: Option<(i32, i32)>,
4655 n: &mut Neighbours,
4656 fctx: &crate::decode::FrameCtx,
4657) {
4658 record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx);
4659}
4660
4661/// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs`
4662/// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4`
4663/// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr).
4664///
4665/// Also stamps libaom's `is_inter_block` verdict for this block into the
4666/// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override
4667/// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] >
4668/// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and
4669/// `get_tx_size_context` reads its BLOCK size rather than its transform band.
4670/// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which
4671/// every block runs; this runs after it (class leaked-band otherwise).
4672fn record_intrabc_mi_rect(
4673 mi_r: usize,
4674 mi_c: usize,
4675 n4_w: usize,
4676 n4_h: usize,
4677 dv: Option<(i32, i32)>,
4678 n: &mut Neighbours,
4679 fctx: &crate::decode::FrameCtx,
4680) {
4681 if dv.is_some() {
4682 for i in 0..n4_w {
4683 if let Some(cell) = n.above_inter.get_mut(mi_c + i) {
4684 *cell = true;
4685 }
4686 }
4687 for i in 0..n4_h {
4688 if let Some(cell) = n.left_inter.get_mut(mi_r + i) {
4689 *cell = true;
4690 }
4691 }
4692 }
4693 fctx.intrabc_mi_grid.with(|g| {
4694 let mut g = g.borrow_mut();
4695 let Some((grid, _, _)) = g.as_mut() else {
4696 return;
4697 };
4698 let info = crate::mvstack::MiInfo {
4699 is_inter: dv.is_some(),
4700 ref_frame: 0,
4701 ref_frame1: NO_REF1,
4702 mv: mv16(dv.unwrap_or((0, 0))),
4703 mv1: (0, 0),
4704 is_new_mv: dv.is_some(),
4705 is_global_mv0: false,
4706 is_global_mv1: false,
4707 size: n4_w as u8,
4708 size_h: n4_h as u8,
4709 };
4710 for r in mi_r..mi_r + n4_h {
4711 for c in mi_c..mi_c + n4_w {
4712 grid.set(r, c, info);
4713 }
4714 }
4715 });
4716}
4717
4718// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
4719// proves a real `skip_mode_present` stream actually reached a block that
4720// picked it, not just that the frame header bit was set.
4721thread_local! {
4722 static SKIP_MODE_HITS: std::cell::Cell<usize> =
4723 const { std::cell::Cell::new(0) };
4724}
4725
4726/// Current value of [`SKIP_MODE_HITS`].
4727#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4728pub(crate) fn skip_mode_hits() -> usize {
4729 SKIP_MODE_HITS.with(|c| c.get())
4730}
4731
4732// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
4733// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
4734// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
4735// reached [`obmc_blend`], not just the header bit.
4736thread_local! {
4737 static OBMC_HITS: std::cell::Cell<usize> =
4738 const { std::cell::Cell::new(0) };
4739}
4740
4741// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
4742// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
4743// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
4744// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
4745// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
4746// decoder used to read with the wrong alphabet, so a gate that asserts this
4747// counter advanced proves the fixed path fired (class
4748// `gate-blind-to-feature`).
4749thread_local! {
4750 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4751}
4752
4753/// Current value of [`FIMV_ALPHABET_HITS`].
4754pub fn fimv_alphabet_hits() -> usize {
4755 FIMV_ALPHABET_HITS.with(|c| c.get())
4756}
4757
4758// lane-fimv r1: how many frame headers this decoder has decoded with
4759// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
4760// prove the encoder really produced the header state under test rather than
4761// assume it.
4762thread_local! {
4763 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4764}
4765
4766/// Current value of [`FIMV_FRAME_HITS`].
4767pub fn fimv_frame_hits() -> usize {
4768 FIMV_FRAME_HITS.with(|c| c.get())
4769}
4770
4771/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
4772/// `force_integer_mv` bit is set.
4773pub fn note_force_integer_mv_frame() {
4774 hit!(FIMV_FRAME_HITS);
4775}
4776
4777/// Current value of [`OBMC_HITS`].
4778#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4779pub(crate) fn obmc_hits() -> usize {
4780 OBMC_HITS.with(|c| c.get())
4781}
4782
4783// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
4784// off the neighbour band -- the positive half of the proof for "an OBMC
4785// neighbour whose switchable interp filter was never recorded". A
4786// fixed-filter frame returns before this point (its neighbours legitimately
4787// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
4788// `interp_filter` symbols were published by `record_inter_rect_mi`.
4789thread_local! {
4790 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4791}
4792
4793/// Current value of [`OBMC_FILTER_BAND_READS`].
4794#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4795pub(crate) fn obmc_filter_band_reads() -> usize {
4796 OBMC_FILTER_BAND_READS.with(|c| c.get())
4797}
4798
4799// lane-scaledref r1: per-case firing counts for the scaled-reference gate
4800// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
4801// reference would pass just as well and prove nothing, so the gate
4802// hard-asserts each combination this round lifts actually occurred:
4803// a compound block with a scaled tap, a warp block whose warp libaom
4804// suppresses because the reference is scaled, an OBMC block, an interintra
4805// block, and an 8x8 leaf.
4806thread_local! {
4807 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4808 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4809 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4810 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4811 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4812 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4813 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4814}
4815
4816/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
4817/// scaled and one unscaled tap.
4818#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4819pub(crate) fn mixed_scale_compound_hits() -> usize {
4820 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
4821}
4822
4823/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
4824/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
4825/// instead because their reference is scaled (libaom `motion_mode_allowed`,
4826/// `blockd.h:1484`).
4827#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4828pub(crate) fn scaled_warp_suppressed_hits() -> usize {
4829 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
4830}
4831
4832/// Current value of [`SCALED_COMPOUND_HITS`].
4833#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4834pub(crate) fn scaled_compound_hits() -> usize {
4835 SCALED_COMPOUND_HITS.with(|c| c.get())
4836}
4837
4838/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
4839pub fn scaled_warp_fallback_hits() -> usize {
4840 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
4841}
4842
4843/// Current value of [`SCALED_OBMC_HITS`].
4844#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4845pub(crate) fn scaled_obmc_hits() -> usize {
4846 SCALED_OBMC_HITS.with(|c| c.get())
4847}
4848
4849/// Current value of [`SCALED_INTERINTRA_HITS`].
4850#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4851pub(crate) fn scaled_interintra_hits() -> usize {
4852 SCALED_INTERINTRA_HITS.with(|c| c.get())
4853}
4854
4855/// Current value of [`SCALED_BLOCK8_HITS`].
4856#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4857pub(crate) fn scaled_block8_hits() -> usize {
4858 SCALED_BLOCK8_HITS.with(|c| c.get())
4859}
4860
4861// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
4862// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
4863// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
4864// 8x8-leaf OBMC block apart from a 16x16+ one.
4865thread_local! {
4866 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4867}
4868
4869// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
4870// pair whose two directions differ (`enable_dual_filter` only -- with dual
4871// filter off both directions take the single symbol, so this can never fire).
4872// A gate asserting it proves the stream really carries dual-filter blocks.
4873thread_local! {
4874 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4875}
4876
4877// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
4878// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
4879// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
4880// no-filter sentinel that made a neighbouring OBMC block panic).
4881thread_local! {
4882 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4883}
4884
4885/// Current value of [`DUAL_FILTER_DIFF_HITS`].
4886#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4887pub(crate) fn dual_filter_diff_hits() -> usize {
4888 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
4889}
4890
4891/// Current value of [`COMPOUND8_FILTER_HITS`].
4892#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4893pub(crate) fn compound8_filter_hits() -> usize {
4894 COMPOUND8_FILTER_HITS.with(|c| c.get())
4895}
4896
4897// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
4898// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
4899// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
4900// -- the gate's proof that a fixture really exercises the alphabet this
4901// round changed, even though the block itself still refuses (warp
4902// estimation/filter not ported).
4903thread_local! {
4904 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
4905 const { std::cell::Cell::new(0) };
4906}
4907
4908/// Current value of [`WARP_SELECTED_HITS`].
4909#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4910pub(crate) fn warp_selected_hits() -> usize {
4911 WARP_SELECTED_HITS.with(|c| c.get())
4912}
4913
4914// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
4915// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
4916// into the compound intermediate) rather than translationally -- the
4917// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
4918// really reached [`crate::warp::warp_affine_compound`].
4919// lane-av1422warp: the 4:2:2 coverage witness has to show compound and warped
4920// motion firing ABOVE the vertical midpoint, and every pre-existing warp
4921// counter is frame-global. These two are the same arms restricted to blocks
4922// whose top mode-info row is in the frame's upper half, which is the half
4923// this lane's evidence covers.
4924thread_local! {
4925 static TOP_HALF_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4926 static TOP_HALF_WARP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4927}
4928
4929/// How many `GLOBAL_GLOBALMV` (compound) inter blocks decoded in the frame's
4930/// upper half -- the block's top mode-info row is under `mi_rows / 2`.
4931///
4932/// NO COMMITTED TEST READS THIS, and none can while the 4:2:2 header refusal
4933/// stands: the pinned 4:2:2 coverage gate asserts the byte pin and the
4934/// refusal by name, so nothing in the suite ever decodes a 4:2:2 stream.
4935/// The figure quoted for that fixture comes from a patch-run-restore build
4936/// with the `EC_AV1_ALLOW_422_PROBE` bypass applied and then reverted, which
4937/// is the same discipline every 4:2:2 lane in this family uses.
4938#[allow(dead_code)]
4939pub(crate) fn top_half_compound_hits() -> usize {
4940 TOP_HALF_COMPOUND_HITS.with(std::cell::Cell::get)
4941}
4942
4943/// How many inter blocks in the frame's upper half satisfy libaom's
4944/// `is_global_mv_block` on at least one reference slot -- mode
4945/// `GLOBAL_GLOBALMV` AND block >= 8x8 AND that slot's own global-motion
4946/// model > `TRANSLATION`. This is the block set whose prediction goes
4947/// through `crate::warp`, and it is exactly `is_global_mv0 || is_global_mv1`
4948/// as computed at the increment site; it is NOT merely "some slot has a
4949/// non-TRANSLATION model", which also counts blocks that are not global-mv
4950/// blocks.
4951///
4952/// Like [`top_half_compound_hits`], no committed test reads it: with the
4953/// 4:2:2 header refusal in force nothing in the suite decodes the stream
4954/// these numbers describe.
4955#[allow(dead_code)]
4956pub(crate) fn top_half_warp_hits() -> usize {
4957 TOP_HALF_WARP_HITS.with(std::cell::Cell::get)
4958}
4959
4960thread_local! {
4961 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
4962 const { std::cell::Cell::new(0) };
4963}
4964
4965/// Current value of [`COMPOUND_WARP_HITS`].
4966#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4967pub(crate) fn compound_warp_hits() -> usize {
4968 COMPOUND_WARP_HITS.with(|c| c.get())
4969}
4970
4971// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
4972// arm ([`decode_inter_block8`]) -- that arm predicted both taps
4973// translationally until r3, so a gate needs to tell a warped 8x8 compound
4974// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
4975thread_local! {
4976 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
4977 const { std::cell::Cell::new(0) };
4978}
4979
4980/// Current value of [`COMPOUND_WARP_HITS_8`].
4981#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4982pub(crate) fn compound_warp_hits_8() -> usize {
4983 COMPOUND_WARP_HITS_8.with(|c| c.get())
4984}
4985
4986// lane-gmaffine r1: how many blocks built their prediction from a
4987// SIX-parameter (`AFFINE`) global-motion model through
4988// `crate::warp::global_warp_params` -- the gate's proof that a stream really
4989// carried an AFFINE `global_motion_params` AND that a block was predicted
4990// with it, not merely that the header parsed one.
4991thread_local! {
4992 static AFFINE_GM_HITS: std::cell::Cell<usize> =
4993 const { std::cell::Cell::new(0) };
4994}
4995
4996/// Current value of [`AFFINE_GM_HITS`].
4997#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4998pub(crate) fn affine_gm_hits() -> usize {
4999 AFFINE_GM_HITS.with(|c| c.get())
5000}
5001
5002// lane-av1gwarp12: how many 16x16+ blocks built their SINGLE-reference
5003// prediction through `crate::warp::global_warp_params` with a FOUR-parameter
5004// (`ROTZOOM`) model. Vanilla aomenc pins its global-motion search to ROTZOOM
5005// (`global_motion_facade.c:24`), so this is the only >TRANSLATION single-ref
5006// global-warp arm a real aomenc stream can reach (AFFINE needs the widened
5007// side build and its own counter, [`AFFINE_GM_HITS`]).
5008thread_local! {
5009 static ROTZOOM_GM_WARP_HITS: std::cell::Cell<usize> =
5010 const { std::cell::Cell::new(0) };
5011}
5012
5013/// Current value of [`ROTZOOM_GM_WARP_HITS`].
5014#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5015pub(crate) fn rotzoom_gm_warp_hits() -> usize {
5016 ROTZOOM_GM_WARP_HITS.with(|c| c.get())
5017}
5018
5019// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
5020// differently at the block's WIDTH than at libaom's
5021// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
5022// pick the wrong motion_mode alphabet.
5023thread_local! {
5024 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5025}
5026
5027/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
5028pub fn tr_reach_longer_side_hits() -> usize {
5029 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
5030}
5031
5032// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
5033// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
5034// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
5035// reads its interp-filter symbol. Counts the blocks where that guard flips
5036// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
5037// and a 4-px side, which we used to suppress the interp read on (a pre-mode
5038// entropy desync one symbol wide).
5039thread_local! {
5040 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5041}
5042
5043/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
5044pub fn gm_nontrans_small_side_hits() -> usize {
5045 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
5046}
5047
5048// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
5049// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
5050// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
5051// only once `find_projection` returned a usable model, unlike
5052// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
5053// proof that the leaf path itself fired, not the 16x16+ one.
5054thread_local! {
5055 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5056 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5057}
5058
5059/// Current value of [`GLOBALMV_HITS_8`].
5060#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5061pub(crate) fn globalmv_hits_8() -> usize {
5062 GLOBALMV_HITS_8.with(|c| c.get())
5063}
5064
5065/// Current value of [`WARP_HITS_8`].
5066#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5067pub(crate) fn warp_hits_8() -> usize {
5068 WARP_HITS_8.with(|c| c.get())
5069}
5070
5071// How many blocks decoded `interintra == 1` with the non-wedge blended
5072// prediction applied (lane-interintra r1) -- the gate's proof that a
5073// stream actually exercised interintra.
5074thread_local! {
5075 static INTERINTRA_HITS: std::cell::Cell<usize> =
5076 const { std::cell::Cell::new(0) };
5077}
5078
5079/// Current value of [`INTERINTRA_HITS`].
5080#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5081pub(crate) fn interintra_hits() -> usize {
5082 INTERINTRA_HITS.with(|c| c.get())
5083}
5084
5085// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
5086// -- the shape `interintra_blend` used to build a square `side x side` intra
5087// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
5088// pre-existing interintra gate passed with that bug, so the rect arm needs
5089// its own counter to stop being vacuous.
5090thread_local! {
5091 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5092}
5093
5094/// Current value of [`INTERINTRA_RECT_HITS`].
5095pub fn interintra_rect_hits() -> usize {
5096 INTERINTRA_RECT_HITS.with(|c| c.get())
5097}
5098
5099// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
5100// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
5101// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
5102// gate fixture actually exercises this alphabet, even though the block
5103// still refuses (the mask blend itself is unported).
5104thread_local! {
5105 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5106 const { std::cell::Cell::new(0) };
5107}
5108
5109/// Current value of [`MASKED_COMPOUND_HITS`].
5110#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5111pub(crate) fn masked_compound_hits() -> usize {
5112 MASKED_COMPOUND_HITS.with(|c| c.get())
5113}
5114
5115// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
5116// masked-compound block whose true footprint is rectangular, i.e. the case
5117// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
5118// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
5119// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
5120thread_local! {
5121 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5122 const { std::cell::Cell::new(0) };
5123}
5124
5125/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
5126#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5127pub(crate) fn rect_masked_compound_hits() -> usize {
5128 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
5129}
5130
5131// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
5132// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
5133// actually exercised the wedge blend, not just the DIFFWTD half of
5134// `MASKED_COMPOUND_HITS`.
5135thread_local! {
5136 static WEDGE_HITS: std::cell::Cell<usize> =
5137 const { std::cell::Cell::new(0) };
5138}
5139
5140/// Current value of [`WEDGE_HITS`].
5141#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5142pub(crate) fn wedge_hits() -> usize {
5143 WEDGE_HITS.with(|c| c.get())
5144}
5145
5146// How many blocks decoded a real wedge-INTERINTRA block
5147// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
5148// a gate fixture exercised the wedge blend (fixed sign 0), not just the
5149// smooth arm counted by `INTERINTRA_HITS`.
5150thread_local! {
5151 static WII_HITS: std::cell::Cell<usize> =
5152 const { std::cell::Cell::new(0) };
5153}
5154
5155/// Current value of [`WII_HITS`].
5156#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5157pub(crate) fn wii_hits() -> usize {
5158 WII_HITS.with(|c| c.get())
5159}
5160
5161// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
5162// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
5163// wide <= 32 && high <= 32). The witness that a gate stream really carries a
5164// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
5165// frame carrying one.
5166thread_local! {
5167 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5168}
5169
5170/// Current value of [`NOCFL_UV_MODE_HITS`].
5171#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5172pub(crate) fn nocfl_uv_mode_hits() -> usize {
5173 NOCFL_UV_MODE_HITS.with(|c| c.get())
5174}
5175
5176/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
5177/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
5178pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
5179 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
5180
5181fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
5182 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
5183}
5184
5185// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
5186// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
5187// the rect wedge masks lifted this round actually fired, not just the square
5188// ones already counted by `WEDGE_HITS`/`WII_HITS`.
5189thread_local! {
5190 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5191 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5192}
5193
5194/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5195pub(crate) fn rect_wedge_hits() -> [usize; 6] {
5196 RECT_WEDGE_HITS.with(|c| c.get())
5197}
5198
5199/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5200pub(crate) fn rect_wii_hits() -> [usize; 6] {
5201 RECT_WII_HITS.with(|c| c.get())
5202}
5203
5204// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
5205// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
5206// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
5207// aomdec, neighbour list included).
5208thread_local! {
5209 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5210}
5211
5212/// Current value of [`OBMC_RECT_LEAF_HITS`].
5213pub(crate) fn obmc_rect_leaf_hits() -> usize {
5214 OBMC_RECT_LEAF_HITS.with(|c| c.get())
5215}
5216
5217// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
5218// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
5219// to be read from the pair's FIRST mi, which is a different block and, when
5220// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
5221// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
5222thread_local! {
5223 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5224}
5225
5226/// Current value of [`OBMC_PAIR_FILTER_HITS`].
5227pub(crate) fn obmc_pair_filter_hits() -> usize {
5228 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
5229}
5230
5231// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
5232// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
5233// own side, so a block overhanging the bottom/right still predicts the full
5234// neighbour strip (the destination write is what clips). We used to shrink the
5235// prediction to the visible part, which at 4 chroma rows/cols also swaps the
5236// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
5237thread_local! {
5238 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5239}
5240
5241/// Current value of [`OBMC_EDGE_SPAN_HITS`].
5242#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5243pub(crate) fn obmc_edge_span_hits() -> usize {
5244 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
5245}
5246
5247/// Current value of [`OBMC_HITS_8`].
5248#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5249pub(crate) fn obmc_hits_8() -> usize {
5250 OBMC_HITS_8.with(|c| c.get())
5251}
5252
5253// lane-rectgate r1: how many 32x32 quadrants actually decoded a
5254// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
5255// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
5256// `VERT_B` all still fall into the generic "a partition type this encoder
5257// never writes" refusal below) -- the gate's proof that a free-partition
5258// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
5259// coincidentally never selecting one.
5260thread_local! {
5261 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
5262 const { std::cell::Cell::new(0) };
5263}
5264
5265/// Current value of [`EXTENDED_PARTITION_HITS`].
5266#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5267pub(crate) fn extended_partition_hits() -> usize {
5268 EXTENDED_PARTITION_HITS.with(|c| c.get())
5269}
5270
5271// lane-partitions r1: how many 32x32 quadrants decoded a real
5272// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
5273// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
5274// gate's proof this round's arms actually fired.
5275thread_local! {
5276 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
5277 const { std::cell::Cell::new(0) };
5278}
5279
5280/// Current value of [`RECT_PARTITION_HITS`].
5281#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5282pub(crate) fn rect_partition_hits() -> usize {
5283 RECT_PARTITION_HITS.with(|c| c.get())
5284}
5285
5286// lane-inter8 r1: how many superblocks an inter tile coded as a single
5287// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
5288// static content, previously a named refusal).
5289thread_local! {
5290 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
5291 /// path decoded as one whole block (its gate's own witness).
5292 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5293 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
5294 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5295 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5296}
5297
5298/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
5299pub(crate) fn inter_sb128_horz_hits() -> usize {
5300 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
5301}
5302
5303/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
5304pub(crate) fn inter_sb128_vert_hits() -> usize {
5305 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
5306}
5307
5308/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
5309pub fn inter_sb128_none_hits() -> usize {
5310 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
5311}
5312
5313thread_local! {
5314 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
5315 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
5316 /// units) -- the gate's witness that the lifted refusal's case fired.
5317 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5318}
5319
5320/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
5321pub fn intra_128_in_inter_hits() -> usize {
5322 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
5323}
5324
5325thread_local! {
5326 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
5327 const { std::cell::Cell::new(0) };
5328}
5329
5330/// Current value of [`INTER_SB_NONE_HITS`].
5331#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5332pub(crate) fn inter_sb_none_hits() -> usize {
5333 INTER_SB_NONE_HITS.with(|c| c.get())
5334}
5335
5336// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
5337// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
5338// path has always run that loop, so only this counter proves the newly-lifted
5339// alphabet value fired.
5340thread_local! {
5341 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
5342 const { std::cell::Cell::new(0) };
5343}
5344
5345/// Current value of [`INTER_SUB16_SPLIT_HITS`].
5346#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5347pub(crate) fn inter_sub16_split_hits() -> usize {
5348 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
5349}
5350
5351// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
5352// while at least one reference picture was SCALED (superres) -- the counter
5353// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
5354thread_local! {
5355 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
5356 const { std::cell::Cell::new(0) };
5357}
5358
5359/// Current value of [`SCALED_LEAF8_HITS`].
5360pub fn scaled_leaf8_hits() -> usize {
5361 SCALED_LEAF8_HITS.with(|c| c.get())
5362}
5363
5364// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
5365// rect pair) were predicted from a SCALED reference -- the counter behind the
5366// lifted "sub-8x8 inter block under a scaled reference" refusal.
5367thread_local! {
5368 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
5369 const { std::cell::Cell::new(0) };
5370}
5371
5372/// Current value of [`SCALED_SUB8_HITS`].
5373pub fn scaled_sub8_hits() -> usize {
5374 SCALED_SUB8_HITS.with(|c| c.get())
5375}
5376
5377// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
5378// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
5379// rect coefficient reader itself fired, not just the strip-level partition
5380// symbol [`RECT_PARTITION_HITS`] already counts.
5381thread_local! {
5382 static RECT_COEFF_HITS: std::cell::Cell<usize> =
5383 const { std::cell::Cell::new(0) };
5384}
5385
5386/// Current value of [`RECT_COEFF_HITS`].
5387#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5388pub(crate) fn rect_coeff_hits() -> usize {
5389 RECT_COEFF_HITS.with(|c| c.get())
5390}
5391
5392// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
5393// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
5394// charter's real-aomenc gate hard-asserts.
5395thread_local! {
5396 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
5397 const { std::cell::Cell::new(0) };
5398}
5399
5400/// Current value of [`RECT_LEAF_COEFF_HITS`].
5401#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5402pub(crate) fn rect_leaf_coeff_hits() -> usize {
5403 RECT_LEAF_COEFF_HITS.with(|c| c.get())
5404}
5405
5406// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
5407// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
5408// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
5409// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
5410// needs rectangular intra prediction" before this round.
5411thread_local! {
5412 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
5413 const { std::cell::Cell::new([0; 3]) };
5414}
5415
5416/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
5417/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
5418#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5419pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
5420 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
5421}
5422
5423// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
5424// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
5425// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
5426// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
5427// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
5428// a single counter cannot tell an axis swap from a working arm
5429// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
5430thread_local! {
5431 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
5432 const { std::cell::Cell::new([0; 2]) };
5433}
5434
5435/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
5436/// (0 = 64x32, 1 = 32x64).
5437pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
5438 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
5439}
5440
5441// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
5442// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
5443// is never incremented) -- the gate's proof that the lifted path ran per depth.
5444thread_local! {
5445 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
5446 const { std::cell::Cell::new([0; 3]) };
5447}
5448
5449// lane-t900 r21: rect intra strips inside an inter frame that read the
5450// screen-content palette syntax (`allow_screen_content_tools` set and the
5451// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
5452// refusal used to guard, so this counter is what keeps its witness gate
5453// non-vacuous.
5454thread_local! {
5455 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5456}
5457
5458/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
5459#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5460pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
5461 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
5462}
5463
5464/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
5465#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5466pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
5467 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
5468}
5469
5470/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
5471#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5472pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
5473 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
5474}
5475
5476// lane-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid
5477// approximation would have resolved off a DIFFERENT CDF row than the real
5478// `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY
5479// frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block"
5480// tally is green on the old code too (class gate-blind-to-feature).
5481thread_local! {
5482 static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell<usize> =
5483 const { std::cell::Cell::new(0) };
5484}
5485
5486/// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`].
5487#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
5488pub(crate) fn txctx_deblock_divergence_hits() -> usize {
5489 TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get)
5490}
5491
5492// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
5493// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
5494// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
5495// rect strip on the inter block path" before this round.
5496thread_local! {
5497 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
5498 const { std::cell::Cell::new([0; 4]) };
5499}
5500
5501/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
5502/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
5503pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
5504 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
5505}
5506
5507// lane-av1444rect: how many 1:4 inter strips at `ss_x == 0` read their chroma
5508// coefficient context over the STRIP'S OWN extent instead of the 4:2:0 pair's
5509// (see [`decode_inter_block`]'s `around_c`). `is_chroma_reference`
5510// (av1_common_int.h:1454) is unconditionally true at ss (0,0), so no pair
5511// exists there; the counter is what keeps a 4:4:4 1:4-strip gate from passing
5512// vacuously (a 4:2:0 stream of the same content leaves it at 0).
5513thread_local! {
5514 static RECT4_INTER_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5515}
5516
5517/// Current value of [`RECT4_INTER_OWN_CHROMA444_HITS`].
5518#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5519pub(crate) fn rect4_inter_own_chroma444_hits() -> usize {
5520 RECT4_INTER_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
5521}
5522
5523/// Resets [`RECT4_INTER_OWN_CHROMA444_HITS`] before a decode.
5524#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5525pub(crate) fn reset_rect4_inter_own_chroma444_hits() {
5526 RECT4_INTER_OWN_CHROMA444_HITS.with(|c| c.set(0));
5527}
5528
5529// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
5530// through one of the key-frame rect readers ([`decode_block_rect4`],
5531// [`decode_block_rect64`]). `Some((size_group, skip))` tells
5532// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
5533// already read by [`decode_inter_block`] and (b) the luma mode comes off
5534// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
5535// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
5536
5537// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
5538// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
5539// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
5540// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
5541thread_local! {
5542 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
5543 const { std::cell::Cell::new(0) };
5544}
5545
5546/// Current value of [`MODE_MI_OVERRIDE_HITS`].
5547#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5548pub(crate) fn mode_mi_override_hits() -> usize {
5549 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
5550}
5551
5552// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
5553// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
5554// mode from the previous tile, where libaom's `up_available`/`left_available`
5555// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
5556// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
5557// per superblock row in `start_row`, so the luma fallback cannot leak the way
5558// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
5559// the invariant that makes the coarse fallback safe.
5560thread_local! {
5561 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
5562 const { std::cell::Cell::new(0) };
5563}
5564
5565/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
5566#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5567pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
5568 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
5569}
5570
5571// lane-cfl r1: how many times a chroma intra-edge filter-type read
5572// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
5573// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
5574// r1 defect would have filtered a chroma edge with the wrong strength.
5575thread_local! {
5576 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
5577 const { std::cell::Cell::new(0) };
5578}
5579
5580/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
5581#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5582pub(crate) fn uv_mode_mi_override_hits() -> usize {
5583 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
5584}
5585
5586// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
5587// `uv_mode` from the mi GRID where the one-slot-per-column map would have
5588// answered differently -- the sub-8x8 pair case where the pair's own first
5589// half had already overwritten the column slot the chroma-ref half reads.
5590thread_local! {
5591 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
5592 const { std::cell::Cell::new(0) };
5593}
5594
5595/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
5596pub fn uv_mode_grid_override_hits() -> usize {
5597 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
5598}
5599
5600// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
5601// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
5602// from an earlier block in that pixel row/column while the mi-exact map --
5603// which an inter block only started writing this round -- correctly says the
5604// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
5605// an INTER mode, and its `uv_mode` "is not set for inter blocks").
5606thread_local! {
5607 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
5608 const { std::cell::Cell::new(0) };
5609}
5610
5611/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
5612#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5613pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
5614 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
5615}
5616
5617// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
5618// suppressed at a TILE edge that is not a frame edge -- the above/left
5619// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
5620// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
5621// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
5622// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
5623// above would decide this tile's chroma edge filter strength.
5624thread_local! {
5625 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
5626 const { std::cell::Cell::new(0) };
5627}
5628
5629/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
5630#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5631pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
5632 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
5633}
5634
5635// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
5636// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
5637// shapes the r1 chroma defect showed up on.
5638thread_local! {
5639 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5640 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5641}
5642
5643/// Current value of [`CFL_BLOCK_HITS`].
5644#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5645pub(crate) fn cfl_block_hits() -> usize {
5646 CFL_BLOCK_HITS.with(|c| c.get())
5647}
5648
5649/// Current value of [`UV_ANGLE_DELTA_HITS`].
5650#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5651pub(crate) fn uv_angle_delta_hits() -> usize {
5652 UV_ANGLE_DELTA_HITS.with(|c| c.get())
5653}
5654
5655// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
5656// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
5657// gate's proof this round's arms actually reached a real block, not just
5658// that `partition_w64` read one of those two symbol values.
5659thread_local! {
5660 static SB_RECT_HITS: std::cell::Cell<usize> =
5661 const { std::cell::Cell::new(0) };
5662}
5663
5664// Current value of [`SB_RECT_HITS`].
5665// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
5666// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
5667// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
5668// non-SPLIT edge arm actually decoded (before this round the bit was read and
5669// thrown away, so that arm was unreachable).
5670thread_local! {
5671 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
5672}
5673
5674/// Current value of [`EDGE_PART_HITS`].
5675#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5676pub(crate) fn edge_part_hits() -> [usize; 4] {
5677 EDGE_PART_HITS.with(|c| c.get())
5678}
5679
5680/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
5681#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5682pub(crate) fn reset_edge_part_hits() {
5683 EDGE_PART_HITS.with(|c| c.set([0; 4]));
5684}
5685
5686fn bump_edge_part(slot: usize) {
5687 hit_do! {
5688 EDGE_PART_HITS.with(|c| {
5689 let mut h = c.get();
5690 h[slot] += 1;
5691 c.set(h);
5692 });
5693 }
5694}
5695
5696#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5697pub(crate) fn sb_rect_hits() -> usize {
5698 SB_RECT_HITS.with(|c| c.get())
5699}
5700
5701// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
5702// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
5703// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
5704// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
5705// paths (intra and inter) feed the same counter.
5706//
5707// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
5708// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
5709// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
5710// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
5711// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
5712// every SB of the last row), so the 32-level slots stay 0 on that content and
5713// only these prove the arm fired.
5714thread_local! {
5715 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
5716 const { std::cell::Cell::new([0; 8]) };
5717}
5718
5719/// Current value of [`EDGE32_HITS`].
5720#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5721pub(crate) fn edge32_hits() -> [usize; 8] {
5722 EDGE32_HITS.with(|c| c.get())
5723}
5724
5725/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
5726/// reads are `if`-conditions, so the counter has to ride the expression.
5727fn bump_edge32_bit(base: usize, bit: usize) -> usize {
5728 bump_edge32(base + bit.min(1));
5729 bit
5730}
5731
5732fn bump_edge32(slot: usize) {
5733 hit_do! {
5734 EDGE32_HITS.with(|c| {
5735 let mut h = c.get();
5736 h[slot] += 1;
5737 c.set(h)
5738 });
5739 }
5740}
5741
5742// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
5743// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
5744// strip) fired. Real aomenc picks these at 64 even with
5745// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
5746// the counter the gate hard-asserts.
5747thread_local! {
5748 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
5749 const { std::cell::Cell::new([0; 4]) };
5750}
5751
5752/// Current value of [`SB_AB_HITS`], summed over the four arms.
5753#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5754pub(crate) fn sb_ab_hits() -> usize {
5755 SB_AB_HITS.with(|c| c.get().iter().sum())
5756}
5757
5758/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
5759/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
5760/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
5761/// proof of all four.
5762#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5763pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
5764 SB_AB_HITS.with(std::cell::Cell::get)
5765}
5766
5767// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
5768// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
5769// strips). Two counters, not one, because a gate that only proved "some 1:4
5770// strip fired" would pass on a stream that never coded the other axis, and
5771// every scan/context table this round added comes in a transposed pair.
5772thread_local! {
5773 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5774 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5775}
5776
5777/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
5778#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5779pub(crate) fn sb_rect4_horz_hits() -> usize {
5780 SB_RECT4_HORZ_HITS.with(|c| c.get())
5781}
5782
5783/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
5784#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5785pub(crate) fn sb_rect4_vert_hits() -> usize {
5786 SB_RECT4_VERT_HITS.with(|c| c.get())
5787}
5788
5789// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
5790// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
5791// strips), the arms the ReelB mid-film extract stops at.
5792thread_local! {
5793 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5794 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5795 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
5796 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
5797 /// `PARTITION_VERT_4`.
5798 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5799 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5800 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
5801 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
5802 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5803 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5804 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5805 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5806}
5807
5808// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
5809// a gate that only counted strips would pass on an all-skip stream, which
5810// exercises none of the new scan/context tables.
5811thread_local! {
5812 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5813}
5814
5815// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
5816// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
5817// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
5818// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
5819// counts the same for a 16x8/8x16 strip below 16x16.
5820thread_local! {
5821 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5822 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5823 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5824}
5825
5826/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
5827#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5828pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
5829 (
5830 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
5831 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
5832 )
5833}
5834
5835/// Current value of `SUB16_SPLIT_HITS`.
5836#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5837pub(crate) fn sub16_split_hits() -> usize {
5838 SUB16_SPLIT_HITS.with(|c| c.get())
5839}
5840
5841// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
5842// luma transform is SPLIT and which therefore leave through that fn's early
5843// return -- the arm that published no `TXFM_CONTEXT` band until this round.
5844thread_local! {
5845 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5846}
5847
5848/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
5849#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5850pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
5851 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
5852}
5853
5854/// Current value of `RECT4_COEFF_HITS`.
5855pub(crate) fn rect4_coeff_hits() -> usize {
5856 RECT4_COEFF_HITS.with(|c| c.get())
5857}
5858
5859// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
5860// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
5861// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
5862// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
5863// asserts the arms it proves separately so a run whose RD only picked one
5864// cannot pass as proof of the others.
5865thread_local! {
5866 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
5867}
5868
5869/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
5870/// inter frame).
5871pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
5872 SB_AB_INTER_HITS.with(std::cell::Cell::get)
5873}
5874
5875// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
5876// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
5877// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
5878// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
5879// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
5880// arm separately so a run whose RD only picked one cannot pass as proof of
5881// four.
5882thread_local! {
5883 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
5884}
5885
5886/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
5887/// inter frame).
5888pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
5889 AB16_INTER_HITS.with(std::cell::Cell::get)
5890}
5891
5892// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
5893// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
5894// counts the odd strips that close a 4:2:0 chroma pair
5895// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
5896// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
5897// the PREVIOUS strip's own mv/ref/filters -- libaom
5898// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
5899// through `is_sub8x8_inter` (same file, :54).
5900thread_local! {
5901 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5902 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5903 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5904 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5905}
5906
5907// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
5908// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
5909// pair's single 8x4 (4x8) chroma unit for BOTH strips.
5910thread_local! {
5911 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
5912 const { std::cell::Cell::new([0; 3]) };
5913}
5914
5915/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
5916/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
5917pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
5918 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
5919 (v[0], v[1], v[2])
5920}
5921
5922/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
5923/// strips, chroma pairs closed, chroma pairs built from two different
5924/// strips' motion vectors)`.
5925pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
5926 (
5927 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
5928 INTER16_VERT4_HITS.with(std::cell::Cell::get),
5929 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
5930 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
5931 )
5932}
5933
5934/// One 16x4 / 4x16 inter strip's chroma situation, handed to
5935/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
5936/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
5937/// that all mean "an ordinary block, chroma of its own".
5938#[derive(Clone, Copy)]
5939pub(crate) struct InterStripChroma {
5940 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
5941 /// read and reconstruct NO chroma at all.
5942 has_chroma: bool,
5943 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
5944 horz: bool,
5945 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
5946 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
5947 /// i.e. the origin of the 8x4 (4x8) chroma transform.
5948 pair_mi: (usize, usize),
5949 /// The previous (even) strip's single-reference MC parameters, `None`
5950 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
5951 /// and the whole chroma block is predicted from THIS strip's mv.
5952 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
5953}
5954
5955/// The single-reference MC parameters of the inter block that decoded
5956/// last -- read by the next 1:4 strip to build its pair's chroma.
5957
5958fn bump_ab16_inter(arm: usize) {
5959 hit_do! {
5960 AB16_INTER_HITS.with(|c| {
5961 let mut v = c.get();
5962 v[arm] += 1;
5963 c.set(v);
5964 });
5965 }
5966}
5967
5968// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
5969// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
5970// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
5971thread_local! {
5972 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5973 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5974 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5975 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5976 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5977 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
5978 /// base mi differs from what the strip's own (odd) mi would have said --
5979 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
5980 /// key frame miss by 1. Zero here means a gate never exercised the fix.
5981 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5982 /// lane-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s.
5983 static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5984 /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip.
5985 static RECT4_16_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5986 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
5987 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
5988 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5989 /// lane-av1-loss64: chroma transform units the frame-edge clip skipped
5990 /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in
5991 /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless
5992 /// block overhanging the frame does NOT code.
5993 static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5994 /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma
5995 /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`,
5996 /// decodeframe.c:1262) instead of leaking the previous occupant's.
5997 static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5998 /// lane-av1-llband: 4x4 chroma transform units a lossless HORZ/VERT strip
5999 /// walked at subsampling 0/0 (one unit per mi cell -- the geometry the
6000 /// hardcoded 4:2:0 span mis-stepped).
6001 static RECT_SPLIT_LOSSLESS_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6002 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma
6003 /// coefficients a lossless frame walked as per-4x4 inter units (the walk
6004 /// that replaced the single rect unit).
6005 static INTRABC_RECT8_LOSSLESS_LUMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6006 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a
6007 /// lossless 4:4:4 frame walked as per-4x4 [`TxbSet::Chroma4`] units.
6008 static INTRABC_RECT8_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6009}
6010
6011/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
6012/// that reconstructed as flat DC before lane-kf1200 r2).
6013pub fn skip_cfl_hits() -> usize {
6014 SKIP_CFL_HITS.with(|c| c.get())
6015}
6016
6017/// How many chroma transform units the frame-edge clip skipped in
6018/// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a
6019/// stream whose lossless blocks never overhang the frame -- a gate asserting
6020/// the clip fired must see this nonzero.
6021pub fn chroma_edge_tu_clip_hits() -> usize {
6022 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get())
6023}
6024
6025/// How many skipped lossless intrabc rect strips had their luma entropy
6026/// bands zeroed per unit (lane-av1-loss64).
6027pub fn skip_lossless_band_reset_hits() -> usize {
6028 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get())
6029}
6030
6031/// How many 4x4 chroma transform units a lossless HORZ/VERT strip walked at
6032/// subsampling 0/0 (lane-av1-llband). Zero means a stream never decoded the
6033/// 4:4:4 lossless unit walk this counter proves -- a gate asserting the fix
6034/// must see this nonzero.
6035pub fn rect_split_lossless_chroma444_hits() -> usize {
6036 RECT_SPLIT_LOSSLESS_CHROMA444_HITS.with(|c| c.get())
6037}
6038
6039/// How many unskipped intrabc 8x4/4x8 leaves a lossless frame walked luma as
6040/// per-4x4 inter units (lane-av1-ibc444rect).
6041pub fn intrabc_rect8_lossless_luma_hits() -> usize {
6042 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.get())
6043}
6044
6045/// How many unskipped intrabc 8x4/4x8 leaves a lossless 4:4:4 frame walked
6046/// chroma as per-4x4 [`TxbSet::Chroma4`] units (lane-av1-ibc444rect).
6047pub fn intrabc_rect8_lossless_chroma_hits() -> usize {
6048 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6049}
6050
6051/// Gate-side reset for the two lane-av1-ibc444rect counters above.
6052pub fn reset_ibc444rect_hits() {
6053 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.set(0));
6054 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6055}
6056
6057/// Gate-side reset for the two lane-av1-loss64 counters above.
6058pub fn reset_loss64_hits() {
6059 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0));
6060 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0));
6061}
6062
6063/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
6064/// from the pair's base mi than the strip's own mi would have given.
6065pub fn rect4_16_uv_pair_filt_hits() -> usize {
6066 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
6067}
6068
6069/// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane.
6070pub fn rect4_16_lossless_chroma_hits() -> usize {
6071 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6072}
6073
6074/// How many 16x4/4x16 strips reconstructed as intra block copy.
6075pub fn rect4_16_intrabc_hits() -> usize {
6076 RECT4_16_INTRABC_HITS.with(|c| c.get())
6077}
6078
6079/// Zero the lane-av1-rect14 pair counters so a gate measures one stream.
6080pub fn reset_rect4_16_pair_hits() {
6081 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6082 RECT4_16_INTRABC_HITS.with(|c| c.set(0));
6083}
6084
6085// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
6086// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
6087// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
6088// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
6089// intra-edge filter type must come from the chroma-reference position).
6090thread_local! {
6091 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6092 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6093}
6094
6095/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
6096pub fn reelc_chroma_counters() -> (usize, usize) {
6097 (
6098 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
6099 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
6100 )
6101}
6102
6103/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
6104/// strips, chroma-reference strips, strips with a coded residual, strips
6105/// whose luma transform is split)`.
6106pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
6107 (
6108 RECT4_16_HORZ_HITS.with(|c| c.get()),
6109 RECT4_16_VERT_HITS.with(|c| c.get()),
6110 RECT4_16_CHROMA_HITS.with(|c| c.get()),
6111 RECT4_16_COEFF_HITS.with(|c| c.get()),
6112 RECT4_16_SPLIT_HITS.with(|c| c.get()),
6113 )
6114}
6115
6116/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
6117pub(crate) fn rect4_32_horz_hits() -> usize {
6118 RECT4_32_HORZ_HITS.with(|c| c.get())
6119}
6120
6121/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
6122pub(crate) fn rect4_32_vert_hits() -> usize {
6123 RECT4_32_VERT_HITS.with(|c| c.get())
6124}
6125
6126/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
6127pub(crate) fn rect4_32_horz_inter_hits() -> usize {
6128 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
6129}
6130
6131/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
6132pub(crate) fn rect4_32_vert_inter_hits() -> usize {
6133 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
6134}
6135
6136/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
6137pub(crate) fn inter_sb_horz_hits() -> usize {
6138 INTER_SB_HORZ_HITS.with(|c| c.get())
6139}
6140
6141/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
6142pub(crate) fn inter_sb_vert_hits() -> usize {
6143 INTER_SB_VERT_HITS.with(|c| c.get())
6144}
6145
6146/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
6147pub(crate) fn inter_sb_horz4_hits() -> usize {
6148 INTER_SB_HORZ4_HITS.with(|c| c.get())
6149}
6150
6151/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
6152pub(crate) fn inter_sb_vert4_hits() -> usize {
6153 INTER_SB_VERT4_HITS.with(|c| c.get())
6154}
6155
6156// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
6157// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
6158// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
6159// just inert-compiled. Zero forever on a passing gate means that gate's
6160// stream never carries `delta_q_present=1` through a rect64 block.
6161thread_local! {
6162 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
6163 const { std::cell::Cell::new(0) };
6164}
6165
6166/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
6167#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6168pub(crate) fn rect64_qidx_drift_hits() -> usize {
6169 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
6170}
6171
6172// lane-partab r1: how many 32x32 quadrants decoded an AB partition
6173// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
6174// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
6175// free-partition gate's proof this round's arms actually fired.
6176thread_local! {
6177 static PARTAB_HITS: std::cell::Cell<usize> =
6178 const { std::cell::Cell::new(0) };
6179}
6180
6181/// Current value of [`PARTAB_HITS`].
6182#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6183pub(crate) fn partab_hits() -> usize {
6184 PARTAB_HITS.with(|c| c.get())
6185}
6186
6187// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
6188// one counter per arm rather than one shared total -- the gate hard-asserts
6189// each of these individually nonzero so a recipe that only ever fires
6190// HORZ_A can't silently stand in for the whole set.
6191thread_local! {
6192 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
6193 const { std::cell::Cell::new(0) };
6194 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
6195 const { std::cell::Cell::new(0) };
6196 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
6197 const { std::cell::Cell::new(0) };
6198 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
6199 const { std::cell::Cell::new(0) };
6200}
6201
6202/// Current value of [`INTRA_HORZ_A_HITS`].
6203#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6204pub(crate) fn intra_horz_a_hits() -> usize {
6205 INTRA_HORZ_A_HITS.with(|c| c.get())
6206}
6207/// Current value of [`INTRA_HORZ_B_HITS`].
6208#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6209pub(crate) fn intra_horz_b_hits() -> usize {
6210 INTRA_HORZ_B_HITS.with(|c| c.get())
6211}
6212/// Current value of [`INTRA_VERT_A_HITS`].
6213#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6214pub(crate) fn intra_vert_a_hits() -> usize {
6215 INTRA_VERT_A_HITS.with(|c| c.get())
6216}
6217/// Current value of [`INTRA_VERT_B_HITS`].
6218#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6219pub(crate) fn intra_vert_b_hits() -> usize {
6220 INTRA_VERT_B_HITS.with(|c| c.get())
6221}
6222
6223// How many [`read_inter_compound_mode`] reads actually happened
6224// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
6225// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
6226// mvstack build), not just that `comp_mode` fired. Still refused right
6227// after (no MV assignment or MC wired), so this only counts attempted
6228// reads.
6229thread_local! {
6230 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
6231 const { std::cell::Cell::new(0) };
6232}
6233
6234/// Current value of [`COMPOUND_MODE_HITS`].
6235#[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds
6236pub(crate) fn compound_mode_hits() -> usize {
6237 COMPOUND_MODE_HITS.with(|c| c.get())
6238}
6239
6240/// How many query blocks folded in at least one temporal MV candidate
6241/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
6242/// temporal-MV gate's own firing counter (lane-av1tmvp).
6243///
6244/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
6245/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
6246/// this file (`decode_inter_block`) still passes `tpl: None` -- this
6247/// counter compiles and the projection math it counts is unit-tested
6248/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
6249/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
6250/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
6251/// against any real stream today. See the module doc on
6252/// `crate::motion_field` and this crate's ledger for the remaining wiring.
6253#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6254pub(crate) fn tmv_hits() -> usize {
6255 crate::mvstack::tmv_hits()
6256}
6257
6258/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
6259/// produced on this thread, the 10-bit inter gate's firing proof.
6260#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6261pub(crate) fn inter_pred_hits() -> usize {
6262 crate::mc::inter_pred_hits()
6263}
6264
6265/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
6266/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
6267/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
6268/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
6269/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
6270/// needs to turn a query block's own resolved `ref_frame` into
6271/// `TplArgs::cur_offset_0` (spec 7.9.3).
6272pub(crate) struct TplFrameArgs<'a> {
6273 pub field: &'a crate::motion_field::TplField,
6274 pub order_hint_bits: u32,
6275 pub order_hint: u32,
6276 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
6277 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
6278 /// frame's own `ref_frame_idx` names for each single reference.
6279 pub ref_order_hints: [u32; 7],
6280}
6281
6282/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
6283/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
6284/// decoded `grid`: every 4x4 unit an inter block covers reads the same
6285/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
6286/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
6287/// exact — every block this crate ever codes is at least 8x8, so no 8x8
6288/// cell straddles two different blocks' values.
6289#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
6290pub(crate) fn build_motion_field(
6291 grid: &MiGrid,
6292 mi_cols: usize,
6293 mi_rows: usize,
6294 order_hint: u32,
6295 order_hint_bits: u32,
6296 ref_order_hints: [u32; 7],
6297 fctx: &FrameCtx,
6298) -> crate::motion_field::MotionField {
6299 let mut field =
6300 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
6301 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
6302 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
6303 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
6304 // referencing one stores only its OTHER side's mv. With
6305 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
6306 // nothing is skipped.
6307 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
6308 // only on the reference frame, so it is 7 table lookups per frame instead
6309 // of two per inter unit.
6310 let other_side: [bool; 8] = std::array::from_fn(|rf| {
6311 let i = rf.wrapping_sub(LAST_FRAME as usize);
6312 order_hint_bits != 0
6313 && i < 7
6314 && (crate::motion_field::get_relative_dist(
6315 order_hint_bits,
6316 ref_order_hints[i],
6317 order_hint,
6318 ) > 0
6319 || ref_order_hints[i] == order_hint)
6320 });
6321 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
6322 // capped at 12 bits per component; a longer one is not stored at all.
6323 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
6324 let (cols, rows, cells) = field.cells_mut();
6325 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
6326 // never touch each other (an 8x8 cell lives in one cell row, and mi row
6327 // `row` writes cell row `row / 2`).
6328 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
6329 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
6330 let out = &mut out[(row / 2 - r0) * cols..][..cols];
6331 for col in 0..mi_cols {
6332 let Some(info) = grid.get_frame(row, col) else {
6333 continue;
6334 };
6335 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
6336 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
6337 // so an intra block -- or an inter block whose every slot is on the
6338 // other side / over the limit -- wipes what an earlier block wrote
6339 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
6340 // share a cell).
6341 if !info.is_inter {
6342 out[col / 2] = None;
6343 continue;
6344 }
6345 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
6346 // qualifying one wins -- a compound block stores its second
6347 // reference's mv, never its first (unless the second is on the
6348 // other side or over the limit). Storing slot 0 unconditionally
6349 // put the wrong (mv, ref_frame_offset) pair in every compound
6350 // block's cell, which a later frame's temporal candidate then
6351 // projected with the wrong reference distance.
6352 let mut saved: Option<crate::motion_field::SavedMv> = None;
6353 for (rf, mv) in [
6354 (info.ref_frame, Some(mv32(info.mv))),
6355 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
6356 ] {
6357 let (Some(mv), true) = (mv, rf > 0) else {
6358 continue;
6359 };
6360 if other_side[rf as usize] {
6361 continue;
6362 }
6363 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
6364 continue;
6365 }
6366 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
6367 }
6368 out[col / 2] = saved;
6369 }
6370 }
6371 };
6372 // lane-mf: the whole-frame pass split over the filter pool in cell-row
6373 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
6374 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
6375 let bands = crate::par::bands(rows, crate::par::filter_threads());
6376 if bands.len() <= 1 {
6377 fill(0, rows, cells);
6378 } else {
6379 let shared = crate::par::Shared::new(cells);
6380 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
6381 // SAFETY: cell rows `r0..r1` are this band's alone.
6382 let cells = unsafe { shared.get() };
6383 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
6384 });
6385 }
6386 if crate::envflags::env_flag!("EC_TRACE_TPL") {
6387 eprintln!("EC_TPL_SAVED oh={order_hint}");
6388 for (r, row) in field.occupancy().iter().enumerate() {
6389 eprintln!("EC_TPL_SAVED r{r} {row}");
6390 }
6391 }
6392 field
6393}
6394
6395/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
6396/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
6397#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6398pub(crate) fn ref_hits(ref_frame: i8) -> usize {
6399 let c = match ref_frame {
6400 LAST2_FRAME => &LAST2_HITS,
6401 LAST3_FRAME => &LAST3_HITS,
6402 GOLDEN_FRAME => &GOLDEN_HITS,
6403 BWDREF_FRAME => &BWDREF_HITS,
6404 ALTREF2_FRAME => &ALTREF2_HITS,
6405 ALTREF_FRAME => &ALTREF_HITS,
6406 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
6407 };
6408 c.with(|v| v.get())
6409}
6410
6411/// The sequence header's `enable_intra_edge_filter`, set once per
6412/// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
6413/// own read of it, kept off the call stack (see that function's own doc
6414/// comment for why) rather than threaded through every `read_plane`/
6415/// `decode_block`/`decode_leaf8` call between here and there.
6416
6417/// Set [`ENABLE_EDGE_FILTER`] for this thread.
6418///
6419/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
6420/// never did -- so an inter frame's intra blocks read whatever value the last
6421/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
6422/// harmless (its own key frame sets it first), but a caller that decodes an
6423/// inter frame directly, or a test harness running several streams on one
6424/// thread, inherits a foreign sequence's bit: decode stops being a pure
6425/// function of the bitstream. `decode_stream` now calls this once per stream
6426/// from the sequence header, which covers every frame including inter ones.
6427pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
6428 fctx.enable_edge_filter.with(|f| f.set(value));
6429}
6430
6431/// Current value of [`ANGLE_DELTA_HITS`].
6432#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6433pub(crate) fn angle_delta_hits() -> usize {
6434 ANGLE_DELTA_HITS.with(|c| c.get())
6435}
6436
6437/// Current value of [`TX_CLASS1_HITS`].
6438#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6439pub(crate) fn tx_class1_hits() -> usize {
6440 TX_CLASS1_HITS.with(|c| c.get())
6441}
6442
6443// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
6444// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
6445// bottom) this thread's decode actually reconstructed -- the same
6446// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
6447// genuinely exercised the sub-8x8 leaf path rather than every attempt
6448// coincidentally landing on `PARTITION_NONE`.
6449thread_local! {
6450 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6451 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
6452 /// sub-blocks (lane-intersub8).
6453 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6454 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
6455 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
6456 /// `[1] = VERT` (two BLOCK_4X8).
6457 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
6458 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
6459 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
6460 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
6461 /// MIXED groups whose chroma reference is INTER while its sibling is
6462 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
6463 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
6464 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
6465 /// so only this cell separates the split arm from the HORZ/VERT one).
6466 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
6467}
6468
6469/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
6470/// mixed groups, split 4x4 leaves)`.
6471pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
6472 SUB8_INTRA_RECT_HITS.with(|c| {
6473 let h = c.get();
6474 (h[0], h[1], h[2], h[3], h[4])
6475 })
6476}
6477
6478/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
6479pub fn sub8_inter_rect_hits() -> (usize, usize) {
6480 SUB8_INTER_RECT_HITS.with(|c| {
6481 let h = c.get();
6482 (h[0], h[1])
6483 })
6484}
6485
6486// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
6487// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
6488// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
6489// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
6490// (b) was 0 for every stream before this round -- the leaf path never touched
6491// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
6492// filtered where libaom skips it. A gate asserts both are non-zero.
6493thread_local! {
6494 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6495 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6496 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
6497 // crosses the cropped frame edge -- the only units for which "clamp at
6498 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
6499 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
6500 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
6501 // whose width or height is not a multiple of 8 is the only shape that
6502 // produces one; the straddling-band gate arms assert it grew.
6503 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6504 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
6505 // (see `Neighbours::skip_written`).
6506 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6507 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
6508 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
6509 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
6510 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
6511 // 8-tall strip pair where only one half is skip must still be FILTERED.
6512 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6513 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6514}
6515
6516/// Current value of `RECT_SKIP_BAND_HITS`.
6517pub fn rect_skip_band_hits() -> usize {
6518 RECT_SKIP_BAND_HITS.with(|c| c.get())
6519}
6520
6521/// Current value of `CDEF_MIXED_SKIP_UNITS`.
6522pub fn cdef_mixed_skip_units() -> usize {
6523 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
6524}
6525
6526/// Current value of `CDEF_SKIPPED_UNITS`.
6527#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6528pub(crate) fn cdef_skipped_units() -> usize {
6529 CDEF_SKIPPED_UNITS.with(|c| c.get())
6530}
6531
6532/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
6533/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
6534pub fn cdef_unwritten_skip_units() -> usize {
6535 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
6536}
6537
6538/// Current value of `INTER8_SKIP_BAND_HITS`.
6539#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6540pub(crate) fn inter8_skip_band_hits() -> usize {
6541 INTER8_SKIP_BAND_HITS.with(|c| c.get())
6542}
6543
6544/// Current value of `CDEF_STRADDLE_UNITS`.
6545#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6546pub(crate) fn cdef_straddle_units() -> usize {
6547 CDEF_STRADDLE_UNITS.with(|c| c.get())
6548}
6549
6550/// Current value of [`SUB8_SPLIT_HITS`].
6551#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6552pub(crate) fn sub8_split_hits() -> usize {
6553 SUB8_SPLIT_HITS.with(|c| c.get())
6554}
6555
6556/// Current value of [`SUB8_INTER_SPLIT_HITS`].
6557pub fn sub8_inter_split_hits() -> usize {
6558 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
6559}
6560
6561// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
6562// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
6563// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
6564// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
6565// first sub-block's type is never the one). Reading it off sub-block 0
6566// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
6567// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
6568// see this rule through this counter.
6569thread_local! {
6570 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6571}
6572
6573/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
6574pub fn sub8_chroma_tx_from_ref_hits() -> usize {
6575 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
6576}
6577
6578fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
6579 if coeffs && first_sub != chroma_ref {
6580 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
6581 }
6582}
6583
6584// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
6585// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
6586// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
6587// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
6588// asserts on these two rather than a plain leaf count.
6589thread_local! {
6590 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6591 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6592 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
6593 /// two 4x4 transform units, predicted one after the other. A separate
6594 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
6595 /// the gate can prove THIS path fired.
6596 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6597 /// 16x8/8x16 intra strips whose prediction actually read past the block's
6598 /// own width (above-right) or height (below-left) -- the samples
6599 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
6600 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
6601 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6602 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
6603 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
6604 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6605}
6606
6607/// Current value of [`RECT8_SPLIT_TX_HITS`].
6608#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6609pub(crate) fn rect8_split_tx_hits() -> usize {
6610 RECT8_SPLIT_TX_HITS.with(|c| c.get())
6611}
6612
6613/// Current value of [`RECT_STRIP_PRED_HITS`].
6614#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6615pub(crate) fn rect_strip_pred_hits() -> usize {
6616 RECT_STRIP_PRED_HITS.with(|c| c.get())
6617}
6618
6619/// Current value of [`RECT_STRIP_REACH_HITS`].
6620#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6621pub(crate) fn rect_strip_reach_hits() -> usize {
6622 RECT_STRIP_REACH_HITS.with(|c| c.get())
6623}
6624
6625/// Current value of [`TX4X8_CODED_HITS`].
6626#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6627pub(crate) fn tx4x8_coded_hits() -> usize {
6628 TX4X8_CODED_HITS.with(|c| c.get())
6629}
6630
6631/// Current value of [`TX8X4_CODED_HITS`].
6632#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6633pub(crate) fn tx8x4_coded_hits() -> usize {
6634 TX8X4_CODED_HITS.with(|c| c.get())
6635}
6636
6637// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
6638// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
6639// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
6640// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
6641// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
6642// (`eob_pt_{16,64,128,256}_chroma_class1`).
6643thread_local! {
6644 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
6645 const { std::cell::Cell::new(0) };
6646}
6647
6648/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
6649#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6650pub(crate) fn chroma_eob_class1_hits() -> usize {
6651 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
6652}
6653
6654/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
6655/// `tx_type` put this block's `eob_pt` on the class-1 row.
6656fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
6657 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
6658 hit!(CHROMA_EOB_CLASS1_HITS);
6659 }
6660}
6661
6662const SUB_MI: u32 = 4;
6663const MI: usize = 4;
6664const SB: usize = 64;
6665/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
6666/// (tile start, superblock-row start).
6667///
6668/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
6669/// `av1_get_partition_plane_context` reads its own zero-initialised
6670/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
6671/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
6672/// (64), which reads identically at every level up to 64x64 but sets the bit
6673/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
6674/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
6675/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
6676const NO_NEIGHBOUR_SIDE: usize = 128;
6677const BLOCK: usize = 32;
6678const SUB: usize = 16;
6679const TX32: usize = 32;
6680const TX16: usize = 16;
6681const TX8: usize = 8;
6682const TX4: usize = 4;
6683const DC_PRED: usize = 0;
6684/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
6685/// carries an angle delta — [`crate::tile`]'s own private copy of the same
6686/// constant.
6687const V_PRED: usize = 1;
6688const H_PRED: usize = 2;
6689/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
6690/// `Fimode_To_Intradir`, libaom `blockd.h`).
6691const D157_PRED: usize = 6;
6692/// The last directional mode, `D67_PRED`.
6693const D67_PRED: usize = 8;
6694/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
6695/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
6696/// codes anything else, so this decoder never reads anything else either.
6697const ANGLE_DELTA_ZERO: usize = 3;
6698const NUM_BASE_LEVELS: i32 = 2;
6699const COEFF_BASE_RANGE: i32 = 12;
6700const BR_STEP: i32 = 3;
6701const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
6702
6703/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
6704/// whose probability mass a superblock or block half outside the frame
6705/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
6706/// duplicated here (that module is another lane's territory this round) and
6707/// kept in step with it by the byte-exact round-trip tests below rather than
6708/// by sharing code.
6709const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
6710const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
6711
6712fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
6713 if crate::envflags::env_flag!("EC_AV1_TRACE") {
6714 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
6715 }
6716}
6717
6718fn element_prob(cdf: &[u16], element: usize) -> u16 {
6719 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
6720}
6721
6722/// The two-symbol CDF a partial superblock/block's forced-split flag is read
6723/// with: the mass of `elements` becomes the probability of the one partition
6724/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
6725/// (the encoder's non-adapting counterpart to this read).
6726fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
6727 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
6728 [32768 - split, 32768, 0]
6729}
6730
6731fn unsupported(what: impl Into<String>) -> Error {
6732 Error::unsupported("AV1 tile", what.into())
6733}
6734
6735/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
6736/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
6737/// same rule.
6738pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
6739 match base_q_idx {
6740 0..=20 => 0,
6741 21..=60 => 1,
6742 61..=120 => 2,
6743 _ => 3,
6744 }
6745}
6746
6747/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
6748/// [`crate::tile`]'s writer generates its scan tables with.
6749fn default_scan(side: usize) -> &'static [u16] {
6750 // One table per transform side (4/8/16/32), built once: this used to be a
6751 // fresh heap allocation plus the whole anti-diagonal walk on every
6752 // transform block read.
6753 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
6754 [
6755 default_scan_gen(4),
6756 default_scan_gen(8),
6757 default_scan_gen(16),
6758 default_scan_gen(32),
6759 ]
6760 });
6761 assert!(
6762 matches!(side, 4 | 8 | 16 | 32),
6763 "no default scan for a {side}-point transform"
6764 );
6765 &SCANS[side.trailing_zeros() as usize - 2]
6766}
6767
6768fn default_scan_gen(side: usize) -> Vec<u16> {
6769 let mut scan = Vec::with_capacity(side * side);
6770 for d in 0..(2 * side - 1) {
6771 let lo = d.saturating_sub(side - 1);
6772 let hi = d.min(side - 1);
6773 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
6774 if d % 2 == 0 {
6775 scan.extend(diagonal.rev());
6776 } else {
6777 scan.extend(diagonal);
6778 }
6779 }
6780 scan
6781}
6782
6783/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
6784/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
6785/// in, instead of the default zigzag. libaom's own tables are keyed by a
6786/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
6787/// physically column-major level buffer, but they decompose to the exact
6788/// same (row, col) walk as a flat row-major traversal of *our* row-major
6789/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
6790/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
6791/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
6792/// transposed (column 0 down every row, then column 1, ...).
6793pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
6794 class_scan_table_wh(side, side, class)
6795}
6796
6797/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
6798/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
6799/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
6800/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
6801/// transcribed with -- `mrow` is the plain row-major raster in our indexing
6802/// and `mcol` its transpose, at rect sizes exactly as at square ones.
6803fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
6804 match class {
6805 TxClass::Vert => (0..(w * h) as u16).collect(),
6806 TxClass::Horiz => (0..w)
6807 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
6808 .collect(),
6809 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
6810 }
6811}
6812
6813fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
6814 match scan_idx {
6815 0 => 0,
6816 i if i <= area / 8 => 1,
6817 i if i <= area / 4 => 2,
6818 _ => 3,
6819 }
6820}
6821
6822/// One cell of [`read_coeffs`]'s level buffer.
6823///
6824/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
6825/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
6826/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
6827/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
6828/// zero cells instead of needing the `row >= side || col >= side` edge test
6829/// this used to run five times per coefficient. Nothing writes a padding
6830/// cell, so the values are the same zeros the test returned.
6831#[inline]
6832fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
6833 grid[row * stride + col] as i32
6834}
6835
6836/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
6837/// `txb_common.h`): everything but the two lone-axis-identity types this
6838/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
6839#[derive(Clone, Copy, PartialEq, Eq)]
6840pub(crate) enum TxClass {
6841 TwoD,
6842 Horiz,
6843 Vert,
6844}
6845
6846impl TxClass {
6847 pub(crate) fn of(tx_type: TxType) -> Self {
6848 match tx_type {
6849 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
6850 // key on axis alone -- FLIPADST is still ADST for this purpose.
6851 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
6852 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
6853 _ => Self::TwoD,
6854 }
6855 }
6856}
6857
6858/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
6859/// table (indexed by the position along the transform's *coded* axis --
6860/// `col` for horiz, `row` for vert) that places their contexts past the 2D
6861/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
6862/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
6863pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
6864 match i {
6865 0 => 26,
6866 1 => 31,
6867 _ => 36,
6868 }
6869}
6870
6871fn base_ctx(
6872 grid: &[u8],
6873 stride: usize,
6874 row: usize,
6875 col: usize,
6876 class: TxClass,
6877 rect_shape: Option<(usize, usize)>,
6878) -> usize {
6879 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
6880 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
6881 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
6882 // position through the full 1D neighbour sum and offset table. Skipping
6883 // that for every class desynced the last (DC) coefficient of a
6884 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
6885 // 0, which then read one extra `BR` symbol at the max and forced a
6886 // spurious third Golomb call).
6887 if class == TxClass::TwoD && row == 0 && col == 0 {
6888 return 0;
6889 }
6890 let offsets: [(usize, usize); 5] = match class {
6891 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
6892 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
6893 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
6894 };
6895 let mag: i32 = offsets
6896 .iter()
6897 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
6898 .sum();
6899 let ctx = ((mag + 1) >> 1).min(4) as usize;
6900 match class {
6901 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
6902 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
6903 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
6904 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
6905 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
6906 // strip, which own a genuinely different table from the square one
6907 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
6908 // square table vs the real ctx 13 the rect table gives).
6909 TxClass::TwoD => {
6910 // lane-rectsplit r4: apply libaom's GENERATING RULE
6911 // (`txb_common.h:199-209`) directly instead of indexing the
6912 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
6913 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
6914 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
6915 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
6916 // so 32 consecutive entries are one COLUMN: the [`cdf`]
6917 // transcriptions are `[col][row]` and this read had them as
6918 // `[row][col]` -- the transpose, i.e. the other shape's rule with
6919 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
6920 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
6921 // pins the rule against the tables over their whole 5x5 domain.
6922 if let Some((w, h)) = rect_shape {
6923 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
6924 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
6925 }
6926 if w < h && row < 2 {
6927 return ctx + 11;
6928 }
6929 if w > h && col < 2 {
6930 return ctx + 16;
6931 }
6932 }
6933 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6934 }
6935 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
6936 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
6937 }
6938}
6939
6940/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
6941/// offsets into the padded level frame (lane-coefread): the tap pattern is a
6942/// function of the tx class alone, which is fixed for a whole transform unit,
6943/// so resolving it once per unit takes the class match and the `(dr, dc)`
6944/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
6945/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
6946/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
6947/// original `(dr, dc)` form.
6948fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
6949 match class {
6950 TxClass::TwoD => (
6951 [stride, 1, stride + 1, 2 * stride, 2],
6952 [stride, 1, stride + 1],
6953 ),
6954 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
6955 TxClass::Vert => (
6956 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
6957 [stride, 1, 2 * stride],
6958 ),
6959 }
6960}
6961
6962/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
6963/// neighbours) + 1) >> 1`, clamped to 4.
6964#[inline(always)]
6965fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
6966 let mut mag = 0u32;
6967 for &t in taps {
6968 mag += u32::from(grid[idx + t]).min(3);
6969 }
6970 (((mag + 1) >> 1) as usize).min(4)
6971}
6972
6973/// [`br_ctx`]'s neighbour sum, off flat taps.
6974#[inline(always)]
6975fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
6976 let mut mag = 0u32;
6977 for &t in taps {
6978 mag += u32::from(grid[idx + t]);
6979 }
6980 (((mag + 1) >> 1) as usize).min(6)
6981}
6982
6983/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
6984/// origin-offset tail the two coefficient readers state inline; kept as the
6985/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
6986/// flat one against.
6987#[cfg(test)]
6988fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
6989 let extra = match class {
6990 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
6991 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
6992 TxClass::Vert => neighbour(grid, stride, row + 2, col),
6993 };
6994 let mag = neighbour(grid, stride, row + 1, col) + neighbour(grid, stride, row, col + 1) + extra;
6995 let mag = (((mag + 1) >> 1).min(6)) as usize;
6996 if row == 0 && col == 0 {
6997 return mag;
6998 }
6999 let near_origin = match class {
7000 TxClass::TwoD => row < 2 && col < 2,
7001 TxClass::Horiz => col == 0,
7002 TxClass::Vert => row == 0,
7003 };
7004 if near_origin { mag + 7 } else { mag + 14 }
7005}
7006
7007/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
7008/// transposed from libaom's column-major buffer into this decoder's row-major
7009/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
7010/// against the real table). Not the square zigzag formula generalized to
7011/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
7012const SCAN_32X16: [u16; 512] = [
7013 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7014 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39, 8,
7015 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72, 41,
7016 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229, 198,
7017 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, 13,
7018 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418, 387,
7019 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326, 295,
7020 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234, 203,
7021 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142, 111, 80,
7022 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19, 485, 454,
7023 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424, 393, 362,
7024 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332, 301, 270,
7025 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178,
7026 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148, 117, 86, 55,
7027 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, 491, 460, 429,
7028 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430, 399, 368, 337,
7029 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338, 307, 276, 245,
7030 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246, 215, 184, 153,
7031 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154, 123, 92, 61, 30,
7032 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 497, 466, 435,
7033 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405, 374, 343, 312,
7034 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251, 220, 189, 158,
7035 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439, 408, 377, 346,
7036 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503, 472, 441, 410,
7037 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443, 412, 381, 350,
7038 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415, 509, 478, 447,
7039 510, 479, 511,
7040];
7041
7042/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
7043/// [`SCAN_32X16`]'s doc comment).
7044const SCAN_16X32: [u16; 512] = [
7045 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,
7046 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
7047 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
7048 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
7049 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
7050 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
7051 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
7052 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
7053 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
7054 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
7055 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
7056 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
7057 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
7058 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
7059 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
7060 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
7061 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
7062 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
7063 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
7064 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
7065 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
7066 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
7067 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
7068 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
7069 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
7070 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
7071];
7072
7073/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
7074/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
7075/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
7076/// the same source).
7077const SCAN_4X8: [u16; 32] = [
7078 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,
7079 23, 26, 29, 27, 30, 31,
7080];
7081
7082/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
7083const SCAN_8X4: [u16; 32] = [
7084 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,
7085 29, 22, 15, 30, 23, 31,
7086];
7087
7088/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
7089/// [`SCAN_32X16`]'s doc comment).
7090const SCAN_16X8: [u16; 128] = [
7091 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,
7092 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
7093 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
7094 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
7095 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
7096 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
7097];
7098
7099/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
7100/// [`SCAN_32X16`]'s doc comment).
7101const SCAN_8X16: [u16; 128] = [
7102 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,
7103 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7104 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7105 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7106 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
7107 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
7108];
7109
7110/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
7111/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
7112/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
7113/// scans column-major (`p = col * height + row`), so a naive copy of
7114/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
7115/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
7116/// are byte-identical to this decoder's [`SCAN_8X16`].
7117const SCAN_32X8: [u16; 256] = [
7118 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7119 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226,
7120 195, 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104,
7121 73, 42, 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200,
7122 169, 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78,
7123 47, 16, 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205,
7124 174, 143, 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83,
7125 52, 21, 239, 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210,
7126 179, 148, 117, 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88,
7127 57, 26, 244, 213, 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215,
7128 184, 153, 122, 91, 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93,
7129 62, 31, 249, 218, 187, 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127,
7130 252, 221, 190, 159, 253, 222, 191, 254, 223, 255,
7131];
7132/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
7133/// 16x64 `PARTITION_VERT_4` strip).
7134const SCAN_8X32: [u16; 256] = [
7135 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,
7136 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7137 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7138 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7139 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
7140 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
7141 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
7142 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
7143 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
7144 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
7145 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
7146 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
7147 239, 246, 253, 247, 254, 255,
7148];
7149/// `Default_Scan_16x4`, this decoder's own row-major transcription of
7150/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
7151/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
7152/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
7153/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
7154/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
7155/// were emitted -- a naive copy installs the transpose (class
7156/// reference-layout-not-spec).
7157const SCAN_16X4: [u16; 64] = [
7158 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,
7159 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
7160 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
7161];
7162/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
7163/// 8x32 `PARTITION_VERT_4` strip).
7164const SCAN_4X16: [u16; 64] = [
7165 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,
7166 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
7167 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
7168];
7169
7170/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
7171/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
7172/// padding already holds.
7173#[inline]
7174fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7175 grid[row * stride + col] as i32
7176}
7177
7178/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
7179/// the rect generalization is libaom's own comment in
7180/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
7181/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
7182/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
7183/// [`decode_block_rect`] codes (see that function's own doc comment).
7184fn base_ctx_rect(
7185 grid: &[u8],
7186 stride: usize,
7187 w: usize,
7188 h: usize,
7189 row: usize,
7190 col: usize,
7191 class: TxClass,
7192) -> usize {
7193 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
7194 // the 2D class short-circuits the DC position.
7195 if class == TxClass::TwoD && row == 0 && col == 0 {
7196 return 0;
7197 }
7198 let offsets: [(usize, usize); 5] = match class {
7199 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7200 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7201 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7202 };
7203 let mag: i32 = offsets
7204 .iter()
7205 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
7206 .sum();
7207 let ctx = ((mag + 1) >> 1).min(4) as usize;
7208 match class {
7209 TxClass::TwoD => {
7210 if w < h && row < 2 {
7211 return ctx + 11;
7212 }
7213 if w > h && col < 2 {
7214 return ctx + 16;
7215 }
7216 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7217 }
7218 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
7219 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
7220 // position along one axis only).
7221 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7222 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7223 }
7224}
7225
7226/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
7227/// neighbour-offset math itself is shape-independent, only the boundary
7228/// clamp needs the real bound in each axis.
7229/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
7230/// its body was character-for-character [`br_ctx`]'s, which
7231/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
7232#[cfg(test)]
7233fn br_ctx_rect(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7234 let extra = match class {
7235 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
7236 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
7237 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
7238 };
7239 let mag = neighbour_rect(grid, stride, row + 1, col)
7240 + neighbour_rect(grid, stride, row, col + 1)
7241 + extra;
7242 let mag = (((mag + 1) >> 1).min(6)) as usize;
7243 if row == 0 && col == 0 {
7244 return mag;
7245 }
7246 let near_origin = match class {
7247 TxClass::TwoD => row < 2 && col < 2,
7248 TxClass::Horiz => col == 0,
7249 TxClass::Vert => row == 0,
7250 };
7251 if near_origin { mag + 7 } else { mag + 14 }
7252}
7253
7254fn dc_vote(dc: Option<bool>) -> i32 {
7255 match dc {
7256 None => 0,
7257 Some(true) => -1,
7258 Some(false) => 1,
7259 }
7260}
7261
7262fn dc_sign_ctx(vote: i32) -> usize {
7263 match vote.signum() {
7264 0 => 0,
7265 -1 => 1,
7266 _ => 2,
7267 }
7268}
7269
7270/// The `tx_type` a CDF symbol names, given the width of the row it was read
7271/// from.
7272///
7273/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
7274/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
7275/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
7276/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
7277/// members are a prefix of the five.
7278///
7279/// One function rather than a `match` at each reader, so
7280/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
7281/// tests the mapping the readers actually use.
7282pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
7283 match cdf_len {
7284 17 => TxType::from_symbol_all16(t),
7285 13 => TxType::from_symbol_set2_12(t),
7286 8 => TxType::from_symbol_set1(t),
7287 _ => TxType::from_symbol(t),
7288 }
7289}
7290
7291/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
7292/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
7293/// (class `table-and-reader-move-together` -- the writer picks its symbol
7294/// through the reader's own map, so the two cannot drift).
7295pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
7296 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
7297}
7298
7299/// The remainder of a level the base and base-range syntax could not reach
7300/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
7301/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
7302pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
7303 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
7304 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
7305 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
7306 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
7307 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
7308 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
7309 // stream_can_carry` enumerates that whole value domain.
7310 //
7311 // So this refusal never names a reader gap: it is always the SYMPTOM of an
7312 // earlier desync (class `refusal-hides-a-defect`), and every historical
7313 // instance was closed by fixing that desync -- lane-dgolomb's
7314 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
7315 // Raising the cap only trades a clean refusal for silent corruption:
7316 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
7317 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
7318 // from a refusal into a frame-0 LUMA MISMATCH.
7319 let mut length = 1u32;
7320 while dec.literal(1) == 0 {
7321 length += 1;
7322 if length > 20 {
7323 return Err(unsupported("a Golomb tail longer than this decoder reads"));
7324 }
7325 }
7326 let mut x = 1u32;
7327 for _ in 1..length {
7328 x = (x << 1) | dec.literal(1);
7329 }
7330 Ok(x - 1)
7331}
7332
7333/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
7334/// [`crate::tile`]'s `write_eob`.
7335fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
7336 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
7337 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
7338
7339 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
7340 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
7341 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
7342 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
7343 // `eob_multi_ctx`). Missing that split desynced the very first
7344 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
7345 // against a real aomdec trace).
7346 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
7347 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
7348 (_, Some(class1)) => class1,
7349 };
7350 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7351 let (range, value) = dec.debug_state();
7352 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
7353 }
7354 let group = dec.symbol(eob_pt) + 1;
7355 if trace {
7356 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
7357 }
7358 let bits = OFFSET_BITS[group];
7359 let mut offset = 0u32;
7360 if bits > 0 {
7361 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
7362 if trace {
7363 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
7364 }
7365 offset = top << (bits - 1);
7366 if bits > 1 {
7367 offset |= dec.literal(bits - 1);
7368 }
7369 }
7370 GROUP_START[group] + offset as usize
7371}
7372
7373/// One transform block's levels, the inverse of [`crate::tile`]'s
7374/// `write_coeffs`, returned as a `side * side` grid in raster order, along
7375/// with the transform type that grid was coded under (`DCT_DCT` when the
7376/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
7377/// 64-point transforms, which never code anything else).
7378///
7379/// # Errors
7380/// Returns an error if the `tx_type` symbol decodes to a value outside its
7381/// CDF's own set (a corrupt or unsupported bitstream) — every value the
7382/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
7383/// produce dispatches to a real inverse transform.
7384/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
7385/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
7386/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
7387/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
7388/// the plane's own predicted mode instead. Every entry this table can
7389/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
7390/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
7391/// table ever names), so unlike the CDF-coded luma path there is no
7392/// ext-tx-set membership check to fall back from here.
7393pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
7394 use crate::intra::{
7395 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
7396 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
7397 };
7398 match mode {
7399 DC_PRED | D45_PRED => TxType::DctDct,
7400 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
7401 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
7402 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
7403 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
7404 }
7405}
7406
7407/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
7408/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
7409/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
7410fn is_smooth_mode(mode: usize) -> bool {
7411 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
7412}
7413
7414/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
7415/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
7416/// nine of them inside the base/sign loops pinned nine sets of values in the
7417/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
7418/// traffic). Out of line, the loop keeps its values in registers and the
7419/// trace output is character-for-character what it was.
7420#[cold]
7421#[inline(never)]
7422fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
7423 eprintln!(
7424 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
7425 );
7426}
7427
7428#[cold]
7429#[inline(never)]
7430fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
7431 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
7432}
7433
7434#[cold]
7435#[inline(never)]
7436fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
7437 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
7438}
7439
7440#[cold]
7441#[inline(never)]
7442fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
7443 let (rng, _) = dec.debug_state();
7444 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
7445}
7446
7447#[cold]
7448#[inline(never)]
7449fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
7450 let (rng, _) = dec.debug_state();
7451 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
7452}
7453
7454#[cold]
7455#[inline(never)]
7456fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
7457 let (rng, _) = dec.debug_state();
7458 eprintln!(
7459 "EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}",
7460 negative as i32
7461 );
7462}
7463
7464#[cold]
7465#[inline(never)]
7466fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
7467 let (rng, _) = dec.debug_state();
7468 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
7469}
7470
7471#[cold]
7472#[inline(never)]
7473fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
7474 let (rng, _) = dec.debug_state();
7475 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
7476}
7477
7478fn read_coeffs(
7479 dec: &mut SymbolDecoder,
7480 coding: &mut TxbTables,
7481 scan: &[u16],
7482 skip_ctx: usize,
7483 sign_ctx: usize,
7484 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
7485 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
7486 // nothing at all; `DctDct` for every luma call and every chroma call at
7487 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
7488 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
7489 default_tx_type: TxType,
7490 // `Some((w, h))` with `w != h` when this read is a superblock-level
7491 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
7492 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
7493 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
7494 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
7495 // caller's block genuinely is `side` x `side`.
7496 rect_shape: Option<(usize, usize)>,
7497) -> Result<(Grid, TxType)> {
7498 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
7499 let side = coding.side;
7500 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7501 let (range, value) = dec.debug_state();
7502 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
7503 }
7504 if crate::envflags::env_flag!("EC_ECDUMP_IN") {
7505 let (range, value) = dec.debug_state();
7506 let bit = dec.debug_bitpos();
7507 eprintln!(
7508 "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})"
7509 );
7510 }
7511 let dbg_txbskip = if coeff_trace_on() {
7512 coding.txb_skip[skip_ctx]
7513 } else {
7514 [0; 3]
7515 };
7516 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
7517 if coeff_trace_on() {
7518 let (rng, _) = dec.debug_state();
7519 eprintln!(
7520 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
7521 coding.side, all_zero as i32
7522 );
7523 }
7524 if crate::envflags::env_flag!("EC_AV1_TELL") {
7525 eprintln!(
7526 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
7527 all_zero as u8,
7528 dec.debug_bitpos(),
7529 dec.debug_state().0
7530 );
7531 }
7532 if trace {
7533 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
7534 }
7535 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7536 let (range, value) = dec.debug_state();
7537 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
7538 }
7539 if all_zero {
7540 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
7541 // shared zero grid instead of allocating and zeroing its own.
7542 return Ok((Grid::Zero(side * side), TxType::DctDct));
7543 }
7544 let mut grid = vec![0i32; side * side];
7545 let mut tx_type = default_tx_type;
7546 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
7547 // The CDF row's own width names its set (lane-cdffwd2: extended
7548 // past the original two-way intra split once wider `reduced_tx_set
7549 // == 0` inter sets joined the table): 17 slots (16 symbols) is
7550 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
7551 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
7552 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
7553 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
7554 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
7555 let len = tx_type_cdf.len();
7556 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
7557 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
7558 }
7559 let t = dec.symbol(tx_type_cdf);
7560 crate::census::tx_type(len, t);
7561 if coeff_trace_on() {
7562 let (rng, _) = dec.debug_state();
7563 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
7564 }
7565 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7566 let (range, value) = dec.debug_state();
7567 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
7568 }
7569 if trace {
7570 eprintln!("TRACE tx_type value={t} len={len}");
7571 }
7572 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
7573 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
7574 })?;
7575 }
7576
7577 let class = TxClass::of(tx_type);
7578 if class != TxClass::TwoD {
7579 hit!(TX_CLASS1_HITS);
7580 hit!(RECT_CLASS1_HITS);
7581 }
7582 let eob = read_eob(dec, coding, class);
7583 if trace {
7584 eprintln!("TRACE eob value={eob}");
7585 }
7586 let ec_trace_coeff = coeff_trace_on();
7587 if ec_trace_coeff {
7588 let (rng, _) = dec.debug_state();
7589 let cls = match class {
7590 TxClass::TwoD => "2d",
7591 TxClass::Horiz => "horiz",
7592 TxClass::Vert => "vert",
7593 };
7594 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
7595 }
7596 let class_scan;
7597 let scan: &[u16] = if class == TxClass::TwoD {
7598 scan
7599 } else {
7600 class_scan = class_scan_table(side, class);
7601 &class_scan
7602 };
7603 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
7604 // coefficient `pos / side`, `pos % side` was a hardware divide where a
7605 // shift and a mask say the same thing, and the level buffer fits a fixed
7606 // 32x32 frame of stack instead of a heap allocation per transform block.
7607 debug_assert!(side.is_power_of_two() && side <= 32);
7608 let sh = side.trailing_zeros();
7609 let col_mask = side - 1;
7610 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
7611 // `stride = side + 4` columns and four spare rows, so the widest read
7612 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
7613 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
7614 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
7615 let stride = side + 4;
7616 let mut levels_buf = [0u8; 36 * 36];
7617 let levels = &mut levels_buf[..stride * stride];
7618 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
7619 // `pos >> sh` / `& mask` decomposition and load the level back out of the
7620 // padded frame just to skip the zeros. The base pass already knows both,
7621 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
7622 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
7623 // pass walks that list in reverse (the base pass runs in reverse scan
7624 // order, so reversing it is forward scan order: the same coefficients, in
7625 // the same order, with the same `c` the trace prints).
7626 let mut nz_buf = [0u16; 1024];
7627 let mut nz_n = 0usize;
7628 let (base_taps, br_taps) = flat_taps(stride, class);
7629 for scan_idx in (0..eob).rev() {
7630 let pos = scan[scan_idx] as usize;
7631 let (row, col) = (pos >> sh, pos & col_mask);
7632 let idx = row * stride + col;
7633 let level = if scan_idx == eob - 1 {
7634 let ctx = eob_coeff_ctx(scan_idx, side * side);
7635 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
7636 if trace {
7637 trace_base_eob(scan_idx, pos, row, col, ctx, v);
7638 }
7639 v
7640 } else {
7641 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
7642 if row == 0 && col == 0 {
7643 0
7644 } else {
7645 base_mag(levels, idx, &base_taps)
7646 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7647 }
7648 } else {
7649 base_ctx(levels, stride, row, col, class, rect_shape)
7650 };
7651 let v = dec.symbol(&mut coding.base[ctx]) as i32;
7652 if ec_trace_coeff {
7653 // `pos` in libaom's column-major `coeff_idx` convention, so
7654 // the ladder lines up with instrumented `aomdec`.
7655 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
7656 }
7657 if trace {
7658 trace_base(scan_idx, pos, row, col, ctx, v);
7659 }
7660 v
7661 };
7662 let level = if level > NUM_BASE_LEVELS {
7663 let ctx = {
7664 let mag = br_mag(levels, idx, &br_taps);
7665 if row == 0 && col == 0 {
7666 mag
7667 } else {
7668 let near_origin = match class {
7669 TxClass::TwoD => row < 2 && col < 2,
7670 TxClass::Horiz => col == 0,
7671 TxClass::Vert => row == 0,
7672 };
7673 if near_origin { mag + 7 } else { mag + 14 }
7674 }
7675 };
7676 let mut level = level;
7677 let mut sent = 0;
7678 loop {
7679 let k = dec.symbol(&mut coding.br[ctx]) as i32;
7680 if ec_trace_coeff {
7681 // lane-leaf8tx r3: the `br` rung was missing from THIS
7682 // path's trace, so the cross-decoder range ladder was
7683 // blind to every base-range symbol and mis-reported the
7684 // first divergence (class [[gate-blind-to-feature]]).
7685 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
7686 }
7687 if trace {
7688 trace_br(scan_idx, pos, row, col, ctx, k);
7689 }
7690 level += k;
7691 sent += BR_STEP;
7692 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
7693 break;
7694 }
7695 }
7696 level
7697 } else {
7698 level
7699 };
7700 if ec_trace_coeff && scan_idx == eob - 1 {
7701 coeff_step_base_eob_level(dec, level);
7702 }
7703 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
7704 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
7705 // added in the sign pass below, straight into `grid`), so the context
7706 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
7707 // byte gather (lane-coefbuf).
7708 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
7709 levels[idx] = level as u8;
7710 if level != 0 {
7711 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
7712 nz_n += 1;
7713 }
7714 }
7715 if ec_trace_coeff {
7716 let (rng, _) = dec.debug_state();
7717 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
7718 }
7719
7720 for &packed in nz_buf[..nz_n].iter().rev() {
7721 let c = (packed >> 4) as usize;
7722 let pos = scan[c] as usize;
7723 let level = (packed & 15) as i32;
7724 let negative = if pos == 0 {
7725 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
7726 if trace {
7727 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
7728 }
7729 v
7730 } else {
7731 dec.literal(1) == 1
7732 };
7733 if ec_trace_coeff {
7734 coeff_step_sign(dec, c, negative);
7735 }
7736 let level = if level > MAX_BR_LEVEL {
7737 let g = read_golomb(dec)?;
7738 if trace {
7739 eprintln!("TRACE golomb pos={pos} value={g}");
7740 }
7741 level + g as i32
7742 } else {
7743 level
7744 };
7745 if ec_trace_coeff {
7746 coeff_step_post_golomb(dec, c, level);
7747 }
7748 grid[pos] = if negative { -level } else { level };
7749 }
7750 Ok((Grid::Own(grid), tx_type))
7751}
7752
7753/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
7754/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
7755/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
7756/// can ever produce, since every `tx_type` this decoder's rect sets can read
7757/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
7758/// rather than guess-decode if a non-2D class ever shows up here, since
7759/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
7760/// form for those.
7761
7762fn read_coeffs_rect(
7763 dec: &mut SymbolDecoder,
7764 coding: &mut TxbTables,
7765 scan: &[u16],
7766 w: usize,
7767 h: usize,
7768 skip_ctx: usize,
7769 sign_ctx: usize,
7770 default_tx_type: TxType,
7771) -> Result<(Grid, TxType)> {
7772 let rect_trace = coeff_trace_on();
7773 let entry_rng = dec.debug_state().0;
7774 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
7775 if rect_trace {
7776 eprintln!(
7777 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
7778 all_zero as i32,
7779 dec.debug_state().0
7780 );
7781 }
7782 if all_zero {
7783 return Ok((Grid::Zero(w * h), TxType::DctDct));
7784 }
7785 let mut grid = vec![0i32; w * h];
7786 hit!(RECT_COEFF_TU_HITS);
7787 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
7788 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
7789 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
7790 // context offsets -- both of which now have rect forms
7791 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
7792 // The rect sets that carry no symbol at all still pass `None` here.
7793 let mut tx_type = default_tx_type;
7794 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
7795 let len = tx_type_cdf.len();
7796 let t = dec.symbol(tx_type_cdf);
7797 crate::census::tx_type(len, t);
7798 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
7799 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
7800 })?;
7801 if rect_trace {
7802 eprintln!(
7803 "EC_COEFF_STEP tag=tx_type plane=0 rng={}",
7804 dec.debug_state().0
7805 );
7806 }
7807 }
7808 let class = TxClass::of(tx_type);
7809 if class != TxClass::TwoD {
7810 hit!(TX_CLASS1_HITS);
7811 }
7812 let eob = read_eob(dec, coding, class);
7813 if rect_trace {
7814 eprintln!(
7815 "EC_COEFF_STEP tag=eob eob={eob} rng={}",
7816 dec.debug_state().0
7817 );
7818 }
7819 let class_scan;
7820 let scan: &[u16] = if class == TxClass::TwoD {
7821 scan
7822 } else {
7823 class_scan = class_scan_table_wh(w, h, class);
7824 &class_scan
7825 };
7826 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
7827 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
7828 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
7829 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
7830 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
7831 // mask rather than a hardware divide.
7832 let stride = w + 4;
7833 let n = stride * (h + 4);
7834 if !(w.is_power_of_two() && n <= 36 * 36) {
7835 panic!("rect coeff scratch w={w} h={h} n={n}");
7836 }
7837 let (mut b96, mut b256, mut b768);
7838 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
7839 let levels: &mut [u8] = if n <= 96 {
7840 b96 = [0u8; 96];
7841 &mut b96[..n]
7842 } else if n <= 256 {
7843 b256 = [0u8; 256];
7844 &mut b256[..n]
7845 } else {
7846 b768 = [0u8; 768];
7847 &mut b768[..n]
7848 };
7849 let wsh = w.trailing_zeros();
7850 let wmask = w - 1;
7851 // lane-coefread: the non-zero list [`read_coeffs`] documents.
7852 let mut nz_buf = [0u16; 1024];
7853 let mut nz_n = 0usize;
7854 let (base_taps, br_taps) = flat_taps(stride, class);
7855 let (wlt, wgt) = (w < h, w > h);
7856 for scan_idx in (0..eob).rev() {
7857 let pos = scan[scan_idx] as usize;
7858 let (row, col) = (pos >> wsh, pos & wmask);
7859 let idx = row * stride + col;
7860 // libaom's column-major `coeff_idx`, for ladder comparison.
7861 let _apos = col * h + row;
7862 let level = if scan_idx == eob - 1 {
7863 let ctx = eob_coeff_ctx(scan_idx, w * h);
7864 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
7865 if rect_trace {
7866 eprintln!(
7867 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
7868 dec.debug_state().0
7869 );
7870 }
7871 v
7872 } else {
7873 let ctx = if class == TxClass::TwoD {
7874 if row == 0 && col == 0 {
7875 0
7876 } else {
7877 let m = base_mag(levels, idx, &base_taps);
7878 if wlt && row < 2 {
7879 m + 11
7880 } else if wgt && col < 2 {
7881 m + 16
7882 } else {
7883 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7884 }
7885 }
7886 } else {
7887 base_ctx_rect(levels, stride, w, h, row, col, class)
7888 };
7889 let v = dec.symbol(&mut coding.base[ctx]) as i32;
7890 if rect_trace {
7891 eprintln!(
7892 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
7893 dec.debug_state().0
7894 );
7895 }
7896 v
7897 };
7898 let level = if level > NUM_BASE_LEVELS {
7899 let ctx = {
7900 let mag = br_mag(levels, idx, &br_taps);
7901 if row == 0 && col == 0 {
7902 mag
7903 } else {
7904 let near_origin = match class {
7905 TxClass::TwoD => row < 2 && col < 2,
7906 TxClass::Horiz => col == 0,
7907 TxClass::Vert => row == 0,
7908 };
7909 if near_origin { mag + 7 } else { mag + 14 }
7910 }
7911 };
7912 let mut level = level;
7913 let mut sent = 0;
7914 loop {
7915 let k = dec.symbol(&mut coding.br[ctx]) as i32;
7916 if rect_trace {
7917 eprintln!(
7918 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
7919 dec.debug_state().0
7920 );
7921 }
7922 level += k;
7923 sent += BR_STEP;
7924 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
7925 break;
7926 }
7927 }
7928 level
7929 } else {
7930 level
7931 };
7932 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
7933 levels[idx] = level as u8;
7934 if level != 0 {
7935 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
7936 nz_n += 1;
7937 }
7938 if rect_trace {
7939 let (rng, _) = dec.debug_state();
7940 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
7941 }
7942 }
7943 if rect_trace {
7944 let (rng, _) = dec.debug_state();
7945 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
7946 }
7947 for &packed in nz_buf[..nz_n].iter().rev() {
7948 let pos = scan[(packed >> 4) as usize] as usize;
7949 let level = (packed & 15) as i32;
7950 let negative = if pos == 0 {
7951 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
7952 } else {
7953 dec.literal(1) == 1
7954 };
7955 if rect_trace {
7956 let (rng, _) = dec.debug_state();
7957 eprintln!(
7958 "EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}",
7959 u8::from(negative)
7960 );
7961 }
7962 let level = if level > MAX_BR_LEVEL {
7963 let g = read_golomb(dec)?;
7964 level + g as i32
7965 } else {
7966 level
7967 };
7968 grid[pos] = if negative { -level } else { level };
7969 }
7970 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
7971 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
7972 // grids differ is a reader defect, one whose grids agree is a transform
7973 // defect.
7974 if crate::envflags::env_flag!("EC_DQCOEFF") {
7975 let nz: Vec<String> = grid
7976 .iter()
7977 .enumerate()
7978 .filter(|&(_, &v)| v != 0)
7979 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
7980 .collect();
7981 eprintln!(
7982 "OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}",
7983 nz.join(",")
7984 );
7985 }
7986 Ok((Grid::Own(grid), tx_type))
7987}
7988
7989/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
7990/// [`read_plane`] family already has.
7991///
7992/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
7993/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
7994/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
7995/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
7996/// enforces that for every strip that reads its chroma through it, but the rect
7997/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
7998/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
7999/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
8000/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
8001/// chroma read desyncs at the FIRST rect leaf of the frame and every later
8002/// symbol -- and therefore every later pixel -- is decoded from the wrong
8003/// place, without ever tripping a refusal (the desynced values stay inside
8004/// every coded alphabet).
8005fn read_chroma_coeffs_rect(
8006 dec: &mut SymbolDecoder,
8007 coding: &mut TxbTables,
8008 scan: &[u16],
8009 w: usize,
8010 h: usize,
8011 skip_ctx: usize,
8012 sign_ctx: usize,
8013 default_tx_type: TxType,
8014 fctx: &crate::decode::FrameCtx,
8015) -> Result<(Grid, TxType)> {
8016 if mono(fctx) {
8017 return Ok((Grid::Zero(w * h), TxType::DctDct));
8018 }
8019 read_coeffs_rect(dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type)
8020}
8021
8022/// What one coded block leaves behind for the blocks that read it as a
8023/// neighbour: whether it coded anything at all, and the sign of its DC —
8024/// [`crate::tile`]'s own private `Neighbour`.
8025#[derive(Clone, Copy, Default)]
8026struct Neighbour {
8027 /// The transform unit's cumulative coefficient level (spec `cul_level`,
8028 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
8029 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
8030 /// boolean (`level != 0`) is enough for every context this decoder read
8031 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
8032 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
8033 /// needs the actual magnitude tier of its above/left neighbours, not
8034 /// just whether they coded anything.
8035 level: u8,
8036 dc: Option<bool>,
8037}
8038
8039/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
8040/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
8041/// grid is dropped, never a panic. One `memset` per grid row instead of a
8042/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
8043/// is contiguous, so this writes exactly the cells the cell loop did,
8044/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
8045/// next row.
8046#[inline]
8047fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
8048 let end = (start + n).min(dst.len());
8049 if start < end {
8050 dst[start..end].fill(v);
8051 }
8052}
8053
8054fn neighbour_state(grid: &[i32]) -> Neighbour {
8055 // lane-coefgrid: the shared zero grid sums to zero by construction; this
8056 // sum has no early exit, so the 60% of units that code nothing used to
8057 // walk their whole grid here.
8058 if is_zero_grid(grid) {
8059 return Neighbour::default();
8060 }
8061 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
8062 Neighbour {
8063 level: cul.min(7) as u8,
8064 dc: (grid[0] != 0).then_some(grid[0] < 0),
8065 }
8066}
8067
8068/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
8069/// transform unit smaller than the block it sits in): `top`/`left` are the
8070/// above/left neighbours' magnitude tiers, each already clamped to 4.
8071pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
8072 [1, 2, 2, 2, 3],
8073 [2, 4, 4, 4, 5],
8074 [2, 4, 4, 4, 5],
8075 [2, 4, 4, 4, 5],
8076 [3, 5, 5, 5, 6],
8077];
8078
8079/// The `skip` flag, its written-instrument bit, and the covering coded
8080/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
8081/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
8082/// nothing else, so a block's row is one fill instead of four, and the
8083/// deblocker's `pu_edge` reads origin and dims off one cache line.
8084#[derive(Clone, Copy)]
8085struct BlkCell {
8086 skip: bool,
8087 written: bool,
8088 org: [u16; 2],
8089 dim: [u8; 2],
8090}
8091
8092/// The neighbour state a block's contexts are read from — a duplicate of
8093/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
8094/// territory this round), kept at the same two granularities the real writer
8095/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
8096/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
8097/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
8098/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
8099/// chroma transform straddling the true, odd-sized frame edge see its
8100/// neighbour's state clamped at its own subsampled edge rather than luma's.
8101#[derive(Clone)]
8102struct Neighbours {
8103 above: Vec<[Neighbour; 3]>,
8104 left: Vec<[Neighbour; 3]>,
8105 above_mode: Vec<usize>,
8106 left_mode: Vec<usize>,
8107 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
8108 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
8109 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
8110 /// luma one -- the same block can (and often does) code a different
8111 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
8112 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
8113 /// within-block neighbour finer than this grid) is luma-only -- a known,
8114 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
8115 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
8116 above_uv_mode: Vec<usize>,
8117 left_uv_mode: Vec<usize>,
8118 above_side: Vec<usize>,
8119 left_side: Vec<usize>,
8120 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
8121 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
8122 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
8123 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
8124 /// array cannot tell the second leaf's partition symbol that the first
8125 /// one was coded at 8x8.
8126 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
8127 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
8128 above_side_mi: Vec<u8>,
8129 left_side_mi: Vec<u8>,
8130 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
8131 /// / row, with the mi position it was written at
8132 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
8133 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
8134 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
8135 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
8136 /// leaf whose neighbour is another split group needs that group's leaf 3
8137 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
8138 /// and read only by [`decode_leaf_split4`]; the position guard makes it
8139 /// fall back to the coarse slot whenever the real neighbour was a block
8140 /// of 8x8 or larger (whose one mode is correct for every row it spans).
8141 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
8142 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
8143 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
8144 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
8145 /// frame is 65536 px = 16384 mi).
8146 sub8_mode_col: Vec<(u16, u8)>,
8147 sub8_mode_row: Vec<(u16, u8)>,
8148 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
8149 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
8150 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
8151 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
8152 /// the leaf above writes the same row slot the block to the left owns.
8153 uv_mode_col: Vec<(u16, u8)>,
8154 uv_mode_row: Vec<(u16, u8)>,
8155 /// Every mi cell's own `uv_mode`, the mi grid libaom's
8156 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
8157 /// blockd.h). lane-t900 r12: the one-slot-per-column
8158 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
8159 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
8160 /// overwrote the row the pair's chroma-ref half then wanted to read --
8161 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
8162 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
8163 uv_mode_grid: Vec<u8>,
8164 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
8165 /// every other band here).
8166 uv_grid_cols: usize,
8167 /// Whether the block above/left of this column/row was coded `skip` --
8168 /// an inter frame's own `skip` context (spec `SkipContext`), which the
8169 /// key-frame writer never tracks (its skip context is always zero); a
8170 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
8171 /// `left_skip`.
8172 above_skip: Vec<bool>,
8173 left_skip: Vec<bool>,
8174 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
8175 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
8176 /// pixels last written over each unit by `set_txfm_ctxs`/
8177 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
8178 /// symbol reads its context from (lane-txselect, spec 5.11.17).
8179 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
8180 /// array is exactly libaom's per-superblock-row reset, since each mi row
8181 /// is only ever visited inside one superblock row.
8182 above_txfm: Vec<u8>,
8183 left_txfm: Vec<u8>,
8184 /// Whether the block above/left of this column/row coded `skip_mode`
8185 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
8186 /// lane-av1comp round 14.
8187 above_skip_mode: Vec<bool>,
8188 left_skip_mode: Vec<bool>,
8189 /// Whether the block above/left was coded inter -- the `is_inter`
8190 /// context (spec `av1_get_intra_inter_context`), a duplicate of
8191 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
8192 above_inter: Vec<bool>,
8193 left_inter: Vec<bool>,
8194 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
8195 /// alphabet) the block above/left of this column/row coded, or `-1` for
8196 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
8197 /// functions (`mvstack::ref_ctx` family) need the real reference, not
8198 /// just "was it inter" (lane-av1refs: every inter block used to be
8199 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
8200 /// enough).
8201 above_ref: Vec<i8>,
8202 left_ref: Vec<i8>,
8203 /// The block above/left's *second* reference frame when it was coded
8204 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
8205 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
8206 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
8207 /// `i8`, once a compound `read_ref_frames` lands.
8208 /// lane-publish2 audit: the "always `None` today" note this doc used to
8209 /// carry is long stale -- compound blocks do occur, and
8210 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
8211 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
8212 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
8213 /// [`crate::mvstack::NeighbourRef`] construction (class
8214 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
8215 above_ref1: Vec<Option<i8>>,
8216 left_ref1: Vec<Option<i8>>,
8217 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
8218 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
8219 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
8220 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
8221 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
8222 above_comp_group_idx: Vec<u8>,
8223 left_comp_group_idx: Vec<u8>,
8224 above_compound_idx: Vec<u8>,
8225 left_compound_idx: Vec<u8>,
8226 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
8227 /// `3` = "no info": an intra neighbour or the frame's own border) of the
8228 /// block above/left of this column/row -- spec
8229 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
8230 above_filter: Vec<[u8; 2]>,
8231 left_filter: Vec<[u8; 2]>,
8232 mi_cols: usize,
8233 mi_rows: usize,
8234 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
8235 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
8236 /// 7.15) never filters an 8x8 luma block whose covering coded block read
8237 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
8238 /// grain [`Self::record_mi`] already writes at), read back at 8x8
8239 /// granularity by [`apply_cdef`] since `skip` is constant across every
8240 /// mi cell one coded block covers.
8241 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
8242 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
8243 /// the `skip` bit at this mi cell during this frame. A fresh
8244 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
8245 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
8246 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
8247 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
8248 /// unobservable from the pixels alone. Counted by
8249 /// [`cdef_unwritten_skip_units`].
8250 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
8251 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
8252 /// which re-enables the loop filter at a prediction boundary between two
8253 /// skipped inter blocks (lane-mergefix r4). Written by
8254 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
8255 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
8256 /// that cell -- the other half of `pu_edge`: libaom tests the edge
8257 /// coordinate against the block's size in the FILTERED plane's own
8258 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
8259 blk_grid: Vec<BlkCell>,
8260 skip_grid_cols_mi: usize,
8261 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
8262 /// never splits a coded block's transform below its own size (round 2:
8263 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
8264 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
8265 /// edge-length lookup (`apply_deblock`).
8266 tx_grid: Vec<u8>,
8267 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
8268 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
8269 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
8270 tx_h_grid: Vec<u8>,
8271 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
8272 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
8273 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
8274 /// does NOT follow luma's `tx_depth` split, so deriving it as
8275 /// `tx_grid / 2` invented chroma transform edges the deblocker then
8276 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
8277 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
8278 /// every caller routes through.
8279 uv_tx_grid: Vec<u8>,
8280 uv_tx_h_grid: Vec<u8>,
8281 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
8282 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
8283 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
8284 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
8285 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
8286 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
8287 /// reference onto `LAST_FRAME`'s own delta).
8288 ref_grid: Vec<i8>,
8289 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
8290 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
8291 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
8292 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
8293 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
8294 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
8295 /// to know which mode produced the value.
8296 delta_lf_grid: Vec<[i8; 4]>,
8297 /// The block above/left's own palette-Y size (0 = not a palette block)
8298 /// and its base colours -- `av1_get_palette_mode_ctx`/
8299 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
8300 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
8301 above_palette_size: Vec<u8>,
8302 left_palette_size: Vec<u8>,
8303 above_palette_colors: Vec<[u16; 8]>,
8304 left_palette_colors: Vec<[u16; 8]>,
8305 /// As the four fields above, for the neighbour's own chroma (U-channel
8306 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
8307 /// palette size/colours (lane-palette2 r1).
8308 above_palette_uv_size: Vec<u8>,
8309 left_palette_uv_size: Vec<u8>,
8310 above_palette_uv_colors: Vec<[u16; 8]>,
8311 left_palette_uv_colors: Vec<[u16; 8]>,
8312 /// This tile's own top-left corner, in 4x4 mode-info units (spec
8313 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
8314 /// neighbour" check compares against this instead of literal `0`, since a
8315 /// block at the tile's own top/left edge has no usable neighbour even
8316 /// though a decoded block sits there in the picture (spec `decode_tile`'s
8317 /// per-tile `clear_above_context`/`left_available`/`up_available`).
8318 /// `0` for a single-tile frame, matching every existing caller exactly.
8319 tile_row0_mi: usize,
8320 tile_col0_mi: usize,
8321}
8322
8323#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8324impl Neighbours {
8325 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
8326 /// true (unpadded) size in 4x4 mode-info units.
8327 fn new(
8328 cols: usize,
8329 rows: usize,
8330 mi_cols: usize,
8331 mi_rows: usize,
8332 fctx: &crate::decode::FrameCtx,
8333 ) -> Self {
8334 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
8335 // neighbour state over the whole 64-row extent, past the frame's last
8336 // mi row (mi_rows 198, block rows 192..208). libaom's own context
8337 // buffers are superblock-aligned for exactly that reason
8338 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
8339 // side arrays to a superblock multiple and leave those cells unread --
8340 // every availability check uses the true `mi_rows`/`mi_cols` below.
8341 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
8342 let (cols, rows) = (cols.next_multiple_of(sb_sub), rows.next_multiple_of(sb_sub));
8343 Self {
8344 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
8345 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
8346 above_mode: vec![DC_PRED; cols],
8347 left_mode: vec![DC_PRED; rows],
8348 above_uv_mode: vec![DC_PRED; cols],
8349 left_uv_mode: vec![DC_PRED; rows],
8350 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
8351 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
8352 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
8353 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
8354 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
8355 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
8356 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
8357 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
8358 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
8359 uv_grid_cols: cols * (SUB / MI),
8360 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
8361 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
8362 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
8363 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
8364 // 16x16 block beside it, which a SUB-grid slot cannot name
8365 // (class context-read-from-one-cell).
8366 above_skip: vec![false; cols * (SUB / MI)],
8367 left_skip: vec![false; rows * (SUB / MI)],
8368 above_skip_mode: vec![false; cols * (SUB / MI)],
8369 left_skip_mode: vec![false; rows * (SUB / MI)],
8370 above_inter: vec![false; cols * (SUB / MI)],
8371 left_inter: vec![false; rows * (SUB / MI)],
8372 above_ref: vec![-1; cols * (SUB / MI)],
8373 left_ref: vec![-1; rows * (SUB / MI)],
8374 above_ref1: vec![None; cols * (SUB / MI)],
8375 left_ref1: vec![None; rows * (SUB / MI)],
8376 above_comp_group_idx: vec![0; cols * (SUB / MI)],
8377 left_comp_group_idx: vec![0; rows * (SUB / MI)],
8378 above_compound_idx: vec![0; cols * (SUB / MI)],
8379 left_compound_idx: vec![0; rows * (SUB / MI)],
8380 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
8381 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
8382 mi_cols,
8383 mi_rows,
8384 blk_grid: vec![
8385 BlkCell {
8386 skip: false,
8387 written: false,
8388 org: [0; 2],
8389 dim: [1; 2]
8390 };
8391 cols * (SUB / MI) * rows * (SUB / MI)
8392 ],
8393 skip_grid_cols_mi: cols * (SUB / MI),
8394 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8395 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8396 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8397 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
8398 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
8399 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
8400 above_palette_size: vec![0; cols * (SUB / MI)],
8401 left_palette_size: vec![0; rows * (SUB / MI)],
8402 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
8403 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
8404 above_palette_uv_size: vec![0; cols * (SUB / MI)],
8405 left_palette_uv_size: vec![0; rows * (SUB / MI)],
8406 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
8407 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
8408 tile_row0_mi: 0,
8409 tile_col0_mi: 0,
8410 }
8411 }
8412
8413 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
8414 /// tile's own column span (`col1_mi` exclusive), plus recording
8415 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
8416 /// availability check below. Left context resets every superblock row
8417 /// regardless of tile ([`Self::start_row`], already called once per SB
8418 /// row by every caller) so it needs no tile-specific reset here.
8419 fn start_tile(
8420 &mut self,
8421 row0_mi: usize,
8422 col0_mi: usize,
8423 col1_mi: usize,
8424 fctx: &crate::decode::FrameCtx,
8425 ) {
8426 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
8427 // are tile-relative, same as every other neighbour lookup here.
8428 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
8429 self.tile_row0_mi = row0_mi;
8430 self.tile_col0_mi = col0_mi;
8431 let end = col1_mi.min(self.above.len());
8432 for i in col0_mi.min(end)..end {
8433 self.above[i] = Default::default();
8434 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
8435 }
8436 let (sc0, sc1) = (
8437 col0_mi / (SUB / MI),
8438 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
8439 );
8440 for i in sc0.min(sc1)..sc1 {
8441 self.above_mode[i] = DC_PRED;
8442 self.above_side[i] = NO_NEIGHBOUR_SIDE;
8443 }
8444 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
8445 // the tile's own mi column span directly.
8446 let mend = col1_mi.min(self.above_skip.len());
8447 for i in col0_mi.min(mend)..mend {
8448 self.above_skip[i] = false;
8449 self.above_skip_mode[i] = false;
8450 self.above_inter[i] = false;
8451 self.above_ref[i] = -1;
8452 self.above_ref1[i] = None;
8453 self.above_comp_group_idx[i] = 0;
8454 self.above_compound_idx[i] = 0;
8455 self.above_filter[i] = [3u8; 2];
8456 }
8457 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
8458 // stale `(row, mode)` from the tile to the LEFT names an mi row this
8459 // tile's first block would read as its own above neighbour.
8460 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
8461 for i in col0_mi.min(mcol_end)..mcol_end {
8462 self.sub8_mode_col[i] = (u16::MAX, 0);
8463 self.uv_mode_col[i] = (u16::MAX, 0);
8464 }
8465 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
8466 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
8467 // not zero) -- without it a second tile column reads the first one's
8468 // resolved transform sizes as its own above context.
8469 let tend = col1_mi.min(self.above_txfm.len());
8470 for i in col0_mi.min(tend)..tend {
8471 self.above_txfm[i] = TXFM_CTX_INIT;
8472 }
8473 }
8474
8475 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
8476 /// for a non-palette block, clearing any stale neighbour state) into every
8477 /// [`SUB`]-grid cell it covers on both the above and left edges --
8478 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
8479 /// call sites are all square blocks).
8480 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
8481 self.record_palette_y_rect(
8482 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
8483 side,
8484 side,
8485 size,
8486 colors,
8487 );
8488 }
8489
8490 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
8491 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
8492 /// [`Self::record`]): a true rect strip's above/left neighbour spans
8493 /// differ.
8494 fn record_palette_y_rect(
8495 &mut self,
8496 mi: (usize, usize),
8497 w: usize,
8498 h: usize,
8499 size: usize,
8500 colors: [u16; 8],
8501 ) {
8502 let (r, c) = mi;
8503 if crate::envflags::env_flag!("EC_PALPUB") {
8504 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
8505 }
8506 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
8507 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
8508 // cell immediately left of the block, not its 16px [`SUB`] cell. The
8509 // old SUB grid let a 16x8 strip pair share one slot, so the second
8510 // strip of mi(0,8) read the FIRST strip's palette size and the colour
8511 // cache came out one entry short (class [[context-read-from-one-cell]]).
8512 for cell in 0..(w / MI).max(1) {
8513 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
8514 *e = size as u8;
8515 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
8516 // neighbour's colours only where its palette size > 0, so a
8517 // non-palette block need not stamp 16 bytes of zeroes here.
8518 if size > 0 {
8519 self.above_palette_colors[c + cell] = colors;
8520 }
8521 }
8522 }
8523 for cell in 0..(h / MI).max(1) {
8524 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
8525 *e = size as u8;
8526 if size > 0 {
8527 self.left_palette_colors[r + cell] = colors;
8528 }
8529 }
8530 }
8531 }
8532
8533 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
8534 /// neighbours that are themselves a palette-Y block, plus
8535 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
8536 /// cache (pred_common.c:73).
8537 ///
8538 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
8539 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
8540 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
8541 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
8542 /// the ctx too made every superblock in the frame's second SB row read
8543 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
8544 /// palette block decoded as "no palette" and the tile desynced from
8545 /// there (class [[cdf-row-held-constant]]).
8546 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
8547 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
8548 }
8549
8550 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
8551 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
8552 /// drops the above neighbour on a 64-px superblock boundary
8553 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
8554 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
8555 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
8556 /// every strip in an SB's top cell row, which libaom does not do.
8557 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
8558 let (r, c) = mi;
8559 let above_ok = r % 16 != 0;
8560 // `xd->above_mbmi` exists for every row but the tile's own first.
8561 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
8562 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
8563 (
8564 usize::from(self.above_palette_size[c]),
8565 self.above_palette_colors[c],
8566 )
8567 } else {
8568 (0, [0u16; 8])
8569 };
8570 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
8571 // is NULL whenever the block sits at its TILE's own left column
8572 // (`left_available`), not the frame's -- without this guard a second
8573 // tile column reads the previous tile's palette colours into its cache
8574 // and its `palette_y_mode` ctx.
8575 let left_ok = c > self.tile_col0_mi;
8576 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
8577 (
8578 usize::from(self.left_palette_size[r]),
8579 self.left_palette_colors[r],
8580 )
8581 } else {
8582 (0, [0u16; 8])
8583 };
8584 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
8585 let mut cache = Vec::with_capacity(16);
8586 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
8587 if cache.last() != Some(&v) {
8588 cache.push(v);
8589 }
8590 };
8591 let (mut ai, mut li) = (0usize, 0usize);
8592 while ai < above_n && li < left_n {
8593 let (va, vl) = (above_colors[ai], left_colors[li]);
8594 if vl < va {
8595 push_dedup(&mut cache, vl);
8596 li += 1;
8597 } else {
8598 push_dedup(&mut cache, va);
8599 ai += 1;
8600 if vl == va {
8601 li += 1;
8602 }
8603 }
8604 }
8605 while ai < above_n {
8606 push_dedup(&mut cache, above_colors[ai]);
8607 ai += 1;
8608 }
8609 while li < left_n {
8610 push_dedup(&mut cache, left_colors[li]);
8611 li += 1;
8612 }
8613 (ctx, cache)
8614 }
8615
8616 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
8617 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
8618 /// same way (lane-palette2 r1).
8619 fn record_palette_uv(
8620 &mut self,
8621 at: (usize, usize),
8622 side: usize,
8623 size: usize,
8624 colors: [u16; 8],
8625 ) {
8626 self.record_palette_uv_rect(
8627 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
8628 side,
8629 side,
8630 size,
8631 colors,
8632 );
8633 }
8634
8635 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
8636 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
8637 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
8638 /// luma resolution regardless of which plane the recorded state is for).
8639 fn record_palette_uv_rect(
8640 &mut self,
8641 mi: (usize, usize),
8642 w: usize,
8643 h: usize,
8644 size: usize,
8645 colors: [u16; 8],
8646 ) {
8647 let (r, c) = mi;
8648 // mi granularity, see [`Self::record_palette_y_rect`].
8649 for cell in 0..(w / MI).max(1) {
8650 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
8651 *e = size as u8;
8652 if size > 0 {
8653 self.above_palette_uv_colors[c + cell] = colors;
8654 }
8655 }
8656 }
8657 for cell in 0..(h / MI).max(1) {
8658 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
8659 *e = size as u8;
8660 if size > 0 {
8661 self.left_palette_uv_colors[r + cell] = colors;
8662 }
8663 }
8664 }
8665 }
8666
8667 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
8668 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
8669 /// no neighbour lookup at all (it is this block's own just-decided Y
8670 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
8671 /// so only the cache is wanted here.
8672 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
8673 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
8674 }
8675
8676 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
8677 /// [`Self::palette_ctx_and_cache_mi`].
8678 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
8679 let (r, c) = mi;
8680 let above_ok = r % 16 != 0;
8681 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
8682 (
8683 usize::from(self.above_palette_uv_size[c]),
8684 self.above_palette_uv_colors[c],
8685 )
8686 } else {
8687 (0, [0u16; 8])
8688 };
8689 // Same tile-relative left availability as the luma cache above.
8690 let left_ok = c > self.tile_col0_mi;
8691 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
8692 (
8693 usize::from(self.left_palette_uv_size[r]),
8694 self.left_palette_uv_colors[r],
8695 )
8696 } else {
8697 (0, [0u16; 8])
8698 };
8699 let mut cache = Vec::with_capacity(16);
8700 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
8701 if cache.last() != Some(&v) {
8702 cache.push(v);
8703 }
8704 };
8705 let (mut ai, mut li) = (0usize, 0usize);
8706 while ai < above_n && li < left_n {
8707 let (va, vl) = (above_colors[ai], left_colors[li]);
8708 if vl < va {
8709 push_dedup(&mut cache, vl);
8710 li += 1;
8711 } else {
8712 push_dedup(&mut cache, va);
8713 ai += 1;
8714 if vl == va {
8715 li += 1;
8716 }
8717 }
8718 }
8719 while ai < above_n {
8720 push_dedup(&mut cache, above_colors[ai]);
8721 ai += 1;
8722 }
8723 while li < left_n {
8724 push_dedup(&mut cache, left_colors[li]);
8725 li += 1;
8726 }
8727 cache
8728 }
8729
8730 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
8731 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
8732 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
8733 /// units as [`Self::fill_skip_grid`].
8734 fn fill_lf_grid(
8735 &mut self,
8736 at_mi: (usize, usize),
8737 side_mi: usize,
8738 tx_px: u8,
8739 ref_frame: i8,
8740 fctx: &crate::decode::FrameCtx,
8741 ) {
8742 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
8743 }
8744
8745 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
8746 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
8747 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
8748 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
8749 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
8750 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
8751 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
8752 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
8753 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
8754 /// block's published transform extent to its own size is exactly that
8755 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
8756 /// that needs it is the 128 root, whose chroma extent (64) is the one
8757 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
8758 /// never suppressed (libaom's `is_inter_block` term), so this is called
8759 /// only from the skipped-inter branch.
8760 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
8761 let (mi_r, mi_c) = at_mi;
8762 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
8763 for rr in 0..h_mi {
8764 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
8765 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
8766 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
8767 }
8768 }
8769
8770 fn fill_lf_grid_rect(
8771 &mut self,
8772 at_mi: (usize, usize),
8773 w_mi: usize,
8774 h_mi: usize,
8775 tx_px: u8,
8776 tx_h_px: u8,
8777 ref_frame: i8,
8778 fctx: &crate::decode::FrameCtx,
8779 ) {
8780 let (mi_r, mi_c) = at_mi;
8781 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
8782 // half its luma one (min 4 px, the smallest transform), capped at
8783 // TX_32X32 -- independent of this block's luma `tx_depth`.
8784 let uv_tx_w = (((w_mi * MI) >> ss_x(fctx)).max(4).min(32)) as u8;
8785 let uv_tx_h = (((h_mi * MI) >> ss_y(fctx)).max(4).min(32)) as u8;
8786 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
8787 eprintln!(
8788 "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}"
8789 );
8790 }
8791 crate::census::tx(tx_px, tx_h_px);
8792 let cur = fctx.current_delta_lf.with(|c| c.get());
8793 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
8794 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
8795 } else {
8796 [cur[0].clamp(-63, 63) as i8; 4]
8797 };
8798 for rr in 0..h_mi {
8799 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
8800 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
8801 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
8802 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
8803 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
8804 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
8805 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
8806 }
8807 if fctx.intra_only.with(std::cell::Cell::get) {
8808 // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size,
8809 // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi),
8810 // xd)` for EVERY block, an intra-only frame's included, and
8811 // `get_tx_size_context` / `txfm_partition_context` read those two
8812 // `TXFM_CONTEXT` bands. This grid carries the same transform size
8813 // over the same footprint, so the publish is this write: the
8814 // `skip && is_inter` term is 0 for every intra-only block that is
8815 // not an intrabc one, and the bodies that can code an intrabc
8816 // block publish their own (the term is then the BLOCK size, a value
8817 // this grid cannot express -- see `decode_block`/`decode_leaf8`).
8818 // Inter frames publish at their own sites and are excluded here
8819 // because their skipped-block term needs the block size too.
8820 txfm_partition_update_rect(
8821 self,
8822 at_mi,
8823 (tx_px as usize, tx_h_px as usize),
8824 (w_mi * MI, h_mi * MI),
8825 );
8826 // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`),
8827 // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size
8828 // instead of its transform band. Every block stamps its own cells
8829 // here; the intrabc bodies re-stamp theirs `true` afterwards
8830 // (`record_intrabc_inter_bands`).
8831 for i in 0..w_mi {
8832 if let Some(cell) = self.above_inter.get_mut(mi_c + i) {
8833 *cell = false;
8834 }
8835 }
8836 for i in 0..h_mi {
8837 if let Some(cell) = self.left_inter.get_mut(mi_r + i) {
8838 *cell = false;
8839 }
8840 }
8841 }
8842 // lane-av1-intrabc r4: publish this coded block's own mi footprint
8843 // into the intrabc MV grid's block-COVERAGE map -- every coded block,
8844 // not just the intrabc ones. A later intrabc block's DV predictor is
8845 // built by libaom's own row/col scans over `xd->mi[]`, which holds an
8846 // `MB_MODE_INFO` for EVERY block and steps by
8847 // `mi_size_wide/height[candidate->bsize]`; without this footprint a
8848 // non-intrabc neighbour reads as uncovered and the scan advances it
8849 // by one cell instead of by its real width.
8850 fctx.intrabc_mi_grid.with(|g| {
8851 if let Some((grid, _, _)) = g.borrow_mut().as_mut() {
8852 grid.cover_rect(mi_r, mi_c, w_mi, h_mi);
8853 }
8854 });
8855 }
8856
8857 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
8858 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
8859 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
8860 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
8861 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
8862 /// dims from the LEAF span and so invented chroma transform edges the
8863 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
8864 /// are already correct from the block's own fill over the same span.
8865 fn fill_lf_grid_leaf_luma(
8866 &mut self,
8867 at_mi: (usize, usize),
8868 w_mi: usize,
8869 h_mi: usize,
8870 tx_px: u8,
8871 tx_h_px: u8,
8872 ) {
8873 let (mi_r, mi_c) = at_mi;
8874 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
8875 eprintln!(
8876 "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}"
8877 );
8878 }
8879 for rr in 0..h_mi {
8880 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
8881 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
8882 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
8883 }
8884 }
8885
8886 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
8887 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
8888 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
8889 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
8890 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
8891 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
8892 }
8893
8894 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
8895 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
8896 let (mi_r, mi_c) = at_mi;
8897 if skip && w_mi != h_mi {
8898 hit!(RECT_SKIP_BAND_HITS);
8899 }
8900 // lane-census: an INTRA frame's blocks never reach the inter
8901 // publisher, and this one is what every coded block writes.
8902 crate::census::block_intra_frame(w_mi, h_mi, skip);
8903 for rr in 0..h_mi {
8904 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
8905 fill_span(
8906 &mut self.blk_grid,
8907 start,
8908 w_mi,
8909 BlkCell {
8910 skip,
8911 written: true,
8912 org: [mi_r as u16, mi_c as u16],
8913 dim: [w_mi as u8, h_mi as u8],
8914 },
8915 );
8916 }
8917 }
8918
8919 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
8920 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
8921 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
8922 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
8923 /// straddle the region with a mix of skip/non-skip blocks).
8924 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
8925 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
8926 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
8927 /// filtered edge's two sides are each exactly one coded block wide.
8928 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
8929 self.blk_grid
8930 .get(mi_r * self.skip_grid_cols_mi + mi_c)
8931 .is_some_and(|c| c.skip)
8932 }
8933
8934 /// The `skip_txfm` context of a block whose top-left mi cell is
8935 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
8936 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
8937 /// with an absent neighbour contributing 0. The mi grid is per tile, so
8938 /// row/column 0 is a tile edge and has no neighbour on that axis.
8939 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
8940 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
8941 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
8942 }
8943
8944 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
8945 (0..2).all(|rr| {
8946 (0..2).all(|cc| {
8947 self.blk_grid
8948 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
8949 .is_some_and(|c| c.skip)
8950 })
8951 })
8952 }
8953
8954 fn start_row(&mut self) {
8955 self.left.iter_mut().for_each(|l| *l = Default::default());
8956 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
8957 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
8958 self.left_side
8959 .iter_mut()
8960 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
8961 self.left_side_mi
8962 .iter_mut()
8963 .for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
8964 self.left_skip.iter_mut().for_each(|s| *s = false);
8965 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
8966 self.left_inter.iter_mut().for_each(|i| *i = false);
8967 self.left_ref.iter_mut().for_each(|r| *r = -1);
8968 self.left_ref1.iter_mut().for_each(|r| *r = None);
8969 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
8970 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
8971 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
8972 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
8973 // context (a tile/SB-row boundary has no left neighbour).
8974 self.sub8_mode_row
8975 .iter_mut()
8976 .for_each(|s| *s = (u16::MAX, 0));
8977 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
8978 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
8979 // are per-mi maps like every other one here, so they reset with the
8980 // row too -- the left guard above is what actually stops a cross-tile
8981 // read, this keeps a stale colour out of the arrays at all.
8982 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
8983 self.left_palette_colors
8984 .iter_mut()
8985 .for_each(|c| *c = [0u16; 8]);
8986 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
8987 self.left_palette_uv_colors
8988 .iter_mut()
8989 .for_each(|c| *c = [0u16; 8]);
8990 // lane-mergefix r2: `av1_zero_left_context` memsets
8991 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
8992 // every superblock row of every tile -- the var-tx left context does
8993 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
8994 // previous tile column's last block otherwise).
8995 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
8996 }
8997
8998 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
8999 /// block that reads it as a neighbour -- [`crate::tile`]'s
9000 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
9001 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
9002 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
9003 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
9004 /// the real value, not just `is_inter`).
9005 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9006 fn record_inter(
9007 &mut self,
9008 at: (usize, usize),
9009 side: usize,
9010 skip: bool,
9011 is_inter: bool,
9012 ref_frame: i8,
9013 filter: [u8; 2],
9014 skip_mode: bool,
9015 ) {
9016 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
9017 }
9018
9019 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
9020 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
9021 /// r1: a true rectangular strip's above-context span (its own width) and
9022 /// left-context span (its own height) differ, unlike every caller before
9023 /// this round (class neighbour-votes-all-its-fields).
9024 #[allow(clippy::too_many_arguments)]
9025 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9026 fn record_inter_rect(
9027 &mut self,
9028 at: (usize, usize),
9029 w_sub: usize,
9030 h_sub: usize,
9031 skip: bool,
9032 is_inter: bool,
9033 ref_frame: i8,
9034 filter: [u8; 2],
9035 skip_mode: bool,
9036 ) {
9037 let (r, c) = at;
9038 self.record_inter_rect_mi(
9039 (r * (SUB / MI), c * (SUB / MI)),
9040 w_sub / MI,
9041 h_sub / MI,
9042 skip,
9043 is_inter,
9044 ref_frame,
9045 filter,
9046 skip_mode,
9047 );
9048 }
9049
9050 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
9051 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
9052 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
9053 /// routes through the wrapper above.
9054 #[allow(clippy::too_many_arguments)]
9055 fn record_inter_rect_mi(
9056 &mut self,
9057 at_mi: (usize, usize),
9058 w_mi: usize,
9059 h_mi: usize,
9060 skip: bool,
9061 is_inter: bool,
9062 ref_frame: i8,
9063 filter: [u8; 2],
9064 skip_mode: bool,
9065 ) {
9066 let (r, c) = at_mi;
9067 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
9068 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
9069 // writes for a whole block class): an INTER block left the luma mode
9070 // map untouched, so a later intra block's `get_intra_edge_filter_type`
9071 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
9072 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
9073 // block in that pixel row -- the directional edge filter then ran at
9074 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
9075 // which for an inter block is an INTER mode (>= NEARESTMV) and is
9076 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
9077 // already stamped it).
9078 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
9079 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
9080 // uv map must read DC_PRED over an inter block's cells too.
9081 if is_inter {
9082 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9083 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9084 }
9085 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
9086 self.above_skip[c..c + w_mi].fill(skip);
9087 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
9088 self.above_inter[c..c + w_mi].fill(is_inter);
9089 self.above_ref[c..c + w_mi].fill(ref_frame);
9090 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
9091 // this with the block's real second reference for a compound block,
9092 // called right after this one (lane-publish2 audit).
9093 self.above_ref1[c..c + w_mi].fill(None);
9094 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
9095 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
9096 // as `3`/`1` even though this block has no second reference.
9097 // `record_compound_ctx` overwrites this with the real bit for an
9098 // actual compound block's cells, called right after this one.
9099 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
9100 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
9101 self.above_filter[c..c + w_mi].fill(filter);
9102 self.left_skip[r..r + h_mi].fill(skip);
9103 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
9104 self.left_inter[r..r + h_mi].fill(is_inter);
9105 self.left_ref[r..r + h_mi].fill(ref_frame);
9106 self.left_ref1[r..r + h_mi].fill(None);
9107 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
9108 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
9109 self.left_filter[r..r + h_mi].fill(filter);
9110 }
9111
9112 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
9113 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
9114 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
9115 /// `get_comp_index_context`) -- called right after `record_inter` for
9116 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
9117 /// stamps `above_ref1`/`left_ref1` with the block's real second
9118 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
9119 /// this is the one caller that actually knows it) -- so the next block's
9120 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
9121 /// neighbour instead of `record_inter`'s single-ref default.
9122 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9123 fn record_compound_ctx(
9124 &mut self,
9125 at: (usize, usize),
9126 side: usize,
9127 ref1: i8,
9128 comp_group_idx: u8,
9129 compound_idx: u8,
9130 ) {
9131 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
9132 }
9133
9134 /// [`Self::record_compound_ctx`] with independent above/left extents,
9135 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
9136 #[allow(clippy::too_many_arguments)]
9137 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9138 fn record_compound_ctx_rect(
9139 &mut self,
9140 at: (usize, usize),
9141 w_sub: usize,
9142 h_sub: usize,
9143 ref1: i8,
9144 comp_group_idx: u8,
9145 compound_idx: u8,
9146 ) {
9147 let (r, c) = at;
9148 self.record_compound_ctx_rect_mi(
9149 (r * (SUB / MI), c * (SUB / MI)),
9150 w_sub / MI,
9151 h_sub / MI,
9152 ref1,
9153 comp_group_idx,
9154 compound_idx,
9155 );
9156 }
9157
9158 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
9159 /// [`Self::record_inter_rect_mi`]).
9160 fn record_compound_ctx_rect_mi(
9161 &mut self,
9162 at_mi: (usize, usize),
9163 w_mi: usize,
9164 h_mi: usize,
9165 ref1: i8,
9166 comp_group_idx: u8,
9167 compound_idx: u8,
9168 ) {
9169 let (r, c) = at_mi;
9170 crate::census::compound();
9171 for cell in 0..w_mi {
9172 self.above_ref1[c + cell] = Some(ref1);
9173 self.above_comp_group_idx[c + cell] = comp_group_idx;
9174 self.above_compound_idx[c + cell] = compound_idx;
9175 }
9176 for cell in 0..h_mi {
9177 self.left_ref1[r + cell] = Some(ref1);
9178 self.left_comp_group_idx[r + cell] = comp_group_idx;
9179 self.left_compound_idx[r + cell] = compound_idx;
9180 }
9181 }
9182
9183 /// The context of a block's partition symbol: delegates to the mi-precise
9184 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
9185 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
9186 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
9187 /// only touches the finer mi arrays -- leaves them stale for the *next*
9188 /// sibling's own partition symbol.
9189 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
9190 let (r, c) = at;
9191 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
9192 }
9193
9194 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
9195 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
9196 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
9197 /// than the enclosing 16x16 slot's stale, shared state.
9198 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
9199 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
9200 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
9201 }
9202
9203 /// The gathered coded/DC-sign state of the blocks above and to the left
9204 /// of a block `side` samples across, per plane.
9205 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
9206 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
9207 }
9208
9209 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
9210 /// units, for the same reason [`Self::record_mi`] does.
9211 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
9212 let side_mi = side / MI;
9213 // One pass over the cells accumulating all three planes, not one pass
9214 // per plane: the three planes of a cell live in the same
9215 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
9216 // cache lines three times (lane-publish). Clamp each edge to the true
9217 // frame extent: a block at the right/bottom edge may be padded beyond
9218 // `mi_cols`/`mi_rows`, and libaom's unavailable context is zero there.
9219 let above_mi = side_mi.min(self.mi_cols.saturating_sub(mi_c));
9220 let left_mi = side_mi.min(self.mi_rows.saturating_sub(mi_r));
9221 let mut out = [(false, false, 0i32); 3];
9222 for cell in 0..above_mi {
9223 let above = &self.above[mi_c + cell];
9224 for (plane, o) in out.iter_mut().enumerate() {
9225 o.0 |= above[plane].level != 0;
9226 o.2 += dc_vote(above[plane].dc);
9227 }
9228 }
9229 for cell in 0..left_mi {
9230 let left = &self.left[mi_r + cell];
9231 for (plane, o) in out.iter_mut().enumerate() {
9232 o.1 |= left[plane].level != 0;
9233 o.2 += dc_vote(left[plane].dc);
9234 }
9235 }
9236 out
9237 }
9238
9239 /// [`Self::around_mi_rect`] for the CHROMA planes of a 4:2:2 frame
9240 /// (lane-av1-422f): libaom `get_txb_ctx_general` reads its above votes
9241 /// over `txb_w_unit` CHROMA 4-px cells, and at ss_x 1 one chroma cell
9242 /// spans TWO luma mi columns. Both cells of a column carry the covering
9243 /// unit's whole-unit dc sign (the same value libaom stores), so the
9244 /// per-luma-mi sum counts each chroma column twice -- and
9245 /// `dc_sign_ctx`'s signum flips whenever the above and left votes have
9246 /// opposite signs with equal magnitude (measured at mi(4,4) plane 1 of
9247 /// the t422 fixture: ours read `dc_sign_cdf[1]`, the oracle row 0).
9248 /// Sampling every second above cell counts each chroma column once,
9249 /// which IS libaom's sum. The left extent is unsubsquared at ss_y 0, so
9250 /// its per-mi cells already line up one-to-one. The level booleans are
9251 /// ORs over duplicated cells, so the sampling cannot change them.
9252 fn around_mi_422_chroma(
9253 &self,
9254 (mi_r, mi_c): (usize, usize),
9255 w: usize,
9256 h: usize,
9257 ) -> [(bool, bool, i32); 3] {
9258 let (w_mi, h_mi) = (w / MI, h / MI);
9259 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9260 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9261 let mut out = [(false, false, 0i32); 3];
9262 for cell in (0..above_mi).step_by(2) {
9263 let above = &self.above[mi_c + cell];
9264 for (plane, o) in out.iter_mut().enumerate() {
9265 o.0 |= above[plane].level != 0;
9266 o.2 += dc_vote(above[plane].dc);
9267 }
9268 }
9269 for cell in 0..left_mi {
9270 let left = &self.left[mi_r + cell];
9271 for (plane, o) in out.iter_mut().enumerate() {
9272 o.1 |= left[plane].level != 0;
9273 o.2 += dc_vote(left[plane].dc);
9274 }
9275 }
9276 if crate::envflags::env_flag!("EC_DCDUMP") {
9277 // lane-av1422mi24: same dump [`Self::around_mi_rect`] prints, so
9278 // a rerouted 4:2:2 chroma gather stays visible under EC_DCDUMP=1.
9279 // The above rows are the SAMPLED (every-second) cells.
9280 for (plane, o) in out.iter().enumerate() {
9281 let vote = o.2;
9282 let ab: Vec<String> = (0..above_mi)
9283 .step_by(2)
9284 .map(|k| {
9285 format!(
9286 "{:?}/{}",
9287 self.above[mi_c + k][plane].dc,
9288 self.above[mi_c + k][plane].level
9289 )
9290 })
9291 .collect();
9292 let lf: Vec<String> = (0..left_mi)
9293 .map(|k| {
9294 format!(
9295 "{:?}/{}",
9296 self.left[mi_r + k][plane].dc,
9297 self.left[mi_r + k][plane].level
9298 )
9299 })
9300 .collect();
9301 eprintln!(
9302 "EC_DCDUMP422 mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
9303 ab.join(","),
9304 lf.join(",")
9305 );
9306 }
9307 }
9308 out
9309 }
9310
9311 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
9312 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
9313 /// extent pattern for a true rectangular strip's own coefficient context.
9314 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
9315 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
9316 }
9317
9318 /// [`Self::around_rect`] taking the block's position directly in 4x4
9319 /// mode-info units, mirroring [`Self::around_mi`].
9320 fn around_mi_rect(
9321 &self,
9322 (mi_r, mi_c): (usize, usize),
9323 w: usize,
9324 h: usize,
9325 ) -> [(bool, bool, i32); 3] {
9326 let (w_mi, h_mi) = (w / MI, h / MI);
9327 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9328 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9329 // [`Self::around_mi`]'s single pass, with the two extents split.
9330 let mut out = [(false, false, 0i32); 3];
9331 for cell in 0..above_mi {
9332 let above = &self.above[mi_c + cell];
9333 for (plane, o) in out.iter_mut().enumerate() {
9334 o.0 |= above[plane].level != 0;
9335 o.2 += dc_vote(above[plane].dc);
9336 }
9337 }
9338 for cell in 0..left_mi {
9339 let left = &self.left[mi_r + cell];
9340 for (plane, o) in out.iter_mut().enumerate() {
9341 o.1 |= left[plane].level != 0;
9342 o.2 += dc_vote(left[plane].dc);
9343 }
9344 }
9345 if crate::envflags::env_flag!("EC_DCDUMP") {
9346 for (plane, o) in out.iter().enumerate() {
9347 let vote = o.2;
9348 let ab: Vec<String> = (0..above_mi)
9349 .map(|k| {
9350 format!(
9351 "{:?}/{}",
9352 self.above[mi_c + k][plane].dc,
9353 self.above[mi_c + k][plane].level
9354 )
9355 })
9356 .collect();
9357 let lf: Vec<String> = (0..left_mi)
9358 .map(|k| {
9359 format!(
9360 "{:?}/{}",
9361 self.left[mi_r + k][plane].dc,
9362 self.left[mi_r + k][plane].level
9363 )
9364 })
9365 .collect();
9366 eprintln!(
9367 "EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
9368 ab.join(","),
9369 lf.join(",")
9370 );
9371 }
9372 }
9373 out
9374 }
9375
9376 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
9377 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
9378 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
9379 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
9380 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
9381 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
9382 /// is always 0, spec's `plane_bsize == tx_size` branch).
9383 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
9384 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
9385 }
9386
9387 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
9388 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
9389 /// context over `tx_size_wide` and the left one over `tx_size_high`.
9390 fn luma_skip_ctx_rect(&self, (mi_r, mi_c): (usize, usize), w_mi: usize, h_mi: usize) -> usize {
9391 let side_mi = w_mi;
9392 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
9393 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
9394 let mut top = 0u8;
9395 let mut left = 0u8;
9396 for cell in 0..above_mi {
9397 top |= self.above[mi_c + cell][0].level;
9398 }
9399 for cell in 0..left_mi {
9400 left |= self.left[mi_r + cell][0].level;
9401 }
9402 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
9403 if crate::envflags::env_flag!("EC_ECDUMP") {
9404 let ab: Vec<String> = (0..above_mi)
9405 .map(|k| self.above[mi_c + k][0].level.to_string())
9406 .collect();
9407 let lf: Vec<String> = (0..left_mi)
9408 .map(|k| self.left[mi_r + k][0].level.to_string())
9409 .collect();
9410 // lane-av1mix: the last few msac register states, so the
9411 // byte-position of the `all_zero` read can be matched against
9412 // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a
9413 // second run.
9414 let recent = crate::msac::symtrace::ecdump_recent(4)
9415 .iter()
9416 .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})"))
9417 .collect::<Vec<_>>()
9418 .join(" ");
9419 eprintln!(
9420 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]",
9421 ab.join(","),
9422 lf.join(","),
9423 recent
9424 );
9425 }
9426 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9427 eprintln!(
9428 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
9429 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
9430 );
9431 }
9432 ctx
9433 }
9434
9435 /// Writes one coded block into every cell it covers, on both grids: the
9436 /// mode/side arrays up to `side`'s own width, and the coefficient-context
9437 /// arrays up to the true frame edge — the units past it are left at their
9438 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
9439 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
9440 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
9441 /// not from this block's own side).
9442 fn record(
9443 &mut self,
9444 at: (usize, usize),
9445 side: usize,
9446 mode: usize,
9447 uv_mode: usize,
9448 grids: &[&[i32]; 3],
9449 ) {
9450 self.record_rect(at, side, side, mode, uv_mode, grids);
9451 }
9452
9453 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
9454 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
9455 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
9456 /// spec's per-edge partition-context rule, so a true rectangular block
9457 /// naturally wants two different values here rather than one.
9458 /// Writes this block's luma `mode` into the mi-granular
9459 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
9460 /// position a *later* neighbour would read it from: the block's LAST mi
9461 /// row for every column it spans (what the block below reads via
9462 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
9463 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
9464 /// read these back, and only when the recorded position is exactly their
9465 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
9466 fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) {
9467 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
9468 let mode = mode as u8;
9469 for cell in 0..mi_w {
9470 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
9471 *slot = (last_r, mode);
9472 }
9473 }
9474 for cell in 0..mi_h {
9475 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
9476 *slot = (last_c, mode);
9477 }
9478 }
9479 }
9480
9481 /// The mi-exact above/left neighbour luma mode for a block whose top-left
9482 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
9483 /// mi position (then the coarse [`SUB`]-grid slot is right by
9484 /// construction). See [`Self::record_mode_mi`].
9485 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
9486 match self.sub8_mode_col.get(mi_c) {
9487 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => {
9488 Some(usize::from(m))
9489 }
9490 _ => None,
9491 }
9492 }
9493
9494 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
9495 match self.sub8_mode_row.get(mi_r) {
9496 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => {
9497 Some(usize::from(m))
9498 }
9499 _ => None,
9500 }
9501 }
9502
9503 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
9504 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
9505 fn record_uv_mode_mi(
9506 &mut self,
9507 mi_r: usize,
9508 mi_c: usize,
9509 mi_w: usize,
9510 mi_h: usize,
9511 uv_mode: usize,
9512 ) {
9513 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
9514 fill_span(
9515 &mut self.uv_mode_col,
9516 mi_c,
9517 mi_w,
9518 (last_r as u16, uv_mode as u8),
9519 );
9520 fill_span(
9521 &mut self.uv_mode_row,
9522 mi_r,
9523 mi_h,
9524 (last_c as u16, uv_mode as u8),
9525 );
9526 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
9527 // covers, so the chroma neighbour read below is a plain grid read.
9528 let stride = self.uv_grid_cols;
9529 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
9530 for row in mi_r..=last_r {
9531 fill_span(
9532 &mut self.uv_mode_grid,
9533 row * stride + mi_c,
9534 n,
9535 uv_mode as u8,
9536 );
9537 }
9538 }
9539
9540 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
9541 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
9542 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
9543 /// block has recorded the exact neighbouring mi.
9544 fn smooth_uv_neighbour(
9545 &self,
9546 mi_r: usize,
9547 mi_c: usize,
9548 r: usize,
9549 c: usize,
9550 fctx: &crate::decode::FrameCtx,
9551 ) -> bool {
9552 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
9553 // REFERENCE block, not off the mi that carries the chroma syntax.
9554 // `set_mi_row_col` (`blockd.h`) takes
9555 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
9556 // only then `chroma_above_mbmi = base_mi[-stride]` /
9557 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
9558 // the ODD mi, so without the snap we looked one mi row/column too far
9559 // down/right -- the mi-exact slot never matched and the coarse
9560 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
9561 // 8x4 at (688, 100) = mi (51, 344): libaom's
9562 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
9563 // `UV_SMOOTH_PRED`), ours was 0, which flips
9564 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
9565 // false for type 1, TRUE for type 0) and upsampled an edge libaom
9566 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
9567 // predicting from it (class `context-read-from-one-cell`).
9568 // lane-av1-444: the snap is the SEQUENCE's subsampling, hardcoded
9569 // `& !1` before -- at subsampling 0/0 libaom's `mi_row & 0` snaps
9570 // nothing, and the hardcoded snap read a 4x4 leaf's smooth
9571 // neighbour two mi away (frame 0 of `av1-profile1-444.ivf`, leaf
9572 // mi(5,15): left neighbour SMOOTH_V at mi(5,14), read at mi(4,13)).
9573 let snap_y = (1usize << ss_y(fctx)) - 1;
9574 let snap_x = (1usize << ss_x(fctx)) - 1;
9575 // The snap IS libaom's `base_mi` de-offsetting (`set_mi_row_col`,
9576 // `av1_common_int.h:1395-1412`): `base_mi` is the block's own mi moved
9577 // by `-(mi_row & ss_y) * stride - (mi_col & ss_x)`. The helper applies
9578 // the two chroma-reference offsets on top of it -- see its own comment
9579 // for which axis each one moves.
9580 self.smooth_uv_neighbour_unsnapped(mi_r & !snap_y, mi_c & !snap_x, r, c, ss_x(fctx))
9581 }
9582
9583 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
9584 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
9585 /// counter wants this: it measures how often the snap CHANGES the answer,
9586 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
9587 /// decode path uses the snapping form.
9588 fn smooth_uv_neighbour_unsnapped(
9589 &self,
9590 mi_r: usize,
9591 mi_c: usize,
9592 r: usize,
9593 c: usize,
9594 ss_x: usize,
9595 ) -> bool {
9596 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
9597 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
9598 // array that `start_tile` does not clear, so a block on a tile's first
9599 // mi row used to read the uv_mode of the block above it in the tile
9600 // ABOVE and filter its chroma edge at that neighbour's strength
9601 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
9602 // at chroma (120, 32), the top-right tile's first block).
9603 let have_above = mi_r > self.tile_row0_mi;
9604 let have_left = mi_c > self.tile_col0_mi;
9605 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
9606 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
9607 {
9608 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
9609 }
9610 // The mi grid is libaom's own read; the two maps below stay as the
9611 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
9612 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
9613 (col < self.uv_grid_cols)
9614 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
9615 .flatten()
9616 .filter(|&m| m != u8::MAX)
9617 .map(usize::from)
9618 };
9619 // libaom's two chroma-reference mi, from `set_mi_row_col`
9620 // (`av1_common_int.h:1400-1401`), with `mi_r`/`mi_c` already
9621 // de-offset by the caller's `(mi_row & ss_y)` / `(mi_col & ss_x)`
9622 // snap -- i.e. already libaom's `base_mi`:
9623 //
9624 // chroma_above_mi = base_mi[-mi_stride + ss_x] row -1, col +ss_x
9625 // chroma_left_mi = base_mi[ss_y*mi_stride - 1] row +ss_y, col -1
9626 //
9627 // SHIPPED: the above COLUMN. It is `+ss_x` wherever `ss_x == 1` --
9628 // 4:2:0, 4:2:2 AND 4:4:0 all carry that column shift, and only 4:4:4
9629 // (`ss_x == 0`) leaves the read where it was. Measured: folding it in
9630 // leaves the 4:2:0 control byte-identical to `aomdec --rawvideo`; the
9631 // boolean it feeds is simply not exercised differently by that stream
9632 // at its blocks. One chroma column spans two luma mi columns, so the
9633 // chroma edge reaches into the right-hand luma block, and that is where
9634 // its reference lives.
9635 //
9636 // NOT SHIPPED -- KNOWN UNRESOLVED: the left read's `+ss_y` ROW term.
9637 // libaom puts the left reference one mi row DOWN at 4:2:0 and 4:4:0
9638 // (`ss_y == 1`) and on its own row at 4:2:2 (`ss_y == 0`); this reads
9639 // its own row at every subsampling. An earlier attempt applied the
9640 // `ss_y` term to the WRONG read (the above) and regressed the
9641 // byte-exact 4:2:0 control, which is what exposed the crossing. No
9642 // committed fixture presents a 1-mi-tall left neighbour (an 8x4 leaf's
9643 // left block) at 4:2:0/4:4:0, so nothing here can witness the correct
9644 // term today -- treat this as a named open discrepancy, not a settled
9645 // one. Unblock: one such stream.
9646 let above_mi = (mi_r.saturating_sub(1), mi_c + ss_x);
9647 let left_mi = (mi_r, mi_c.saturating_sub(1));
9648 let above = match self.uv_mode_col.get(above_mi.1) {
9649 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, above_mi.0, above_mi.1) => m,
9650 Some(&(row, m)) if have_above && usize::from(row) == above_mi.0 => usize::from(m),
9651 _ if have_above => self.above_uv_mode[c],
9652 _ => DC_PRED,
9653 };
9654 let left = match self.uv_mode_row.get(left_mi.0) {
9655 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, left_mi.0, left_mi.1) => m,
9656 Some(&(col, m)) if have_left && usize::from(col) == left_mi.1 => usize::from(m),
9657 _ if have_left => self.left_uv_mode[r],
9658 _ => DC_PRED,
9659 };
9660 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
9661 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
9662 }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| {
9663 !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if usize::from(col) == mi_c - 1 && usize::from(cm) == m)
9664 }) {
9665 hit!(UV_MODE_GRID_OVERRIDE_HITS);
9666 }
9667 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
9668 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
9669 // have been filtered at the wrong strength by the coarse map alone.
9670 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
9671 hit!(UV_MODE_MI_OVERRIDE_HITS);
9672 }
9673 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
9674 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
9675 {
9676 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
9677 }
9678 is_smooth_mode(above) || is_smooth_mode(left)
9679 }
9680
9681 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
9682 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
9683 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
9684 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
9685 /// holding an OLDER, larger block's mode -- it only ever recorded into the
9686 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
9687 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
9688 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
9689 /// a different CDF for the same mode value).
9690 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
9691 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
9692 /// only when `up_available` and `left_mbmi` only when `left_available`;
9693 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
9694 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
9695 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
9696 /// strip's mode as its "left neighbour" (measured on the band fixture at
9697 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
9698 fn modes_above_left_mi(
9699 &self,
9700 mi_r: usize,
9701 mi_c: usize,
9702 fallback: (usize, usize),
9703 ) -> (usize, usize) {
9704 let above = if mi_r > self.tile_row0_mi {
9705 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
9706 } else {
9707 DC_PRED
9708 };
9709 let left = if mi_c > self.tile_col0_mi {
9710 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
9711 } else {
9712 DC_PRED
9713 };
9714 (above, left)
9715 }
9716
9717 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
9718 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
9719 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
9720 /// per superblock row and never per tile, so the first block column of
9721 /// tile 2..N read the previous tile's mode as its left neighbour, and the
9722 /// above band survives across a tile ROW boundary the same way lane-mtfix's
9723 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
9724 /// `up_available`/`left_available` and uses DC_PRED otherwise
9725 /// ([`Self::modes_above_left_mi`]).
9726 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
9727 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
9728 let (above, left) =
9729 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
9730 if above != self.above_mode[c] || left != self.left_mode[r] {
9731 hit!(MODE_MI_OVERRIDE_HITS);
9732 }
9733 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
9734 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
9735 {
9736 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
9737 }
9738 // A neighbour the coarse band offered where the tile edge makes it
9739 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
9740 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
9741 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
9742 {
9743 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
9744 }
9745 (above, left)
9746 }
9747
9748 fn record_rect(
9749 &mut self,
9750 at: (usize, usize),
9751 w: usize,
9752 h: usize,
9753 mode: usize,
9754 uv_mode: usize,
9755 grids: &[&[i32]; 3],
9756 ) {
9757 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
9758 }
9759
9760 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
9761 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
9762 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
9763 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
9764 /// the [`SUB`]-unit path does).
9765 fn record_rect_mi(
9766 &mut self,
9767 at_mi: (usize, usize),
9768 w: usize,
9769 h: usize,
9770 mode: usize,
9771 uv_mode: usize,
9772 grids: &[&[i32]; 3],
9773 ) {
9774 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
9775 // lane-inter4 r2: a strip whose own footprint runs past the frame's
9776 // last 16-px column/row stamps only the cells that exist (libaom's
9777 // arrays are padded past the frame and those cells are never read).
9778 for cell in 0..w / SUB {
9779 if c + cell >= self.above_mode.len() {
9780 break;
9781 }
9782 self.above_mode[c + cell] = mode;
9783 self.above_uv_mode[c + cell] = uv_mode;
9784 self.above_side[c + cell] = w;
9785 }
9786 for cell in 0..h / SUB {
9787 if r + cell >= self.left_mode.len() {
9788 break;
9789 }
9790 self.left_mode[r + cell] = mode;
9791 self.left_uv_mode[r + cell] = uv_mode;
9792 self.left_side[r + cell] = h;
9793 }
9794 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
9795 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
9796 self.record_mi_rect(at_mi, w, h, grids);
9797 }
9798
9799 /// The coefficient-context half of [`Self::record`], taking the block's
9800 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
9801 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
9802 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
9803 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
9804 self.record_mi_rect(at_mi, side, side, grids);
9805 }
9806
9807 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
9808 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
9809 fn record_mi_rect(&mut self, at_mi: (usize, usize), w: usize, h: usize, grids: &[&[i32]; 3]) {
9810 let (mi_r, mi_c) = at_mi;
9811 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
9812 let (w_mi, h_mi) = (w / MI, h / MI);
9813 if crate::envflags::env_flag!("EC_ECPUB") {
9814 eprintln!(
9815 "EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}",
9816 states[0].level
9817 );
9818 }
9819 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
9820 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
9821 // A chroma 4x4 unit straddling the true luma edge is still whole in
9822 // chroma's own halved grid, so libaom rounds the luma bound up to the
9823 // plane's own 4x4 unit before clamping a subsampled plane
9824 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
9825 let round_up_even = |n: usize| n.div_ceil(2) * 2;
9826 let bound_h = [
9827 self.mi_rows,
9828 round_up_even(self.mi_rows),
9829 round_up_even(self.mi_rows),
9830 ];
9831 let bound_w = [
9832 self.mi_cols,
9833 round_up_even(self.mi_cols),
9834 round_up_even(self.mi_cols),
9835 ];
9836 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
9837 // past the padded side arrays (mi_rows 198, block rows 192..208);
9838 // libaom's own arrays are superblock-sized, so those cells simply
9839 // have no reader -- [`fill_span`] drops them, as the `break` did.
9840 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
9841 // predicate is three contiguous runs: all planes, chroma only, none
9842 // (lane-mi).
9843 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
9844 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
9845 let uv_only = [Neighbour::default(), states[1], states[2]];
9846 fill_span(&mut self.left, mi_r, luma_h, states);
9847 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
9848 fill_span(
9849 &mut self.left,
9850 mi_r + chroma_h,
9851 h_mi - chroma_h,
9852 [Neighbour::default(); 3],
9853 );
9854 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
9855 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
9856 let uv_only_w = [Neighbour::default(), states[1], states[2]];
9857 fill_span(&mut self.above, mi_c, luma_w, states);
9858 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
9859 fill_span(
9860 &mut self.above,
9861 mi_c + chroma_w,
9862 w_mi - chroma_w,
9863 [Neighbour::default(); 3],
9864 );
9865 }
9866
9867 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
9868 /// inside a coded block whose luma transform is smaller than its own
9869 /// side (`TxMode::Select`): the real per-transform-unit coefficient
9870 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
9871 /// coarse per-block `tx_grid`/`fill_lf_grid` state
9872 /// [`Self::record_split_luma`] still writes once for the whole block.
9873 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
9874 /// the caller's own [`Self::record_split_luma`] call sets those once,
9875 /// at the block's own true side, not this TU's.
9876 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
9877 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
9878 }
9879
9880 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
9881 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
9882 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
9883 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
9884 /// coefficient-context arrays are indexed by luma mi, the convention
9885 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
9886 /// clamp included.
9887 fn record_mi_chroma(
9888 &mut self,
9889 (mi_r, mi_c): (usize, usize),
9890 w_px: usize,
9891 h_px: usize,
9892 plane: usize,
9893 grid: &[i32],
9894 ) {
9895 let round_up_even = |n: usize| n.div_ceil(2) * 2;
9896 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
9897 let state = neighbour_state(grid);
9898 if crate::envflags::env_flag!("EC_CHROMA_PUB") {
9899 eprintln!(
9900 "EC_CHROMA_PUB plane={plane} mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={} dc={}",
9901 state.level,
9902 state.dc.map_or(-1, |s| i32::from(s))
9903 );
9904 }
9905 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
9906 self.left[mi_r + cell][plane] = state;
9907 }
9908 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
9909 self.above[mi_c + cell][plane] = state;
9910 }
9911 }
9912
9913 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
9914 /// r1): the above context spans the unit's width, the left context its
9915 /// height, which for a square unit is the same loop it always was.
9916 fn record_mi_luma_rect(
9917 &mut self,
9918 (mi_r, mi_c): (usize, usize),
9919 w_px: usize,
9920 h_px: usize,
9921 grid: &[i32],
9922 ) {
9923 let state = neighbour_state(grid);
9924 if crate::envflags::env_flag!("EC_ECPUB") {
9925 eprintln!(
9926 "EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}",
9927 state.level
9928 );
9929 }
9930 for cell in 0..h_px / MI {
9931 if mi_r + cell < self.mi_rows {
9932 self.left[mi_r + cell][0] = state;
9933 }
9934 }
9935 for cell in 0..w_px / MI {
9936 if mi_c + cell < self.mi_cols {
9937 self.above[mi_c + cell][0] = state;
9938 }
9939 }
9940 }
9941
9942 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
9943 /// block whose luma was decoded as several transform units through
9944 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
9945 /// whole-block luma write -- everything [`Self::record`] does except
9946 /// plane 0, which is already correct per-TU by the time this runs.
9947 fn record_split_luma(
9948 &mut self,
9949 at: (usize, usize),
9950 side: usize,
9951 mode: usize,
9952 uv_mode: usize,
9953 chroma_grids: [&[i32]; 2],
9954 ) {
9955 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
9956 }
9957
9958 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
9959 /// extents in pixels (lane-rectsplit r1), the same relationship
9960 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
9961 /// luma transform split into several square units needs exactly this
9962 /// bookkeeping, at its own true rectangular extents.
9963 fn record_split_luma_rect(
9964 &mut self,
9965 at: (usize, usize),
9966 w: usize,
9967 h: usize,
9968 mode: usize,
9969 uv_mode: usize,
9970 chroma_grids: [&[i32]; 2],
9971 ) {
9972 let (r, c) = at;
9973 self.record_split_luma_rect_mi(
9974 (r * (SUB / MI), c * (SUB / MI)),
9975 w,
9976 h,
9977 mode,
9978 uv_mode,
9979 chroma_grids,
9980 );
9981 }
9982
9983 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
9984 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
9985 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
9986 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
9987 /// convention [`decode_block_rect4`] already established for 1:4 strips.
9988 fn record_split_luma_rect_mi(
9989 &mut self,
9990 at_mi: (usize, usize),
9991 w: usize,
9992 h: usize,
9993 mode: usize,
9994 uv_mode: usize,
9995 chroma_grids: [&[i32]; 2],
9996 ) {
9997 let (mi_r, mi_c) = at_mi;
9998 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
9999 for cell in 0..w.div_ceil(SUB) {
10000 if c + cell >= self.above_mode.len() {
10001 break;
10002 }
10003 self.above_mode[c + cell] = mode;
10004 self.above_uv_mode[c + cell] = uv_mode;
10005 self.above_side[c + cell] = w;
10006 }
10007 for cell in 0..h.div_ceil(SUB) {
10008 if r + cell >= self.left_mode.len() {
10009 break;
10010 }
10011 self.left_mode[r + cell] = mode;
10012 self.left_uv_mode[r + cell] = uv_mode;
10013 self.left_side[r + cell] = h;
10014 }
10015
10016 let (w_mi, h_mi) = (w / MI, h / MI);
10017 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
10018 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
10019 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
10020 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
10021 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10022 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
10023 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
10024 let plane = plane_idx + 1;
10025 let state = neighbour_state(grid);
10026 for cell in 0..h_mi {
10027 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
10028 self.left[mi_r + cell][plane] = state;
10029 }
10030 }
10031 for cell in 0..w_mi {
10032 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
10033 self.above[mi_c + cell][plane] = state;
10034 }
10035 }
10036 }
10037 }
10038}
10039
10040/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
10041/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
10042/// exactly — including its skip context, which the real key-frame writer
10043/// always writes at a fixed context of zero (it never tracks a neighbour-based
10044/// one for intra blocks; that is the inter-frame writer's rule instead).
10045/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
10046/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
10047/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
10048/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
10049/// plain DC chroma.
10050/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
10051/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
10052/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
10053/// instead (the defect commit 1a89ed9 fixed at the square sites).
10054pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
10055 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
10056 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
10057}
10058
10059/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
10060/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
10061/// bound (spec `filter_intra_mode_info` never reads a symbol there).
10062pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
10063 match side {
10064 4 => Some(0),
10065 8 => Some(1),
10066 16 => Some(2),
10067 32 => Some(3),
10068 _ => None,
10069 }
10070}
10071
10072/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
10073/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
10074/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
10075/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
10076fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
10077 match (bw, bh) {
10078 (32, 16) => Some(4),
10079 (16, 32) => Some(5),
10080 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
10081 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
10082 // here dropped that symbol on every DC_PRED strip of that size and
10083 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
10084 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
10085 (16, 8) => Some(6),
10086 (8, 16) => Some(7),
10087 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
10088 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
10089 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
10090 (4, 8) => Some(8),
10091 (8, 4) => Some(9),
10092 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
10093 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
10094 // `use_filter_intra` symbol on those strips although aomenc writes
10095 // one for every DC_PRED block of that shape with
10096 // `--enable-filter-intra=1` (its default), silently desyncing the
10097 // tile (class symbol-consumption-gap).
10098 (32, 8) => Some(10),
10099 (8, 32) => Some(11),
10100 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
10101 // strips), rows 17/16 of `default_filter_intra_cdfs`.
10102 (16, 4) => Some(12),
10103 (4, 16) => Some(13),
10104 _ if bw == bh => filter_intra_size_class(bw),
10105 _ => None,
10106 }
10107}
10108
10109/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
10110/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
10111/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
10112/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
10113/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
10114pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
10115 palette_bsize_ctx_wh(side, side)
10116}
10117
10118/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
10119/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
10120/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
10121/// for ANY bsize, not just the square ones a hand-picked table happened to
10122/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
10123/// row breaks the moment its indexing field moves off the diagonal, and a
10124/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
10125/// block dimension is a power of two, so `bw*bh` always is too and
10126/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
10127/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
10128fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
10129 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
10130 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
10131 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
10132 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
10133 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
10134 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
10135 if bw > 64 || bh > 64 || bw * bh < 64 {
10136 return None;
10137 }
10138 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
10139}
10140
10141/// A just-decoded palette-Y block's own size, base colours (only the first
10142/// `size` entries are real), and per-pixel colour-index map (`side*side`,
10143/// row-major, each entry `< size`).
10144struct PaletteY {
10145 size: usize,
10146 colors: [u16; 8],
10147 map: Vec<u8>,
10148}
10149
10150/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
10151/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
10152/// shared between U and V, both co-located after 4:2:0 subsampling) plus
10153/// each plane's own base colours.
10154struct PaletteUv {
10155 size: usize,
10156 u_colors: [u16; 8],
10157 v_colors: [u16; 8],
10158 map: Vec<u8>,
10159}
10160
10161/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
10162/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
10163/// `get_unsigned_bits`, which is the same formula): smallest `n` with
10164/// `2^n >= x`, `0` for `x <= 1`.
10165pub(crate) fn ceil_log2(x: u32) -> u32 {
10166 if x < 2 {
10167 0
10168 } else {
10169 32 - (x - 1).leading_zeros()
10170 }
10171}
10172
10173/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
10174/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
10175fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
10176 let l = ceil_log2(n as u32);
10177 let m = (1usize << l) - n;
10178 let v = dec.literal(l - 1) as usize;
10179 if v < m {
10180 v
10181 } else {
10182 (v << 1) - m + dec.literal(1) as usize
10183 }
10184}
10185
10186/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
10187/// colours (already-known, from the above/left neighbours) with the
10188/// ascending `transmitted` ones (delta-coded off the wire) back into one
10189/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
10190/// value picks the cached copy first, matching the C `<=`.
10191fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
10192 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
10193 let (mut ci, mut ti) = (0, 0);
10194 while ci < cached.len() && ti < transmitted.len() {
10195 if cached[ci] <= transmitted[ti] {
10196 out.push(cached[ci]);
10197 ci += 1;
10198 } else {
10199 out.push(transmitted[ti]);
10200 ti += 1;
10201 }
10202 }
10203 out.extend_from_slice(&cached[ci..]);
10204 out.extend_from_slice(&transmitted[ti..]);
10205 out
10206}
10207
10208/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
10209/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
10210/// each delta's width, the `range` bound and the clamp) is sized by
10211/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
10212/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
10213/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
10214/// the msac range, so a cross-decoder range ladder stays bit-identical
10215/// through the whole miscount -- only the decoded VALUE differs (class
10216/// `compare-range-not-tell`'s blind spot). (this
10217/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
10218/// (one flag bit each, in cache order), then delta-codes the remainder
10219/// (first value raw, each following delta `>= 1` off a shrinking bit width),
10220/// and merges the two ascending lists back together.
10221fn read_palette_colors_y(
10222 dec: &mut SymbolDecoder,
10223 n: usize,
10224 cache: &[u16],
10225 fctx: &crate::decode::FrameCtx,
10226) -> [u16; 8] {
10227 let mut cached = Vec::with_capacity(n);
10228 for &c in cache {
10229 if cached.len() >= n {
10230 break;
10231 }
10232 if dec.literal(1) == 1 {
10233 cached.push(c);
10234 }
10235 }
10236 let bd = u32::from(bit_depth(fctx));
10237 let max_val = (1i32 << bd) - 1;
10238 let mut colors = [0u16; 8];
10239 let n_cached = cached.len();
10240 if n_cached < n {
10241 let mut transmitted = Vec::with_capacity(n - n_cached);
10242 let first = dec.literal(bd) as u16;
10243 transmitted.push(first);
10244 if n_cached + 1 < n {
10245 let min_bits = bd - 3;
10246 let mut bits = min_bits + dec.literal(2);
10247 let mut range = (1i32 << bd) - i32::from(first) - 1;
10248 for _ in (n_cached + 1)..n {
10249 let delta = dec.literal(bits) as i32 + 1;
10250 let prev = *transmitted.last().unwrap();
10251 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
10252 range -= i32::from(val) - i32::from(prev);
10253 bits = bits.min(ceil_log2(range.max(0) as u32));
10254 transmitted.push(val);
10255 }
10256 }
10257 let merged = merge_colors(&transmitted, &cached);
10258 colors[..n].copy_from_slice(&merged);
10259 } else {
10260 colors[..n].copy_from_slice(&cached[..n]);
10261 }
10262 colors
10263}
10264
10265/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
10266/// `bit_depth` (see [`read_palette_colors_y`]): U reads
10267/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
10268/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
10269/// unbiased by `+1` -- both differences from Y's own reader, matching the C
10270/// side by side). V never uses a cache: a leading bit picks either `n` raw
10271/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
10272/// rather than clamp.
10273fn read_palette_colors_uv(
10274 dec: &mut SymbolDecoder,
10275 n: usize,
10276 cache: &[u16],
10277 fctx: &crate::decode::FrameCtx,
10278) -> ([u16; 8], [u16; 8]) {
10279 let mut cached = Vec::with_capacity(n);
10280 for &c in cache {
10281 if cached.len() >= n {
10282 break;
10283 }
10284 if dec.literal(1) == 1 {
10285 cached.push(c);
10286 }
10287 }
10288 let bd = u32::from(bit_depth(fctx));
10289 let max_val = 1i32 << bd;
10290 let mut u_colors = [0u16; 8];
10291 let n_cached = cached.len();
10292 if n_cached < n {
10293 let mut transmitted = Vec::with_capacity(n - n_cached);
10294 let first = dec.literal(bd) as u16;
10295 transmitted.push(first);
10296 if n_cached + 1 < n {
10297 let min_bits = bd - 3;
10298 let mut bits = min_bits + dec.literal(2);
10299 let mut range = max_val - i32::from(first);
10300 for _ in (n_cached + 1)..n {
10301 let delta = dec.literal(bits) as i32;
10302 let prev = *transmitted.last().unwrap();
10303 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
10304 range -= i32::from(val) - i32::from(prev);
10305 bits = bits.min(ceil_log2(range.max(0) as u32));
10306 transmitted.push(val);
10307 }
10308 }
10309 let merged = merge_colors(&transmitted, &cached);
10310 u_colors[..n].copy_from_slice(&merged);
10311 } else {
10312 u_colors[..n].copy_from_slice(&cached[..n]);
10313 }
10314 let mut v_colors = [0u16; 8];
10315 if dec.literal(1) == 1 {
10316 let min_bits_v = bd - 4;
10317 let bits = min_bits_v + dec.literal(2);
10318 v_colors[0] = dec.literal(bd) as u16;
10319 for i in 1..n {
10320 let mut delta = dec.literal(bits) as i32;
10321 if delta != 0 && dec.literal(1) == 1 {
10322 delta = -delta;
10323 }
10324 let mut val = i32::from(v_colors[i - 1]) + delta;
10325 if val < 0 {
10326 val += max_val;
10327 }
10328 if val >= max_val {
10329 val -= max_val;
10330 }
10331 v_colors[i] = val as u16;
10332 }
10333 } else {
10334 for i in 0..n {
10335 v_colors[i] = dec.literal(bd) as u16;
10336 }
10337 }
10338 (u_colors, v_colors)
10339}
10340
10341/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
10342/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
10343/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
10344const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
10345
10346/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
10347/// map's own per-pixel context and colour-order permutation, from the
10348/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
10349/// selection sort). `map`'s stride is `side` (this decoder never crops a
10350/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
10351/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
10352/// actual colour index to store.
10353pub(crate) fn palette_color_index_context(
10354 map: &[u8],
10355 side: usize,
10356 row: usize,
10357 col: usize,
10358 n: usize,
10359) -> (usize, [u8; 8]) {
10360 let left = if col >= 1 {
10361 Some(map[row * side + col - 1])
10362 } else {
10363 None
10364 };
10365 let up_left = if col >= 1 && row >= 1 {
10366 Some(map[(row - 1) * side + col - 1])
10367 } else {
10368 None
10369 };
10370 let up = if row >= 1 {
10371 Some(map[(row - 1) * side + col])
10372 } else {
10373 None
10374 };
10375 let mut scores = [0i32; 8];
10376 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
10377 if let Some(v) = neighbour {
10378 scores[v as usize] += weight;
10379 }
10380 }
10381 let mut color_order = [0u8; 8];
10382 for i in 0..8 {
10383 color_order[i] = i as u8;
10384 }
10385 for i in 0..3 {
10386 let mut max = scores[i];
10387 let mut max_idx = i;
10388 for j in (i + 1)..n {
10389 if scores[j] > max {
10390 max = scores[j];
10391 max_idx = j;
10392 }
10393 }
10394 if max_idx != i {
10395 let max_score = scores[max_idx];
10396 let max_color = color_order[max_idx];
10397 for k in (i + 1..=max_idx).rev() {
10398 scores[k] = scores[k - 1];
10399 color_order[k] = color_order[k - 1];
10400 }
10401 scores[i] = max_score;
10402 color_order[i] = max_color;
10403 }
10404 }
10405 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
10406 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
10407 (ctx as usize, color_order)
10408}
10409
10410/// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512):
10411/// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block
10412/// cut by the frame's bottom or right mi edge codes its colour-index map only
10413/// over this part and replicates it outward -- reading the full `bw x bh` grid
10414/// consumed symbols libaom never wrote and desynced the rest of the tile
10415/// (lane-svtinter; class map-read-past-frame-edge).
10416fn palette_onscreen(
10417 mi_r: usize,
10418 mi_c: usize,
10419 bw: usize,
10420 bh: usize,
10421 fctx: &crate::decode::FrameCtx,
10422) -> (usize, usize) {
10423 // lane-palw: the ENCODER's own in-process reconstruct runs on a
10424 // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
10425 // frame encoders publish the header's mi dims onto it themselves
10426 // (`encode.rs`, beside their `true_width`/`true_height`) so that this
10427 // clamp and `tile::write_color_index_map`'s now agree there too.
10428 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
10429 palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
10430}
10431
10432/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
10433/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
10434/// compute the same on-screen extent or the decoder reads a different number
10435/// of symbols than the encoder wrote.
10436pub(crate) fn palette_onscreen_dims(
10437 mi_r: usize,
10438 mi_c: usize,
10439 bw: usize,
10440 bh: usize,
10441 (mi_rows, mi_cols): (usize, usize),
10442) -> (usize, usize) {
10443 (
10444 bw.min(mi_cols.saturating_sub(mi_c) * MI),
10445 bh.min(mi_rows.saturating_sub(mi_r) * MI),
10446 )
10447}
10448
10449/// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus
10450/// the SAME sub-8 bump the caller's own `(bw >> ss).max(4)` applies to the
10451/// block dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move
10452/// together or a cut 8-wide block reads its chroma map at the wrong width.
10453/// lane-av1-444: the shifts are the sequence's own subsampling (a 4:4:4
10454/// intra-in-inter palette read its chroma map at the 4:2:0 extent and
10455/// panicked feeding the 4:2:0-sized prediction to a full-size reconstruct).
10456pub(crate) fn palette_onscreen_uv(
10457 luma: (usize, usize),
10458 on: (usize, usize),
10459 chroma: (usize, usize),
10460 ss: (usize, usize),
10461) -> (usize, usize) {
10462 (
10463 (on.0 >> ss.0) + (chroma.0 - (luma.0 >> ss.0)),
10464 (on.1 >> ss.1) + (chroma.1 - (luma.1 >> ss.1)),
10465 )
10466}
10467
10468/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
10469/// map's wavefront decode over a `side x side` grid, read over the on-screen
10470/// `on_side x on_side` corner (see [`palette_onscreen`]).
10471fn decode_color_index_map(
10472 dec: &mut SymbolDecoder,
10473 cdfs: &mut Cdfs,
10474 n: usize,
10475 side: usize,
10476 on: (usize, usize),
10477 uv: bool,
10478) -> Vec<u8> {
10479 decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv)
10480}
10481
10482/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
10483/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
10484/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
10485/// independently rather than one shared `side` -- the square call above is
10486/// just `bw == bh`.
10487fn decode_color_index_map_wh(
10488 dec: &mut SymbolDecoder,
10489 cdfs: &mut Cdfs,
10490 n: usize,
10491 bw: usize,
10492 bh: usize,
10493 // `(onscreenWidth, onscreenHeight)` in this plane's own units.
10494 on: (usize, usize),
10495 uv: bool,
10496) -> Vec<u8> {
10497 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
10498 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
10499 if on_bw < bw || on_bh < bh {
10500 hit!(PALETTE_ONSCREEN_CUT_HITS);
10501 }
10502 let mut map = vec![0u8; bw * bh];
10503 if trace {
10504 let (rng, _) = dec.debug_state();
10505 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
10506 }
10507 map[0] = read_uniform(dec, n) as u8;
10508 if trace {
10509 let (rng, _) = dec.debug_state();
10510 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
10511 }
10512 for i in 1..(on_bw + on_bh - 1) {
10513 let j_hi = i.min(on_bw - 1);
10514 let j_lo = i.saturating_sub(on_bh - 1);
10515 for j in (j_lo..=j_hi).rev() {
10516 let row = i - j;
10517 let col = j;
10518 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
10519 if trace {
10520 let (rng, _) = dec.debug_state();
10521 let row_cdf = if uv {
10522 &cdfs.palette_uv_color_index[n - 2][ctx]
10523 } else {
10524 &cdfs.palette_y_color_index[n - 2][ctx]
10525 };
10526 eprintln!(
10527 "EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}",
10528 row_cdf[0], row_cdf[n]
10529 );
10530 }
10531 let symbol = if uv {
10532 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
10533 } else {
10534 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
10535 };
10536 map[row * bw + col] = color_order[symbol];
10537 if trace {
10538 let (rng, _) = dec.debug_state();
10539 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
10540 }
10541 }
10542 }
10543 palette_replicate(&mut map, bw, bh, on);
10544 map
10545}
10546
10547/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
10548/// last on-screen column then the last on-screen row are replicated over the
10549/// off-screen remainder, so the prediction still covers the whole block. The
10550/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
10551/// so the pixels it prices and reconstructs are the ones the on-screen
10552/// symbols it writes really decode to.
10553pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
10554 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
10555 for row in 0..on_bh {
10556 let last = map[row * bw + on_bw - 1];
10557 map[row * bw + on_bw..row * bw + bw].fill(last);
10558 }
10559 for row in on_bh..bh {
10560 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
10561 }
10562}
10563
10564/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
10565/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
10566/// size class comes from [`filter_intra_size_class_rect`] instead of the
10567/// square-only [`filter_intra_size_class`], and the palette read (when
10568/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
10569/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
10570/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
10571/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
10572#[allow(clippy::too_many_arguments)]
10573fn read_intra_mode_rect(
10574 dec: &mut SymbolDecoder,
10575 cdfs: &mut Cdfs,
10576 above_mode: usize,
10577 left_mode: usize,
10578 cfl: bool,
10579 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
10580 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
10581 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
10582 // chroma is coded once, on the closing strip). Every other caller is a
10583 // block big enough to own its chroma and passes `true`.
10584 has_chroma: bool,
10585 bw: usize,
10586 bh: usize,
10587 enable_filter_intra: bool,
10588 skip_ctx: usize,
10589 allow_screen_content_tools: bool,
10590 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
10591 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
10592 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
10593 palette: Option<(usize, &[u16])>,
10594 palette_uv_cache: &[u16],
10595 mi_r: usize,
10596 mi_c: usize,
10597 fctx: &crate::decode::FrameCtx,
10598) -> Result<(
10599 bool,
10600 usize,
10601 i32,
10602 usize,
10603 i32,
10604 Option<(i32, i32)>,
10605 Option<usize>,
10606 Option<PaletteY>,
10607 Option<PaletteUv>,
10608 // lane-av1-intrabc: the block vector, `Some` exactly when this block's
10609 // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns
10610 // straight out of `read_intra_frame_mode_info` then, so every later field
10611 // of the tuple is at its default (mode/uv_mode DC, no angle, no palette,
10612 // no filter intra). A caller that can reconstruct intrabc at its shape
10613 // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by
10614 // name with the same string it always did.
10615 Option<(i32, i32)>,
10616)> {
10617 // lane-av1mono: libaom guards every chroma symbol read with
10618 // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
10619 // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
10620 // `palette_uv` even on a chroma-reference strip. Fold the plane count
10621 // into the same `has_chroma` this reader already gates on.
10622 let has_chroma = has_chroma && !mono(fctx);
10623 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
10624 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
10625 if ec_istep {
10626 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
10627 // (decodemv.c:818), printed at the same point: before the first
10628 // mode-info symbol of the block, so a cross-decoder range ladder can
10629 // be keyed on the BLOCK, not just on the symbol sequence.
10630 eprintln!(
10631 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}",
10632 enable_filter_intra as i32,
10633 filter_intra_size_class_rect(bw, bh),
10634 dec.debug_state().0
10635 );
10636 }
10637 macro_rules! istep {
10638 ($name:literal, $val:expr) => {
10639 if ec_istep {
10640 let (rng, _) = dec.debug_state();
10641 eprintln!(
10642 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
10643 $name, $val
10644 );
10645 }
10646 };
10647 }
10648 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
10649 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
10650 // the one point every rect caller routes through, so no call site can
10651 // offer the 14-symbol CFL alphabet on a 64-axis block (class
10652 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
10653 let cfl = if cfl && bw.max(bh) > 32 {
10654 hit!(NOCFL_UV_MODE_HITS);
10655 false
10656 } else {
10657 cfl
10658 };
10659 // lane-intra14 r1: on the INTER block path everything up to and including
10660 // `is_inter` was already read by [`decode_inter_block`], so this reader
10661 // starts at the mode syntax with the `skip` that caller read.
10662 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
10663 let skip = if let Some((_, skip)) = inter {
10664 skip
10665 } else {
10666 // Same `intra_segment_id` placement as the square reader above.
10667 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
10668 if seg_id_pre_skip(fctx) {
10669 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
10670 }
10671 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
10672 istep!("skip", skip as i32);
10673 if !seg_id_pre_skip(fctx) {
10674 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
10675 }
10676 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
10677 istep!("cdef", 0);
10678 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
10679 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
10680 // `false`.
10681 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
10682 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
10683 istep!("dq", 0);
10684 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
10685 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
10686 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
10687 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
10688 // rect strips read it exactly like square leaves ([`read_intra_mode`],
10689 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
10690 // decoder at the FIRST symbol of the first rect block of every
10691 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
10692 // block at this shape is out of scope, so the flag is consumed and
10693 // refused by name when it fires.
10694 if allow_intrabc_frame(fctx) {
10695 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
10696 hit!(RECT_INTRABC_READS);
10697 istep!("intrabc", use_intrabc as i32);
10698 if use_intrabc {
10699 hit!(INTRABC_HITS);
10700 // libaom `read_intrabc_info`: the DV read, then an immediate
10701 // return out of the mode-info read -- no `y_mode`, no `uv_mode`,
10702 // no angle deltas, no palette, no filter intra. The caller owns
10703 // the reconstruction at its own shape.
10704 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx);
10705 return Ok((
10706 skip,
10707 DC_PRED,
10708 0,
10709 DC_PRED,
10710 0,
10711 None,
10712 None,
10713 None,
10714 None,
10715 Some(dv),
10716 ));
10717 }
10718 }
10719 skip
10720 };
10721 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
10722 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
10723 // off `kf_y_mode_cdf[above][left]`).
10724 let mode = if let Some((size_group, _)) = inter {
10725 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
10726 dec.symbol(&mut cdfs.y_mode[size_group])
10727 } else {
10728 let above_ctx = INTRA_MODE_CTX[above_mode];
10729 let left_ctx = INTRA_MODE_CTX[left_mode];
10730 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
10731 };
10732 istep!("mode", mode as i32);
10733 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
10734 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
10735 } else {
10736 0
10737 };
10738 istep!("angle_y", angle_delta_y);
10739 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
10740 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
10741 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
10742 // here, from the block's own size, is the single point every caller routes
10743 // through -- a caller passing `true` for a >32 strip used to pick the
10744 // 14-symbol CFL CDF, same value but a different range (class
10745 // wrong-alphabet-same-value).
10746 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
10747 let uv_mode = if !has_chroma {
10748 DC_PRED
10749 } else if cfl {
10750 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
10751 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
10752 } else {
10753 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
10754 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
10755 };
10756 istep!("uv_mode", uv_mode as i32);
10757 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
10758 Some(read_cfl_alphas(dec, cdfs))
10759 } else {
10760 None
10761 };
10762 if has_chroma && (9..=12).contains(&uv_mode) {
10763 hit!(SMOOTH_UV_HITS);
10764 }
10765 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
10766 hit!(DIRECTIONAL_UV_HITS);
10767 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
10768 } else {
10769 0
10770 };
10771 istep!("angle_uv", angle_delta_uv);
10772 if angle_delta_uv != 0 {
10773 hit!(UV_ANGLE_DELTA_HITS);
10774 }
10775 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
10776 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
10777 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
10778 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
10779 // colours only here, the colour-index maps deferred past `filter_intra`
10780 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
10781 // runs from the caller, after the whole mode-info read).
10782 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
10783 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
10784 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
10785 // r6: this is the exact site the removed blanket refusal used to
10786 // guard -- reached for EVERY rect strip in a screen-content frame,
10787 // independent of whether the block ends up using a palette.
10788 hit!(RECT_SCREEN_CONTENT_HITS);
10789 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
10790 let use_palette_y =
10791 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
10792 if use_palette_y {
10793 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
10794 let colors = read_palette_colors_y(dec, n, cache, fctx);
10795 palette_y_pending = Some((n, colors));
10796 }
10797 let palette_uv_mode_ctx = usize::from(use_palette_y);
10798 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
10799 if has_chroma
10800 && uv_mode == DC_PRED
10801 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
10802 {
10803 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
10804 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
10805 palette_uv_pending = Some((n, u_colors, v_colors));
10806 }
10807 }
10808 let mut filter_intra = None;
10809 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10810 let (rng, _) = dec.debug_state();
10811 eprintln!(
10812 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
10813 class={:?} rng={rng}",
10814 enable_filter_intra as i32,
10815 filter_intra_size_class_rect(bw, bh)
10816 );
10817 }
10818 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
10819 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
10820 if mode == DC_PRED
10821 && enable_filter_intra
10822 && palette_y_pending.is_none()
10823 && let Some(class) = filter_intra_size_class_rect(bw, bh)
10824 {
10825 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
10826 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10827 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
10828 }
10829 istep!("use_filter_intra", use_filter_intra as i32);
10830 if use_filter_intra {
10831 hit!(FILTER_INTRA_HITS);
10832 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
10833 istep!("filter_intra_mode", fi_mode as i32);
10834 filter_intra = Some(fi_mode);
10835 }
10836 }
10837 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
10838 // same order as [`read_intra_mode`]'s own square path.
10839 let palette_y = palette_y_pending.map(|(n, colors)| {
10840 let map = decode_color_index_map_wh(
10841 dec,
10842 cdfs,
10843 n,
10844 bw,
10845 bh,
10846 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
10847 false,
10848 );
10849 hit!(PALETTE_HITS);
10850 hit!(PALETTE_RECT_HITS);
10851 PaletteY {
10852 size: n,
10853 colors,
10854 map,
10855 }
10856 });
10857 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
10858 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
10859 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
10860 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
10861 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
10862 // chroma palette and desynced the tile from there.
10863 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
10864 let on = palette_onscreen_uv(
10865 (bw, bh),
10866 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
10867 (cw, ch),
10868 (ss_x(fctx), ss_y(fctx)),
10869 );
10870 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
10871 hit!(PALETTE_UV_HITS);
10872 PaletteUv {
10873 size: n,
10874 u_colors,
10875 v_colors,
10876 map,
10877 }
10878 });
10879 Ok((
10880 skip,
10881 mode,
10882 angle_delta_y,
10883 uv_mode,
10884 angle_delta_uv,
10885 alpha,
10886 filter_intra,
10887 palette_y,
10888 palette_uv,
10889 None,
10890 ))
10891}
10892
10893/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
10894/// at the strip's REAL mi position. `av1_get_palette_cache` reads
10895/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
10896/// block, so each strip owns its own rows and columns and no aliasing rule
10897/// is needed (lane-kf900 r6).
10898#[allow(clippy::too_many_arguments)]
10899fn record_strip_palette(
10900 n: &mut Neighbours,
10901 mi: (usize, usize),
10902 bw: usize,
10903 bh: usize,
10904 y_size: usize,
10905 y_colors: [u16; 8],
10906 uv_size: usize,
10907 uv_colors: [u16; 8],
10908) {
10909 let (r, c) = mi;
10910 // lane-t900 r23 rung: every publication of a block's palette state into
10911 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
10912 // path left a stale `left_palette_size` behind when
10913 // `av1_get_palette_mode_ctx` disagrees with libaom's.
10914 if crate::envflags::env_flag!("EC_PALPUB") {
10915 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
10916 }
10917 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
10918 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
10919 // existed because the 16px [`SUB`] cell held one slot for all the strips
10920 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
10921 // real neighbour leaf 1 reads.
10922 {
10923 for cell in 0..(bw / MI).max(1) {
10924 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
10925 *e = y_size as u8;
10926 n.above_palette_uv_size[c + cell] = uv_size as u8;
10927 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
10928 // colours of a size-0 neighbour are never read.
10929 if y_size > 0 {
10930 n.above_palette_colors[c + cell] = y_colors;
10931 }
10932 if uv_size > 0 {
10933 n.above_palette_uv_colors[c + cell] = uv_colors;
10934 }
10935 }
10936 }
10937 }
10938 {
10939 for cell in 0..(bh / MI).max(1) {
10940 if n.left_palette_size.get(r + cell).is_none() {
10941 break;
10942 }
10943 n.left_palette_size[r + cell] = y_size as u8;
10944 n.left_palette_uv_size[r + cell] = uv_size as u8;
10945 if y_size > 0 {
10946 n.left_palette_colors[r + cell] = y_colors;
10947 }
10948 if uv_size > 0 {
10949 n.left_palette_uv_colors[r + cell] = uv_colors;
10950 }
10951 }
10952 }
10953}
10954
10955/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
10956fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
10957 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| {
10958 i32::from(y.data[ly * y.width + lx])
10959 })
10960}
10961
10962/// Everything a rect strip already read out of the stream before its luma
10963/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
10964/// (nine values that would otherwise be nine more parameters).
10965struct RectStripModes {
10966 skip: bool,
10967 mode: usize,
10968 angle_delta_y: i32,
10969 uv_predict_mode: usize,
10970 angle_delta_uv: i32,
10971 alpha: Option<(i32, i32)>,
10972 filter_intra: Option<usize>,
10973 smooth_neighbor: bool,
10974 smooth_neighbor_uv: bool,
10975 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
10976 /// mapped through the colour table), sliced per transform unit below --
10977 /// palette prediction reads no edge pixels, so a unit's slice of the
10978 /// whole-block map IS its prediction. Without this a palette strip whose
10979 /// transform splits predicted DC and came out flat grey while the entropy
10980 /// stream stayed in sync (the coefficients are read either way).
10981 palette_y: Option<Vec<u16>>,
10982 /// As `palette_y`, for the un-split chroma transform (U, V).
10983 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
10984}
10985
10986/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
10987/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
10988/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
10989/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
10990/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
10991/// TX_32X16`) and only the second reaches a square -- the reason
10992/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
10993/// already square) mis-tiled 1:4 strips.
10994fn depth_to_tx_wh(
10995 bw: usize,
10996 bh: usize,
10997 depth: usize,
10998 fctx: &crate::decode::FrameCtx,
10999) -> (usize, usize) {
11000 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
11001 // `read_tx_size`: the lossless early return comes before
11002 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
11003 if lossless(fctx) {
11004 return (4, 4);
11005 }
11006 let (mut w, mut h) = (bw.min(64), bh.min(64));
11007 for _ in 0..depth {
11008 match w.cmp(&h) {
11009 std::cmp::Ordering::Greater => w /= 2,
11010 std::cmp::Ordering::Less => h /= 2,
11011 std::cmp::Ordering::Equal => {
11012 w /= 2;
11013 h /= 2;
11014 }
11015 }
11016 }
11017 (w, h)
11018}
11019
11020/// lane-av1-422stripanchor: [`decode_rect_split`]'s 4-wide-strip port of the
11021/// split4 floored-pair anchor ([`sub8_leaf_chroma422`]'s rule). A 1-mi-wide
11022/// strip (luma `(4, 16)` / `(4, 8)`) has NO chroma plane block of its own at
11023/// ss (1, 0) -- `av1_ss_size_lookup[BLOCK_4X16][1][0]` and
11024/// `[BLOCK_4X8][1][0]` are both BLOCK_INVALID (`common_data.c`), and a
11025/// 2-px-wide area is not a transform shape. The strip pairs with its
11026/// even-column sibling (`is_chroma_reference`'s `mi_col & 1` column clause,
11027/// the rule [`decode_rect4_16_strip`] implements one partition level up), and
11028/// the ODD-column strip codes the PAIR's `(4, bh)` plane anchored at
11029/// `av1_setup_dst_planes`' mi-exact floor `(mi_col & !1) * MI >> ss_x`, with
11030/// the entropy context on the floored cell. Returns
11031/// `(pair block width, pair block height, write anchor x, entropy mi column)`
11032/// for that pair, or `None` when the strip keeps its own plane block at its
11033/// own origin -- which is every 4:2:0 and 4:4:4 cell (their chroma is never
11034/// 2 px wide) and every 4:2:2 strip of 8 px or more.
11035fn chroma422_pair_plane(
11036 ss_x: bool,
11037 ss_y: bool,
11038 mi_col: usize,
11039 bw: usize,
11040 bh: usize,
11041) -> Option<(usize, usize, usize, usize)> {
11042 if ss_x && !ss_y && (bw >> 1) == 2 {
11043 Some((4, bh, ((mi_col & !1) * MI) >> 1, mi_col & !1))
11044 } else {
11045 None
11046 }
11047}
11048
11049/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
11050/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
11051/// rect path here refused by name until now ("per-unit rect prediction is not
11052/// ported").
11053///
11054/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
11055/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
11056/// strip the very first step already lands on a SQUARE transform
11057/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
11058/// every further step halves a square) -- so each unit is square and reads
11059/// through the ordinary square [`read_plane`]. What is genuinely rectangular
11060/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
11061/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
11062/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
11063/// split by luma's depth.
11064///
11065/// Each unit predicts off whatever the earlier units of this same block
11066/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
11067/// inside `av1_foreach_transformed_block`, raster order), which is exactly
11068/// what predicting the whole strip in one shot got wrong.
11069#[allow(clippy::too_many_arguments)]
11070fn decode_rect_split(
11071 dec: &mut SymbolDecoder,
11072 cdfs: &mut Cdfs,
11073 neighbours: &mut Neighbours,
11074 at_mi: (usize, usize),
11075 bw: usize,
11076 bh: usize,
11077 // The transform unit's own width and height in pixels. Square for every
11078 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
11079 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
11080 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
11081 tx_w: usize,
11082 tx_h: usize,
11083 m: &RectStripModes,
11084 y: &mut PlaneBuf<'static>,
11085 u: &mut PlaneBuf<'static>,
11086 v: &mut PlaneBuf<'static>,
11087 base_q_idx: u8,
11088 reduced_tx_set: bool,
11089 fctx: &crate::decode::FrameCtx,
11090) -> Result<()> {
11091 let (mi_r, mi_c) = at_mi;
11092 let (px, py) = (mi_c * MI, mi_r * MI);
11093 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
11094 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
11095 // lane-av1-422blockhalf: at ss (1,0) the tall/wide 1:2 and 1:4 strips'
11096 // chroma plane block is BLOCK_INVALID (`av1_ss_size_lookup[...][1][0]`,
11097 // blockd.h -- the 4:2:2 column maps BLOCK_8X16/16X32/32X64/64X128 and
11098 // BLOCK_8X32/16X64, plus 4-wide BLOCK_4X16, to BLOCK_INVALID), so
11099 // `av1_get_max_uv_txsize` indexes `max_txsize_rect_lookup` OUT OF BOUNDS
11100 // and the pinned Release oracle byte there is TX_4X8 (the lane-av1-422m
11101 // measurement). The plane is still coded -- `decode_token_recon_block`
11102 // steps it in that (4, 8) unit shape -- so the strip's chroma tiles into
11103 // 4x8 rect units, plane-major.
11104 let chroma_422_oob = ss_x(fctx) == 1
11105 && ss_y(fctx) == 0
11106 && matches!(
11107 (bw, bh),
11108 (8, 16) | (16, 32) | (32, 64) | (64, 128) | (8, 32) | (16, 64)
11109 );
11110 // lane-av1-422stripanchor: the 4-wide strips' PAIR chroma -- the ported
11111 // floored-pair anchor. `chroma422_pair_plane` is `Some` exactly when this
11112 // strip's own chroma block would be 2 px wide at ss (1, 0); the pair's
11113 // plane is then `(4, chroma_h)` written at the FLOORED cell
11114 // (`chroma_x`), and the skip/tiled chroma arms below tile it in (4, 8)
11115 // units (the OOB `max_txsize_rect_lookup[BLOCK_INVALID]` byte, TX_4X8 --
11116 // the same walk the (8, 32) class takes). The lossless raster arm keeps
11117 // the strip's own geometry: no caller of this function can present a
11118 // 4-wide strip yet (the enumeration test pins the five callers at
11119 // `8 <= min`), and the skip/tiled arms are the routes a future caller
11120 // needs.
11121 let chroma422_pair = chroma422_pair_plane(ss_x(fctx) == 1, ss_y(fctx) == 0, mi_c, bw, bh);
11122 let chroma_422_pair_wide = chroma422_pair.is_some();
11123 let (chroma_block_w, chroma_block_h, chroma_x) =
11124 chroma422_pair.map_or((chroma_w, chroma_h, cpx), |(w, h, x, _)| (w, h, x));
11125 // The chroma transform is picked before any symbol is read, so an
11126 // unsupported chroma shape refuses before this strip desyncs the tile.
11127 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
11128 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
11129 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
11130 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
11131 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
11132 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
11133 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
11134 // squares a rect transform down to a CDF set by
11135 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
11136 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
11137 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
11138 // paths already prove for these same shapes.
11139 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
11140 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
11141 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
11142 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
11143 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
11144 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
11145 _ => None,
11146 };
11147 // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted
11148 // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled
11149 // below; everything else still needs a single-unit table.
11150 // lane-av1-422: a 4:2:2 strip's chroma plane keeps the strip's HEIGHT and
11151 // halves only the width, so a rect luma strip codes a SQUARE chroma block
11152 // (16x8 luma -> 8x8 chroma) -- the square rows below. At 4:2:0 and 4:4:4 a
11153 // rect strip's chroma is itself rect, so the square rows are unreachable
11154 // there and cannot change their results.
11155 // lane-av1-422blockhalf: the tiled arms below handle every shape this
11156 // strip can carry (including the 4:2:2 BLOCK_INVALID planes), so the
11157 // diagnostic names only the shapes that would actually refuse -- it used
11158 // to fire for every tiled square too (the parent lane's `chroma=8x8`
11159 // rows) and sent the next lane chasing handled shapes.
11160 let chroma_tiled = chroma_422_pair_wide
11161 || chroma_422_oob
11162 || matches!(
11163 (chroma_w, chroma_h),
11164 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)
11165 );
11166 if !m.skip {
11167 if let Some(i) = match (chroma_w, chroma_h) {
11168 (32, 8) => Some(0),
11169 (8, 32) => Some(1),
11170 (8, 4) => Some(2),
11171 (4, 8) => Some(3),
11172 _ => None,
11173 } {
11174 hit_do! {
11175 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
11176 let mut hits = c.get();
11177 hits[i] += 1;
11178 c.set(hits);
11179 });
11180 }
11181 }
11182 if !m.skip && chroma.is_none() && !chroma_tiled {
11183 // Diagnostic for the next caller that lands here (class
11184 // refusal-names-a-correlate: the message names the tool, not the
11185 // shape); the refusal below keeps its inventory-pinned wording.
11186 eprintln!(
11187 "EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} \
11188 chroma={chroma_w}x{chroma_h}"
11189 );
11190 }
11191 }
11192 // lane-rectsplit r2 (verifier finding): with both callers wired
11193 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
11194 // 64x32/32x64) every shape that reaches here has a table above, so this
11195 // arm is UNREACHABLE today. It stays as the shape guard for the next
11196 // caller -- a new strip size would otherwise hit the `expect` below and
11197 // panic instead of refusing by name -- and so stays in
11198 // `refusal_inventory::REFUSALS`.
11199 if !m.skip && chroma.is_none() && !chroma_tiled {
11200 return Err(unsupported(
11201 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
11202 ));
11203 }
11204 hit!(RECT_SPLIT_TX_HITS);
11205 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
11206 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
11207 }
11208 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
11209 // A square unit reads through the ordinary square [`read_plane`]; a rect
11210 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
11211 // the very tables the unsplit 16x8/32x16 paths use.
11212 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
11213 (w, h) if w == h => None,
11214 (16, 8) | (8, 16) => Some((
11215 if reduced_tx_set {
11216 TxbSet::LumaRect16x8
11217 } else {
11218 TxbSet::LumaRect16x8Set1
11219 },
11220 if tx_w == 16 {
11221 &SCAN_16X8[..]
11222 } else {
11223 &SCAN_8X16[..]
11224 },
11225 )),
11226 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
11227 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
11228 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
11229 // strip, read through the `luma_64corner` arm below instead of a rect
11230 // table -- a 64-length axis codes only its low 32 coefficients
11231 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
11232 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
11233 // depth-0 arm already reads on the key-frame path.
11234 //
11235 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
11236 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
11237 // sub-8x8 intra leaves still refused: with those lifted (r2) the
11238 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
11239 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
11240 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
11241 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
11242 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
11243 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
11244 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
11245 (64, 32) | (32, 64) => None,
11246 _ => {
11247 return Err(unsupported(format!(
11248 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
11249 coefficient tables for that shape here)"
11250 )));
11251 }
11252 };
11253 // The `None` above that is NOT the square arm.
11254 let luma_64corner = tx_w != tx_h;
11255 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
11256 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
11257 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
11258 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
11259 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
11260 // per-unit rect walk stay wired above/below; the round that finds that
11261 // defect deletes this refusal and nothing else.
11262 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
11263 let luma_scan = default_scan(tx_w.min(tx_h));
11264 let zero_tu = vec![0i32; tx_w * tx_h];
11265 // The strip's OWN edge availability, the fallback for a transform unit
11266 // whose top-right/bottom-left pixels fall outside the strip.
11267 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11268 for tu_row in 0..bh / tx_h {
11269 for tu_col in 0..bw / tx_w {
11270 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
11271 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
11272 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
11273 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
11274 // libaom clips `av1_foreach_transformed_block_in_plane` to
11275 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
11276 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
11277 // TOP-LEFT sample falls outside the frame is never coded. We read
11278 // coefficients for those phantom units and desynced the stream at
11279 // the very next symbol.
11280 if tu_px >= y.true_width || tu_py >= y.true_height {
11281 continue;
11282 }
11283 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
11284 // transform unit INSIDE a block, which is a different rule from
11285 // the standalone-block table [`Reach::of`] applies -- and the
11286 // reason a depth-2 superblock strip came out one sample off
11287 // before this: `Reach::of(tx, ..)` answered as if the unit were
11288 // its own block at that superblock position.
11289 // * top-right: if the unit's right neighbour is still inside the
11290 // strip the pixels are already reconstructed (`col_off +
11291 // tx_wide < plane_bw`); otherwise only the strip's own top row
11292 // of units can reach past it, through the block-level answer.
11293 // * bottom-left: a unit that is not in the strip's left column
11294 // has none (`col_off > 0` returns 0); inside the strip
11295 // (`row_off + tx_high < plane_bh`) they are the left
11296 // neighbour's, already reconstructed; the last row falls back
11297 // to the block-level answer.
11298 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
11299 // The unit's own window on the block's palette prediction.
11300 if let Some(buf) = &m.palette_y {
11301 let tu_buf: Vec<u16> = (0..tx_h)
11302 .flat_map(|i| {
11303 let base = (row_off + i) * bw + col_off;
11304 buf[base..base + tx_w].iter().copied()
11305 })
11306 .collect();
11307 set_palette_pred(tu_buf, fctx);
11308 }
11309 if m.skip {
11310 push_intra_rect(
11311 0,
11312 tu_px,
11313 tu_py,
11314 tx_w,
11315 tx_h,
11316 m.mode,
11317 m.angle_delta_y,
11318 tu_reach,
11319 &zero_tu,
11320 None,
11321 m.filter_intra,
11322 m.smooth_neighbor,
11323 fctx,
11324 );
11325 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
11326 } else if luma_64corner && luma_rect.is_none() {
11327 // The un-split 64-level luma transform: `read_coeffs` on the
11328 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
11329 // and the real rect shape passed through for
11330 // `av1_nz_map_ctx_offset` -- byte for byte
11331 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
11332 // 64-level strip gate already proves. `tx_type` is not coded
11333 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
11334 // the square-up size is TX_64X64), and this unit covers its
11335 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
11336 if crate::envflags::env_flag!("EC_RECT64TU") {
11337 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
11338 }
11339 hit_do! {
11340 RECT64_CORNER_TU_HITS.with(|c| {
11341 let mut v = c.get();
11342 v[usize::from(tx_h > tx_w)] += 1;
11343 c.set(v);
11344 });
11345 }
11346 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
11347 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
11348 let (corner, tu_tx_type) = read_coeffs(
11349 dec,
11350 &mut coding,
11351 default_scan(TX32),
11352 0,
11353 dc_sign_ctx(tu_around.2),
11354 TxType::DctDct,
11355 Some((tx_w, tx_h)),
11356 )?;
11357 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
11358 let mut tu_grid = vec![0i32; tx_w * tx_h];
11359 for row in 0..ch {
11360 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
11361 }
11362 let residual = dequant_and_inverse_typed_wh(
11363 &tu_grid,
11364 tx_w,
11365 tx_h,
11366 crate::decode::bit_depth(fctx),
11367 block_q_idx(fctx),
11368 plane_q_delta(0, fctx).0,
11369 plane_q_delta(0, fctx).1,
11370 tu_tx_type,
11371 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
11372 );
11373 push_intra_rect(
11374 0,
11375 tu_px,
11376 tu_py,
11377 tx_w,
11378 tx_h,
11379 m.mode,
11380 m.angle_delta_y,
11381 tu_reach,
11382 &residual,
11383 None,
11384 m.filter_intra,
11385 m.smooth_neighbor,
11386 fctx,
11387 );
11388 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
11389 } else if let Some((rect_set, rect_scan)) = luma_rect {
11390 // The rect-unit twin of the square arm below: same contexts,
11391 // same order, through the rect coefficient reader. The
11392 // `tx_type` CDF row of a filter-intra block is
11393 // `fimode_to_intradir[filter_intra_mode]`, never the block's
11394 // own (always DC_PRED) mode -- [`read_plane`] applies that
11395 // for the square arm, so this one must too.
11396 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
11397 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
11398 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
11399 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
11400 // neighbour-magnitude table is for a unit SMALLER than its
11401 // block. [`decode_block_rect`]'s own unsplit read passes a
11402 // literal 0 for the same reason; this arm applied the table
11403 // unconditionally and desynced every depth-0 rect strip that
11404 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
11405 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
11406 0
11407 } else {
11408 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
11409 };
11410 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
11411 let (tu_grid, tu_tx_type) = read_coeffs_rect(
11412 dec,
11413 &mut coding,
11414 rect_scan,
11415 tx_w,
11416 tx_h,
11417 tu_skip_ctx,
11418 dc_sign_ctx(tu_around.2),
11419 TxType::DctDct,
11420 )?;
11421 let residual = dequant_and_inverse_typed_wh(
11422 &tu_grid,
11423 tx_w,
11424 tx_h,
11425 crate::decode::bit_depth(fctx),
11426 block_q_idx(fctx),
11427 plane_q_delta(0, fctx).0,
11428 plane_q_delta(0, fctx).1,
11429 tu_tx_type,
11430 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
11431 );
11432 push_intra_rect(
11433 0,
11434 tu_px,
11435 tu_py,
11436 tx_w,
11437 tx_h,
11438 m.mode,
11439 m.angle_delta_y,
11440 tu_reach,
11441 &residual,
11442 None,
11443 m.filter_intra,
11444 m.smooth_neighbor,
11445 fctx,
11446 );
11447 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
11448 } else {
11449 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
11450 // This unit is smaller than the block it sits in, so
11451 // `txb_skip_ctx` is the neighbour-magnitude table, not the
11452 // lone-TU 0 (spec `get_txb_ctx_general`).
11453 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
11454 let tu_grid = read_plane(
11455 dec,
11456 cdfs,
11457 luma_set,
11458 &luma_scan,
11459 0,
11460 tu_around,
11461 m.mode,
11462 m.mode,
11463 m.angle_delta_y,
11464 tu_reach,
11465 y,
11466 tu_px,
11467 tu_py,
11468 tx_w,
11469 tx_w,
11470 base_q_idx,
11471 None,
11472 m.filter_intra,
11473 Some(tu_skip_ctx),
11474 m.smooth_neighbor,
11475 fctx,
11476 )?;
11477 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
11478 }
11479 }
11480 }
11481 // CHROMA: one un-split rect transform for the whole strip.
11482 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
11483 // units -- each stamps its own neighbour context as it is read, and the
11484 // whole-block `record_split_luma_rect_mi` below would overwrite all of
11485 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
11486 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
11487 // collected here and replayed after that record.
11488 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
11489 // The chroma_tiled arm below stamps each unit's coefficient context
11490 // immediately (so the NEXT unit reads it), then the whole-strip
11491 // `record_split_luma_rect_mi` rewrites every chroma cell with ONE
11492 // whole-strip state and the per-unit DC signs and levels are lost
11493 // (class `override-slot-on-one-arm`). The units are collected here and
11494 // replayed after that record, the way the lossless arm's
11495 // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail
11496 // already do.
11497 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
11498 let ac = m.alpha.map(|_| {
11499 // lane-av1-422stripanchor: the pair unit's CfL source is the PAIR's
11500 // luma -- the 8-px-wide region the floored 4-px chroma block covers
11501 // (`av1_setup_dst_planes`' floor), never the odd strip's own 4 px.
11502 if chroma_422_pair_wide {
11503 cfl_src_rect((mi_c & !1) * MI, py, 8, bh)
11504 } else {
11505 cfl_src_rect(px, py, bw, bh)
11506 }
11507 });
11508 let reach = if chroma_422_pair_wide {
11509 // The chroma units predict off the PAIR block's edges: an odd-column
11510 // strip's pair starts 4 luma px to the strip's left, so the strip's
11511 // own answer names the wrong above/right samples (the pair16 arm's
11512 // `pair_reach`, one partition level up).
11513 Reach::of_rect(8, bh, (mi_c & !1) * MI, py, y.width, y.height, fctx)
11514 } else {
11515 block_reach
11516 };
11517 let (u_grid, v_grid) = if mono(fctx) {
11518 // lane-av1mono: a monochrome frame codes no chroma coefficients on
11519 // any block (`plane < av1_num_planes == 1`), so the whole chroma
11520 // section -- the skipped-strip pushes, the lossless raster and the
11521 // un-split `read_coeffs_rect` below -- is bypassed.
11522 let zero = Grid::Zero(chroma_w * chroma_h);
11523 (zero.clone(), zero)
11524 } else if m.skip {
11525 let zero = Grid::Zero(chroma_block_w * chroma_block_h);
11526 if chroma_422_pair_wide || chroma_422_oob {
11527 // lane-av1-422blockhalf: libaom predicts an INTRA strip's chroma
11528 // per transform unit even when the strip is skipped
11529 // (`decode_token_recon_block`'s per-TU plane walk runs before the
11530 // skip guard), so the BLOCK_INVALID plane predicts as (4, 8)
11531 // units -- one whole-plane push here would ask the intra
11532 // predictor for a 1:8 rect it never needs.
11533 // lane-av1-422stripanchor: the 4-wide strip's PAIR plane does the
11534 // same, over the pair's own `(chroma_block_w, chroma_block_h)`
11535 // grid at the floored anchor `chroma_x`.
11536 let (uw, uh) = (4usize, 8usize);
11537 for plane_idx in 1..=2 {
11538 if let Some((ub, vb)) = &m.palette_uv {
11539 let buf = if plane_idx == 1 { ub } else { vb };
11540 set_palette_pred(buf.clone(), fctx);
11541 }
11542 for cu_row in 0..chroma_block_h / uh {
11543 for cu_col in 0..chroma_block_w / uw {
11544 push_intra_rect(
11545 plane_idx,
11546 chroma_x + cu_col * uw,
11547 cpy + cu_row * uh,
11548 uw,
11549 uh,
11550 m.uv_predict_mode,
11551 m.angle_delta_uv,
11552 reach,
11553 &ZERO_RESIDUAL[..uw * uh],
11554 m.alpha
11555 .zip(ac.clone())
11556 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
11557 None,
11558 m.smooth_neighbor_uv,
11559 fctx,
11560 );
11561 }
11562 }
11563 }
11564 } else {
11565 if let Some((ub, _)) = &m.palette_uv {
11566 set_palette_pred(ub.clone(), fctx);
11567 }
11568 push_intra_rect(
11569 1,
11570 cpx,
11571 cpy,
11572 chroma_w,
11573 chroma_h,
11574 m.uv_predict_mode,
11575 m.angle_delta_uv,
11576 reach,
11577 &zero,
11578 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11579 None,
11580 m.smooth_neighbor_uv,
11581 fctx,
11582 );
11583 if let Some((_, vb)) = &m.palette_uv {
11584 set_palette_pred(vb.clone(), fctx);
11585 }
11586 push_intra_rect(
11587 2,
11588 cpx,
11589 cpy,
11590 chroma_w,
11591 chroma_h,
11592 m.uv_predict_mode,
11593 m.angle_delta_uv,
11594 reach,
11595 &zero,
11596 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
11597 None,
11598 m.smooth_neighbor_uv,
11599 fctx,
11600 );
11601 }
11602 (zero.clone(), zero)
11603 } else if lossless(fctx) {
11604 // lane-lossless: the strip's chroma plane block is coded as 4x4
11605 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
11606 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
11607 // (`decode_token_recon_block`'s mu-chunk loop, measured against
11608 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
11609 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
11610 // offset (our `+3` row base) whenever the plane block is bigger than
11611 // the transform.
11612 let scan4 = default_scan(4);
11613 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
11614 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
11615 // lane-av1-llband: one 4x4 chroma unit's extent in LUMA pixels -- 4
11616 // chroma px scaled by the plane's own subsampling. The hardcoded 8
11617 // was the 4:2:0 unit's span; at 4:4:4 a unit is 4x4 LUMA px (one mi
11618 // cell), and the 8-px step made every unit past the first column/row
11619 // read its `txb_skip` context at the WRONG mi (two cells over) and
11620 // stamp a 2-cell span with one unit's state -- the polluted above-band
11621 // cell behind a 16x8 leaf's U bc=2 unit of the 444 lossless key frame
11622 // (measured: oracle `EC_DBGCTX` reads 1-cell spans at 1-mi steps;
11623 // ours read `above[28..29]` where the oracle read `above[26]`).
11624 let span_x = 4 << ss_x(fctx);
11625 let span_y = 4 << ss_y(fctx);
11626 let mut last = [Grid::Zero(16), Grid::Zero(16)];
11627 for plane_idx in 1..=2 {
11628 for cu_row in 0..ch_n {
11629 for cu_col in 0..cw_n {
11630 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
11631 let cu_around = neighbours.around_mi_rect(cu_mi, span_x, span_y);
11632 let cu_reach = tu_reach(
11633 bw,
11634 bh,
11635 cu_col * span_x,
11636 cu_row * span_y,
11637 span_x,
11638 block_reach,
11639 px,
11640 py,
11641 y.width,
11642 y.height,
11643 fctx,
11644 );
11645 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
11646 if let Some((ub, vb)) = &m.palette_uv {
11647 let pbuf = if plane_idx == 1 { ub } else { vb };
11648 set_palette_pred(
11649 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
11650 fctx,
11651 );
11652 }
11653 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
11654 let grid = read_plane(
11655 dec,
11656 cdfs,
11657 TxbSet::Chroma4,
11658 &scan4,
11659 plane_idx,
11660 cu_around[plane_idx],
11661 m.mode,
11662 m.uv_predict_mode,
11663 m.angle_delta_uv,
11664 cu_reach,
11665 plane,
11666 cu_x,
11667 cu_y,
11668 4,
11669 4,
11670 base_q_idx,
11671 m.alpha
11672 .zip(ac)
11673 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
11674 None,
11675 offset,
11676 m.smooth_neighbor_uv,
11677 fctx,
11678 )?;
11679 if span_x == 4 && span_y == 4 {
11680 hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS);
11681 }
11682 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid);
11683 ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y));
11684 last[plane_idx - 1] = grid;
11685 }
11686 }
11687 }
11688 let [ug, vg] = last;
11689 (ug, vg)
11690 } else if chroma_tiled {
11691 let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) =
11692 if chroma_422_pair_wide || chroma_422_oob {
11693 // lane-av1-422blockhalf / lane-av1-422stripanchor: the
11694 // BLOCK_INVALID-plane chroma's (4, 8) units -- the Release
11695 // oracle's out-of-bounds `max_txsize_rect_lookup` byte (TX_4X8,
11696 // see above). For the 4-wide strip the units tile the PAIR's
11697 // plane, stepping from the floored anchor.
11698 (4, 8, TxbSet::ChromaRect8x4, &SCAN_4X8)
11699 } else {
11700 match (chroma_w, chroma_h) {
11701 (64, 32) | (32, 64) | (32, 32) => (32, 32, TxbSet::Chroma32, default_scan(32)),
11702 (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16),
11703 (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32),
11704 // lane-av1-422: the 4:2:2 square chroma planes (height unhalved),
11705 // through the square reader like every other square chroma unit.
11706 (16, 16) => (16, 16, TxbSet::Chroma16, default_scan(16)),
11707 (8, 8) => (8, 8, TxbSet::Chroma8, default_scan(8)),
11708 _ => unreachable!("chroma_tiled"),
11709 }
11710 };
11711 // lane-av1-422: the witness counter, keyed to ss (1,0) so only a 4:2:2
11712 // frame's square chroma units count it.
11713 if uw == uh && ss_x(fctx) == 1 && ss_y(fctx) == 0 {
11714 hit!(CHROMA422_SQUARE_HITS);
11715 }
11716 if chroma_422_pair_wide {
11717 hit!(CHROMA422_PAIR_WIDE_HITS);
11718 }
11719 let (nw, nh) = (chroma_block_w / uw, chroma_block_h / uh);
11720 // lane-av1-422stripanchor: the pair's plane block is BLOCK_INVALID
11721 // whatever the pair size (`num_pels_log2_lookup[255]` reads 0xff in
11722 // the pinned Release oracle), so its txb_skip rows always carry the
11723 // bigger-plane +3 (the av1422q rule the pair16 arm measures).
11724 let bigger = chroma_422_pair_wide || chroma_w * chroma_h > uw * uh;
11725 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
11726 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra;
11727 // smaller rect units (the 4:2:2 BLOCK_INVALID-plane (4, 8)s) take the
11728 // mode-indexed default, the same rule the unsplit arm below applies.
11729 let default_tx = if uw.max(uh) >= 32 {
11730 TxType::DctDct
11731 } else {
11732 default_intra_tx_type(m.uv_predict_mode as u8)
11733 };
11734 let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)];
11735 for plane_idx in 1..=2 {
11736 for cu_row in 0..nh {
11737 for cu_col in 0..nw {
11738 let luma_span_x = uw << ss_x(fctx);
11739 let luma_span_y = uh << ss_y(fctx);
11740 let cu_mi = (
11741 mi_r + cu_row * (luma_span_y / MI),
11742 if chroma_422_pair_wide {
11743 mi_c & !1
11744 } else {
11745 mi_c
11746 } + cu_col * (luma_span_x / MI),
11747 );
11748 // lane-av1-422blockhalf: the 4:2:2 (4, 8) units read their
11749 // chroma context per chroma cell
11750 // ([`Neighbours::around_mi_422_chroma`], the block-8
11751 // rule) -- the plain rect walk samples one chroma cell
11752 // twice at ss_x 1. Every pre-existing shape keeps its own
11753 // walk.
11754 // lane-av1422mi24: the plain rect walk's double-count
11755 // hits EVERY unit shape at ss (1,0), not just the (4, 8)
11756 // one -- the (8, 8) unit of a 16x8 intra-in-inter strip
11757 // read its above dc votes twice and its U dc_sign one
11758 // ctx row high (t422 frame 1). Route every ss (1,0)
11759 // unit through the every-second-above-cell sampling;
11760 // 4:2:0/4:4:4 keep the plain walk verbatim.
11761 let cu_around = if chroma_422_oob || (ss_x(fctx) == 1 && ss_y(fctx) == 0) {
11762 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
11763 } else {
11764 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
11765 };
11766 let (cu_x, cu_y) = (chroma_x + cu_col * uw, cpy + cu_row * uh);
11767 let cfl = m.alpha.map(|(au, av)| {
11768 let alpha = if plane_idx == 1 { au } else { av };
11769 (
11770 alpha,
11771 if chroma_422_pair_wide {
11772 // The unit's co-located luma is the PAIR's
11773 // 8-px-wide band at the floored mi column.
11774 cfl_src_rect(
11775 (mi_c & !1) * MI + cu_col * luma_span_x,
11776 py + cu_row * luma_span_y,
11777 luma_span_x,
11778 luma_span_y,
11779 )
11780 } else {
11781 cfl_src_rect(
11782 px + cu_col * luma_span_x,
11783 py + cu_row * luma_span_y,
11784 luma_span_x,
11785 luma_span_y,
11786 )
11787 },
11788 )
11789 });
11790 // lane-av1-422kf: the palette colour map is consumed per
11791 // unit here like every other chroma arm (`av1_visit_palette`
11792 // feeds the whole plane block; window it to this unit).
11793 // Without this the square chroma rows decoded a uv-palette
11794 // strip's chroma as plain DC (class same-symbols-silent-
11795 // prediction: the rng stayed in sync, only the prediction
11796 // was dropped).
11797 if let Some((ub, vb)) = &m.palette_uv {
11798 let buf = if plane_idx == 1 { ub } else { vb };
11799 set_palette_pred(
11800 palette_window(buf, chroma_block_w, cu_col * uw, cu_row * uh, uw, uh),
11801 fctx,
11802 );
11803 }
11804 // 32x32 does not fit read_coeffs_rect's scratch (768). The
11805 // square reader is the path every other 32x32 chroma unit uses.
11806 let levels = if uw == uh {
11807 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
11808 read_plane(
11809 dec,
11810 cdfs,
11811 set,
11812 scan,
11813 plane_idx,
11814 cu_around[plane_idx],
11815 m.mode,
11816 m.uv_predict_mode,
11817 m.angle_delta_uv,
11818 reach,
11819 plane,
11820 cu_x,
11821 cu_y,
11822 uw,
11823 uw,
11824 base_q_idx,
11825 cfl,
11826 None,
11827 bigger.then_some(3),
11828 m.smooth_neighbor_uv,
11829 fctx,
11830 )?
11831 } else {
11832 let skip_ctx = usize::from(cu_around[plane_idx].0)
11833 + usize::from(cu_around[plane_idx].1)
11834 + usize::from(bigger) * 3;
11835 let mut coding = cdfs.txb(set, m.uv_predict_mode);
11836 let (levels, tx_type) = read_coeffs_rect(
11837 dec,
11838 &mut coding,
11839 scan,
11840 uw,
11841 uh,
11842 skip_ctx,
11843 dc_sign_ctx(cu_around[plane_idx].2),
11844 default_tx,
11845 )?;
11846 let residual = dequant_and_inverse_typed_wh(
11847 &levels,
11848 uw,
11849 uh,
11850 crate::decode::bit_depth(fctx),
11851 block_q_idx(fctx),
11852 plane_q_delta(plane_idx, fctx).0,
11853 plane_q_delta(plane_idx, fctx).1,
11854 tx_type,
11855 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
11856 );
11857 push_intra_rect(
11858 plane_idx,
11859 cu_x,
11860 cu_y,
11861 uw,
11862 uh,
11863 m.uv_predict_mode,
11864 m.angle_delta_uv,
11865 reach,
11866 &residual,
11867 cfl,
11868 None,
11869 m.smooth_neighbor_uv,
11870 fctx,
11871 );
11872 levels
11873 };
11874 neighbours.record_mi_chroma(
11875 cu_mi,
11876 luma_span_x,
11877 luma_span_y,
11878 plane_idx,
11879 &levels,
11880 );
11881 tiled_chroma_units.push((
11882 cu_mi,
11883 plane_idx,
11884 levels.clone(),
11885 luma_span_x,
11886 luma_span_y,
11887 ));
11888 last[plane_idx - 1] = levels;
11889 }
11890 }
11891 }
11892 (last[0].clone(), last[1].clone())
11893 } else {
11894 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
11895 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
11896 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
11897 // so only the 16x8/8x16 pair takes the mode-indexed default.
11898 let default_tx = if chroma_w.max(chroma_h) >= 32 {
11899 TxType::DctDct
11900 } else {
11901 default_intra_tx_type(m.uv_predict_mode as u8)
11902 };
11903 // lane-av1422mi24: at ss (1,0) the chroma above span is `bw >> 1`
11904 // chroma cells spread over `bw` luma mi columns -- the per-mi gather
11905 // counts every chroma column's whole-unit dc sign twice (the t422
11906 // frame-1 mi(26,60) intra-in-inter strip's U dc_sign read one ctx
11907 // row high). Luma keeps the per-mi gather; the two chroma planes
11908 // take [`Neighbours::around_mi_422_chroma`]'s every-second
11909 // above-cell sampling, like every other 4:2:2 chroma gather.
11910 let mut around = neighbours.around_mi_rect(at_mi, bw, bh);
11911 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
11912 let c = neighbours.around_mi_422_chroma(at_mi, bw, bh);
11913 around[1] = c[1];
11914 around[2] = c[2];
11915 }
11916 let mut grids: Vec<Grid> = Vec::with_capacity(2);
11917 for plane_idx in 1..=2 {
11918 let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
11919 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
11920 let (levels, tx_type) = read_coeffs_rect(
11921 dec,
11922 &mut coding,
11923 chroma_scan,
11924 chroma_w,
11925 chroma_h,
11926 skip_ctx,
11927 dc_sign_ctx(around[plane_idx].2),
11928 default_tx,
11929 )?;
11930 // The same delta_q proof the unsplit rect64 path records
11931 // (lane-rectsplit r4: lifting the split-transform refusal moved
11932 // superblock strips onto this path, so only counting there would
11933 // leave the delta_q gate's counter silent for them).
11934 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
11935 hit!(RECT64_QIDX_DRIFT_HITS);
11936 }
11937 let residual = dequant_and_inverse_typed_wh(
11938 &levels,
11939 chroma_w,
11940 chroma_h,
11941 crate::decode::bit_depth(fctx),
11942 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
11943 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
11944 // reading `current_q_idx` here dropped the segment feature
11945 // that every other dequant site applies (class
11946 // `parsed-then-discarded`).
11947 block_q_idx(fctx),
11948 plane_q_delta(plane_idx, fctx).0,
11949 plane_q_delta(plane_idx, fctx).1,
11950 tx_type,
11951 block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, tx_type),
11952 );
11953 let cfl = m
11954 .alpha
11955 .zip(ac)
11956 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
11957 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
11958 if let Some((ub, vb)) = &m.palette_uv {
11959 let buf = if plane_idx == 1 { ub } else { vb };
11960 set_palette_pred(buf.clone(), fctx);
11961 }
11962 push_intra_rect(
11963 plane_idx,
11964 cpx,
11965 cpy,
11966 chroma_w,
11967 chroma_h,
11968 m.uv_predict_mode,
11969 m.angle_delta_uv,
11970 reach,
11971 &residual,
11972 cfl,
11973 None,
11974 m.smooth_neighbor_uv,
11975 fctx,
11976 );
11977 grids.push(levels);
11978 }
11979 let mut it = grids.into_iter();
11980 (it.next().unwrap(), it.next().unwrap())
11981 };
11982 neighbours.record_split_luma_rect_mi(
11983 at_mi,
11984 bw,
11985 bh,
11986 m.mode,
11987 m.uv_predict_mode,
11988 [&u_grid, &v_grid],
11989 );
11990 for (cu_mi, plane, unit, span_w, span_h) in &ll_chroma_units {
11991 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
11992 }
11993 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
11994 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
11995 }
11996 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
11997 neighbours.fill_lf_grid_rect(
11998 (mi_r, mi_c),
11999 bw / MI,
12000 bh / MI,
12001 tx_w as u8,
12002 tx_h as u8,
12003 0,
12004 fctx,
12005 );
12006 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12007 let (rng, _) = dec.debug_state();
12008 eprintln!(
12009 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
12010 tx={tx_w}x{tx_h} rng={rng}"
12011 );
12012 }
12013 Ok(())
12014}
12015
12016/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
12017/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
12018/// because it predicts squares only. Every pixel here goes through the rect
12019/// machinery the key-frame paths already prove: [`decode_rect_split`], which
12020/// at `depth == 0` is the unsplit strip as a single transform unit and
12021/// beyond it the per-unit walk of [`depth_to_tx_wh`].
12022///
12023/// What is genuinely different from [`decode_block_rect`] is the mode
12024/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
12025/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
12026/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
12027/// intra-in-inter arm's own reads at the rect footprint, including its
12028/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
12029/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
12030/// square and this arm) and a nonzero luma angle delta refused by name.
12031///
12032/// The strip's own neighbour records (luma per transform unit, chroma, skip
12033/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
12034/// inter-side bands and the mi map.
12035#[allow(clippy::too_many_arguments)]
12036/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
12037/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
12038/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
12039/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
12040/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
12041/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
12042/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
12043/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
12044/// table here rather than a shift of `bw.min(bh)`.
12045fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
12046 Some(match (bw.min(bh), bw.max(bh)) {
12047 (8, 16) => (1usize, 1usize),
12048 (16, 32) => (2, 2),
12049 (32, 64) => (3, 3),
12050 (8, 32) => (1, 2),
12051 (16, 64) => (2, 3),
12052 _ => return None,
12053 })
12054}
12055
12056/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
12057/// block path"): the shapes that can reach that arm, enumerated against the
12058/// MEASURED domain of the inter block path
12059/// ([`INTER_BLOCK_SHAPES`], the census the gate
12060/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
12061/// fills from three real streams).
12062///
12063/// [`decode_intra_rect_in_inter`] is called from one site, under
12064/// `write_w != side || write_h != side`, and only after two earlier arms have
12065/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
12066/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
12067/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
12068/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
12069/// and each of those has a row, so the refusal names a shape no measured
12070/// stream can present.
12071#[test]
12072fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
12073 let mut checked = 0;
12074 for &(side, w, h) in &INTER_BLOCK_SHAPES {
12075 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
12076 continue;
12077 }
12078 assert!(
12079 intra_in_inter_size_row(w, h).is_some(),
12080 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
12081 the \"no size-group/tx-category row\" refusal"
12082 );
12083 checked += 1;
12084 }
12085 assert_eq!(
12086 checked, 10,
12087 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
12088 lookup, not the 10 this claim was measured over"
12089 );
12090}
12091
12092/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
12093/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
12094/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
12095/// matched before the square arm's `log2` shortcut).
12096///
12097/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
12098/// row here"; the enumeration below is what proves no conformant block can
12099/// reach it.
12100pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
12101 Some(match (write_w, write_h) {
12102 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
12103 // below maps 128 to row 4 (BLOCK_16X32).
12104 (64, 128) => 14,
12105 (128, 64) => 15,
12106 (128, 128) => 16,
12107 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
12108 (16, 32) => 4,
12109 (32, 16) => 5,
12110 (32, 64) => 6,
12111 (64, 32) => 7,
12112 (8, 32) => 8,
12113 (32, 8) => 9,
12114 (16, 64) => 10,
12115 (64, 16) => 11,
12116 // lane-inter4 r3: the 16x16-level rect inter leaves.
12117 (8, 16) => 12,
12118 (16, 8) => 13,
12119 _ => return None,
12120 })
12121}
12122
12123/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
12124/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
12125/// `block_size_wide`/`block_size_high`).
12126#[cfg(test)]
12127const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
12128 (4, 4),
12129 (4, 8),
12130 (8, 4),
12131 (8, 8),
12132 (8, 16),
12133 (16, 8),
12134 (16, 16),
12135 (16, 32),
12136 (32, 16),
12137 (32, 32),
12138 (32, 64),
12139 (64, 32),
12140 (64, 64),
12141 (64, 128),
12142 (128, 64),
12143 (128, 128),
12144 (4, 16),
12145 (16, 4),
12146 (8, 32),
12147 (32, 8),
12148 (16, 64),
12149 (64, 16),
12150];
12151
12152/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
12153/// shape with no CDF row here" names a shape no conformant stream can present.
12154///
12155/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
12156/// whose `write_w.min(write_h) >= 8` clause is libaom's
12157/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
12158/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
12159/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
12160/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
12161/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
12162/// clause rejects before the lookup.
12163#[test]
12164fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
12165 let mut rows = std::collections::BTreeSet::new();
12166 let mut excluded = 0;
12167 for (w, h) in BLOCK_SIZES_ALL_WH {
12168 if w.min(h) < 8 {
12169 excluded += 1;
12170 assert!(
12171 w == 4 || h == 4,
12172 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
12173 );
12174 continue;
12175 }
12176 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
12177 panic!(
12178 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
12179 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
12180 )
12181 });
12182 assert!(
12183 row < 17,
12184 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
12185 );
12186 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
12187 }
12188 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
12189 assert_eq!(
12190 rows.len(),
12191 17,
12192 "17 eligible footprints must fill all 17 rows of the motion_mode table"
12193 );
12194}
12195
12196/// lane-av1-422stripanchor, format-cell census for the 4-wide-strip pair port
12197/// ([`chroma422_pair_plane`], [`decode_rect_split`]'s chroma routing): over
12198/// every `BLOCK_SIZES_ALL` footprint at every subsampling cell, the pair arm
12199/// fires exactly when libaom's own `av1_ss_size_lookup[..][1][0]` column
12200/// (`common_data.c`) marks the plane block BLOCK_INVALID AND the plane would
12201/// be 2 px wide -- the 4-wide footprints. The tall/wide BLOCK_INVALID shapes
12202/// stay on the pre-existing `chroma_422_oob` (4, 8) tiling, and 4:2:0 /
12203/// 4:4:4 never enter either arm (the byte-identical claim, checked per cell).
12204#[test]
12205fn chroma422_pair_plane_matches_the_ss_size_lookup_cells() {
12206 // The `av1_ss_size_lookup[..][1][0]` column verbatim (pinned oracle,
12207 // `common_data.c`), keyed by footprint: `true` = BLOCK_INVALID.
12208 let ss10_invalid: &[(&str, bool)] = &[
12209 ("4x4", false),
12210 ("4x8", true),
12211 ("8x4", false),
12212 ("8x8", false),
12213 ("8x16", true),
12214 ("16x8", false),
12215 ("16x16", false),
12216 ("16x32", true),
12217 ("32x16", false),
12218 ("32x32", false),
12219 ("32x64", true),
12220 ("64x32", false),
12221 ("64x64", false),
12222 ("64x128", true),
12223 ("128x64", false),
12224 ("128x128", false),
12225 ("4x16", true),
12226 ("16x4", false),
12227 ("8x32", true),
12228 ("32x8", false),
12229 ("16x64", true),
12230 ("64x16", false),
12231 ];
12232 for (footprint, invalid10) in ss10_invalid {
12233 let (w, h) = footprint.split_once('x').unwrap();
12234 let (bw, bh) = (w.parse::<usize>().unwrap(), h.parse::<usize>().unwrap());
12235 // BLOCK_4X4 is the SQUARE path's leaf, never a strip: its ss cell is
12236 // valid because a (2, 4) plane area rounds UP to the 4x4 read
12237 // (`sub8_leaf_chroma422`'s own rule), and it never reaches
12238 // [`decode_rect_split`] at all.
12239 if (bw, bh) == (4, 4) {
12240 continue;
12241 }
12242 // 4:2:0 and 4:4:4: the port never fires, whatever the footprint.
12243 for (ss_x, ss_y) in [(false, false), (true, true)] {
12244 assert!(
12245 chroma422_pair_plane(ss_x, ss_y, 7, bw, bh).is_none(),
12246 "{bw}x{bh} at ss ({ss_x}, {ss_y}) must keep its own plane block"
12247 );
12248 }
12249 // 4:2:2: the pair arm is exactly the 2-px-wide (4-wide) slice of the
12250 // BLOCK_INVALID column, anchored at the floored mi column.
12251 let pair = chroma422_pair_plane(true, false, 7, bw, bh);
12252 assert_eq!(
12253 pair.is_some(),
12254 *invalid10 && bw == 4,
12255 "{bw}x{bh} at ss (1, 0): pair routing disagrees with ss_size_lookup"
12256 );
12257 if let Some((block_w, block_h, x, ctx_col)) = pair {
12258 assert_eq!((block_w, block_h), (4, bh), "{bw}x{bh} pair plane shape");
12259 assert_eq!(x, ((7 & !1) * MI) >> 1, "{bw}x{bh} floored write anchor");
12260 assert_eq!(ctx_col, 6, "{bw}x{bh} entropy cell is the floored column");
12261 // An even-column strip anchors at its own cell.
12262 let (x_even, col_even) = match chroma422_pair_plane(true, false, 6, bw, bh) {
12263 Some((_, _, x, c)) => (x, c),
12264 None => panic!("{bw}x{bh} lost its pair arm at an even mi_col"),
12265 };
12266 assert_eq!(
12267 (x_even, col_even),
12268 (12, 6),
12269 "even column keeps its own cell"
12270 );
12271 }
12272 }
12273 // The tall/wide BLOCK_INVALID shapes (8 px wide or more) are the
12274 // `chroma_422_oob` tiling's residents, not the pair arm's: both are
12275 // 4:2:2-only, so the two arms partition the BLOCK_INVALID column.
12276 for (bw, bh) in [
12277 (8usize, 16),
12278 (16, 32),
12279 (32, 64),
12280 (64, 128),
12281 (8, 32),
12282 (16, 64),
12283 ] {
12284 assert!(chroma422_pair_plane(true, false, 7, bw, bh).is_none());
12285 }
12286}
12287
12288fn decode_intra_rect_in_inter(
12289 dec: &mut SymbolDecoder,
12290 cdfs: &mut Cdfs,
12291 neighbours: &mut Neighbours,
12292 at: (usize, usize),
12293 bw: usize,
12294 bh: usize,
12295 skip: bool,
12296 allow_screen_content_tools: bool,
12297 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
12298 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
12299 strip16: Option<(bool, bool)>,
12300 y: &mut PlaneBuf<'static>,
12301 u: &mut PlaneBuf<'static>,
12302 v: &mut PlaneBuf<'static>,
12303 base_q_idx: u8,
12304 fctx: &crate::decode::FrameCtx,
12305) -> Result<()> {
12306 // `at` is in MI units (the inter path's own unit since lane-inter4);
12307 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
12308 // below are still keyed by.
12309 let (mi_r, mi_c) = at;
12310 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
12311 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
12312 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
12313 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
12314 // finding -- the category is NOT the same for every strip size).
12315 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
12316 // it is refused by name rather than read from the wrong CDF row.
12317 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
12318 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
12319 // tx-depth category is 1 -- but nothing here has to know either, because
12320 // the strip decodes through the very body the KEY FRAME path proves for
12321 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
12322 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
12323 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
12324 // inter-frame difference is the mode-info read, which
12325 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
12326 // `y_mode[0]` plus the `skip` this caller already read.
12327 if let Some((horz, has_chroma)) = strip16 {
12328 // lane-t900 r22: the screen-content refusal here was STALE (class
12329 // stale-premise): [`decode_rect4_16_strip`] takes
12330 // `allow_screen_content_tools` and reads the whole palette syntax
12331 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
12332 // pair) -- the key frame proves that body. Lifted with the 10-bit
12333 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
12334 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
12335 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
12336 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
12337 let res = decode_rect4_16_strip(
12338 dec,
12339 cdfs,
12340 neighbours,
12341 (mi_r, mi_c),
12342 horz,
12343 has_chroma,
12344 // The inter strips of the same partition publish their own
12345 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
12346 // has nothing to add here.
12347 None,
12348 y,
12349 u,
12350 v,
12351 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
12352 allow_screen_content_tools,
12353 base_q_idx,
12354 fctx.tx_select_inter.with(std::cell::Cell::get),
12355 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
12356 fctx,
12357 );
12358 fctx.intra_in_inter_mode.with(|c| c.set(None));
12359 let (mode, uv, (tx_w, tx_h)) = res?;
12360 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
12361 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
12362 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
12363 // block of an inter frame, intra ones included, and
12364 // `txfm_partition_update` for the var-tx context. The key-frame body
12365 // writes neither (a key frame has no var-tx tree and its own readers
12366 // use the deblock grid), so the block AFTER this strip read a stale
12367 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
12368 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
12369 // 16x16 row.
12370 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12371 for i in 0..bw / MI {
12372 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
12373 *cell = tx_w as u8;
12374 }
12375 }
12376 for i in 0..bh / MI {
12377 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
12378 *cell = tx_h as u8;
12379 }
12380 }
12381 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
12382 // coarse 16-px cell holds one entry for the whole 16x16 and the last
12383 // block to write it wins).
12384 neighbours.above_mode[c] = mode;
12385 neighbours.left_mode[r] = mode;
12386 if let Some(uvm) = uv {
12387 neighbours.above_uv_mode[c] = uvm;
12388 neighbours.left_uv_mode[r] = uvm;
12389 }
12390 neighbours.above_side[c] = bw;
12391 neighbours.left_side[r] = bh;
12392 if crate::envflags::env_flag!("EC_INTRA16X4") {
12393 eprintln!(
12394 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
12395 mi_c * MI,
12396 mi_r * MI
12397 );
12398 }
12399 hit_do! {
12400 INTRA16X4_IN_INTER_HITS.with(|h| {
12401 let mut v = h.get();
12402 v[usize::from(!horz)] += 1;
12403 v[2] += usize::from(has_chroma);
12404 h.set(v);
12405 });
12406 }
12407 return Ok(());
12408 }
12409 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
12410 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
12411 // puts BLOCK_128X64/64X128/128X128 in group 3 and
12412 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
12413 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
12414 // block decodes through the very body the KEY FRAME path proves for this
12415 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
12416 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
12417 // `Reach` rule and the frame-edge write clip). The only inter-frame
12418 // differences live inside that body: the mode-info read
12419 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
12420 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
12421 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
12422 // palette (>64) do not exist at this size and are refused by name there.
12423 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
12424 // `intra128_in_inter_witness2.obu` (gate
12425 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
12426 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
12427 // all 15 frames, so the hits are counted out of exact frames (class
12428 // `counter-from-refused-stream`). What r16/r17 could not find, and what
12429 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
12430 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
12431 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
12432 // where the frame EDGE forces it: a partial last superblock row has
12433 // `has_rows128 == false`, so the 128x64 top half is implied, and a
12434 // partial last column implies the 64x128 left half. Put content no
12435 // reference holds (a fresh smooth ramp) in exactly those two bands of an
12436 // inter frame and the encoder codes those forced halves INTRA.
12437 if bw.max(bh) == 128 {
12438 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
12439 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
12440 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
12441 // palette_syntax`), so a 128-root half consumes no palette syntax and
12442 // a screen-content frame's half is syntactically identical to the
12443 // non-screen one this arm already decodes byte-exact.
12444 if coeff_trace_on() {
12445 // lane-t900 r16: which decode-order frame this arm fires in --
12446 // interleaved with the `EC_COEFF_FRAME` markers, this is what
12447 // proves the hit is counted out of a frame that compares exact
12448 // (class `counter-from-refused-stream`).
12449 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
12450 }
12451 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
12452 let res = decode_block_128rect(
12453 dec,
12454 cdfs,
12455 neighbours,
12456 (r, c),
12457 bw,
12458 bh,
12459 y,
12460 u,
12461 v,
12462 base_q_idx,
12463 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
12464 allow_screen_content_tools,
12465 fctx.tx_select_inter.with(std::cell::Cell::get),
12466 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
12467 fctx,
12468 );
12469 fctx.intra_in_inter_mode.with(|c| c.set(None));
12470 return res;
12471 }
12472 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
12473 if crate::envflags::env_flag!("EC_OBMCREC") {
12474 eprintln!(
12475 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
12476 );
12477 }
12478 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
12479 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
12480 // can arrive here are enumerated against the measured block-shape
12481 // census ([`INTER_BLOCK_SHAPES`]) by
12482 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
12483 // -- every one of them has a row, so this arm names a shape no stream
12484 // has been able to present.
12485 return Err(unsupported(format!(
12486 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
12487 )));
12488 };
12489 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
12490 // screen-content frame ("palette syntax is consumed for square blocks
12491 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
12492 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
12493 // it, while the 2:1 reader inlined further down now codes the same syntax
12494 // itself. A real `--tune-content=screen` inter stream reached this refusal
12495 // on 8x16 / 16x8 strips (gate
12496 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
12497 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
12498 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
12499 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
12500 // luma/chroma transform tables, the per-unit split walk and the strip's
12501 // own neighbour records). The ONLY difference on an inter frame is the
12502 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
12503 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
12504 // this caller already read. `tx_cat` above is the same category those
12505 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
12506 // `decode_block_rect64`), asserted here so a future shape cannot drift.
12507 if bw.max(bh) == 4 * bw.min(bh) {
12508 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
12509 fctx.intra_in_inter_mode
12510 .with(|c| c.set(Some((size_group, skip))));
12511 let res = if bw.max(bh) == 64 {
12512 decode_block_rect64(
12513 dec,
12514 cdfs,
12515 neighbours,
12516 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
12517 bw,
12518 bh,
12519 y,
12520 u,
12521 v,
12522 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
12523 allow_screen_content_tools,
12524 base_q_idx,
12525 fctx.tx_select_inter.with(std::cell::Cell::get),
12526 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
12527 fctx,
12528 )
12529 } else {
12530 decode_block_rect4(
12531 dec,
12532 cdfs,
12533 neighbours,
12534 (mi_r, mi_c),
12535 bw,
12536 bh,
12537 None,
12538 y,
12539 u,
12540 v,
12541 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
12542 allow_screen_content_tools,
12543 base_q_idx,
12544 fctx.tx_select_inter.with(std::cell::Cell::get),
12545 fctx,
12546 )
12547 .map(|_| ())
12548 };
12549 fctx.intra_in_inter_mode.with(|c| c.set(None));
12550 res?;
12551 let shape = match (bw, bh) {
12552 (64, 16) => 0,
12553 (16, 64) => 1,
12554 (32, 8) => 2,
12555 _ => 3,
12556 };
12557 hit_do! {
12558 INTRA_RECT4_IN_INTER_HITS.with(|h| {
12559 let mut v = h.get();
12560 v[shape] += 1;
12561 h.set(v);
12562 });
12563 }
12564 return Ok(());
12565 }
12566 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
12567 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
12568 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
12569 // own, so a cross-decoder bisection could only see the block's first
12570 // coefficient. Same names/format as [`read_tx_size`]'s rung.
12571 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
12572 if step_trace {
12573 eprintln!(
12574 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
12575 dec.debug_state().0
12576 );
12577 }
12578 if mode >= 13 {
12579 return Err(unsupported(
12580 "an intra mode this decoder does not code (round 2)",
12581 ));
12582 }
12583 // lane-angleinter (merged on main for the square intra-in-inter arm):
12584 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
12585 // directional predictor; this arm refused a nonzero one before the merge.
12586 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
12587 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
12588 } else {
12589 0
12590 };
12591 if angle_delta_y != 0 {
12592 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
12593 }
12594 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
12595 // superblock-level strip reads the no-CFL alphabet -- the same split
12596 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
12597 //
12598 // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
12599 // (libaom `decodemv.c:933`).
12600 let has_chroma = !mono(fctx);
12601 let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
12602 let uv_mode = if !has_chroma {
12603 DC_PRED
12604 } else if cfl_allowed {
12605 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
12606 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
12607 } else {
12608 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
12609 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
12610 };
12611 if step_trace {
12612 eprintln!(
12613 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
12614 u8::from(cfl_allowed),
12615 dec.debug_state().0
12616 );
12617 }
12618 if (9..=12).contains(&uv_mode) {
12619 hit!(SMOOTH_UV_HITS);
12620 }
12621 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
12622 Some(read_cfl_alphas(dec, cdfs))
12623 } else {
12624 None
12625 };
12626 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
12627 DC_PRED
12628 } else {
12629 uv_mode
12630 };
12631 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
12632 hit!(DIRECTIONAL_UV_HITS);
12633 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
12634 } else {
12635 0
12636 };
12637 if angle_delta_uv != 0 {
12638 hit!(UV_ANGLE_DELTA_HITS);
12639 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
12640 }
12641 // `read_palette_mode_info` (spec 5.11.13), in the position
12642 // `read_intra_block_mode_info` writes it: after the chroma mode and
12643 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
12644 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
12645 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
12646 // skipping the syntax here desynced the tile at the strip's own symbol.
12647 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
12648 // context and colour cache at its own mi position, and the two
12649 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
12650 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
12651 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
12652 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
12653 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
12654 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
12655 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
12656 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
12657 let use_palette_y =
12658 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
12659 if use_palette_y {
12660 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
12661 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
12662 }
12663 // A 2:1 strip of at least 8x8 is always a chroma reference, so
12664 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
12665 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
12666 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
12667 let use_palette_uv = has_chroma
12668 && uv_mode == DC_PRED
12669 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
12670 if crate::envflags::env_flag!("EC_PALSYN") {
12671 eprintln!(
12672 "EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
12673 use_palette_y as i32,
12674 use_palette_uv as i32,
12675 dec.debug_state().0
12676 );
12677 }
12678 if use_palette_uv {
12679 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
12680 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
12681 palette_uv_pending = Some((n, u_colors, v_colors));
12682 }
12683 }
12684 // lane-fiinter (merged on main for the square intra-in-inter arm):
12685 // `read_filter_intra_mode_info` is the tail of
12686 // `read_intra_block_mode_info`, after the palette syntax (refused whole
12687 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
12688 // 2:1 strips with both sides <= 32 -- their own CDF rows
12689 // ([`filter_intra_size_class_rect`]).
12690 let mut filter_intra = None;
12691 if mode == DC_PRED
12692 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
12693 // `av1_filter_intra_allowed` excludes a palette-Y block.
12694 && palette_y_pending.is_none()
12695 && let Some(class) = filter_intra_size_class_rect(bw, bh)
12696 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
12697 {
12698 hit!(FILTER_INTRA_HITS);
12699 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
12700 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
12701 }
12702 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
12703 let palette_y = palette_y_pending.map(|(n, colors)| {
12704 let map = decode_color_index_map_wh(
12705 dec,
12706 cdfs,
12707 n,
12708 bw,
12709 bh,
12710 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
12711 false,
12712 );
12713 hit!(PALETTE_HITS);
12714 hit!(PALETTE_RECT_HITS);
12715 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
12716 PaletteY {
12717 size: n,
12718 colors,
12719 map,
12720 }
12721 });
12722 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
12723 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
12724 let on = palette_onscreen_uv(
12725 (bw, bh),
12726 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
12727 (cw, ch),
12728 (ss_x(fctx), ss_y(fctx)),
12729 );
12730 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
12731 hit!(PALETTE_UV_HITS);
12732 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
12733 PaletteUv {
12734 size: n,
12735 u_colors,
12736 v_colors,
12737 map,
12738 }
12739 });
12740 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
12741 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
12742 // chroma ones -- [`decode_block_rect`]'s own pair.
12743 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
12744 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
12745 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
12746 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
12747 // one exactly as [`decode_leaf8`] already does (class
12748 // context-read-from-one-cell).
12749 let coarse_pair = neighbours.modes_above_left(r, c);
12750 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
12751 if (nb_above_mode, nb_left_mode) != coarse_pair {
12752 hit!(EDGE_FILTER_MI_FIX_HITS);
12753 }
12754 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
12755 if smooth_neighbor {
12756 hit!(SMOOTH_LUMA_HITS);
12757 }
12758 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
12759 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
12760 // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside
12761 // an inter frame codes no depth symbol either (`xd->lossless` is per
12762 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
12763 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
12764 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
12765 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
12766 let d = match tx_cat {
12767 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
12768 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
12769 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
12770 };
12771 if step_trace {
12772 eprintln!(
12773 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
12774 dec.debug_state().0
12775 );
12776 }
12777 d
12778 } else {
12779 0
12780 };
12781 if depth != 0 || lossless(fctx) {
12782 hit!(TX_DEPTH_HITS);
12783 // lane-intrasplit r1: a split intra strip in an inter frame walks the
12784 // key frame's own per-TU path ([`decode_rect_split`] below); what was
12785 // wrong when this refusal was written was the depth SYMBOL, not the walk.
12786 hit_do! {
12787 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
12788 let mut v = h.get();
12789 v[depth.min(2)] += 1;
12790 h.set(v);
12791 });
12792 }
12793 }
12794 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
12795 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
12796 // the two are indistinguishable when the diagnostic fires on splits alone.
12797 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
12798 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
12799 }
12800 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
12801 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
12802 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
12803 // of an inter frame, intra ones included -- with the skip term 0 it
12804 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
12805 // and `left_txfm_context` to `tx_size_high` over its height. This strip
12806 // wrote neither, so the next block's var-tx `txfm_partition` context read
12807 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
12808 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
12809 // mi(16,0) and desyncing the tile at that symbol.
12810 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12811 let modes = RectStripModes {
12812 skip,
12813 mode,
12814 angle_delta_y,
12815 uv_predict_mode,
12816 angle_delta_uv,
12817 alpha,
12818 filter_intra,
12819 smooth_neighbor,
12820 smooth_neighbor_uv,
12821 palette_y: palette_y
12822 .as_ref()
12823 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
12824 palette_uv: palette_uv.as_ref().map(|p| {
12825 (
12826 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12827 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12828 )
12829 }),
12830 };
12831 decode_rect_split(
12832 dec,
12833 cdfs,
12834 neighbours,
12835 (mi_r, mi_c),
12836 bw,
12837 bh,
12838 tx_w,
12839 tx_h,
12840 &modes,
12841 y,
12842 u,
12843 v,
12844 base_q_idx,
12845 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
12846 fctx,
12847 )?;
12848 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
12849 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
12850 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
12851 // left column over its height. This arm wrote neither before lane-intrasplit
12852 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
12853 // context across the strip's footprint.
12854 for i in 0..bw / MI {
12855 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
12856 *cell = tx_w as u8;
12857 }
12858 }
12859 for i in 0..bh / MI {
12860 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
12861 *cell = tx_h as u8;
12862 }
12863 }
12864 // The strip's own palette state into the mi-granular neighbour bands, so
12865 // the next block's colour cache and `palette_y_mode` context are libaom's.
12866 record_strip_palette(
12867 neighbours,
12868 (mi_r, mi_c),
12869 bw,
12870 bh,
12871 palette_y.as_ref().map_or(0, |p| p.size),
12872 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
12873 palette_uv.as_ref().map_or(0, |p| p.size),
12874 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
12875 );
12876 let class = match bw.max(bh) {
12877 64 => 0,
12878 32 => 1,
12879 _ => 2,
12880 };
12881 hit_do! {
12882 INTRA_RECT_IN_INTER_HITS.with(|h| {
12883 let mut v = h.get();
12884 v[class] += 1;
12885 h.set(v);
12886 });
12887 }
12888 Ok(())
12889}
12890
12891/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real
12892/// mi `(mi_r, mi_c)` (lane-av1-intrabc).
12893///
12894/// libaom treats an intrabc block as INTER for everything except the mode-info
12895/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA`
12896/// (`blockd.h:373`), so
12897///
12898/// * `parse_decode_block` reads the transform size through the INTER var-tx
12899/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose
12900/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and
12901/// whose leaves publish their own resolved size back;
12902/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT
12903/// frame's own pre-loop-filter reconstruction, at the coded block vector
12904/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`);
12905/// * `decode_token_recon_block`'s inter branch then reads one residual per
12906/// transform unit, through the INTER coefficient sets
12907/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane
12908/// inheriting the colocated luma unit's coded `tx_type`.
12909///
12910/// Text order is libaom's: transform tree, prediction, luma residual, chroma
12911/// residual, bookkeeping. A skipped block codes no residual at all -- the
12912/// prediction is the reconstruction.
12913#[allow(clippy::too_many_arguments)]
12914fn decode_intrabc_rect(
12915 dec: &mut SymbolDecoder,
12916 cdfs: &mut Cdfs,
12917 neighbours: &mut Neighbours,
12918 (mi_r, mi_c): (usize, usize),
12919 (bw, bh): (usize, usize),
12920 skip: bool,
12921 (dv_row, dv_col): (i32, i32),
12922 y: &mut PlaneBuf<'static>,
12923 u: &mut PlaneBuf<'static>,
12924 v: &mut PlaneBuf<'static>,
12925 base_q_idx: u8,
12926 fctx: &crate::decode::FrameCtx,
12927) -> Result<()> {
12928 hit!(INTRABC_RECT_HITS);
12929 // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
12930 let idx = usize::from(bh > bw);
12931 if skip {
12932 INTRABC_RECT_SKIPPED_HITS.with(|c| {
12933 let mut seen = c.get();
12934 seen[idx] += 1;
12935 c.set(seen);
12936 });
12937 } else {
12938 INTRABC_RECT_CODED_HITS.with(|c| {
12939 let mut seen = c.get();
12940 seen[idx] += 1;
12941 c.set(seen);
12942 });
12943 }
12944 let (px, py) = (mi_c * MI, mi_r * MI);
12945 let (cpx, cpy) = (px / 2, py / 2);
12946 // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the
12947 // halved shape's own `max_txsize_rect_lookup` entry IS that size for every
12948 // shape this helper is called at, so the uv plane block is ONE unit --
12949 // the same call `decode_token_recon_block`'s own chroma loop makes.
12950 let (cw, ch) = (bw / 2, bh / 2);
12951 // lane-av1-intrabc r2: the square stride the proven INTER path uses
12952 // (`side`). The residual grids, the prediction windows AND
12953 // `TxParams::stride` are all laid out at it -- the block's own width
12954 // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h`
12955 // exceeds the stride).
12956 let side = bw.max(bh);
12957 let cside = cw.max(ch);
12958 // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right
12959 // or bottom frame edge reads no transform-tree symbol for the units
12960 // outside it.
12961 let mi_cols = 2 * y.true_width.div_ceil(8);
12962 let mi_rows = 2 * y.true_height.div_ceil(8);
12963 let leaves = read_block_tx_size_rect(
12964 dec,
12965 cdfs,
12966 neighbours,
12967 (mi_r, mi_c),
12968 (bw, bh),
12969 (mi_cols, mi_rows),
12970 skip,
12971 fctx,
12972 )?;
12973 if leaves.is_some() {
12974 hit!(INTRABC_RECT_VARTX_HITS);
12975 }
12976 // The whole-block prediction: `predict_inter_block` runs once, before any
12977 // coefficient is read. `flush_recon` first -- the source is this frame's
12978 // own reconstruction, including the writes this superblock has queued.
12979 flush_recon(fctx, y, u, v);
12980 // `mc::predict_with_filter` writes a DENSE window; the residual machinery
12981 // reads it at the square stride, so re-lay it -- the same step the inter
12982 // path takes for its own square prediction buffer.
12983 let mut pred_y_dense = vec![0u16; bw * bh];
12984 mc::predict_with_filter(
12985 &y.data,
12986 y.width,
12987 y.true_width,
12988 y.true_height,
12989 mv_to_q4(px, dv_col, 0),
12990 mv_to_q4(py, dv_row, 0),
12991 bw,
12992 bh,
12993 mc::InterpFilterKind::Bilinear,
12994 &mut pred_y_dense,
12995 fctx,
12996 );
12997 let mut pred_y = vec![0u16; side * side];
12998 for row in 0..bh {
12999 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
13000 }
13001 let mut pred_u_dense = vec![0u16; cw * ch];
13002 mc::predict_with_filter(
13003 &u.data,
13004 u.width,
13005 u.true_width,
13006 u.true_height,
13007 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13008 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13009 cw,
13010 ch,
13011 mc::InterpFilterKind::Bilinear,
13012 &mut pred_u_dense,
13013 fctx,
13014 );
13015 let mut pred_u = vec![0u16; cside * cside];
13016 for row in 0..ch {
13017 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
13018 }
13019 let mut pred_v_dense = vec![0u16; cw * ch];
13020 mc::predict_with_filter(
13021 &v.data,
13022 v.width,
13023 v.true_width,
13024 v.true_height,
13025 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13026 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13027 cw,
13028 ch,
13029 mc::InterpFilterKind::Bilinear,
13030 &mut pred_v_dense,
13031 fctx,
13032 );
13033 let mut pred_v = vec![0u16; cside * cside];
13034 for row in 0..ch {
13035 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
13036 }
13037 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
13038 let luma_tx_type: TxType;
13039 let (luma_grid, u_grid, v_grid);
13040 if skip {
13041 // No residual syntax at all: the prediction IS the block.
13042 // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes
13043 // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip
13044 // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm.
13045 push_mc_rect(
13046 0,
13047 px,
13048 py,
13049 side,
13050 bw,
13051 bh,
13052 Pred::Inline(&pred_y, side),
13053 &ZERO_RESIDUAL[..side * side],
13054 fctx,
13055 );
13056 push_mc_rect(
13057 1,
13058 cpx,
13059 cpy,
13060 cside,
13061 cw,
13062 ch,
13063 Pred::Inline(&pred_u, cside),
13064 &ZERO_RESIDUAL[..cside * cside],
13065 fctx,
13066 );
13067 push_mc_rect(
13068 2,
13069 cpx,
13070 cpy,
13071 cside,
13072 cw,
13073 ch,
13074 Pred::Inline(&pred_v, cside),
13075 &ZERO_RESIDUAL[..cside * cside],
13076 fctx,
13077 );
13078 if let Some(ls) = leaves.as_ref() {
13079 // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s
13080 // skip arm performs -- libaom `av1_reset_entropy_context`
13081 // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a
13082 // SKIPPED block zeroes its whole entropy-band footprint. This
13083 // helper serves `decode_block_rect4`'s 1:4 strips on this tree,
13084 // so a skipped lossless strip whose `leaves` resolved (every
13085 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
13086 // returns the 4x4 grid before it looks at `skip`) left the
13087 // PREVIOUS occupant's luma bands standing and the NEXT block's
13088 // partition parse diverged from libaom's: the 320x242 lossless
13089 // sb128 gate read a phantom unskipped 8x32 intrabc strip at
13090 // mi(56,66) right after the skipped 8x16 one at mi(48,66).
13091 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
13092 for &(row, col, tw, th) in ls {
13093 neighbours.record_mi_luma_rect(
13094 (mi_r + row, mi_c + col),
13095 tw,
13096 th,
13097 &ZERO_RESIDUAL[..tw * th],
13098 );
13099 }
13100 }
13101 luma_tx_type = TxType::DctDct;
13102 luma_grid = Grid::Zero(side * side);
13103 u_grid = Grid::Zero(cside * cside);
13104 v_grid = Grid::Zero(cside * cside);
13105 } else {
13106 match leaves.as_ref() {
13107 None => {
13108 // One whole-block rectangular transform unit.
13109 // lane-av1422mi24: at ss (1,0) the chroma above span is
13110 // `bw >> 1` chroma cells spread over `bw` luma mi columns --
13111 // the per-mi gather counts every chroma column's whole-unit
13112 // dc sign twice (t422 frame 1, the mi(26,60) intra-in-inter
13113 // strip's U dc_sign read ctx 1 where the oracle's cell sum
13114 // is 0 -> ctx 0). Luma keeps the per-mi gather; the two
13115 // chroma planes take
13116 // [`Neighbours::around_mi_422_chroma`]'s every-second
13117 // above-cell sampling, like every other 4:2:2 chroma gather.
13118 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
13119 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
13120 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
13121 around[1] = c[1];
13122 around[2] = c[2];
13123 }
13124 let (grid, tx_type) = read_inter_plane_rect(
13125 dec,
13126 cdfs,
13127 rect_inter_luma_set(bw, bh, fctx)?,
13128 (bw, bh),
13129 side,
13130 0,
13131 around[0],
13132 0,
13133 y,
13134 px,
13135 py,
13136 Pred::Inline(&pred_y, side),
13137 None,
13138 None,
13139 fctx,
13140 )?;
13141 luma_tx_type = tx_type;
13142 luma_grid = embed_grid_stride(&grid, bw, bh, side);
13143 let (ug, _) = read_inter_plane_rect(
13144 dec,
13145 cdfs,
13146 rect_inter_chroma_set(cw, ch)?,
13147 (cw, ch),
13148 cside,
13149 1,
13150 around[1],
13151 0,
13152 u,
13153 cpx,
13154 cpy,
13155 Pred::Inline(&pred_u, cside),
13156 Some(luma_tx_type),
13157 None,
13158 fctx,
13159 )?;
13160 u_grid = embed_grid_stride(&ug, cw, ch, cside);
13161 let (vg, _) = read_inter_plane_rect(
13162 dec,
13163 cdfs,
13164 rect_inter_chroma_set(cw, ch)?,
13165 (cw, ch),
13166 cside,
13167 2,
13168 around[2],
13169 0,
13170 v,
13171 cpx,
13172 cpy,
13173 Pred::Inline(&pred_v, cside),
13174 Some(luma_tx_type),
13175 None,
13176 fctx,
13177 )?;
13178 v_grid = embed_grid_stride(&vg, cw, ch, cside);
13179 }
13180 Some(leaves) => {
13181 // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies
13182 // the split override to LUMA only, per leaf -- the step the
13183 // proven inter var-tx path applies right after its own residual
13184 // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the
13185 // leaf's own transform edges are never filtered.
13186 for &(row, col, tw, th) in leaves.iter() {
13187 neighbours.fill_lf_grid_leaf_luma(
13188 (mi_r + row, mi_c + col),
13189 tw / MI,
13190 th / MI,
13191 tw as u8,
13192 th as u8,
13193 );
13194 }
13195 // One residual per transform unit, in the order the tree coded
13196 // them; each unit reads its own neighbour-magnitude context off
13197 // the units already decoded before it, and every unit adds onto
13198 // its own window of the block's single prediction.
13199 let mut first_tx_type = TxType::DctDct;
13200 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
13201 let tu_mi = (mi_r + row, mi_c + col);
13202 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
13203 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
13204 let (tu_grid, tu_tx_type) = if tw == th {
13205 let scan = default_scan(tw.min(32));
13206 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
13207 read_inter_plane(
13208 dec,
13209 cdfs,
13210 inter_txbset_for(tw, reduced),
13211 scan,
13212 0,
13213 neighbours.around_mi(tu_mi, tw)[0],
13214 0,
13215 y,
13216 tu_px,
13217 tu_py,
13218 tw,
13219 base_q_idx,
13220 tu_pred,
13221 None,
13222 Some(tu_skip_ctx),
13223 fctx,
13224 )?
13225 } else {
13226 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
13227 read_inter_plane_rect(
13228 dec,
13229 cdfs,
13230 rect_inter_luma_set(tw, th, fctx)?,
13231 (tw, th),
13232 side,
13233 0,
13234 neighbours.around_mi_rect(tu_mi, tw, th)[0],
13235 0,
13236 y,
13237 tu_px,
13238 tu_py,
13239 tu_pred,
13240 None,
13241 Some(tu_skip_ctx),
13242 fctx,
13243 )?
13244 };
13245 if idx == 0 {
13246 first_tx_type = tu_tx_type;
13247 }
13248 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
13249 }
13250 // `av1_get_tx_type`'s chroma lookup lands on the colocated
13251 // LUMA unit, which for a split block is the top-left one.
13252 luma_tx_type = first_tx_type;
13253 // lane-av1422mi24: same 4:2:2 chroma gather rule as the
13254 // `None` arm above -- the per-mi rect gather double-counts
13255 // each chroma column's whole-unit dc sign at ss (1,0).
13256 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
13257 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
13258 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
13259 around[1] = c[1];
13260 around[2] = c[2];
13261 }
13262 let (ug, _) = read_inter_plane_rect(
13263 dec,
13264 cdfs,
13265 rect_inter_chroma_set(cw, ch)?,
13266 (cw, ch),
13267 cside,
13268 1,
13269 around[1],
13270 0,
13271 u,
13272 cpx,
13273 cpy,
13274 Pred::Inline(&pred_u, cside),
13275 Some(luma_tx_type),
13276 None,
13277 fctx,
13278 )?;
13279 u_grid = embed_grid_stride(&ug, cw, ch, cside);
13280 let (vg, _) = read_inter_plane_rect(
13281 dec,
13282 cdfs,
13283 rect_inter_chroma_set(cw, ch)?,
13284 (cw, ch),
13285 cside,
13286 2,
13287 around[2],
13288 0,
13289 v,
13290 cpx,
13291 cpy,
13292 Pred::Inline(&pred_v, cside),
13293 Some(luma_tx_type),
13294 None,
13295 fctx,
13296 )?;
13297 v_grid = embed_grid_stride(&vg, cw, ch, cside);
13298 luma_grid = Grid::Zero(side * side);
13299 }
13300 }
13301 }
13302 let _ = luma_tx_type;
13303 // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the
13304 // next block reads a neighbour mode, its own block size in both `TXFM`
13305 // bands (already done by `read_block_tx_size_rect`), a zeroed palette
13306 // state (a stale entry would feed the next block's colour cache), and its
13307 // DV into the intrabc mi grid the next block's DV predictor reads.
13308 if leaves.is_some() {
13309 neighbours.record_split_luma_rect_mi(
13310 (mi_r, mi_c),
13311 bw,
13312 bh,
13313 DC_PRED,
13314 DC_PRED,
13315 [&u_grid, &v_grid],
13316 );
13317 } else {
13318 neighbours.record_rect_mi(
13319 (mi_r, mi_c),
13320 bw,
13321 bh,
13322 DC_PRED,
13323 DC_PRED,
13324 &[&luma_grid, &u_grid, &v_grid],
13325 );
13326 }
13327 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
13328 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
13329 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
13330 neighbours.fill_lf_grid_rect(
13331 (mi_r, mi_c),
13332 bw / MI,
13333 bh / MI,
13334 bw.min(64) as u8,
13335 bh.min(64) as u8,
13336 0,
13337 fctx,
13338 );
13339 record_intrabc_mi_rect(
13340 mi_r,
13341 mi_c,
13342 bw / MI,
13343 bh / MI,
13344 Some((dv_row, dv_col)),
13345 neighbours,
13346 fctx,
13347 );
13348 Ok(())
13349}
13350
13351/// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root
13352/// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape
13353/// `decode_block_128rect` refused by name before this port. libaom decodes
13354/// such a block through the INTER machinery (an intrabc block
13355/// `is_inter_block`): `predict_inter_block` copies the whole block from this
13356/// frame's own reconstruction at the integer block vector once, then
13357/// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks --
13358/// per chunk every plane, luma units at the block's own resolved transform
13359/// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at
13360/// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per
13361/// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits
13362/// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`,
13363/// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in
13364/// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here.
13365#[allow(clippy::too_many_arguments)]
13366fn decode_intrabc_128rect(
13367 dec: &mut SymbolDecoder,
13368 cdfs: &mut Cdfs,
13369 neighbours: &mut Neighbours,
13370 (mi_r, mi_c): (usize, usize),
13371 (bw, bh): (usize, usize),
13372 skip: bool,
13373 (dv_row, dv_col): (i32, i32),
13374 y: &mut PlaneBuf<'static>,
13375 u: &mut PlaneBuf<'static>,
13376 v: &mut PlaneBuf<'static>,
13377 base_q_idx: u8,
13378 fctx: &crate::decode::FrameCtx,
13379) -> Result<()> {
13380 hit!(INTRABC_128RECT_HITS);
13381 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13382 let (rng, _) = dec.debug_state();
13383 eprintln!(
13384 "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}"
13385 );
13386 }
13387 let (px, py) = (mi_c * MI, mi_r * MI);
13388 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis
13389 // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's
13390 // `mv_to_q4(cpy, dv_row, ss_y(fctx))` calls two lines below already
13391 // scaled the DV on the y axis by ITS OWN subsampling, so the hardcoded
13392 // `/2` origin and extent made the prediction window half as tall as
13393 // the motion vector asked for), 4:2:2 is HALF-WIDTH and FULL-HEIGHT,
13394 // 4:4:4 is luma-sized. At ss (1,1) every value below is the old
13395 // `bw / 2, bh / 2` line-for-line.
13396 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
13397 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
13398 // The square strides the proven INTER path lays its residual grids,
13399 // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2
13400 // note): 128/64 here.
13401 let side = bw.max(bh);
13402 let cside = cw.max(ch);
13403 // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code
13404 // nothing (`decode_reconstruct_tx`'s max_blocks_* early return).
13405 let mi_cols = 2 * y.true_width.div_ceil(8);
13406 let mi_rows = 2 * y.true_height.div_ceil(8);
13407 // An intrabc block is is_inter_block: the tx tree is the INTER one, and
13408 // [`read_block_tx_size_rect`]'s 128-root branch already carries the
13409 // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree
13410 // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid)
13411 // arms (lane-sb128c r7).
13412 let leaves = read_block_tx_size_rect(
13413 dec,
13414 cdfs,
13415 neighbours,
13416 (mi_r, mi_c),
13417 (bw, bh),
13418 (mi_cols, mi_rows),
13419 skip,
13420 fctx,
13421 )?;
13422 // Whole-block prediction, once, before any coefficient is read
13423 // (`predict_inter_block`); the source is this frame's own
13424 // reconstruction, including the writes this superblock has queued.
13425 flush_recon(fctx, y, u, v);
13426 let mut pred_y_dense = vec![0u16; bw * bh];
13427 mc::predict_with_filter(
13428 &y.data,
13429 y.width,
13430 y.true_width,
13431 y.true_height,
13432 mv_to_q4(px, dv_col, 0),
13433 mv_to_q4(py, dv_row, 0),
13434 bw,
13435 bh,
13436 mc::InterpFilterKind::Bilinear,
13437 &mut pred_y_dense,
13438 fctx,
13439 );
13440 let mut pred_y = vec![0u16; side * side];
13441 for row in 0..bh {
13442 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
13443 }
13444 let mut pred_u_dense = vec![0u16; cw * ch];
13445 mc::predict_with_filter(
13446 &u.data,
13447 u.width,
13448 u.true_width,
13449 u.true_height,
13450 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13451 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13452 cw,
13453 ch,
13454 mc::InterpFilterKind::Bilinear,
13455 &mut pred_u_dense,
13456 fctx,
13457 );
13458 let mut pred_u = vec![0u16; cside * cside];
13459 for row in 0..ch {
13460 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
13461 }
13462 let mut pred_v_dense = vec![0u16; cw * ch];
13463 mc::predict_with_filter(
13464 &v.data,
13465 v.width,
13466 v.true_width,
13467 v.true_height,
13468 mv_to_q4(cpx, dv_col, ss_x(fctx)),
13469 mv_to_q4(cpy, dv_row, ss_y(fctx)),
13470 cw,
13471 ch,
13472 mc::InterpFilterKind::Bilinear,
13473 &mut pred_v_dense,
13474 fctx,
13475 );
13476 let mut pred_v = vec![0u16; cside * cside];
13477 for row in 0..ch {
13478 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
13479 }
13480 let (luma_grid, u_grid, v_grid);
13481 // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour
13482 // contexts per transform unit -- the replay after this fn's end-of-block
13483 // record restores them (the record itself re-stamps both planes with ONE
13484 // composed state, class `override-slot-on-one-arm`).
13485 let mut mu_chroma = false;
13486 if skip {
13487 // No residual syntax at all: the prediction IS the block. Strides are
13488 // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes
13489 // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun).
13490 push_mc_rect(
13491 0,
13492 px,
13493 py,
13494 side,
13495 bw,
13496 bh,
13497 Pred::Inline(&pred_y, side),
13498 &ZERO_RESIDUAL[..side * side],
13499 fctx,
13500 );
13501 push_mc_rect(
13502 1,
13503 cpx,
13504 cpy,
13505 cside,
13506 cw,
13507 ch,
13508 Pred::Inline(&pred_u, cside),
13509 &ZERO_RESIDUAL[..cside * cside],
13510 fctx,
13511 );
13512 push_mc_rect(
13513 2,
13514 cpx,
13515 cpy,
13516 cside,
13517 cw,
13518 ch,
13519 Pred::Inline(&pred_v, cside),
13520 &ZERO_RESIDUAL[..cside * cside],
13521 fctx,
13522 );
13523 if let Some(ls) = leaves.as_ref() {
13524 // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4
13525 // grid before it looks at `skip`; the skipped block still zeroes
13526 // its entropy-band footprint over every unit (libaom
13527 // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) --
13528 // the same arm [`decode_intrabc_rect`]'s loss64 merge added.
13529 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
13530 for &(row, col, tw, th) in ls {
13531 neighbours.record_mi_luma_rect(
13532 (mi_r + row, mi_c + col),
13533 tw,
13534 th,
13535 &ZERO_RESIDUAL[..tw * th],
13536 );
13537 }
13538 }
13539 luma_grid = Grid::Zero(side * side);
13540 u_grid = Grid::Zero(cside * cside);
13541 v_grid = Grid::Zero(cside * cside);
13542 } else {
13543 let leaves = leaves
13544 .expect("read_block_tx_size_rect returns None only for skip below 128 at this shape");
13545 // libaom `get_transform_size`'s split override applies to LUMA only,
13546 // per leaf -- each unit's own transform edges get filtered
13547 // ([`decode_intrabc_rect`]'s P2, the proven inter path's step).
13548 for &(row, col, tw, th) in leaves.iter() {
13549 neighbours.fill_lf_grid_leaf_luma(
13550 (mi_r + row, mi_c + col),
13551 tw / MI,
13552 th / MI,
13553 tw as u8,
13554 th as u8,
13555 );
13556 }
13557 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
13558 let mut u_units: Vec<i32> = Vec::new();
13559 let mut v_units: Vec<i32> = Vec::new();
13560 let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new();
13561 // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose
13562 // top-left sample is outside the frame codes nothing.
13563 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
13564 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
13565 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
13566 debug_assert_eq!(
13567 tw, th,
13568 "a square TX_64X64 tree root only yields square leaves"
13569 );
13570 let tu_mi = (mi_r + row, mi_c + col);
13571 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
13572 if tu_px >= y.true_width || tu_py >= y.true_height {
13573 continue;
13574 }
13575 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
13576 let scan = default_scan(tw.min(32));
13577 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
13578 let (tu_grid, tu_tx_type) = read_inter_plane(
13579 dec,
13580 cdfs,
13581 inter_txbset_for(tw, reduced),
13582 &scan,
13583 0,
13584 neighbours.around_mi(tu_mi, tw)[0],
13585 0,
13586 y,
13587 tu_px,
13588 tu_py,
13589 tw,
13590 base_q_idx,
13591 tu_pred,
13592 None,
13593 Some(tu_skip_ctx),
13594 fctx,
13595 )?;
13596 leaf_tx_types.push((row, col, tw, th, tu_tx_type));
13597 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
13598 // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64
13599 // mu chunk before the next one starts: once this chunk's leaves
13600 // are done, its chroma is read immediately (the inter 128 path's
13601 // interleave).
13602 let chunk = (row / 16, col / 16);
13603 let done = idx + 1 == leaves.len()
13604 || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk;
13605 if done {
13606 let (cr, cc) = chunk;
13607 // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one
13608 // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster
13609 // within the chunk, plane-major inside the chunk.
13610 let cu_tx = 32usize;
13611 // lane-av1-ibc128chunk: a 64x64 mu chunk's chroma plane
13612 // block is PER-AXIS `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at
13613 // 4:2:0, TWO STACKED TX_32X32 at 4:2:2 (the chunk's chroma
13614 // plane block is 32x64 there), four at 4:4:4. The old
13615 // `chunk_chroma = cside * 64 / side` walked a
13616 // `chroma_side`-SQUARE chunk, i.e. the 4:2:0 count on both
13617 // axes: at 4:2:2 it read HALF the chroma units of a chunk
13618 // (one 32x32 at the chunk's top-left instead of two), left
13619 // the chunk's lower 32 chroma rows with no residual at all,
13620 // and stamped every unit's entropy context over a 16x16-mi
13621 // luma span instead of 16x8. The same defect and the same
13622 // per-axis repair as `decode_inter_block`'s
13623 // `chunk_chroma_w/chunk_chroma_h` (lane-av1-422bigblock,
13624 // witnessed on `422_sb128_3f.obu`).
13625 let chunk_chroma_w = (64usize) >> ss_x(fctx);
13626 let chunk_chroma_h = (64usize) >> ss_y(fctx);
13627 // The unit's own footprint on the LUMA mi grid, per axis:
13628 // `(32 << ss) px` = `(32 << ss) / MI` mi -- 16x16 at 4:2:0,
13629 // 16x8 at 4:2:2, 8x8 at 4:4:4. `around_mi_rect` reads and
13630 // `record_mi_chroma` stamp exactly the unit's own cells.
13631 let unit_luma_w = cu_tx << ss_x(fctx);
13632 let unit_luma_h = cu_tx << ss_y(fctx);
13633 INTRABC_128RECT_CHUNK_SHAPE.with(|c| {
13634 c.set((chunk_chroma_w << 8) | chunk_chroma_h);
13635 });
13636 let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16));
13637 let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16));
13638 let units_x = chunk_w_mi / (unit_luma_w / MI);
13639 let units_y = chunk_h_mi / (unit_luma_h / MI);
13640 if lossless(fctx) {
13641 // TX_4X4 chroma units over this chunk (lane-lossless2's
13642 // walk, shared with the inter 128 path).
13643 read_inter_chroma_lossless(
13644 dec,
13645 cdfs,
13646 neighbours,
13647 u,
13648 v,
13649 Pred::Inline(&pred_u, cside),
13650 Pred::Inline(&pred_v, cside),
13651 (mi_r, mi_c),
13652 (cpx, cpy),
13653 (cc * chunk_chroma_w, cr * chunk_chroma_h),
13654 (chunk_chroma_w, chunk_chroma_h),
13655 (cw, ch),
13656 cside,
13657 0,
13658 base_q_idx,
13659 &mut u_units,
13660 &mut v_units,
13661 fctx,
13662 )?;
13663 // lane-av1-ibcrect: read_inter_chroma_lossless stamped
13664 // every TX_4X4 unit's own context (`record_mi_chroma`
13665 // inside the walk) -- the end-of-block record below must
13666 // not overwrite them with the composed grid (the inter
13667 // 128 path sets the same flag on this arm).
13668 mu_chroma = true;
13669 continue;
13670 }
13671 let cu_scan = default_scan(cu_tx);
13672 for plane_idx in 1..3 {
13673 let (src, buf) = if plane_idx == 1 {
13674 (Pred::Inline(&pred_u, cside), &mut *u)
13675 } else {
13676 (Pred::Inline(&pred_v, cside), &mut *v)
13677 };
13678 for ur in 0..units_y {
13679 for uc in 0..units_x {
13680 let unit_mi = (
13681 mi_r + cr * 16 + ur * (unit_luma_h / MI),
13682 mi_c + cc * 16 + uc * (unit_luma_w / MI),
13683 );
13684 // Per unit, AFTER the earlier units' stamps: this
13685 // unit's coefficient context must see them.
13686 let cu_around =
13687 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h);
13688 if crate::envflags::env_flag!("EC_ECDUMP") {
13689 for p in 1..3 {
13690 let ab: Vec<String> = (0..unit_luma_w / MI)
13691 .map(|k| {
13692 format!(
13693 "{:?}/{}",
13694 neighbours.above[unit_mi.1 + k][p].dc,
13695 neighbours.above[unit_mi.1 + k][p].level
13696 )
13697 })
13698 .collect();
13699 let lf: Vec<String> = (0..unit_luma_h / MI)
13700 .map(|k| {
13701 format!(
13702 "{:?}/{}",
13703 neighbours.left[unit_mi.0 + k][p].dc,
13704 neighbours.left[unit_mi.0 + k][p].level
13705 )
13706 })
13707 .collect();
13708 eprintln!(
13709 "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]",
13710 cu_around[p].0,
13711 cu_around[p].1,
13712 cu_around[p].2,
13713 ab.join(","),
13714 lf.join(",")
13715 );
13716 }
13717 }
13718 let (cu_x, cu_y) = (
13719 cpx + cc * chunk_chroma_w + uc * cu_tx,
13720 cpy + cr * chunk_chroma_h + ur * cu_tx,
13721 );
13722 // `av1_get_tx_type` (blockd.h:1291): an inter
13723 // block's chroma unit never codes a tx_type; it
13724 // inherits the coded type of the luma leaf
13725 // covering its own quadrant (all of this chunk's
13726 // leaves are read by now).
13727 let unit_rel_mi = (unit_mi.0 - mi_r, unit_mi.1 - mi_c);
13728 let covering = leaf_tx_types
13729 .iter()
13730 .copied()
13731 .find(|&(lr, lc, lw, lh, _)| {
13732 lr <= unit_rel_mi.0
13733 && unit_rel_mi.0 < lr + lh / MI
13734 && lc <= unit_rel_mi.1
13735 && unit_rel_mi.1 < lc + lw / MI
13736 })
13737 .map(|(_, _, _, _, t)| t);
13738 // The prediction window is the block's own square
13739 // `cside` buffer with the unit's true per-axis
13740 // position inside it.
13741 let cu_pred = src.offset(
13742 (cr * chunk_chroma_h + ur * cu_tx) * cside
13743 + cc * chunk_chroma_w
13744 + uc * cu_tx,
13745 );
13746 let cu_grid = read_inter_plane(
13747 dec,
13748 cdfs,
13749 TxbSet::Chroma32,
13750 &cu_scan,
13751 plane_idx,
13752 cu_around[plane_idx],
13753 0,
13754 buf,
13755 cu_x,
13756 cu_y,
13757 cu_tx,
13758 base_q_idx,
13759 cu_pred,
13760 Some(covering.unwrap_or(TxType::DctDct)),
13761 Some(3),
13762 fctx,
13763 )?
13764 .0;
13765 // Immediately, so the NEXT unit reads this one's
13766 // coefficient context.
13767 neighbours.record_mi_chroma(
13768 unit_mi,
13769 unit_luma_w,
13770 unit_luma_h,
13771 plane_idx,
13772 &cu_grid,
13773 );
13774 if crate::envflags::env_flag!("EC_ECDUMP") {
13775 let st = crate::decode::neighbour_state(&cu_grid);
13776 eprintln!(
13777 "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})",
13778 st.dc, st.level
13779 );
13780 }
13781 hit!(CHROMA_SPLIT_TX_HITS);
13782 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(c.get() + 1));
13783 // lane-av1-ibcrect: per-unit chroma context -- the
13784 // end-of-block record's composed-grid re-stamp
13785 // must not stand (replayed below).
13786 mu_chroma = true;
13787 let dst = mu_units(
13788 if plane_idx == 1 {
13789 &mut u_units
13790 } else {
13791 &mut v_units
13792 },
13793 cside * cside,
13794 );
13795 for rr in 0..cu_tx {
13796 let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * cside
13797 + cc * chunk_chroma_w
13798 + uc * cu_tx;
13799 dst[start..start + cu_tx]
13800 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
13801 }
13802 }
13803 }
13804 }
13805 }
13806 }
13807 // The block-level luma bands were recorded per leaf above; the
13808 // composed chroma grids carry every unit in place.
13809 luma_grid = Grid::Zero(side * side);
13810 u_grid = if u_units.is_empty() {
13811 Grid::Zero(cside * cside)
13812 } else {
13813 Grid::Own(std::mem::take(&mut u_units))
13814 };
13815 v_grid = if v_units.is_empty() {
13816 Grid::Zero(cside * cside)
13817 } else {
13818 Grid::Own(std::mem::take(&mut v_units))
13819 };
13820 }
13821 // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a
13822 // neighbour reads a mode, zeroed palette state, the skip grid, the
13823 // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them),
13824 // and the DV into the intrabc mi grid.
13825 if skip {
13826 neighbours.record_rect_mi(
13827 (mi_r, mi_c),
13828 bw,
13829 bh,
13830 DC_PRED,
13831 DC_PRED,
13832 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
13833 );
13834 } else {
13835 neighbours.record_split_luma_rect_mi(
13836 (mi_r, mi_c),
13837 bw,
13838 bh,
13839 DC_PRED,
13840 DC_PRED,
13841 [&u_grid[..], &v_grid[..]],
13842 );
13843 }
13844 // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER
13845 // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside
13846 // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps
13847 // both planes with ONE `neighbour_state(composed_grid)` over the whole
13848 // span -- level = the SUM of every unit's levels and dc = the top-left
13849 // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128
13850 // inter block: the next block read a stale `dc_sign_ctx` one row low).
13851 // Measured on this shape: the 128x64 block at mi(64,32) of the
13852 // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared
13853 // into chunk-0's cells and the block below read `txb_skip` off the sum.
13854 // Replay every coded unit's own state after the record, in mu-chunk order
13855 // so a later unit still wins over an earlier one on the shared seam cells
13856 // (the composed construction `mu_chroma_units` uses, transcribed here).
13857 if mu_chroma {
13858 let cu = if lossless(fctx) { 4usize } else { 32usize };
13859 // The unit's own footprint on the LUMA mi grid (the chroma context
13860 // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s
13861 // convention), PER AXIS: `cu << ss` px, i.e. 8 px per TX_4x4 unit and
13862 // 64 px per TX_32X32 one at 4:2:0 -- 4 px / 32 px at 4:2:2.
13863 let unit_luma_w = cu << ss_x(fctx);
13864 let unit_luma_h = cu << ss_y(fctx);
13865 // A 64x64 mu chunk's chroma plane block is PER-AXIS
13866 // `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at 4:2:0 (ONE TX_32X32 per
13867 // chunk), 32x64 at 4:2:2 (TWO STACKED), 64x64 at 4:4:4 (FOUR);
13868 // `av1_get_max_uv_txsize` caps the unit at 32 on each axis.
13869 let chunk_chroma_w = (64usize) >> ss_x(fctx);
13870 let chunk_chroma_h = (64usize) >> ss_y(fctx);
13871 if lossless(fctx) {
13872 // lane-av1-ibc128chunk, PRE-EXISTING and NOT this lane's: on a
13873 // LOSSLESS frame `cu` is 4 and the composed plane grid is a raster
13874 // of TX_4x4 units, not a `cu`-per-chunk tiling -- so `rows`/`cols`
13875 // below (which count mu CHUNKS at the 4:2:0 chunk extent) do not
13876 // enumerate it, and this arm re-stamps only the 4x4 at each
13877 // chunk's top-left with a 2x2-mi span. The twin
13878 // (`decode_inter_block`'s `mu_chroma_units`, lane-av1-llinter)
13879 // instead raster-walks the WHOLE plane block at `cu` steps, and
13880 // that is the correct shape here too. It is left as-is on purpose:
13881 // it is a 4:2:0 defect, not a subsampling square-cut, and fixing
13882 // it would change 4:2:0 LOSSLESS output -- which this lane's
13883 // byte-identity requirement forbids doing on an unverified
13884 // reconstruction. Measured unreachability: this arm is entered
13885 // 0 times by the whole `lossless` and `intrabc` gate battery
13886 // (temporary env-gated counter in the arm). Unblock: one
13887 // lossless sb128 4:2:0 stream coding a NON-SKIP 128-root
13888 // intrabc strip (`--lossless=1 --sb-size=128
13889 // --min-partition-size=64 --enable-rect-partitions=1
13890 // --enable-intrabc=1` over near-match screen content).
13891 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
13892 for cr in 0..rows {
13893 for cc in 0..cols {
13894 let unit_mi = (
13895 mi_r + cr * (unit_luma_h / MI),
13896 mi_c + cc * (unit_luma_w / MI),
13897 );
13898 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
13899 let mut unit = Vec::with_capacity(cu * cu);
13900 for rr in 0..cu {
13901 let start = (cr * chunk_chroma_h + rr) * cside + cc * chunk_chroma_w;
13902 unit.extend_from_slice(&grid[start..start + cu]);
13903 }
13904 neighbours.record_mi_chroma(
13905 unit_mi,
13906 unit_luma_w,
13907 unit_luma_h,
13908 plane_idx,
13909 &unit,
13910 );
13911 }
13912 }
13913 }
13914 } else {
13915 // The chunk count on each axis, then EVERY unit inside each
13916 // chunk at its own mi origin, its own `(cu << ss)`-px entropy-cell
13917 // span, and its own quadrant of the composed plane grid -- the
13918 // twin's loop (decode_inter_block's `mu_chroma_units`,
13919 // lane-av1-444 c8). lane-av1-ibc128chunk: the loop used to count
13920 // mu CHUNKS in `rows`/`cols` and then step the mi origin and read
13921 // the grid PER UNIT, which only agrees when a chunk holds exactly
13922 // one unit. At 4:2:0 (`chunk_chroma == cu`) it is
13923 // line-identical to the old walk; at 4:2:2 and 4:4:4 a chunk holds
13924 // 2 or 4, so the old body reached only the first of the stacked
13925 // units and the rest of the chunk kept the composed-grid smearing
13926 // this replay exists to undo. A unit the frame edge clipped codes
13927 // nothing and carries no composed samples beyond the clip, so it
13928 // replays as the zero state exactly like libaom's uncoded unit.
13929 let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);
13930 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
13931 for cr in 0..rows {
13932 for cc in 0..cols {
13933 for kr in 0..ur {
13934 for kc in 0..uc {
13935 let unit_mi = (
13936 mi_r + (cr * 64 + kr * unit_luma_h) / MI,
13937 mi_c + (cc * 64 + kc * unit_luma_w) / MI,
13938 );
13939 let (cy, cx) =
13940 (cr * chunk_chroma_h + kr * cu, cc * chunk_chroma_w + kc * cu);
13941 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
13942 let mut unit = Vec::with_capacity(cu * cu);
13943 for rr in 0..cu {
13944 let start = (cy + rr) * cside + cx;
13945 unit.extend_from_slice(&grid[start..start + cu]);
13946 }
13947 neighbours.record_mi_chroma(
13948 unit_mi,
13949 unit_luma_w,
13950 unit_luma_h,
13951 plane_idx,
13952 &unit,
13953 );
13954 }
13955 }
13956 }
13957 }
13958 }
13959 }
13960 }
13961 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
13962 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
13963 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
13964 neighbours.fill_lf_grid_rect(
13965 (mi_r, mi_c),
13966 bw / MI,
13967 bh / MI,
13968 bw.min(64) as u8,
13969 bh.min(64) as u8,
13970 0,
13971 fctx,
13972 );
13973 record_intrabc_mi_rect(
13974 mi_r,
13975 mi_c,
13976 bw / MI,
13977 bh / MI,
13978 Some((dv_row, dv_col)),
13979 neighbours,
13980 fctx,
13981 );
13982 Ok(())
13983}
13984
13985/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
13986/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
13987/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
13988/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
13989/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
13990/// has no rectangular-transform coefficient reader, and a chroma plane here
13991/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
13992/// with no depth-based square-tiling escape the way luma's own resolved
13993/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
13994/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
13995#[allow(clippy::too_many_arguments)]
13996fn decode_block_rect(
13997 dec: &mut SymbolDecoder,
13998 cdfs: &mut Cdfs,
13999 neighbours: &mut Neighbours,
14000 at: (usize, usize),
14001 bw: usize,
14002 bh: usize,
14003 y: &mut PlaneBuf<'static>,
14004 u: &mut PlaneBuf<'static>,
14005 v: &mut PlaneBuf<'static>,
14006 enable_filter_intra: bool,
14007 allow_screen_content_tools: bool,
14008 base_q_idx: u8,
14009 tx_select: bool,
14010 reduced_tx_set: bool,
14011 fctx: &crate::decode::FrameCtx,
14012) -> Result<()> {
14013 let (r, c) = at;
14014 let (px, py) = (c * SUB, r * SUB);
14015 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14016 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14017 let palette_uv_cache = neighbours.palette_uv_cache(at);
14018 let (
14019 skip,
14020 mode,
14021 angle_delta_y,
14022 uv_mode,
14023 angle_delta_uv,
14024 alpha,
14025 filter_intra,
14026 palette_y,
14027 palette_uv,
14028 intrabc,
14029 ) = read_intra_mode_rect(
14030 dec,
14031 cdfs,
14032 nb_above_mode,
14033 nb_left_mode,
14034 true,
14035 true,
14036 bw,
14037 bh,
14038 enable_filter_intra,
14039 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
14040 allow_screen_content_tools,
14041 Some((palette_ctx, &palette_cache)),
14042 &palette_uv_cache,
14043 r * (SUB / MI),
14044 c * (SUB / MI),
14045 fctx,
14046 )?;
14047
14048 if let Some((dv_row, dv_col)) = intrabc {
14049 return decode_intrabc_rect(
14050 dec,
14051 cdfs,
14052 neighbours,
14053 (r * (SUB / MI), c * (SUB / MI)),
14054 (bw, bh),
14055 skip,
14056 (dv_row, dv_col),
14057 y,
14058 u,
14059 v,
14060 base_q_idx,
14061 fctx,
14062 );
14063 }
14064 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14065 if smooth_neighbor {
14066 hit!(SMOOTH_LUMA_HITS);
14067 }
14068 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
14069 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
14070 // `uv_mode`, not the luma one.
14071 let smooth_neighbor_uv =
14072 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
14073 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
14074 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
14075 // rectangle just as happily), so a `use_filter_intra` strip at this level
14076 // predicts instead of refusing. The below-16x16 leaf arm
14077 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
14078 if filter_intra.is_some() {
14079 hit!(FILTER_INTRA_RECT_HITS);
14080 }
14081 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14082 DC_PRED
14083 } else {
14084 uv_mode
14085 };
14086 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14087 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
14088 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
14089 // one did not, so with `--enable-tx-size-search=0` -- which several gate
14090 // recipes use -- the decoder consumed a symbol the encoder never wrote and
14091 // desynced the tile from that point on. That is why both strips of the
14092 // pinned HORZ quadrant were wrong from their very first pixel, and why our
14093 // range after the read equalled the oracle's range for the whole block.
14094 // lane-av1mixloss: the lossless-segment early return
14095 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment
14096 // rect block codes no depth symbol here either (class sweep of the sub8
14097 // leaf's fix).
14098 let depth = if tx_select && !lossless(fctx) {
14099 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
14100 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
14101 // intra-only frame publishes them from every block too
14102 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
14103 // 1920x792 128-superblock stream,
14104 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
14105 // `tx_size_cat2` row 1 where libaom reads row 2.
14106 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
14107 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
14108 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14109 eprintln!(
14110 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
14111 dec.debug_state().0
14112 );
14113 }
14114 d
14115 } else {
14116 0
14117 };
14118 // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame
14119 // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
14120 publish_txfm_bands_if_in_inter(
14121 neighbours,
14122 (mi_r, mi_c),
14123 depth_to_tx_wh(bw, bh, depth, fctx),
14124 (bw, bh),
14125 fctx,
14126 );
14127 if depth != 0 || lossless(fctx) {
14128 hit!(TX_DEPTH_HITS);
14129 // lane-rectsplit r1: a split transform is predicted and reconstructed
14130 // per transform unit, each unit taking its edges from the previous
14131 // unit's reconstruction inside this same strip (spec 5.11.36) --
14132 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
14133 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
14134 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
14135 eprintln!(
14136 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
14137 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
14138 angle_y={angle_delta_y}"
14139 );
14140 }
14141 let modes = RectStripModes {
14142 skip,
14143 mode,
14144 angle_delta_y,
14145 uv_predict_mode,
14146 angle_delta_uv,
14147 alpha,
14148 filter_intra,
14149 smooth_neighbor,
14150 smooth_neighbor_uv,
14151 palette_y: palette_y
14152 .as_ref()
14153 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
14154 palette_uv: palette_uv.as_ref().map(|p| {
14155 (
14156 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
14157 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
14158 )
14159 }),
14160 };
14161 if palette_y.is_some() || palette_uv.is_some() {
14162 hit!(PALETTE_SPLIT_TX_HITS);
14163 }
14164 decode_rect_split(
14165 dec,
14166 cdfs,
14167 neighbours,
14168 (mi_r, mi_c),
14169 bw,
14170 bh,
14171 tx_w,
14172 tx_h,
14173 &modes,
14174 y,
14175 u,
14176 v,
14177 base_q_idx,
14178 reduced_tx_set,
14179 fctx,
14180 )?;
14181 // This early return skips this fn's own tail, so the palette
14182 // neighbour state has to be stamped HERE too: without it a split-tx
14183 // strip left the above/left palette arrays holding a DEAD block's
14184 // colours, and the next block's colour cache
14185 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
14186 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
14187 // and only those pixels were wrong (lane-palette2 r10).
14188 let (py_size, py_colors) = palette_y
14189 .as_ref()
14190 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14191 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
14192 let (puv_size, puv_colors) = palette_uv
14193 .as_ref()
14194 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14195 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
14196 hit!(RECT_PARTITION_HITS);
14197 return Ok(());
14198 }
14199 let (tx_w, tx_h) = (bw, bh);
14200 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14201 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14202 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
14203 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14204 let (rng, _) = dec.debug_state();
14205 eprintln!(
14206 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
14207 skip={} tx={depth} rng={rng}",
14208 skip as i32
14209 );
14210 }
14211 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
14212 // block's prediction is the reconstructed colour-index map, set fresh
14213 // right before each `reconstruct_rect` call below (lane-palette2 r4).
14214 if let Some(ref pyv) = palette_y {
14215 let buf: Vec<u16> = pyv
14216 .map
14217 .iter()
14218 .map(|&idx| pyv.colors[idx as usize])
14219 .collect();
14220 set_palette_pred(buf, fctx);
14221 }
14222 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
14223 (
14224 puv.map
14225 .iter()
14226 .map(|&idx| puv.u_colors[idx as usize])
14227 .collect(),
14228 puv.map
14229 .iter()
14230 .map(|&idx| puv.v_colors[idx as usize])
14231 .collect(),
14232 )
14233 });
14234 if skip {
14235 push_intra_rect(
14236 0,
14237 px,
14238 py,
14239 bw,
14240 bh,
14241 mode,
14242 angle_delta_y,
14243 reach,
14244 &ZERO_RESIDUAL[..bw * bh],
14245 None,
14246 filter_intra,
14247 smooth_neighbor,
14248 fctx,
14249 );
14250 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
14251 if let Some((ub, _)) = &palette_uv_bufs {
14252 set_palette_pred(ub.clone(), fctx);
14253 }
14254 push_intra_rect(
14255 1,
14256 cpx,
14257 cpy,
14258 chroma_w,
14259 chroma_h,
14260 uv_predict_mode,
14261 angle_delta_uv,
14262 reach,
14263 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14264 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14265 None,
14266 smooth_neighbor_uv,
14267 fctx,
14268 );
14269 if let Some((_, vb)) = &palette_uv_bufs {
14270 set_palette_pred(vb.clone(), fctx);
14271 }
14272 push_intra_rect(
14273 2,
14274 cpx,
14275 cpy,
14276 chroma_w,
14277 chroma_h,
14278 uv_predict_mode,
14279 angle_delta_uv,
14280 reach,
14281 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14282 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14283 None,
14284 smooth_neighbor_uv,
14285 fctx,
14286 );
14287 neighbours.record_rect(
14288 at,
14289 bw,
14290 bh,
14291 mode,
14292 uv_predict_mode,
14293 &[
14294 &ZERO_RESIDUAL[..bw * bh],
14295 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14296 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14297 ],
14298 );
14299 } else {
14300 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
14301 // reduces both size pairs to their square-up CDF sets
14302 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
14303 // doc comments); the scan order and 2D context tables are the real
14304 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
14305 let luma_scan: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 };
14306 // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a
14307 // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16
14308 // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis).
14309 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
14310 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
14311 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
14312 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8),
14313 (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16),
14314 // lane-av1-422: a 4:2:2 strip halves only the width. A 32x16
14315 // luma strip's chroma is a 16x16 SQUARE (`TxbSet::Chroma16`, the
14316 // set any 16x16 chroma plane reads); a 16x32 strip's chroma is
14317 // 8x32, whose entropy set is the 16x16 one and whose DCT-only
14318 // default follows the >=32 rule below -- the same pairing the
14319 // (8,32) row of [`decode_rect_split`]'s chroma table proves. At
14320 // 4:2:0 and 4:4:4 a strip's chroma is itself rect, so neither row
14321 // is reachable there.
14322 (16, 16) => (TxbSet::Chroma16, default_scan(16)),
14323 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
14324 _ => {
14325 return Err(unsupported(
14326 "a rectangular chroma transform whose size has no coefficient table",
14327 ));
14328 }
14329 };
14330 let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 {
14331 TxType::DctDct
14332 } else {
14333 default_intra_tx_type(uv_predict_mode as u8)
14334 };
14335 // lane-rectwire r3: real coefficients desync a pixel-exact gate
14336 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
14337 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
14338 // pixel (not a subtle context-table off-by-one), while the sibling
14339 // non-rect quadrants of the same frame match. Range-ladder bisection
14340 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
14341 // but the intra key-frame path has no traced symbol between the
14342 // partition read and the first coefficient block (mode/skip/tx_depth
14343 // reads are all untraced in libaom's decodeframe.c intra path, unlike
14344 // the inter EC_TRACE_MODE this round added), so a same-length range
14345 // comparison wasn't reachable within budget -- see
14346 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
14347 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
14348 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
14349 // libaom and match). lane-rectwire r4: range-ladder against the
14350 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
14351 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
14352 // both confirmed in sync -- rng=58692 on both sides right after
14353 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
14354 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
14355 // immediately after: ours moves rng 58692 -> 43570, which cannot be
14356 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
14357 // its own tx_size read) unless oracle's tx symbol is a near-certainty
14358 // CDF that barely narrows the range -- i.e. this decoder's
14359 // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for
14360 // a 32x16/16x32 strip is the first diverging symbol, not the
14361 // coefficient-context math r3 already cleared. Not confirmed byte-
14362 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
14363 // `read_tx_size`'s own rng, not attempted this round -- budget), so
14364 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
14365 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
14366 // it unconditionally where both square paths gate on `tx_select`. With
14367 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
14368 // decoder consumed one that was never there.
14369 {
14370 // lane-av1422warp r20: this 32x16/16x32 strip reader is the SIBLING of
14371 // `decode_leaf_rect`, and it was the one left ungated: at ss (1,0) the
14372 // strip's chroma is a square (side/2, side) block whose above cells
14373 // spread over `side` LUMA mi columns, so the per-mi rect gather
14374 // double-counts every chroma column's whole-unit dc sign. Measured on
14375 // the pinned 4:2:2 rotzoom stream (a1.obu frame 0): the chroma-U 4x4
14376 // transform of the 32x16 strip at mi(68,16) reads its DC sign from
14377 // `dc_sign_ctx` 1 where libaom reads row 0 -- the first read of
14378 // 45260 whose pre-state, bit position and symbol all match and only
14379 // the CDF row differs, and the first divergence in the EC_SYMR
14380 // sequence (all 45259 reads before it pair exactly). Luma keeps the
14381 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
14382 let mut around = neighbours.around_rect(at, bw, bh);
14383 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
14384 let c2 =
14385 neighbours.around_mi_422_chroma((at.0 * (SUB / MI), at.1 * (SUB / MI)), bw, bh);
14386 around[1] = c2[1];
14387 around[2] = c2[2];
14388 }
14389 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
14390 let (luma_levels, luma_tx_type) = read_coeffs_rect(
14391 dec,
14392 &mut luma_coding,
14393 luma_scan,
14394 bw,
14395 bh,
14396 0,
14397 dc_sign_ctx(around[0].2),
14398 TxType::DctDct,
14399 )?;
14400 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14401 let (rng, _) = dec.debug_state();
14402 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
14403 }
14404 let luma_residual = dequant_and_inverse_typed_wh(
14405 &luma_levels,
14406 bw,
14407 bh,
14408 crate::decode::bit_depth(fctx),
14409 block_q_idx(fctx),
14410 plane_q_delta(0, fctx).0,
14411 plane_q_delta(0, fctx).1,
14412 luma_tx_type,
14413 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
14414 );
14415 push_intra_rect(
14416 0,
14417 px,
14418 py,
14419 bw,
14420 bh,
14421 mode,
14422 angle_delta_y,
14423 reach,
14424 &luma_residual,
14425 None,
14426 filter_intra,
14427 smooth_neighbor,
14428 fctx,
14429 );
14430 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
14431 if let Some((ub, _)) = &palette_uv_bufs {
14432 set_palette_pred(ub.clone(), fctx);
14433 }
14434 let u_default_tx = chroma_default_tx;
14435 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
14436 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
14437 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
14438 dec,
14439 &mut u_coding,
14440 chroma_scan,
14441 chroma_w,
14442 chroma_h,
14443 u_skip_ctx,
14444 dc_sign_ctx(around[1].2),
14445 u_default_tx,
14446 fctx,
14447 )?;
14448 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14449 let (rng, _) = dec.debug_state();
14450 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
14451 }
14452 let u_residual = dequant_and_inverse_typed_wh(
14453 &u_levels,
14454 chroma_w,
14455 chroma_h,
14456 crate::decode::bit_depth(fctx),
14457 block_q_idx(fctx),
14458 plane_q_delta(1, fctx).0,
14459 plane_q_delta(1, fctx).1,
14460 u_tx_type,
14461 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
14462 );
14463 push_intra_rect(
14464 1,
14465 cpx,
14466 cpy,
14467 chroma_w,
14468 chroma_h,
14469 uv_predict_mode,
14470 angle_delta_uv,
14471 reach,
14472 &u_residual,
14473 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14474 None,
14475 smooth_neighbor_uv,
14476 fctx,
14477 );
14478 if let Some((_, vb)) = &palette_uv_bufs {
14479 set_palette_pred(vb.clone(), fctx);
14480 }
14481 let v_default_tx = chroma_default_tx;
14482 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
14483 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
14484 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
14485 dec,
14486 &mut v_coding,
14487 chroma_scan,
14488 chroma_w,
14489 chroma_h,
14490 v_skip_ctx,
14491 dc_sign_ctx(around[2].2),
14492 v_default_tx,
14493 fctx,
14494 )?;
14495 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14496 let (rng, _) = dec.debug_state();
14497 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
14498 }
14499 let v_residual = dequant_and_inverse_typed_wh(
14500 &v_levels,
14501 chroma_w,
14502 chroma_h,
14503 crate::decode::bit_depth(fctx),
14504 block_q_idx(fctx),
14505 plane_q_delta(2, fctx).0,
14506 plane_q_delta(2, fctx).1,
14507 v_tx_type,
14508 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
14509 );
14510 push_intra_rect(
14511 2,
14512 cpx,
14513 cpy,
14514 chroma_w,
14515 chroma_h,
14516 uv_predict_mode,
14517 angle_delta_uv,
14518 reach,
14519 &v_residual,
14520 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14521 None,
14522 smooth_neighbor_uv,
14523 fctx,
14524 );
14525 neighbours.record_rect(
14526 at,
14527 bw,
14528 bh,
14529 mode,
14530 uv_predict_mode,
14531 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
14532 );
14533 hit!(RECT_COEFF_HITS);
14534 }
14535 }
14536 let (py_size, py_colors) = palette_y
14537 .as_ref()
14538 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14539 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
14540 let (puv_size, puv_colors) = palette_uv
14541 .as_ref()
14542 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14543 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
14544 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14545 neighbours.fill_lf_grid_rect(
14546 (mi_r, mi_c),
14547 bw / MI,
14548 bh / MI,
14549 tx_w as u8,
14550 tx_h as u8,
14551 0,
14552 fctx,
14553 );
14554 hit!(RECT_PARTITION_HITS);
14555 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14556 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
14557 }
14558 Ok(())
14559}
14560
14561/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
14562/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
14563/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
14564/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
14565/// the second strip of a HORZ/VERT split sits offset by half the 16x16
14566/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
14567/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
14568/// previous strip is directly above (same column, `mi_h` rows up) or
14569/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
14570/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
14571/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
14572/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
14573/// this strip's real position, never the coarse `record_rect` (which the
14574/// caller uses once, after both strips, exactly like the `VERT_B` arm next
14575/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
14576/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
14577/// chroma half (`TxbSet::ChromaRect8x4`) at 4:2:0 -- an 8x8 *square* chroma
14578/// plane (`TxbSet::Chroma8` + the default scan) at 4:2:2 (lane-av1-422e:
14579/// half-width, unhalved height), the two size classes one level
14580/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
14581#[allow(clippy::too_many_arguments)]
14582fn decode_leaf_rect(
14583 dec: &mut SymbolDecoder,
14584 cdfs: &mut Cdfs,
14585 neighbours: &mut Neighbours,
14586 outer_at: (usize, usize),
14587 leaf_mi: (usize, usize),
14588 bw: usize,
14589 bh: usize,
14590 prev_leaf: Option<((usize, usize), usize)>,
14591 y: &mut PlaneBuf<'static>,
14592 u: &mut PlaneBuf<'static>,
14593 v: &mut PlaneBuf<'static>,
14594 enable_filter_intra: bool,
14595 allow_screen_content_tools: bool,
14596 base_q_idx: u8,
14597 tx_select: bool,
14598 reduced_tx_set: bool,
14599 fctx: &crate::decode::FrameCtx,
14600) -> Result<usize> {
14601 let _ = base_q_idx;
14602 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
14603 eprintln!(
14604 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
14605 dec.debug_state().0
14606 );
14607 }
14608 let (r, c) = outer_at;
14609 let mut above_mode = neighbours.above_mode[c];
14610 let mut left_mode = neighbours.left_mode[r];
14611 let (mi_w, mi_h) = (bw / MI, bh / MI);
14612 if let Some(((pr, pc), pmode)) = prev_leaf {
14613 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
14614 above_mode = pmode;
14615 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
14616 left_mode = pmode;
14617 }
14618 }
14619 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
14620 // cannot hold the modes a split (or a pair of strips) leaves behind, so
14621 // when the map holds the block at exactly this strip's above/left mi it
14622 // is the neighbour libaom's `above_mi`/`left_mi` reads.
14623 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
14624 // availability-correct -- four 16x8 strips share one coarse 16x16
14625 // `left_mode` cell too, so the fallback must not stand in for an absent
14626 // tile-edge neighbour.
14627 let (above_mode, left_mode) =
14628 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
14629 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
14630 if smooth_neighbor {
14631 hit!(SMOOTH_LUMA_HITS);
14632 }
14633 // The palette-Y mode CDF row is picked by the neighbours' palette use
14634 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
14635 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
14636 // a palette narrows the wrong interval and desyncs the tile even when the
14637 // decoded bit is the same. The cell is the 16px-SUB cell containing the
14638 // leaf (the palette neighbour arrays have no finer granularity).
14639 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
14640 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
14641 // exclusion and the neighbour palette lookup itself are mi-granular
14642 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
14643 let pal_at = leaf_mi;
14644 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
14645 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
14646 let (
14647 skip,
14648 mode,
14649 angle_delta_y,
14650 uv_mode,
14651 angle_delta_uv,
14652 alpha,
14653 filter_intra,
14654 palette_y,
14655 palette_uv,
14656 intrabc,
14657 ) = read_intra_mode_rect(
14658 dec,
14659 cdfs,
14660 above_mode,
14661 left_mode,
14662 true,
14663 true,
14664 bw,
14665 bh,
14666 enable_filter_intra,
14667 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
14668 allow_screen_content_tools,
14669 Some((palette_ctx, &palette_cache)),
14670 &palette_uv_cache,
14671 leaf_mi.0,
14672 leaf_mi.1,
14673 fctx,
14674 )?;
14675
14676 if let Some((dv_row, dv_col)) = intrabc {
14677 decode_intrabc_rect(
14678 dec,
14679 cdfs,
14680 neighbours,
14681 leaf_mi,
14682 (bw, bh),
14683 skip,
14684 (dv_row, dv_col),
14685 y,
14686 u,
14687 v,
14688 base_q_idx,
14689 fctx,
14690 )?;
14691 return Ok(DC_PRED);
14692 }
14693 // lane-kf900 r4: palette prediction on this shape, the same colour-index
14694 // map -> base colours buffer [`decode_block_rect`] hands each
14695 // `reconstruct_rect` through [`set_palette_pred`].
14696 if palette_y.is_some() || palette_uv.is_some() {
14697 hit!(RECT4_PALETTE_HITS);
14698 }
14699 let palette_y_buf: Option<Vec<u16>> = palette_y
14700 .as_ref()
14701 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
14702 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
14703 (
14704 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
14705 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
14706 )
14707 });
14708 let (pal_y_size, pal_y_colors) = palette_y
14709 .as_ref()
14710 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14711 let (pal_uv_size, pal_uv_colors) = palette_uv
14712 .as_ref()
14713 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14714 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
14715 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
14716 }
14717 if filter_intra.is_some() {
14718 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
14719 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
14720 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
14721 // below already makes; this refusal was square-only prose.
14722 hit!(FILTER_INTRA_RECT_HITS);
14723 hit!(FILTER_INTRA_RECT_SUB16_HITS);
14724 }
14725 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14726 DC_PRED
14727 } else {
14728 uv_mode
14729 };
14730 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
14731 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
14732 // a constant `false`.
14733 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
14734 let depth = if tx_select && !lossless(fctx) {
14735 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
14736 // every other rect reader now does -- a no-op on a key frame.
14737 // lane-av1mixloss: libaom `read_tx_size`'s first line
14738 // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return
14739 // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment
14740 // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4).
14741 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
14742 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
14743 // read was the leaf's own txb_skip.
14744 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
14745 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
14746 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
14747 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
14748 // count (3), different CDF row: a wrong-table read of a real symbol,
14749 // the class that cost lane-rectsplit r1 its 64x32 depth.
14750 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
14751 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
14752 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
14753 // function also decodes) sit at depth 2, so they read
14754 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
14755 // while `tx_size_cat2` belongs to the 32-level shapes
14756 // ([`decode_block_rect`]). Both tables carry three symbols, so the
14757 // wrong one decodes a plausible depth from the wrong probabilities:
14758 // the range diverges silently at the first such leaf and every later
14759 // symbol in the tile is read from the wrong place (class
14760 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
14761 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
14762 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14763 eprintln!(
14764 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
14765 leaf_mi.0,
14766 leaf_mi.1,
14767 dec.debug_state().0
14768 );
14769 }
14770 d
14771 } else {
14772 0
14773 };
14774 // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads
14775 // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
14776 publish_txfm_bands_if_in_inter(
14777 neighbours,
14778 leaf_mi,
14779 depth_to_tx_wh(bw, bh, depth, fctx),
14780 (bw, bh),
14781 fctx,
14782 );
14783 if depth != 0 || lossless(fctx) {
14784 // The same per-transform-unit walk the bigger strips take
14785 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
14786 // depth 2), addressed at this leaf's own mi position.
14787 hit!(TX_DEPTH_HITS);
14788 hit!(SUB16_SPLIT_HITS);
14789 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
14790 let modes = RectStripModes {
14791 skip,
14792 mode,
14793 angle_delta_y,
14794 uv_predict_mode,
14795 angle_delta_uv,
14796 alpha,
14797 filter_intra,
14798 smooth_neighbor,
14799 // lane-rectsplitx r3: the split arm hard-coded `false` here while
14800 // the unsplit arm below passes the real neighbour answer -- chroma
14801 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
14802 smooth_neighbor_uv,
14803 palette_y: palette_y_buf.clone(),
14804 palette_uv: palette_uv_bufs.clone(),
14805 };
14806 if palette_y.is_some() || palette_uv.is_some() {
14807 hit!(PALETTE_SPLIT_TX_HITS);
14808 }
14809 decode_rect_split(
14810 dec,
14811 cdfs,
14812 neighbours,
14813 leaf_mi,
14814 bw,
14815 bh,
14816 tx_w,
14817 tx_h,
14818 &modes,
14819 y,
14820 u,
14821 v,
14822 base_q_idx,
14823 reduced_tx_set,
14824 fctx,
14825 )?;
14826 record_strip_palette(
14827 neighbours,
14828 pal_at,
14829 bw,
14830 bh,
14831 pal_y_size,
14832 pal_y_colors,
14833 pal_uv_size,
14834 pal_uv_colors,
14835 );
14836 return Ok(mode);
14837 }
14838 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
14839 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
14840 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14841 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14842 let (luma_levels, u_levels, v_levels);
14843 if skip {
14844 luma_levels = Grid::Zero(bw * bh);
14845 u_levels = Grid::Zero(chroma_w * chroma_h);
14846 v_levels = Grid::Zero(chroma_w * chroma_h);
14847 if let Some(b) = &palette_y_buf {
14848 set_palette_pred(b.clone(), fctx);
14849 }
14850 push_intra_rect(
14851 0,
14852 px,
14853 py,
14854 bw,
14855 bh,
14856 mode,
14857 angle_delta_y,
14858 reach,
14859 &luma_levels,
14860 None,
14861 filter_intra,
14862 smooth_neighbor,
14863 fctx,
14864 );
14865 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
14866 if let Some((ub, _)) = &palette_uv_bufs {
14867 set_palette_pred(ub.clone(), fctx);
14868 }
14869 push_intra_rect(
14870 1,
14871 cpx,
14872 cpy,
14873 chroma_w,
14874 chroma_h,
14875 uv_predict_mode,
14876 angle_delta_uv,
14877 reach,
14878 &u_levels,
14879 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14880 None,
14881 smooth_neighbor_uv,
14882 fctx,
14883 );
14884 if let Some((_, vb)) = &palette_uv_bufs {
14885 set_palette_pred(vb.clone(), fctx);
14886 }
14887 push_intra_rect(
14888 2,
14889 cpx,
14890 cpy,
14891 chroma_w,
14892 chroma_h,
14893 uv_predict_mode,
14894 angle_delta_uv,
14895 reach,
14896 &v_levels,
14897 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14898 None,
14899 smooth_neighbor_uv,
14900 fctx,
14901 );
14902 } else {
14903 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
14904 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
14905 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
14906 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
14907 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
14908 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
14909 // lane-av1-422e: a 4:2:2 strip halves only the width, so the chroma
14910 // half of a 16x8/8x16 luma leaf is an 8x8 SQUARE (`TxbSet::Chroma8` +
14911 // the default scan -- the pairing any 8x8 chroma plane reads). 4:2:0
14912 // halves both axes (8x4/4x8 rect, `TxbSet::ChromaRect8x4`); 4:4:4
14913 // leaves the full 16x8/8x16 rect (`TxbSet::ChromaRect16x8`).
14914 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
14915 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 {
14916 if bw == 16 {
14917 (&SCAN_16X8, &SCAN_16X8)
14918 } else {
14919 (&SCAN_8X16, &SCAN_8X16)
14920 }
14921 } else if chroma_422 {
14922 if bw == 16 {
14923 (&SCAN_16X8, default_scan(8))
14924 } else {
14925 (&SCAN_8X16, default_scan(8))
14926 }
14927 } else if bw == 16 {
14928 (&SCAN_16X8, &SCAN_8X4)
14929 } else {
14930 (&SCAN_8X16, &SCAN_4X8)
14931 };
14932 let chroma_rect_set = if ss_x(fctx) == 0 {
14933 TxbSet::ChromaRect16x8
14934 } else if chroma_422 {
14935 TxbSet::Chroma8
14936 } else {
14937 TxbSet::ChromaRect8x4
14938 };
14939 // lane-av1422warp: at ss (1,0) this leaf's chroma is a SQUARE
14940 // (side/2, side) block, so `side` chroma 4-px cells above it spread
14941 // over `side` LUMA mi columns -- one chroma column per PAIR of luma
14942 // mi cells, and both carry the covering unit's whole-unit dc sign.
14943 // The per-mi rect gather therefore double-counts every chroma
14944 // column's sign. `around_mi_422_chroma`'s every-second above-cell
14945 // sampling is libaom's `txb_w_unit` sum, and every other 4:2:2 chroma
14946 // gather in this file already routes through it (see the gate at this
14947 // arm's siblings); this one did not, so a 4:2:2 rect leaf voted over
14948 // luma unit counts. Measured on the pinned 4:2:2 rotzoom stream
14949 // (a1.obu frame 0): the 16x8 leaf at mi(48,28) resolved its V plane's
14950 // dc sign from vote 0 (`dc_sign_cdf[0]`) where the oracle resolves a
14951 // negative vote (`dc_sign_cdf[1]`), which is the first bit-position
14952 // divergence in the frame (the bit offset is a clean constant through
14953 // coefficient unit 1418 and turns 6 bits at 1419). Luma keeps the
14954 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
14955 let mut around = neighbours.around_mi_rect(leaf_mi, bw, bh);
14956 if chroma_422 {
14957 let c = neighbours.around_mi_422_chroma(leaf_mi, bw, bh);
14958 around[1] = c[1];
14959 around[2] = c[2];
14960 }
14961 let luma_set = if reduced_tx_set {
14962 TxbSet::LumaRect16x8
14963 } else {
14964 TxbSet::LumaRect16x8Set1
14965 };
14966 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
14967 let (l_levels, luma_tx_type) = read_coeffs_rect(
14968 dec,
14969 &mut luma_coding,
14970 luma_scan,
14971 bw,
14972 bh,
14973 0,
14974 dc_sign_ctx(around[0].2),
14975 TxType::DctDct,
14976 )?;
14977 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
14978 let nz: Vec<(usize, i32)> = l_levels
14979 .iter()
14980 .copied()
14981 .enumerate()
14982 .filter(|(_, v)| *v != 0)
14983 .collect();
14984 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
14985 }
14986 luma_levels = l_levels;
14987 let luma_residual = dequant_and_inverse_typed_wh(
14988 &luma_levels,
14989 bw,
14990 bh,
14991 crate::decode::bit_depth(fctx),
14992 block_q_idx(fctx),
14993 plane_q_delta(0, fctx).0,
14994 plane_q_delta(0, fctx).1,
14995 luma_tx_type,
14996 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
14997 );
14998 if let Some(b) = &palette_y_buf {
14999 set_palette_pred(b.clone(), fctx);
15000 }
15001 push_intra_rect(
15002 0,
15003 px,
15004 py,
15005 bw,
15006 bh,
15007 mode,
15008 angle_delta_y,
15009 reach,
15010 &luma_residual,
15011 None,
15012 filter_intra,
15013 smooth_neighbor,
15014 fctx,
15015 );
15016 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15017 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
15018 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
15019 let mut u_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
15020 let (u_l, u_tx_type) = read_chroma_coeffs_rect(
15021 dec,
15022 &mut u_coding,
15023 chroma_scan,
15024 chroma_w,
15025 chroma_h,
15026 u_skip_ctx,
15027 dc_sign_ctx(around[1].2),
15028 u_default_tx,
15029 fctx,
15030 )?;
15031 u_levels = u_l;
15032 let u_residual = dequant_and_inverse_typed_wh(
15033 &u_levels,
15034 chroma_w,
15035 chroma_h,
15036 crate::decode::bit_depth(fctx),
15037 block_q_idx(fctx),
15038 plane_q_delta(1, fctx).0,
15039 plane_q_delta(1, fctx).1,
15040 u_tx_type,
15041 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
15042 );
15043 if let Some((ub, _)) = &palette_uv_bufs {
15044 set_palette_pred(ub.clone(), fctx);
15045 }
15046 push_intra_rect(
15047 1,
15048 cpx,
15049 cpy,
15050 chroma_w,
15051 chroma_h,
15052 uv_predict_mode,
15053 angle_delta_uv,
15054 reach,
15055 &u_residual,
15056 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15057 None,
15058 smooth_neighbor_uv,
15059 fctx,
15060 );
15061 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
15062 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
15063 let mut v_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
15064 let (v_l, v_tx_type) = read_chroma_coeffs_rect(
15065 dec,
15066 &mut v_coding,
15067 chroma_scan,
15068 chroma_w,
15069 chroma_h,
15070 v_skip_ctx,
15071 dc_sign_ctx(around[2].2),
15072 v_default_tx,
15073 fctx,
15074 )?;
15075 v_levels = v_l;
15076 let v_residual = dequant_and_inverse_typed_wh(
15077 &v_levels,
15078 chroma_w,
15079 chroma_h,
15080 crate::decode::bit_depth(fctx),
15081 block_q_idx(fctx),
15082 plane_q_delta(2, fctx).0,
15083 plane_q_delta(2, fctx).1,
15084 v_tx_type,
15085 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
15086 );
15087 if let Some((_, vb)) = &palette_uv_bufs {
15088 set_palette_pred(vb.clone(), fctx);
15089 }
15090 push_intra_rect(
15091 2,
15092 cpx,
15093 cpy,
15094 chroma_w,
15095 chroma_h,
15096 uv_predict_mode,
15097 angle_delta_uv,
15098 reach,
15099 &v_residual,
15100 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15101 None,
15102 smooth_neighbor_uv,
15103 fctx,
15104 );
15105 hit!(RECT_LEAF_COEFF_HITS);
15106 }
15107 neighbours.record_mi_rect(
15108 leaf_mi,
15109 bw,
15110 bh,
15111 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
15112 );
15113 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
15114 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
15115 // The leaf's own palette state (`0` clears, as this site always did
15116 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
15117 // AXIS only until the pair's closing leaf: the coarse cell holds one
15118 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
15119 // real left neighbour leaf 1 reads (lane-kf900 r4).
15120 record_strip_palette(
15121 neighbours,
15122 pal_at,
15123 bw,
15124 bh,
15125 pal_y_size,
15126 pal_y_colors,
15127 pal_uv_size,
15128 pal_uv_colors,
15129 );
15130 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
15131 // rows -- record the whole span, not one cell.
15132 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
15133 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
15134 Ok(mode)
15135}
15136
15137/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
15138/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
15139/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
15140/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
15141/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
15142/// strip's mode so this one's mode context sees its true above/left
15143/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
15144///
15145/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
15146/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
15147/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
15148/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
15149/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
15150/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
15151/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
15152///
15153/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
15154/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
15155/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
15156/// unexamined.
15157#[allow(clippy::too_many_arguments)]
15158fn decode_block_rect4(
15159 dec: &mut SymbolDecoder,
15160 cdfs: &mut Cdfs,
15161 neighbours: &mut Neighbours,
15162 strip_mi: (usize, usize),
15163 bw: usize,
15164 bh: usize,
15165 prev_strip: Option<((usize, usize), usize)>,
15166 y: &mut PlaneBuf<'static>,
15167 u: &mut PlaneBuf<'static>,
15168 v: &mut PlaneBuf<'static>,
15169 enable_filter_intra: bool,
15170 allow_screen_content_tools: bool,
15171 base_q_idx: u8,
15172 tx_select: bool,
15173 fctx: &crate::decode::FrameCtx,
15174) -> Result<(usize, usize)> {
15175 let _ = base_q_idx;
15176 let (mi_r, mi_c) = strip_mi;
15177 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
15178 let (mi_w, mi_h) = (bw / MI, bh / MI);
15179 let mut above_mode = neighbours.above_mode[c];
15180 let mut left_mode = neighbours.left_mode[r];
15181 if let Some(((pr, pc), pmode)) = prev_strip {
15182 if pc == mi_c && mi_r == pr + mi_h {
15183 above_mode = pmode;
15184 } else if pr == mi_r && mi_c == pc + mi_w {
15185 left_mode = pmode;
15186 }
15187 }
15188 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
15189 // availability-correct neighbour modes (see
15190 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
15191 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
15192 let (above_mode, left_mode) =
15193 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
15194 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
15195 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
15196 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
15197 // wrong interval, so a screen-content tile desynced at the first strip
15198 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
15199 let pal_at = (mi_r, mi_c);
15200 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
15201 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
15202 let (
15203 skip,
15204 mode,
15205 angle_delta_y,
15206 uv_mode,
15207 angle_delta_uv,
15208 alpha,
15209 filter_intra,
15210 palette_y,
15211 palette_uv,
15212 intrabc,
15213 ) = read_intra_mode_rect(
15214 dec,
15215 cdfs,
15216 above_mode,
15217 left_mode,
15218 true,
15219 true,
15220 bw,
15221 bh,
15222 enable_filter_intra,
15223 neighbours.skip_txfm_ctx(mi_r, mi_c),
15224 allow_screen_content_tools,
15225 Some((palette_ctx, &palette_cache)),
15226 &palette_uv_cache,
15227 mi_r,
15228 mi_c,
15229 fctx,
15230 )?;
15231 if let Some((dv_row, dv_col)) = intrabc {
15232 decode_intrabc_rect(
15233 dec,
15234 cdfs,
15235 neighbours,
15236 strip_mi,
15237 (bw, bh),
15238 skip,
15239 (dv_row, dv_col),
15240 y,
15241 u,
15242 v,
15243 base_q_idx,
15244 fctx,
15245 )?;
15246 return Ok((DC_PRED, DC_PRED));
15247 }
15248 // lane-kf900 r4: palette prediction on this shape, exactly as
15249 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
15250 // mapped through the base colours IS the prediction (it reads no edge
15251 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
15252 if palette_y.is_some() || palette_uv.is_some() {
15253 hit!(RECT4_PALETTE_HITS);
15254 }
15255 let palette_y_buf: Option<Vec<u16>> = palette_y
15256 .as_ref()
15257 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
15258 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
15259 (
15260 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15261 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15262 )
15263 });
15264 let (pal_y_size, pal_y_colors) = palette_y
15265 .as_ref()
15266 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15267 let (pal_uv_size, pal_uv_colors) = palette_uv
15268 .as_ref()
15269 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15270 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
15271 if smooth_neighbor {
15272 hit!(SMOOTH_LUMA_HITS);
15273 }
15274 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
15275 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
15276 // `r * (SUB / MI)` names a different mi column and the chroma
15277 // edge-filter strength was read from the wrong neighbour (measured:
15278 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
15279 // with luma bit-exact).
15280 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
15281 if filter_intra.is_some() {
15282 hit!(FILTER_INTRA_RECT_HITS);
15283 if bw > bh {
15284 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
15285 } else {
15286 hit!(FILTER_INTRA_RECT4_VERT_HITS);
15287 }
15288 }
15289 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15290 DC_PRED
15291 } else {
15292 uv_mode
15293 };
15294 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
15295 // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no
15296 // depth symbol here either (class sweep of the sub8 leaf's fix).
15297 let depth = if tx_select && !lossless(fctx) {
15298 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
15299 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
15300 // intra-only frame publishes them from every block too
15301 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
15302 // 1920x792 128-superblock stream,
15303 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
15304 // `tx_size_cat2` row 1 where libaom reads row 2.
15305 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
15306 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
15307 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15308 eprintln!(
15309 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
15310 dec.debug_state().0
15311 );
15312 }
15313 d
15314 } else {
15315 0
15316 };
15317 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
15318 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
15319 publish_txfm_bands_if_in_inter(
15320 neighbours,
15321 (mi_r, mi_c),
15322 depth_to_tx_wh(bw, bh, depth, fctx),
15323 (bw, bh),
15324 fctx,
15325 );
15326 if depth != 0 || lossless(fctx) {
15327 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
15328 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
15329 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
15330 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
15331 // both interleave in every real stream.
15332 hit!(TX_DEPTH_HITS);
15333 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
15334 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
15335 // predicted -- depth 1 fires FIRST in every attempt that splits at
15336 // all, so a depth-2-only lift could never be gated. The r1 mismatch
15337 // was never the rect unit: it was the neighbour MODE the strip reads
15338 // (see `modes_above_left_mi`).
15339 let which = if depth == 1 {
15340 &RECT4_SPLIT_DEPTH1_HITS
15341 } else {
15342 &RECT4_SPLIT_DEPTH2_HITS
15343 };
15344 hit_do! { which.with(|c| c.set(c.get() + 1)); }
15345 let modes = RectStripModes {
15346 skip,
15347 mode,
15348 angle_delta_y,
15349 uv_predict_mode,
15350 angle_delta_uv,
15351 alpha,
15352 filter_intra,
15353 smooth_neighbor,
15354 smooth_neighbor_uv,
15355 palette_y: palette_y_buf.clone(),
15356 palette_uv: palette_uv_bufs.clone(),
15357 };
15358 if palette_y.is_some() || palette_uv.is_some() {
15359 hit!(PALETTE_SPLIT_TX_HITS);
15360 }
15361 decode_rect_split(
15362 dec,
15363 cdfs,
15364 neighbours,
15365 (mi_r, mi_c),
15366 bw,
15367 bh,
15368 tx_w,
15369 tx_h,
15370 &modes,
15371 y,
15372 u,
15373 v,
15374 base_q_idx,
15375 false,
15376 fctx,
15377 )?;
15378 record_strip_palette(
15379 neighbours,
15380 pal_at,
15381 bw,
15382 bh,
15383 pal_y_size,
15384 pal_y_colors,
15385 pal_uv_size,
15386 pal_uv_colors,
15387 );
15388 if bw > bh {
15389 hit!(RECT4_32_HORZ_HITS);
15390 } else {
15391 hit!(RECT4_32_VERT_HITS);
15392 }
15393 if !skip {
15394 hit!(RECT4_COEFF_HITS);
15395 }
15396 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
15397 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
15398 // frame, so this 1:4 strip -- which is also the INTER frame's reader
15399 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
15400 // transform size in both TXFM_CONTEXT bands. Without it the next block
15401 // reads the row's stale value.
15402 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
15403 return Ok((mode, uv_predict_mode));
15404 }
15405 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
15406 // that is 8 px tall, so each strip stamps every cell it touches and the
15407 // LAST strip wins -- which is the right answer for the block below/right
15408 // of the 32x32, the only reader outside it. Written after this strip's
15409 // own context read above, never before.
15410 for cell in 0..bw.div_ceil(SUB) {
15411 neighbours.above_mode[c + cell] = mode;
15412 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
15413 neighbours.above_side[c + cell] = bw;
15414 }
15415 for cell in 0..bh.div_ceil(SUB) {
15416 neighbours.left_mode[r + cell] = mode;
15417 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
15418 neighbours.left_side[r + cell] = bh;
15419 }
15420 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
15421 // [`decode_leaf_rect`] does (the split arm above records these through
15422 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
15423 // `sub8_mode_row` holding the previous block, and the next 32x32's
15424 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
15425 // fixture).
15426 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
15427 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
15428 let (px, py) = (mi_c * MI, mi_r * MI);
15429 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
15430 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
15431 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15432 // lane-av1-444: the strip's chroma shape follows the subsampling.
15433 // 4:2:0 codes 16x4/4x16 (`TxbSet::Chroma8`); 4:4:4 codes the strip
15434 // itself, 32x8/8x32 (`get_txsize_entropy_ctx(TX_32X8)` =
15435 // `(wide_log2 + high_log2 + 1) >> 1` = the 16x16 set,
15436 // `TxbSet::Chroma16`). The caller set is closed -- this reader only
15437 // ever sees 32x8 / 8x32 luma and the sequence header admits ss 0/0
15438 // and 1/1 only -- so the table is exhaustive.
15439 let chroma422_rect32 = (chroma_w, chroma_h) == (4, 32) && ss_x(fctx) == 1 && ss_y(fctx) == 0;
15440 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
15441 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
15442 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
15443 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8[..]),
15444 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32[..]),
15445 // lane-av1-422: a 4:2:2 1:4 strip halves only the width, so the
15446 // landscape leaves (32x8, 16x4 luma) code their chroma as the RECT
15447 // (16,8)/(8,4) -- the same TxbSet/scan pair the (16,8)/(8,4) rows of
15448 // [`decode_rect_split`]'s chroma table use.
15449 // lane-av1-422p: the PORTRAIT leaf occurs too -- the pinned
15450 // fixture's frame 2 carries an 8x32 strip at ss(1,0), whose (4, 32)
15451 // chroma block `ss_size_lookup[BLOCK_8X32][1][0]` marks
15452 // BLOCK_INVALID (255, enums.h). BLOCK_INVALID does not mean
15453 // "uncodable": `av1_get_tx_size` reads `max_txsize_rect_lookup[255]`
15454 // OUT OF BOUNDS there, the byte at +255 in the pinned Release oracle
15455 // is 0x05 = TX_4X8 (the `decode_token_recon_block` copy at
15456 // 0xc0d030, objdump-measured), and `av1_get_adjusted_tx_size` has no
15457 // TX_4X8 case. libaom HAS the transform, so the shape CHUNKS (the
15458 // `chroma422_rect32` arm below) into FOUR stacked TX_4X8 units per
15459 // plane (`tx_size_high_unit[TX_4X8] = 2`: blk_row 0, 2, 4, 6)
15460 // instead of refusing; no coefficient-table row is added, because
15461 // BLOCK_4X32 is not a table libaom has. 4:2:0 and 4:4:4 never land
15462 // here (their 8x32 strips read (4, 16) and (8, 32)), so the row is
15463 // 4:2:2-only.
15464 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8[..]),
15465 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
15466 // lane-av1-422p: the units' own set/scan -- the whole-rect read
15467 // below never sees this row, the `chroma422_rect32` arm chunks
15468 // first. Anything else is still a named-lane gap.
15469 (4, 32) if ss_x(fctx) == 1 && ss_y(fctx) == 0 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
15470 _ => unreachable!("decode_block_rect4 chroma shape set is closed: {chroma_w}x{chroma_h}"),
15471 };
15472 let luma_scan: &[u16] = if bw > bh { &SCAN_32X8 } else { &SCAN_8X32 };
15473 let (luma_levels, u_levels, v_levels) = if skip {
15474 (
15475 vec![0i32; bw * bh],
15476 vec![0i32; chroma_w * chroma_h],
15477 vec![0i32; chroma_w * chroma_h],
15478 )
15479 } else if chroma422_rect32 {
15480 // lane-av1-422p: the (4, 32) plane as FOUR TX_4X8 units per plane,
15481 // plane-major (every U unit, then every V) -- the walk the pinned
15482 // oracle's `decode_token_recon_block` makes for the BLOCK_INVALID
15483 // plane block: TX_4X8, so stepr = `tx_size_high_unit[TX_4X8]` = 2
15484 // 4-px rows and stepc = 1, unit rows at chroma y 0, 8, 16, 24.
15485 // Luma is the same single TX_8X32 rect the general arm reads.
15486 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
15487 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
15488 let (luma_levels, luma_tx_type) = read_coeffs_rect(
15489 dec,
15490 &mut luma_coding,
15491 luma_scan,
15492 bw,
15493 bh,
15494 0,
15495 dc_sign_ctx(around[0].2),
15496 TxType::DctDct,
15497 )?;
15498 hit!(RECT4_COEFF_HITS);
15499 let luma_residual = dequant_and_inverse_typed_wh(
15500 &luma_levels,
15501 bw,
15502 bh,
15503 crate::decode::bit_depth(fctx),
15504 block_q_idx(fctx),
15505 plane_q_delta(0, fctx).0,
15506 plane_q_delta(0, fctx).1,
15507 luma_tx_type,
15508 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15509 );
15510 if let Some(b) = &palette_y_buf {
15511 set_palette_pred(b.clone(), fctx);
15512 }
15513 push_intra_rect(
15514 0,
15515 px,
15516 py,
15517 bw,
15518 bh,
15519 mode,
15520 angle_delta_y,
15521 reach,
15522 &luma_residual,
15523 None,
15524 filter_intra,
15525 smooth_neighbor,
15526 fctx,
15527 );
15528 // CfL parameters are computed ONCE per block over the strip's luma
15529 // (`are_parameters_computed`) and shared by all four units, as in
15530 // every other chunk arm.
15531 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15532 let mut unit_grids: Vec<((usize, usize), usize, Grid)> = Vec::new();
15533 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
15534 for unit_row in 0..4usize {
15535 let unit_mi = (mi_r + unit_row * 2, mi_c);
15536 let unit_reach = tu_reach_rect(
15537 bw,
15538 bh,
15539 0,
15540 unit_row * 8,
15541 8,
15542 8,
15543 reach,
15544 px,
15545 py,
15546 y.width,
15547 y.height,
15548 fctx,
15549 );
15550 if let Some((ub, vb)) = &palette_uv_bufs {
15551 let pbuf = if plane == 1 { ub } else { vb };
15552 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
15553 }
15554 // Each unit is read and recorded IMMEDIATELY: unit row 0's
15555 // `txb_skip_ctx` still sees the real above/left neighbour
15556 // states, a lower unit sees this block's own upper unit's
15557 // (libaom's per-unit `set_entropy_context`), and the lower
15558 // unit predicts off the upper one's reconstructed samples.
15559 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
15560 let unit_grid = read_rect_chroma_unit(
15561 dec,
15562 cdfs,
15563 TxbSet::ChromaRect8x4,
15564 &SCAN_4X8,
15565 4,
15566 8,
15567 plane,
15568 chroma_around[plane],
15569 uv_predict_mode,
15570 angle_delta_uv,
15571 unit_reach,
15572 buf,
15573 cpx,
15574 cpy + unit_row * 8,
15575 base_q_idx,
15576 // `get_txb_ctx_general`'s chroma branch
15577 // (txb_common.h): plane_bsize is BLOCK_INVALID (255)
15578 // here, `num_pels_log2_lookup[255]` = 255 (the +255
15579 // byte of the decodetxb copy at 0xc0de70,
15580 // objdump-measured) exceeds `BLOCK_4X8`'s 5, so the
15581 // ctx_offset is 10 -- the port's offset-7-first
15582 // `txb_skip_chroma_8` stores the offset-10 rows at
15583 // rows 3..6, hence +3.
15584 Some(3),
15585 alpha
15586 .zip(ac)
15587 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
15588 smooth_neighbor_uv,
15589 fctx,
15590 )?;
15591 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
15592 unit_grids.push((unit_mi, plane, unit_grid));
15593 }
15594 }
15595 // The whole-block stamp rewrites the chroma cells ONE state wide,
15596 // which would erase the unit boundary the next block reads (class
15597 // `override-slot-on-one-arm`), so it carries zero chroma grids and
15598 // the per-unit writes replay after it. Its luma cells and side
15599 // spans are this arm's own bookkeeping.
15600 let zero_chroma = vec![0i32; chroma_w * chroma_h];
15601 neighbours.record_mi_rect(
15602 (mi_r, mi_c),
15603 bw,
15604 bh,
15605 &[&luma_levels[..], &zero_chroma[..], &zero_chroma[..]],
15606 );
15607 for (unit_mi, plane, grid) in &unit_grids {
15608 neighbours.record_mi_chroma(*unit_mi, 8, 8, *plane, grid);
15609 }
15610 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
15611 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
15612 record_strip_palette(
15613 neighbours,
15614 pal_at,
15615 bw,
15616 bh,
15617 pal_y_size,
15618 pal_y_colors,
15619 pal_uv_size,
15620 pal_uv_colors,
15621 );
15622 if bw > bh {
15623 hit!(RECT4_32_HORZ_HITS);
15624 } else {
15625 hit!(RECT4_32_VERT_HITS);
15626 }
15627 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
15628 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
15629 // frame, so this 1:4 strip -- which is also the INTER frame's reader
15630 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
15631 // transform size in both TXFM_CONTEXT bands. Without it the next block
15632 // reads the row's stale value.
15633 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
15634 return Ok((mode, uv_predict_mode));
15635 } else {
15636 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
15637 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
15638 let (luma_levels, luma_tx_type) = read_coeffs_rect(
15639 dec,
15640 &mut luma_coding,
15641 luma_scan,
15642 bw,
15643 bh,
15644 0,
15645 dc_sign_ctx(around[0].2),
15646 TxType::DctDct,
15647 )?;
15648 let mut planes = Vec::with_capacity(2);
15649 for plane in 1..3 {
15650 // `av1_get_tx_type` (`blockd.h:1278`): the mode-indexed type
15651 // stands only while it is a member of this tx size's set; a
15652 // 32x8/8x32 chroma transform (4:4:4) squares up to TX_32X32,
15653 // whose intra set is `EXT_TX_SET_DCTONLY` -- every ADST clamps
15654 // to DCT_DCT there, and ADST is undefined at widths above 16.
15655 let default_tx = if chroma_w.max(chroma_h) >= 32 {
15656 TxType::DctDct
15657 } else {
15658 default_intra_tx_type(uv_predict_mode as u8)
15659 };
15660 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
15661 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
15662 let (levels, tx_type) = read_chroma_coeffs_rect(
15663 dec,
15664 &mut coding,
15665 chroma_scan,
15666 chroma_w,
15667 chroma_h,
15668 skip_ctx,
15669 dc_sign_ctx(around[plane].2),
15670 default_tx,
15671 fctx,
15672 )?;
15673 planes.push((levels, tx_type));
15674 }
15675 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
15676 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
15677 hit!(RECT4_COEFF_HITS);
15678 let luma_residual = dequant_and_inverse_typed_wh(
15679 &luma_levels,
15680 bw,
15681 bh,
15682 crate::decode::bit_depth(fctx),
15683 block_q_idx(fctx),
15684 plane_q_delta(0, fctx).0,
15685 plane_q_delta(0, fctx).1,
15686 luma_tx_type,
15687 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15688 );
15689 if let Some(b) = &palette_y_buf {
15690 set_palette_pred(b.clone(), fctx);
15691 }
15692 push_intra_rect(
15693 0,
15694 px,
15695 py,
15696 bw,
15697 bh,
15698 mode,
15699 angle_delta_y,
15700 reach,
15701 &luma_residual,
15702 None,
15703 filter_intra,
15704 smooth_neighbor,
15705 fctx,
15706 );
15707 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15708 for (plane, _buf, levels, tx_type) in [
15709 (1usize, &mut *u, &u_levels, u_tx_type),
15710 (2, &mut *v, &v_levels, v_tx_type),
15711 ] {
15712 let residual = dequant_and_inverse_typed_wh(
15713 levels,
15714 chroma_w,
15715 chroma_h,
15716 crate::decode::bit_depth(fctx),
15717 block_q_idx(fctx),
15718 plane_q_delta(plane, fctx).0,
15719 plane_q_delta(plane, fctx).1,
15720 tx_type,
15721 block_iqmatrix(fctx, plane, chroma_w, chroma_h, tx_type),
15722 );
15723 if let Some((ub, vb)) = &palette_uv_bufs {
15724 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
15725 }
15726 push_intra_rect(
15727 plane,
15728 cpx,
15729 cpy,
15730 chroma_w,
15731 chroma_h,
15732 uv_predict_mode,
15733 angle_delta_uv,
15734 reach,
15735 &residual,
15736 alpha
15737 .zip(ac)
15738 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
15739 None,
15740 smooth_neighbor_uv,
15741 fctx,
15742 );
15743 }
15744 neighbours.record_mi_rect(
15745 (mi_r, mi_c),
15746 bw,
15747 bh,
15748 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
15749 );
15750 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
15751 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
15752 record_strip_palette(
15753 neighbours,
15754 pal_at,
15755 bw,
15756 bh,
15757 pal_y_size,
15758 pal_y_colors,
15759 pal_uv_size,
15760 pal_uv_colors,
15761 );
15762 if bw > bh {
15763 hit!(RECT4_32_HORZ_HITS);
15764 } else {
15765 hit!(RECT4_32_VERT_HITS);
15766 }
15767 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
15768 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
15769 // frame, so this 1:4 strip -- which is also the INTER frame's reader
15770 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
15771 // transform size in both TXFM_CONTEXT bands. Without it the next block
15772 // reads the row's stale value.
15773 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
15774 return Ok((mode, uv_predict_mode));
15775 };
15776 if let Some(b) = &palette_y_buf {
15777 set_palette_pred(b.clone(), fctx);
15778 }
15779 push_intra_rect(
15780 0,
15781 px,
15782 py,
15783 bw,
15784 bh,
15785 mode,
15786 angle_delta_y,
15787 reach,
15788 &luma_levels,
15789 None,
15790 filter_intra,
15791 smooth_neighbor,
15792 fctx,
15793 );
15794 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15795 if chroma422_rect32 {
15796 // lane-av1-422p: `predict_and_reconstruct_intra_block` (decodeframe.c
15797 // ~1000) predicts EVERY unit regardless of `skip_txfm`, so the skip
15798 // arm walks the same four TX_4X8 units per plane -- the lower unit
15799 // predicts off the upper one's predicted samples. No coefficients
15800 // are coded; the tail's whole-block zero stamp below is the state
15801 // libaom's `set_entropy_context` leaves.
15802 for (plane, _buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
15803 for unit_row in 0..4usize {
15804 let unit_reach = tu_reach_rect(
15805 bw,
15806 bh,
15807 0,
15808 unit_row * 8,
15809 8,
15810 8,
15811 reach,
15812 px,
15813 py,
15814 y.width,
15815 y.height,
15816 fctx,
15817 );
15818 if let Some((ub, vb)) = &palette_uv_bufs {
15819 let pbuf = if plane == 1 { ub } else { vb };
15820 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
15821 }
15822 push_intra_rect(
15823 plane,
15824 cpx,
15825 cpy + unit_row * 8,
15826 4,
15827 8,
15828 uv_predict_mode,
15829 angle_delta_uv,
15830 unit_reach,
15831 &ZERO_RESIDUAL[..4 * 8],
15832 alpha
15833 .zip(ac)
15834 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
15835 None,
15836 smooth_neighbor_uv,
15837 fctx,
15838 );
15839 }
15840 }
15841 } else {
15842 if let Some((ub, _)) = &palette_uv_bufs {
15843 set_palette_pred(ub.clone(), fctx);
15844 }
15845 push_intra_rect(
15846 1,
15847 cpx,
15848 cpy,
15849 chroma_w,
15850 chroma_h,
15851 uv_predict_mode,
15852 angle_delta_uv,
15853 reach,
15854 &u_levels,
15855 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15856 None,
15857 smooth_neighbor_uv,
15858 fctx,
15859 );
15860 if let Some((_, vb)) = &palette_uv_bufs {
15861 set_palette_pred(vb.clone(), fctx);
15862 }
15863 push_intra_rect(
15864 2,
15865 cpx,
15866 cpy,
15867 chroma_w,
15868 chroma_h,
15869 uv_predict_mode,
15870 angle_delta_uv,
15871 reach,
15872 &v_levels,
15873 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15874 None,
15875 smooth_neighbor_uv,
15876 fctx,
15877 );
15878 }
15879 neighbours.record_mi_rect(
15880 (mi_r, mi_c),
15881 bw,
15882 bh,
15883 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
15884 );
15885 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
15886 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
15887 record_strip_palette(
15888 neighbours,
15889 pal_at,
15890 bw,
15891 bh,
15892 pal_y_size,
15893 pal_y_colors,
15894 pal_uv_size,
15895 pal_uv_colors,
15896 );
15897 if bw > bh {
15898 hit!(RECT4_32_HORZ_HITS);
15899 } else {
15900 hit!(RECT4_32_VERT_HITS);
15901 }
15902 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
15903 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
15904 // frame, so this 1:4 strip -- which is also the INTER frame's reader
15905 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
15906 // transform size in both TXFM_CONTEXT bands. Without it the next block
15907 // reads the row's stale value.
15908 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
15909 Ok((mode, uv_predict_mode))
15910}
15911
15912/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
15913/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
15914/// down, and the first shape here whose luma block is a single mi row (or
15915/// column).
15916///
15917/// What is new at this size is CHROMA. `is_chroma_reference`
15918/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
15919/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
15920/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
15921/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
15922/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
15923/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
15924/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
15925///
15926/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
15927/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
15928/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
15929/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
15930/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
15931/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
15932/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
15933/// shape's own CDF row.
15934///
15935/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
15936/// refuses by name rather than guess-decode.
15937#[allow(clippy::too_many_arguments)]
15938fn decode_rect4_16(
15939 dec: &mut SymbolDecoder,
15940 cdfs: &mut Cdfs,
15941 neighbours: &mut Neighbours,
15942 at16: (usize, usize),
15943 horz: bool,
15944 y: &mut PlaneBuf<'static>,
15945 u: &mut PlaneBuf<'static>,
15946 v: &mut PlaneBuf<'static>,
15947 enable_filter_intra: bool,
15948 allow_screen_content_tools: bool,
15949 base_q_idx: u8,
15950 tx_select: bool,
15951 reduced_tx_set: bool,
15952 fctx: &crate::decode::FrameCtx,
15953) -> Result<()> {
15954 let (r, c) = at16;
15955 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
15956 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
15957 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
15958 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
15959 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
15960 let mut prev: Option<((usize, usize), usize)> = None;
15961 let mut last_mode = DC_PRED;
15962 let mut last_uv_mode = DC_PRED;
15963 for i in 0..4usize {
15964 let lmi = if horz {
15965 (mi_row0 + i, mi_col0)
15966 } else {
15967 (mi_row0, mi_col0 + i)
15968 };
15969 // lane-av1-444: at 4:4:4 every strip is its own chroma reference
15970 // (no mi-parity test at ss 0/0, and the strip's own chroma block is
15971 // already >= 4x4) -- there is no 4:2:0 pair to close.
15972 // lane-av1-422o: the parity rule is per axis, straight out of
15973 // `is_chroma_reference`: a HORZ 16x4 strip (1 mi tall) keeps the
15974 // `ss_y == 0 -> every strip a reference` row rule, but a VERT 4x16
15975 // strip (1 mi wide) keeps the COLUMN clause `(mi_col & 1) || !(bw &
15976 // 1) || !ss_x`, which with bw == 1 mi reduces to `mi_col odd` for
15977 // every ss_x == 1 format -- the ODD strip closes the pair and reads
15978 // the chroma, exactly like 4:2:0. (VERT_4 partitions start on an
15979 // even mi_col, so `i % 2 == 1` is that clause.)
15980 let has_chroma = i % 2 == 1 || (horz && ss_y(fctx) == 0) || (!horz && ss_x(fctx) == 0);
15981 let (mode, uv, _tx) = decode_rect4_16_strip(
15982 dec,
15983 cdfs,
15984 neighbours,
15985 lmi,
15986 horz,
15987 has_chroma,
15988 prev,
15989 y,
15990 u,
15991 v,
15992 enable_filter_intra,
15993 allow_screen_content_tools,
15994 base_q_idx,
15995 tx_select,
15996 reduced_tx_set,
15997 fctx,
15998 )?;
15999 if let Some(m) = uv {
16000 last_uv_mode = m;
16001 }
16002 last_mode = mode;
16003 prev = Some((lmi, mode));
16004 }
16005 // The coarse 16-px cell holds one entry for the whole 16x16: the last
16006 // strip is what a block below (right) sees through it, the mi-exact maps
16007 // above answering everything finer.
16008 neighbours.above_mode[c] = last_mode;
16009 neighbours.left_mode[r] = last_mode;
16010 neighbours.above_uv_mode[c] = last_uv_mode;
16011 neighbours.left_uv_mode[r] = last_uv_mode;
16012 neighbours.above_side[c] = bw;
16013 neighbours.left_side[r] = bh;
16014 Ok(())
16015}
16016
16017/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
16018/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
16019/// block path can decode a SINGLE intra strip of a partition whose other
16020/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
16021/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
16022/// every strip publishes its own mi-exact mode). Returns
16023/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
16024/// Intrabc reconstruction for a rect strip that OWNS its chroma
16025/// (`bw/2 x bh/2` at the strip origin). 16x4/4x16 is not this shape -- that
16026/// pair goes through [`decode_rect4_16_intrabc`].
16027///
16028/// This is the same control flow as the unmerged lane's `decode_intrabc_rect`
16029/// (predict once, then one residual per transform unit on the INTER sets,
16030/// chroma inherits luma's `tx_type`), written against the helpers that exist
16031/// on this tree so a 2:1 strip no longer hides the 16x4 pair witness. The
16032/// merge with lane-av1-intrabc should keep one of the two bodies; the call
16033/// shape is the same.
16034#[allow(clippy::too_many_arguments)]
16035fn decode_intrabc_owned_rect(
16036 dec: &mut SymbolDecoder,
16037 cdfs: &mut Cdfs,
16038 neighbours: &mut Neighbours,
16039 (mi_r, mi_c): (usize, usize),
16040 (bw, bh): (usize, usize),
16041 skip: bool,
16042 (dv_row, dv_col): (i32, i32),
16043 y: &mut PlaneBuf<'static>,
16044 u: &mut PlaneBuf<'static>,
16045 v: &mut PlaneBuf<'static>,
16046 base_q_idx: u8,
16047 tx_select: bool,
16048 reduced_tx_set: bool,
16049 fctx: &crate::decode::FrameCtx,
16050) -> Result<()> {
16051 let _ = base_q_idx;
16052 let (px, py) = (mi_c * MI, mi_r * MI);
16053 let (cw, ch) = (bw / 2, bh / 2);
16054 let side = bw.max(bh);
16055 let cside = cw.max(ch);
16056 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
16057 let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get);
16058 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
16059 // `read_block_tx_size_rect` keys on this cell. A key frame forces it
16060 // false; the real bit is the caller's `tx_select`. Restored before return.
16061 fctx.tx_select_inter.with(|c| c.set(tx_select));
16062 let restore = ReducedTxRestore {
16063 fctx,
16064 saved_reduced,
16065 saved_tx,
16066 };
16067
16068 flush_recon(fctx, y, u, v);
16069 let pred_y = predict_intrabc_window(y, px, py, bw, bh, dv_col, dv_row, true, side, fctx);
16070 let pred_u = predict_intrabc_window(
16071 u,
16072 px / 2,
16073 py / 2,
16074 cw,
16075 ch,
16076 dv_col,
16077 dv_row,
16078 false,
16079 cside,
16080 fctx,
16081 );
16082 let pred_v = predict_intrabc_window(
16083 v,
16084 px / 2,
16085 py / 2,
16086 cw,
16087 ch,
16088 dv_col,
16089 dv_row,
16090 false,
16091 cside,
16092 fctx,
16093 );
16094
16095 let mi_cols = 2 * y.true_width.div_ceil(8);
16096 let mi_rows = 2 * y.true_height.div_ceil(8);
16097 let leaves = read_block_tx_size_rect(
16098 dec,
16099 cdfs,
16100 neighbours,
16101 (mi_r, mi_c),
16102 (bw, bh),
16103 (mi_cols, mi_rows),
16104 skip,
16105 fctx,
16106 )?;
16107 let mut luma_tx_type = TxType::DctDct;
16108 let luma_grid;
16109 let u_grid;
16110 let v_grid;
16111 if skip {
16112 // `reconstruct_mc_rect` indexes the residual at the square stride.
16113 // `bw * bh` underruns on a VERT strip (8x16: stride 16, 16 rows, index 136).
16114 push_mc_rect(
16115 0,
16116 px,
16117 py,
16118 side,
16119 bw,
16120 bh,
16121 Pred::Inline(&pred_y, side),
16122 &ZERO_RESIDUAL[..side * bh],
16123 fctx,
16124 );
16125 push_mc_rect(
16126 1,
16127 px / 2,
16128 py / 2,
16129 cside,
16130 cw,
16131 ch,
16132 Pred::Inline(&pred_u, cside),
16133 &ZERO_RESIDUAL[..cside * ch],
16134 fctx,
16135 );
16136 push_mc_rect(
16137 2,
16138 px / 2,
16139 py / 2,
16140 cside,
16141 cw,
16142 ch,
16143 Pred::Inline(&pred_v, cside),
16144 &ZERO_RESIDUAL[..cside * ch],
16145 fctx,
16146 );
16147 if let Some(ls) = leaves.as_ref() {
16148 // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`,
16149 // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its
16150 // whole entropy-band footprint. The non-skip arm below writes
16151 // those bands per transform unit and the tail's
16152 // `record_split_luma_rect_mi` writes chroma only, so without
16153 // this walk a skipped strip whose `leaves` resolved (every
16154 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
16155 // returns the 4x4 grid before it looks at `skip`) leaked the
16156 // PREVIOUS occupant's luma bands into the next block's
16157 // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped
16158 // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128
16159 // stream left a stale 7 in left[48] and mi(48,68)'s first
16160 // transform unit read `txb_skip_ctx` 3 where aomdec reads 1).
16161 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
16162 for &(row, col, tw, th) in ls {
16163 neighbours.record_mi_luma_rect(
16164 (mi_r + row, mi_c + col),
16165 tw,
16166 th,
16167 &ZERO_RESIDUAL[..tw * th],
16168 );
16169 }
16170 }
16171 luma_grid = Grid::Zero(side * side);
16172 u_grid = Grid::Zero(cside * cside);
16173 v_grid = Grid::Zero(cside * cside);
16174 } else if let Some(ls) = leaves.as_ref() {
16175 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
16176 let tu_mi = (mi_r + row, mi_c + col);
16177 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
16178 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
16179 let (g, tt) = if tw == th {
16180 read_inter_plane(
16181 dec,
16182 cdfs,
16183 inter_txbset_for(tw, reduced_tx_set),
16184 &default_scan(tw.min(32)),
16185 0,
16186 neighbours.around_mi(tu_mi, tw)[0],
16187 0,
16188 y,
16189 tu_px,
16190 tu_py,
16191 tw,
16192 base_q_idx,
16193 tu_pred,
16194 None,
16195 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
16196 fctx,
16197 )?
16198 } else {
16199 read_inter_plane_rect(
16200 dec,
16201 cdfs,
16202 rect_inter_luma_set(tw, th, fctx)?,
16203 (tw, th),
16204 side,
16205 0,
16206 neighbours.around_mi_rect(tu_mi, tw, th)[0],
16207 0,
16208 y,
16209 tu_px,
16210 tu_py,
16211 tu_pred,
16212 None,
16213 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
16214 fctx,
16215 )?
16216 };
16217 if idx == 0 {
16218 luma_tx_type = tt;
16219 }
16220 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
16221 if tw != th {
16222 neighbours.fill_lf_grid_leaf_luma(
16223 (tu_mi.0, tu_mi.1),
16224 tw / MI,
16225 th / MI,
16226 tw as u8,
16227 th as u8,
16228 );
16229 }
16230 }
16231 luma_grid = Grid::Zero(side * side);
16232 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16233 let (ug, _) = read_inter_plane_rect(
16234 dec,
16235 cdfs,
16236 rect_inter_chroma_set(cw, ch)?,
16237 (cw, ch),
16238 cside,
16239 1,
16240 around[1],
16241 0,
16242 u,
16243 px / 2,
16244 py / 2,
16245 Pred::Inline(&pred_u, cside),
16246 Some(luma_tx_type),
16247 None,
16248 fctx,
16249 )?;
16250 let (vg, _) = read_inter_plane_rect(
16251 dec,
16252 cdfs,
16253 rect_inter_chroma_set(cw, ch)?,
16254 (cw, ch),
16255 cside,
16256 2,
16257 around[2],
16258 0,
16259 v,
16260 px / 2,
16261 py / 2,
16262 Pred::Inline(&pred_v, cside),
16263 Some(luma_tx_type),
16264 None,
16265 fctx,
16266 )?;
16267 u_grid = ug;
16268 v_grid = vg;
16269 } else {
16270 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16271 let (g, tt) = read_inter_plane_rect(
16272 dec,
16273 cdfs,
16274 rect_inter_luma_set(bw, bh, fctx)?,
16275 (bw, bh),
16276 side,
16277 0,
16278 around[0],
16279 0,
16280 y,
16281 px,
16282 py,
16283 Pred::Inline(&pred_y, side),
16284 None,
16285 None,
16286 fctx,
16287 )?;
16288 luma_tx_type = tt;
16289 luma_grid = g;
16290 let (ug, _) = read_inter_plane_rect(
16291 dec,
16292 cdfs,
16293 rect_inter_chroma_set(cw, ch)?,
16294 (cw, ch),
16295 cside,
16296 1,
16297 around[1],
16298 0,
16299 u,
16300 px / 2,
16301 py / 2,
16302 Pred::Inline(&pred_u, cside),
16303 Some(luma_tx_type),
16304 None,
16305 fctx,
16306 )?;
16307 let (vg, _) = read_inter_plane_rect(
16308 dec,
16309 cdfs,
16310 rect_inter_chroma_set(cw, ch)?,
16311 (cw, ch),
16312 cside,
16313 2,
16314 around[2],
16315 0,
16316 v,
16317 px / 2,
16318 py / 2,
16319 Pred::Inline(&pred_v, cside),
16320 Some(luma_tx_type),
16321 None,
16322 fctx,
16323 )?;
16324 u_grid = ug;
16325 v_grid = vg;
16326 }
16327 drop(restore);
16328 if leaves.is_some() {
16329 neighbours.record_split_luma_rect_mi(
16330 (mi_r, mi_c),
16331 bw,
16332 bh,
16333 DC_PRED,
16334 DC_PRED,
16335 [&u_grid, &v_grid],
16336 );
16337 } else {
16338 neighbours.record_rect_mi(
16339 (mi_r, mi_c),
16340 bw,
16341 bh,
16342 DC_PRED,
16343 DC_PRED,
16344 &[&luma_grid, &u_grid, &v_grid],
16345 );
16346 }
16347 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
16348 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
16349 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
16350 neighbours.fill_lf_grid_rect(
16351 (mi_r, mi_c),
16352 bw / MI,
16353 bh / MI,
16354 bw.min(64) as u8,
16355 bh.min(64) as u8,
16356 0,
16357 fctx,
16358 );
16359 record_intrabc_mi_rect(
16360 mi_r,
16361 mi_c,
16362 bw / MI,
16363 bh / MI,
16364 Some((dv_row, dv_col)),
16365 neighbours,
16366 fctx,
16367 );
16368 let _ = luma_tx_type;
16369 Ok(())
16370}
16371
16372fn predict_intrabc_window(
16373 plane: &PlaneBuf<'_>,
16374 px: usize,
16375 py: usize,
16376 w: usize,
16377 h: usize,
16378 dv_col: i32,
16379 dv_row: i32,
16380 luma: bool,
16381 stride: usize,
16382 fctx: &crate::decode::FrameCtx,
16383) -> Vec<u16> {
16384 let mut dense = vec![0u16; w * h];
16385 mc::predict_with_filter(
16386 &plane.data,
16387 plane.width,
16388 plane.true_width,
16389 plane.true_height,
16390 mv_to_q4(px, dv_col, if luma { 0 } else { ss_x(fctx) }),
16391 mv_to_q4(py, dv_row, if luma { 0 } else { ss_y(fctx) }),
16392 w,
16393 h,
16394 mc::InterpFilterKind::Bilinear,
16395 &mut dense,
16396 fctx,
16397 );
16398 let mut laid = vec![0u16; stride * stride];
16399 for row in 0..h {
16400 laid[row * stride..][..w].copy_from_slice(&dense[row * w..][..w]);
16401 }
16402 laid
16403}
16404
16405struct ReducedTxRestore<'a> {
16406 fctx: &'a crate::decode::FrameCtx,
16407 saved_reduced: bool,
16408 saved_tx: bool,
16409}
16410impl Drop for ReducedTxRestore<'_> {
16411 fn drop(&mut self) {
16412 self.fctx
16413 .reduced_tx_set_inter
16414 .with(|c| c.set(self.saved_reduced));
16415 self.fctx.tx_select_inter.with(|c| c.set(self.saved_tx));
16416 }
16417}
16418
16419/// Reconstruction of one intrabc 16x4 / 4x16 strip (lane-av1-rect14).
16420///
16421/// A 1:4 strip is a PAIR. Both children share one chroma block, and only the
16422/// odd-mi member codes it (`is_chroma_reference`, `av1_common_int.h:1454`:
16423/// the bottom strip of a `HORZ_4`, the right strip of a `VERT_4`). The chroma
16424/// plane block is `ss_size_lookup[BLOCK_16X4][1][1] == BLOCK_8X4` (and
16425/// `BLOCK_4X8` for `VERT_4`) at the PAIR origin -- `setup_pred_plane`'s
16426/// `mi_row -= 1` when the block is one mi tall on an odd row. Luma is this
16427/// strip's own footprint, copied from this strip's DV. The block is
16428/// `is_inter_block`, so the residual uses the INTER sets and chroma inherits
16429/// the luma unit's coded `tx_type`.
16430///
16431/// Not [`decode_intrabc_rect`]: that helper (lane-av1-intrabc, not on this
16432/// tree) predicts chroma at `bw/2 x bh/2` of the strip itself. At 16x4 that
16433/// is an 8x2 half-pair at the odd strip -- wrong size, wrong origin, and it
16434/// would code chroma on every strip.
16435#[allow(clippy::too_many_arguments)]
16436fn decode_rect4_16_intrabc(
16437 dec: &mut SymbolDecoder,
16438 cdfs: &mut Cdfs,
16439 neighbours: &mut Neighbours,
16440 lmi: (usize, usize),
16441 horz: bool,
16442 has_chroma: bool,
16443 skip: bool,
16444 (dv_row, dv_col): (i32, i32),
16445 y: &mut PlaneBuf<'static>,
16446 u: &mut PlaneBuf<'static>,
16447 v: &mut PlaneBuf<'static>,
16448 base_q_idx: u8,
16449 tx_select: bool,
16450 reduced_tx_set: bool,
16451 fctx: &crate::decode::FrameCtx,
16452) -> Result<(usize, Option<usize>, (usize, usize))> {
16453 let _ = base_q_idx;
16454 hit!(RECT4_16_INTRABC_HITS);
16455 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
16456 let (mi_w, mi_h) = (bw / MI, bh / MI);
16457 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
16458 let side = bw.max(bh);
16459 // `rect_inter_luma_set` reads the frame cell. A key frame's tile decoder
16460 // publishes `reduced_tx_set` into it; set it here too so a caller that
16461 // passed the bit explicitly cannot disagree with the set we read.
16462 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
16463 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
16464 let restored = scopeguard_reduced(fctx, saved_reduced);
16465
16466 flush_recon(fctx, y, u, v);
16467 let mut pred_y_dense = vec![0u16; bw * bh];
16468 mc::predict_with_filter(
16469 &y.data,
16470 y.width,
16471 y.true_width,
16472 y.true_height,
16473 mv_to_q4(px, dv_col, 0),
16474 mv_to_q4(py, dv_row, 0),
16475 bw,
16476 bh,
16477 mc::InterpFilterKind::Bilinear,
16478 &mut pred_y_dense,
16479 fctx,
16480 );
16481 let mut pred_y = vec![0u16; side * side];
16482 for row in 0..bh {
16483 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
16484 }
16485
16486 let (pw, ph) = if horz { (16usize, 8usize) } else { (8, 16) };
16487 let (cw, ch) = (pw / 2, ph / 2);
16488 let pair_mi = if has_chroma {
16489 if horz {
16490 (lmi.0 - 1, lmi.1)
16491 } else {
16492 (lmi.0, lmi.1 - 1)
16493 }
16494 } else {
16495 lmi
16496 };
16497 let (cpx, cpy) = if has_chroma {
16498 (pair_mi.1 * MI / 2, pair_mi.0 * MI / 2)
16499 } else {
16500 (0, 0)
16501 };
16502 let cside = cw.max(ch);
16503 let (pred_u, pred_v) = if has_chroma {
16504 let mut ud = vec![0u16; cw * ch];
16505 mc::predict_with_filter(
16506 &u.data,
16507 u.width,
16508 u.true_width,
16509 u.true_height,
16510 mv_to_q4(cpx, dv_col, ss_x(fctx)),
16511 mv_to_q4(cpy, dv_row, ss_y(fctx)),
16512 cw,
16513 ch,
16514 mc::InterpFilterKind::Bilinear,
16515 &mut ud,
16516 fctx,
16517 );
16518 let mut us = vec![0u16; cside * cside];
16519 for row in 0..ch {
16520 us[row * cside..][..cw].copy_from_slice(&ud[row * cw..][..cw]);
16521 }
16522 let mut vd = vec![0u16; cw * ch];
16523 mc::predict_with_filter(
16524 &v.data,
16525 v.width,
16526 v.true_width,
16527 v.true_height,
16528 mv_to_q4(cpx, dv_col, ss_x(fctx)),
16529 mv_to_q4(cpy, dv_row, ss_y(fctx)),
16530 cw,
16531 ch,
16532 mc::InterpFilterKind::Bilinear,
16533 &mut vd,
16534 fctx,
16535 );
16536 let mut vs = vec![0u16; cside * cside];
16537 for row in 0..ch {
16538 vs[row * cside..][..cw].copy_from_slice(&vd[row * cw..][..cw]);
16539 }
16540 (us, vs)
16541 } else {
16542 (Vec::new(), Vec::new())
16543 };
16544
16545 // Key-frame `tx_select` is the parameter. `tx_select_inter` is forced
16546 // false for a key frame, so `read_block_tx_size_rect` would skip the
16547 // symbol; read it here against the parameter the intra path already uses.
16548 // A skipped intrabc block predicts the whole footprint once and codes
16549 // no residual (`decode_token_recon_block`'s inter branch). Lossless
16550 // still forces TX_4X4 when the block is coded.
16551 let leaves = if skip || (!lossless(fctx) && !tx_select) {
16552 None
16553 } else if lossless(fctx) {
16554 let mut leaves = Vec::new();
16555 for row in 0..bh / MI {
16556 for col in 0..bw / MI {
16557 leaves.push((row, col, 4usize, 4usize));
16558 }
16559 }
16560 Some(leaves)
16561 } else {
16562 let ctx = txfm_partition_ctx_rect(
16563 neighbours.above_txfm[lmi.1],
16564 neighbours.left_txfm[lmi.0],
16565 side,
16566 bw,
16567 bh,
16568 );
16569 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
16570 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
16571 let (rng, _) = dec.debug_state();
16572 eprintln!(
16573 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
16574 lmi.0,
16575 lmi.1,
16576 u8::from(split)
16577 );
16578 }
16579 if !split {
16580 None
16581 } else {
16582 let (sub_w, sub_h) = sub_tx_size_map(bw, bh);
16583 let mi_cols = 2 * y.true_width.div_ceil(8);
16584 let mi_rows = 2 * y.true_height.div_ceil(8);
16585 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(lmi.1));
16586 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(lmi.0));
16587 let mut out = Vec::new();
16588 for row in (0..bh / MI).step_by(sub_h / MI) {
16589 for col in (0..bw / MI).step_by(sub_w / MI) {
16590 read_var_tx_size(
16591 dec,
16592 cdfs,
16593 neighbours,
16594 lmi,
16595 side,
16596 (max_w_mi, max_h_mi),
16597 (sub_w, sub_h),
16598 1,
16599 row,
16600 col,
16601 &mut out,
16602 );
16603 }
16604 }
16605 Some(out)
16606 }
16607 };
16608 let (tx_w, tx_h) = leaves
16609 .as_ref()
16610 .and_then(|ls| ls.first())
16611 .map_or((bw, bh), |l| (l.2, l.3));
16612
16613 let mut luma_tx_type = TxType::DctDct;
16614 let luma_grid;
16615 let mut u_grid = Grid::Zero(cw * ch);
16616 let mut v_grid = Grid::Zero(cw * ch);
16617 let chroma_stamped_per_unit;
16618
16619 if skip {
16620 push_mc_rect(
16621 0,
16622 px,
16623 py,
16624 side,
16625 bw,
16626 bh,
16627 Pred::Inline(&pred_y, side),
16628 &ZERO_RESIDUAL[..side * bh],
16629 fctx,
16630 );
16631 luma_grid = Grid::Zero(bw * bh);
16632 if has_chroma {
16633 push_mc_rect(
16634 1,
16635 cpx,
16636 cpy,
16637 cside,
16638 cw,
16639 ch,
16640 Pred::Inline(&pred_u, cside),
16641 &ZERO_RESIDUAL[..cside * ch],
16642 fctx,
16643 );
16644 push_mc_rect(
16645 2,
16646 cpx,
16647 cpy,
16648 cside,
16649 cw,
16650 ch,
16651 Pred::Inline(&pred_v, cside),
16652 &ZERO_RESIDUAL[..cside * ch],
16653 fctx,
16654 );
16655 }
16656 chroma_stamped_per_unit = false;
16657 } else if let Some(ls) = leaves.as_ref() {
16658 if lossless(fctx) {
16659 for &(row, col, _tw, _th) in ls {
16660 let tu_mi = (lmi.0 + row, lmi.1 + col);
16661 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
16662 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
16663 let (g, _) = read_inter_plane(
16664 dec,
16665 cdfs,
16666 if reduced_tx_set {
16667 TxbSet::Luma4Inter
16668 } else {
16669 TxbSet::Luma4InterSet1
16670 },
16671 &default_scan(4),
16672 0,
16673 neighbours.around_mi(tu_mi, 4)[0],
16674 0,
16675 y,
16676 tu_px,
16677 tu_py,
16678 4,
16679 base_q_idx,
16680 tu_pred,
16681 None,
16682 Some(neighbours.luma_skip_ctx(tu_mi, 1)),
16683 fctx,
16684 )?;
16685 neighbours.record_mi_luma_rect(tu_mi, 4, 4, &g);
16686 }
16687 } else {
16688 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
16689 let tu_mi = (lmi.0 + row, lmi.1 + col);
16690 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
16691 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
16692 let (g, tt) = if tw == th {
16693 read_inter_plane(
16694 dec,
16695 cdfs,
16696 inter_txbset_for(tw, reduced_tx_set),
16697 &default_scan(tw.min(32)),
16698 0,
16699 neighbours.around_mi(tu_mi, tw)[0],
16700 0,
16701 y,
16702 tu_px,
16703 tu_py,
16704 tw,
16705 base_q_idx,
16706 tu_pred,
16707 None,
16708 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
16709 fctx,
16710 )?
16711 } else {
16712 read_inter_plane_rect(
16713 dec,
16714 cdfs,
16715 rect_inter_luma_set(tw, th, fctx)?,
16716 (tw, th),
16717 side,
16718 0,
16719 neighbours.around_mi_rect(tu_mi, tw, th)[0],
16720 0,
16721 y,
16722 tu_px,
16723 tu_py,
16724 tu_pred,
16725 None,
16726 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
16727 fctx,
16728 )?
16729 };
16730 if idx == 0 {
16731 luma_tx_type = tt;
16732 }
16733 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
16734 }
16735 }
16736 luma_grid = Grid::Zero(bw * bh);
16737 chroma_stamped_per_unit = has_chroma && lossless(fctx);
16738 if has_chroma && lossless(fctx) {
16739 let (mut uo, mut vo) = (Vec::new(), Vec::new());
16740 read_inter_chroma_lossless(
16741 dec,
16742 cdfs,
16743 neighbours,
16744 u,
16745 v,
16746 Pred::Inline(&pred_u, cside),
16747 Pred::Inline(&pred_v, cside),
16748 pair_mi,
16749 (cpx, cpy),
16750 (0, 0),
16751 (cw, ch),
16752 (cw, ch),
16753 cside,
16754 0,
16755 base_q_idx,
16756 &mut uo,
16757 &mut vo,
16758 fctx,
16759 )?;
16760 u_grid = if uo.is_empty() {
16761 Grid::Zero(cw * ch)
16762 } else {
16763 Grid::Own(uo)
16764 };
16765 v_grid = if vo.is_empty() {
16766 Grid::Zero(cw * ch)
16767 } else {
16768 Grid::Own(vo)
16769 };
16770 } else if has_chroma {
16771 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
16772 let (ug, _) = read_inter_plane_rect(
16773 dec,
16774 cdfs,
16775 rect_inter_chroma_set(cw, ch)?,
16776 (cw, ch),
16777 cside,
16778 1,
16779 around[1],
16780 0,
16781 u,
16782 cpx,
16783 cpy,
16784 Pred::Inline(&pred_u, cside),
16785 Some(luma_tx_type),
16786 None,
16787 fctx,
16788 )?;
16789 u_grid = ug;
16790 let (vg, _) = read_inter_plane_rect(
16791 dec,
16792 cdfs,
16793 rect_inter_chroma_set(cw, ch)?,
16794 (cw, ch),
16795 cside,
16796 2,
16797 around[2],
16798 0,
16799 v,
16800 cpx,
16801 cpy,
16802 Pred::Inline(&pred_v, cside),
16803 Some(luma_tx_type),
16804 None,
16805 fctx,
16806 )?;
16807 v_grid = vg;
16808 }
16809 } else {
16810 let around = neighbours.around_mi_rect(lmi, bw, bh);
16811 let (g, tt) = read_inter_plane_rect(
16812 dec,
16813 cdfs,
16814 rect_inter_luma_set(bw, bh, fctx)?,
16815 (bw, bh),
16816 side,
16817 0,
16818 around[0],
16819 0,
16820 y,
16821 px,
16822 py,
16823 Pred::Inline(&pred_y, side),
16824 None,
16825 None,
16826 fctx,
16827 )?;
16828 luma_tx_type = tt;
16829 luma_grid = g;
16830 chroma_stamped_per_unit = false;
16831 if has_chroma {
16832 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
16833 let (ug, _) = read_inter_plane_rect(
16834 dec,
16835 cdfs,
16836 rect_inter_chroma_set(cw, ch)?,
16837 (cw, ch),
16838 cside,
16839 1,
16840 around[1],
16841 0,
16842 u,
16843 cpx,
16844 cpy,
16845 Pred::Inline(&pred_u, cside),
16846 Some(luma_tx_type),
16847 None,
16848 fctx,
16849 )?;
16850 u_grid = ug;
16851 let (vg, _) = read_inter_plane_rect(
16852 dec,
16853 cdfs,
16854 rect_inter_chroma_set(cw, ch)?,
16855 (cw, ch),
16856 cside,
16857 2,
16858 around[2],
16859 0,
16860 v,
16861 cpx,
16862 cpy,
16863 Pred::Inline(&pred_v, cside),
16864 Some(luma_tx_type),
16865 None,
16866 fctx,
16867 )?;
16868 v_grid = vg;
16869 }
16870 }
16871 drop(restored);
16872
16873 if leaves.is_none() {
16874 neighbours.record_mi_luma_rect(lmi, bw, bh, &luma_grid);
16875 }
16876 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, DC_PRED);
16877 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
16878 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
16879 for cell in 0..mi_w {
16880 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
16881 *slot = bw as u8;
16882 }
16883 }
16884 for cell in 0..mi_h {
16885 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
16886 *slot = bh as u8;
16887 }
16888 }
16889 let mut last_uv = None;
16890 if has_chroma {
16891 hit!(RECT4_16_CHROMA_HITS);
16892 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, DC_PRED);
16893 if !chroma_stamped_per_unit {
16894 let u_state = neighbour_state(&u_grid);
16895 let v_state = neighbour_state(&v_grid);
16896 let round_up_even = |n: usize| n.div_ceil(2) * 2;
16897 let bound_h = round_up_even(neighbours.mi_rows);
16898 let bound_w = round_up_even(neighbours.mi_cols);
16899 for cell in 0..(ph / MI) {
16900 if pair_mi.0 + cell < bound_h
16901 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
16902 {
16903 slot[1] = u_state;
16904 slot[2] = v_state;
16905 }
16906 }
16907 for cell in 0..(pw / MI) {
16908 if pair_mi.1 + cell < bound_w
16909 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
16910 {
16911 slot[1] = u_state;
16912 slot[2] = v_state;
16913 }
16914 }
16915 }
16916 last_uv = Some(DC_PRED);
16917 }
16918 if horz {
16919 hit!(RECT4_16_HORZ_HITS);
16920 } else {
16921 hit!(RECT4_16_VERT_HITS);
16922 }
16923 record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]);
16924 if leaves.is_none() {
16925 // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs`
16926 // with `skip && is_inter`, or the unsplit unit). A split tree already
16927 // published per leaf inside `read_var_tx_size`.
16928 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
16929 }
16930 record_intrabc_mi_rect(
16931 lmi.0,
16932 lmi.1,
16933 mi_w,
16934 mi_h,
16935 Some((dv_row, dv_col)),
16936 neighbours,
16937 fctx,
16938 );
16939 Ok((DC_PRED, last_uv, (tx_w, tx_h)))
16940}
16941
16942/// Restores `reduced_tx_set_inter` when the intrabc pair reader returns,
16943/// including through `?`.
16944struct ReducedRestore<'a> {
16945 fctx: &'a crate::decode::FrameCtx,
16946 saved: bool,
16947}
16948impl Drop for ReducedRestore<'_> {
16949 fn drop(&mut self) {
16950 self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved));
16951 }
16952}
16953fn scopeguard_reduced(fctx: &crate::decode::FrameCtx, saved: bool) -> ReducedRestore<'_> {
16954 ReducedRestore { fctx, saved }
16955}
16956
16957#[allow(clippy::too_many_arguments)]
16958fn decode_rect4_16_strip(
16959 dec: &mut SymbolDecoder,
16960 cdfs: &mut Cdfs,
16961 neighbours: &mut Neighbours,
16962 lmi: (usize, usize),
16963 horz: bool,
16964 has_chroma: bool,
16965 prev: Option<((usize, usize), usize)>,
16966 y: &mut PlaneBuf<'static>,
16967 u: &mut PlaneBuf<'static>,
16968 v: &mut PlaneBuf<'static>,
16969 enable_filter_intra: bool,
16970 allow_screen_content_tools: bool,
16971 base_q_idx: u8,
16972 tx_select: bool,
16973 reduced_tx_set: bool,
16974 fctx: &crate::decode::FrameCtx,
16975) -> Result<(usize, Option<usize>, (usize, usize))> {
16976 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
16977 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
16978 let (mi_w, mi_h) = (bw / MI, bh / MI);
16979 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
16980 let mut last_uv_mode: Option<usize> = None;
16981 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
16982 // aliases all four strips onto one entry, so the mi-exact map wins and
16983 // the previous strip stands in on the split axis.
16984 let mut above_mode = neighbours.above_mode[c];
16985 let mut left_mode = neighbours.left_mode[r];
16986 if let Some(((pr, pc), pmode)) = prev {
16987 if pc == lmi.1 && lmi.0 == pr + mi_h {
16988 above_mode = pmode;
16989 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
16990 left_mode = pmode;
16991 }
16992 }
16993 let (above_mode, left_mode) =
16994 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
16995 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
16996 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
16997 // off CDF row 0 and every cache hit off an empty cache.
16998 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
16999 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
17000 let (
17001 skip,
17002 mode,
17003 angle_delta_y,
17004 uv_mode,
17005 angle_delta_uv,
17006 alpha,
17007 filter_intra,
17008 palette_y,
17009 palette_uv,
17010 intrabc,
17011 ) = read_intra_mode_rect(
17012 dec,
17013 cdfs,
17014 above_mode,
17015 left_mode,
17016 true,
17017 has_chroma,
17018 bw,
17019 bh,
17020 enable_filter_intra,
17021 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
17022 allow_screen_content_tools,
17023 Some((palette_ctx, &palette_cache)),
17024 &palette_uv_cache,
17025 lmi.0,
17026 lmi.1,
17027 fctx,
17028 )?;
17029 if let Some(dv) = intrabc {
17030 return decode_rect4_16_intrabc(
17031 dec,
17032 cdfs,
17033 neighbours,
17034 lmi,
17035 horz,
17036 has_chroma,
17037 skip,
17038 dv,
17039 y,
17040 u,
17041 v,
17042 base_q_idx,
17043 tx_select,
17044 reduced_tx_set,
17045 fctx,
17046 );
17047 }
17048 if palette_y.is_some() || palette_uv.is_some() {
17049 hit!(RECT4_PALETTE_HITS);
17050 }
17051 // The colour-index map through the base colours IS the prediction.
17052 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
17053 // chroma transform this closing strip codes.
17054 let palette_y_buf: Option<Vec<u16>> = palette_y
17055 .as_ref()
17056 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
17057 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
17058 (
17059 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
17060 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
17061 )
17062 });
17063 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
17064 if smooth_neighbor {
17065 hit!(SMOOTH_LUMA_HITS);
17066 }
17067 if filter_intra.is_some() {
17068 hit!(FILTER_INTRA_RECT_HITS);
17069 }
17070 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
17071 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
17072 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
17073 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
17074 // lane-av1mixloss: the lossless-segment early return
17075 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a
17076 // lossless-segment strip codes no depth symbol here either (class
17077 // sweep of the sub8 leaf's fix).
17078 let depth = if tx_select && !lossless(fctx) {
17079 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
17080 // (`get_tx_size_context`, libaom `pred_common.h:342`).
17081 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
17082 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
17083 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17084 eprintln!(
17085 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
17086 lmi.0,
17087 lmi.1,
17088 dec.debug_state().0
17089 );
17090 }
17091 d
17092 } else {
17093 0
17094 };
17095 if depth != 0 {
17096 hit!(TX_DEPTH_HITS);
17097 hit!(RECT4_16_SPLIT_HITS);
17098 }
17099 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
17100 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
17101 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
17102 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
17103 if depth != 0 || lossless(fctx) {
17104 // [`decode_rect_split`]'s per-unit walk, inlined because the
17105 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
17106 // the strip (that function codes one chroma transform per block).
17107 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
17108 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
17109 // unit predicts off the units before it in raster order.
17110 let rect_unit = tx_w != tx_h;
17111 let zero_tu = vec![0i32; tx_w * tx_h];
17112 for tu_row in 0..bh / tx_h {
17113 for tu_col in 0..bw / tx_w {
17114 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
17115 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
17116 let tu_reach =
17117 Reach::of_tu(bw, bh, tu_col * tx_w, tu_row * tx_h, tx_w, tx_h, reach);
17118 if let Some(b) = &palette_y_buf {
17119 let tu_buf: Vec<u16> = (0..tx_h)
17120 .flat_map(|i| {
17121 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
17122 b[base..base + tx_w].iter().copied()
17123 })
17124 .collect();
17125 set_palette_pred(tu_buf, fctx);
17126 }
17127 if skip {
17128 push_intra_rect(
17129 0,
17130 tu_px,
17131 tu_py,
17132 tx_w,
17133 tx_h,
17134 mode,
17135 angle_delta_y,
17136 tu_reach,
17137 &zero_tu,
17138 None,
17139 filter_intra,
17140 smooth_neighbor,
17141 fctx,
17142 );
17143 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
17144 } else if rect_unit {
17145 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
17146 // 32 coded positions and the `TX_4X4` `tx_type` row:
17147 // exactly [`TxbSet::LumaRect4x8`].
17148 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
17149 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
17150 let set = if reduced_tx_set {
17151 TxbSet::LumaRect4x8
17152 } else {
17153 TxbSet::LumaRect4x8Set1
17154 };
17155 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
17156 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
17157 let (tu_grid, tu_tx_type) = read_coeffs_rect(
17158 dec,
17159 &mut coding,
17160 tu_scan,
17161 tx_w,
17162 tx_h,
17163 tu_skip_ctx,
17164 dc_sign_ctx(tu_around.2),
17165 TxType::DctDct,
17166 )?;
17167 let residual = dequant_and_inverse_typed_wh(
17168 &tu_grid,
17169 tx_w,
17170 tx_h,
17171 crate::decode::bit_depth(fctx),
17172 block_q_idx(fctx),
17173 plane_q_delta(0, fctx).0,
17174 plane_q_delta(0, fctx).1,
17175 tu_tx_type,
17176 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
17177 );
17178 push_intra_rect(
17179 0,
17180 tu_px,
17181 tu_py,
17182 tx_w,
17183 tx_h,
17184 mode,
17185 angle_delta_y,
17186 tu_reach,
17187 &residual,
17188 None,
17189 filter_intra,
17190 smooth_neighbor,
17191 fctx,
17192 );
17193 if tu_grid.iter().any(|&l| l != 0) {
17194 hit!(RECT4_16_COEFF_HITS);
17195 }
17196 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
17197 } else {
17198 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
17199 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
17200 let tu_grid = read_plane(
17201 dec,
17202 cdfs,
17203 txbset_for(tx_w, reduced_tx_set),
17204 default_scan(tx_w),
17205 0,
17206 tu_around,
17207 mode,
17208 mode,
17209 angle_delta_y,
17210 tu_reach,
17211 y,
17212 tu_px,
17213 tu_py,
17214 tx_w,
17215 tx_w,
17216 base_q_idx,
17217 None,
17218 filter_intra,
17219 Some(tu_skip_ctx),
17220 smooth_neighbor,
17221 fctx,
17222 )?;
17223 if tu_grid.iter().any(|&l| l != 0) {
17224 hit!(RECT4_16_COEFF_HITS);
17225 }
17226 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
17227 }
17228 }
17229 }
17230 } else {
17231 let levels = if skip {
17232 let zeros = Grid::Zero(bw * bh);
17233 if let Some(b) = &palette_y_buf {
17234 set_palette_pred(b.clone(), fctx);
17235 }
17236 push_intra_rect(
17237 0,
17238 px,
17239 py,
17240 bw,
17241 bh,
17242 mode,
17243 angle_delta_y,
17244 reach,
17245 &zeros,
17246 None,
17247 filter_intra,
17248 smooth_neighbor,
17249 fctx,
17250 );
17251 zeros
17252 } else {
17253 // The strip's luma TU *is* the strip (`plane_bsize ==
17254 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
17255 // `txb_skip_ctx` at 0.
17256 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
17257 let set = if reduced_tx_set {
17258 TxbSet::LumaRect16x4
17259 } else {
17260 TxbSet::LumaRect16x4Set1
17261 };
17262 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
17263 let (levels, tx_type) = read_coeffs_rect(
17264 dec,
17265 &mut coding,
17266 scan,
17267 bw,
17268 bh,
17269 0,
17270 dc_sign_ctx(around.2),
17271 TxType::DctDct,
17272 )?;
17273 let residual = dequant_and_inverse_typed_wh(
17274 &levels,
17275 bw,
17276 bh,
17277 crate::decode::bit_depth(fctx),
17278 block_q_idx(fctx),
17279 plane_q_delta(0, fctx).0,
17280 plane_q_delta(0, fctx).1,
17281 tx_type,
17282 block_iqmatrix(fctx, 0, bw, bh, tx_type),
17283 );
17284 if let Some(b) = &palette_y_buf {
17285 set_palette_pred(b.clone(), fctx);
17286 }
17287 push_intra_rect(
17288 0,
17289 px,
17290 py,
17291 bw,
17292 bh,
17293 mode,
17294 angle_delta_y,
17295 reach,
17296 &residual,
17297 None,
17298 filter_intra,
17299 smooth_neighbor,
17300 fctx,
17301 );
17302 hit!(RECT4_16_COEFF_HITS);
17303 levels
17304 };
17305 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
17306 }
17307 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
17308 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
17309 // `update_partition_context` writes `partition_context_lookup[
17310 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
17311 // the left (mirrored under VERT_4).
17312 for cell in 0..mi_w {
17313 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
17314 *slot = bw as u8;
17315 }
17316 }
17317 for cell in 0..mi_h {
17318 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
17319 *slot = bh as u8;
17320 }
17321 }
17322 if has_chroma {
17323 hit!(RECT4_16_CHROMA_HITS);
17324 // lane-av1-444: at 4:4:4 there is no pair -- every strip is its
17325 // own chroma reference and codes its own 16x4 / 4x16 chroma
17326 // block. (`set_mi_offsets`'s chroma snap is the zero offset at
17327 // ss 0/0, so the neighbour reads below anchor at the strip.)
17328 let (pair_mi, pw, ph) = if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
17329 (lmi, bw, bh)
17330 } else if ss_y(fctx) == 0 && horz {
17331 // lane-av1-422: chroma height is NOT subsampled, so a HORZ
17332 // 16x4 strip is its own chroma reference (`is_chroma_reference`
17333 // at ss(1,0): bh == 1 mi, so the row clause reduces to
17334 // `!ss_y`) and codes its own `ss_size_lookup[BLOCK_16X4][1][0]`
17335 // = BLOCK_8X4 chroma block -- a valid transform, no pair.
17336 // (lane-av1-422o: a VERTICAL 4x16 strip now falls through to
17337 // the pair merge below -- its own chroma block
17338 // `ss_size_lookup[BLOCK_4X16][1][0]` is BLOCK_INVALID, the
17339 // walk proved such leaves exist, and libaom codes the pair's
17340 // chroma from the closing strip; the chunk lives in the
17341 // `chroma422_pair16` arm below.)
17342 (lmi, bw, bh)
17343 } else if horz {
17344 ((lmi.0 - 1, lmi.1), 16, 8)
17345 } else {
17346 ((lmi.0, lmi.1 - 1), 8, 16)
17347 };
17348 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
17349 let (cpx, cpy) = (ppx >> ss_x(fctx), ppy >> ss_y(fctx));
17350 let (cw, ch) = (pw >> ss_x(fctx), ph >> ss_y(fctx));
17351 // lane-av1-422o: the 4:2:2 pair's chroma of a VERT 4x16 strip
17352 // pair: (4, 16) at ss(1,0). The bsize is still BLOCK_4X16, whose
17353 // `ss_size_lookup[..][1][0]` is BLOCK_INVALID, so libaom's
17354 // `av1_get_tx_size` reads `max_txsize_rect_lookup[255]` -- the
17355 // out-of-bounds byte is TX_4X8 in the pinned Release oracle, and
17356 // `av1_get_adjusted_tx_size` has no TX_4X8 case to adjust it.
17357 // `decode_token_recon_block` walks unit_width =
17358 // ROUND_POWER_OF_TWO(1, 1) = 1, unit_height = 4, with stepr =
17359 // tx_size_high_unit[TX_4X8] = 2: TWO TX_4X8 units per plane
17360 // (chroma rows 0..8 and 8..16), plane-major. Even the skip arm
17361 // walks per unit: `predict_and_reconstruct_intra_block` predicts
17362 // every unit regardless of `skip_txfm`.
17363 let chroma422_pair16 = (cw, ch) == (4, 16) && ss_x(fctx) == 1;
17364 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
17365 DC_PRED
17366 } else {
17367 uv_mode
17368 };
17369 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
17370 hit!(RECT4_16_CHROMA_DIR_HITS);
17371 }
17372 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
17373 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
17374 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
17375 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
17376 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
17377 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
17378 // the pair's top-left luma mi, never this leaf's odd row/column.
17379 // Reading `lmi` here named the leaf directly above (a non-chroma
17380 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
17381 // SMOOTH neighbour: filt_type 0 instead of 1 turned
17382 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
17383 // directional chroma strip, moving 4 samples by 1.
17384 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c, fctx);
17385 // lane-av1422warp: `smooth_uv_neighbour_unsnapped` now takes the
17386 // frame's own `ss_x` -- the unsnapped read is the pair-merge witness
17387 // counter's mirror of the snapping form, and the shipped read offsets
17388 // the above COLUMN by `+ss_x` (libaom's `chroma_above_mi`).
17389 if smooth_neighbor_uv
17390 != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c, ss_x(fctx))
17391 {
17392 hit!(RECT4_16_UV_PAIR_FILT_HITS);
17393 }
17394 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane
17395 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is
17396 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major
17397 // (`decode_token_recon_block`), not one `ChromaRect8x4`. Reading
17398 // the rect here consumed one symbol block too few and desynced
17399 // the next strip's `skip` (measured: lossless sb128 320x240,
17400 // mi(1,20) uv_mode matched, the following skip did not).
17401 let lossless_pair = lossless(fctx);
17402 let (u_levels, v_levels) = if lossless_pair {
17403 hit!(RECT4_16_LOSSLESS_CHROMA_HITS);
17404 if skip {
17405 for plane in 1..3usize {
17406 for rr in 0..ch / 4 {
17407 for cc in 0..cw / 4 {
17408 let (ox, oy) = (cc * 4, rr * 4);
17409 let cu_reach = tu_reach(
17410 pw,
17411 ph,
17412 ox * 2,
17413 oy * 2,
17414 8,
17415 pair_reach,
17416 ppx,
17417 ppy,
17418 y.width,
17419 y.height,
17420 fctx,
17421 );
17422 if let Some((ub, vb)) = &palette_uv_bufs {
17423 let buf = if plane == 1 { ub } else { vb };
17424 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
17425 }
17426 push_intra(
17427 plane,
17428 cpx + ox,
17429 cpy + oy,
17430 4,
17431 uv_predict_mode,
17432 angle_delta_uv,
17433 cu_reach,
17434 &ZERO_RESIDUAL[..16],
17435 None,
17436 None,
17437 smooth_neighbor_uv,
17438 fctx,
17439 );
17440 let cu_mi = (
17441 pair_mi.0 + (oy << ss_y(fctx)) / MI,
17442 pair_mi.1 + (ox << ss_x(fctx)) / MI,
17443 );
17444 neighbours.record_mi_chroma(
17445 cu_mi,
17446 4 << ss_x(fctx),
17447 4 << ss_y(fctx),
17448 plane,
17449 &ZERO_RESIDUAL[..16],
17450 );
17451 }
17452 }
17453 }
17454 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
17455 } else {
17456 let scan4 = default_scan(4);
17457 // `get_txb_ctx`: offset 10 (our tables store it at +3)
17458 // when the plane block is larger than the transform.
17459 let offset = Some(3usize);
17460 let mut uo = vec![0i32; cw * ch];
17461 let mut vo = vec![0i32; cw * ch];
17462 for plane in 1..3usize {
17463 for rr in 0..ch / 4 {
17464 for cc in 0..cw / 4 {
17465 let (ox, oy) = (cc * 4, rr * 4);
17466 if cpx + ox >= u.true_width || cpy + oy >= u.true_height {
17467 continue;
17468 }
17469 // The unit's stamp is its own span: aom
17470 // `av1_set_entropy_contexts` (blockd.c:29)
17471 // memsets exactly `tx_size_wide_unit` x
17472 // `tx_size_high_unit` cells at the unit's own
17473 // `(aoff, loff)` -- for TX_4X4 ONE above cell
17474 // and ONE left cell. `(oy / 2, ox / 2)` +
17475 // `(8, 8)` is the 4:2:0 subsampled form (one
17476 // chroma cell = 8 luma px = 2 mi cells); at
17477 // 4:4:4 a unit is ONE mi cell, and the 2x2
17478 // smear let a 4-wide strip's later units
17479 // overwrite the NEXT COLUMN's above cell with
17480 // their own state -- a column aom never sees
17481 // this block write -- so the following block's
17482 // `all_zero` read the wrong `txb_skip` row
17483 // (frame-0 read #452, the llkf named gap).
17484 let cu_mi = (
17485 pair_mi.0 + (oy << ss_y(fctx)) / MI,
17486 pair_mi.1 + (ox << ss_x(fctx)) / MI,
17487 );
17488 // One luma-mi cell: the chroma entropy arrays
17489 // are subsampled, and our bands replicate that
17490 // one entry over the unit's two cells
17491 // (`read_intra_chroma_lossless`).
17492 let cu_around = neighbours.around_mi(cu_mi, MI);
17493 let cu_reach = tu_reach(
17494 pw,
17495 ph,
17496 ox * 2,
17497 oy * 2,
17498 8,
17499 pair_reach,
17500 ppx,
17501 ppy,
17502 y.width,
17503 y.height,
17504 fctx,
17505 );
17506 if let Some((ub, vb)) = &palette_uv_bufs {
17507 let buf = if plane == 1 { ub } else { vb };
17508 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
17509 }
17510 let buf: &mut PlaneBuf<'static> =
17511 if plane == 1 { &mut *u } else { &mut *v };
17512 let cu_grid = read_plane(
17513 dec,
17514 cdfs,
17515 TxbSet::Chroma4,
17516 &scan4,
17517 plane,
17518 cu_around[plane],
17519 mode,
17520 uv_predict_mode,
17521 angle_delta_uv,
17522 cu_reach,
17523 buf,
17524 cpx + ox,
17525 cpy + oy,
17526 4,
17527 4,
17528 base_q_idx,
17529 None,
17530 None,
17531 offset,
17532 smooth_neighbor_uv,
17533 fctx,
17534 )?;
17535 neighbours.record_mi_chroma(
17536 cu_mi,
17537 4 << ss_x(fctx),
17538 4 << ss_y(fctx),
17539 plane,
17540 &cu_grid,
17541 );
17542 hit!(CHROMA_SPLIT_TX_HITS);
17543 let dst = if plane == 1 { &mut uo } else { &mut vo };
17544 for row in 0..4 {
17545 let start = (oy + row) * cw + ox;
17546 dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]);
17547 }
17548 }
17549 }
17550 }
17551 (Grid::Own(uo), Grid::Own(vo))
17552 }
17553 } else if skip {
17554 let zeros = Grid::Zero(cw * ch);
17555 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
17556 // ~1000) predicts EVERY plane and only guards the residual on
17557 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
17558 // DC + alpha * luma-AC. Dropping the CfL term here left a
17559 // chroma-only bounded box on ReelC's key frames.
17560 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
17561 if alpha.is_some() {
17562 hit!(CHROMA_SKIP_CFL_HITS);
17563 }
17564 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
17565 if chroma422_pair16 {
17566 // lane-av1-422o: two TX_4X8 units, each predicted on
17567 // its own edges (the lower one off the upper one's
17568 // samples); no coefficients are coded, and libaom's
17569 // `set_entropy_context` zeroed the block's own cells,
17570 // so the pair-wide zero stamp below stays correct.
17571 for unit_row in 0..2usize {
17572 let unit_reach = tu_reach_rect(
17573 pw,
17574 ph,
17575 0,
17576 unit_row * 8,
17577 8,
17578 8,
17579 pair_reach,
17580 ppx,
17581 ppy,
17582 y.width,
17583 y.height,
17584 fctx,
17585 );
17586 if let Some((ub, vb)) = &palette_uv_bufs {
17587 let pbuf = if plane == 1 { ub } else { vb };
17588 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
17589 }
17590 push_intra_rect(
17591 plane,
17592 cpx,
17593 cpy + unit_row * 8,
17594 4,
17595 8,
17596 uv_predict_mode,
17597 angle_delta_uv,
17598 unit_reach,
17599 &ZERO_RESIDUAL[..4 * 8],
17600 alpha
17601 .zip(ac)
17602 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
17603 None,
17604 smooth_neighbor_uv,
17605 fctx,
17606 );
17607 }
17608 } else {
17609 if let Some((ub, vb)) = &palette_uv_bufs {
17610 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
17611 }
17612 push_intra_rect(
17613 plane,
17614 cpx,
17615 cpy,
17616 cw,
17617 ch,
17618 uv_predict_mode,
17619 angle_delta_uv,
17620 pair_reach,
17621 &zeros,
17622 alpha
17623 .zip(ac)
17624 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
17625 None,
17626 smooth_neighbor_uv,
17627 fctx,
17628 );
17629 }
17630 }
17631 (zeros.clone(), zeros)
17632 } else if chroma422_pair16 {
17633 // lane-av1-422o: the pair's 4x16 chroma as TWO TX_4X8 units
17634 // per plane, plane-major (every U unit, then every V). Each
17635 // unit: the `ChromaRect8x4` tables (`get_txsize_entropy_ctx`
17636 // squares TX_4X8 up to the 8x8 class), `SCAN_4X8`, and a
17637 // `txb_skip_ctx` of above+left in the OFFSET-10 rows -- the
17638 // offset comes from `num_pels_log2_lookup[plane_bsize] >
17639 // num_pels_log2_lookup[BLOCK_4X8]` with plane_bsize =
17640 // BLOCK_INVALID (255), and the byte at that table's +255 in
17641 // the pinned Release oracle is 255 (`cmpb` against the
17642 // `0xc0db70` copy decodetxb.c links), i.e. the bigger-plane
17643 // arm: +3 on the offset-7-first chroma tables. No tx_type
17644 // symbol (only y plane's is transmitted); the unit's type is
17645 // `intra_mode_to_tx_type(UV mode)` kept by the all-16 ext-tx
17646 // set -- [`read_rect_chroma_unit`]'s own default. CfL params
17647 // are computed ONCE per block (`are_parameters_computed`)
17648 // over the pair's luma, shared by both units. Each unit is
17649 // predicted and recorded immediately, so the lower unit
17650 // reads the upper one's coefficient context.
17651 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
17652 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
17653 for unit_row in 0..2usize {
17654 let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1);
17655 let unit_reach = tu_reach_rect(
17656 pw,
17657 ph,
17658 0,
17659 unit_row * 8,
17660 8,
17661 8,
17662 pair_reach,
17663 ppx,
17664 ppy,
17665 y.width,
17666 y.height,
17667 fctx,
17668 );
17669 if let Some((ub, vb)) = &palette_uv_bufs {
17670 let pbuf = if plane == 1 { ub } else { vb };
17671 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
17672 }
17673 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
17674 let unit_grid = read_rect_chroma_unit(
17675 dec,
17676 cdfs,
17677 TxbSet::ChromaRect8x4,
17678 &SCAN_4X8,
17679 4,
17680 8,
17681 plane,
17682 chroma_around[plane],
17683 uv_predict_mode,
17684 angle_delta_uv,
17685 unit_reach,
17686 buf,
17687 cpx,
17688 cpy + unit_row * 8,
17689 base_q_idx,
17690 // lane-av1-422q: the offset-10 rows -- the same
17691 // measured rule as the 4x32 arm (plane_bsize
17692 // BLOCK_INVALID for the pair's BLOCK_4X16 too;
17693 // num_pels_log2_lookup[255] = 0xff at the
17694 // 0xc0de70 copy -> +3 on the offset-7-first
17695 // chroma tables; see lanes/av1422q.report.md).
17696 Some(3),
17697 alpha
17698 .zip(ac)
17699 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
17700 smooth_neighbor_uv,
17701 fctx,
17702 )?;
17703 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
17704 }
17705 }
17706 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
17707 } else {
17708 // lane-av1422ctxgather: 4:2:2's chroma above votes sample
17709 // every second luma-mi cell
17710 // ([`Neighbours::around_mi_422_chroma`]: at ss_x 1 one
17711 // chroma 4-px column spans two luma mi columns, and the
17712 // plain per-mi gather counts each column's whole-unit dc
17713 // sign twice). The left extent is unsubsampled at ss_y 0,
17714 // so its per-mi cells already line up one-to-one.
17715 let around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
17716 neighbours.around_mi_422_chroma(pair_mi, pw, ph)
17717 } else {
17718 neighbours.around_mi_rect(pair_mi, pw, ph)
17719 };
17720 // lane-av1-444: the strip's own 16x4 / 4x16 chroma at ss 0/0
17721 // (`TxbSet::Chroma8`, `get_txsize_entropy_ctx(TX_16X4)` =
17722 // the 8x8 set); 4:2:0 keeps the pair's 8x4 / 4x8.
17723 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (cw, ch) {
17724 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
17725 (4, 8) => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
17726 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
17727 // lane-av1-444: 4:4:4's own-strip vert chroma is (4,16)
17728 // -- one TX_4X16. (lane-av1-422o: the 4:2:2 pair's
17729 // (4,16) never reaches this row; `chroma422_pair16`
17730 // intercepts it above and chunks it into TX_4X8 units.)
17731 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
17732 // lane-av1-422: a 4:2:2 HORZ pair (16x8 luma) keeps the
17733 // pair's height: an 8x8 SQUARE chroma block, the same
17734 // `TxbSet::Chroma8` set any 8x8 chroma plane reads. The
17735 // 4:2:0 pair's chroma is 8x4 and 4:4:4's is 16x4, so this
17736 // row is unreachable there. It is also the witness arm:
17737 // a restored `/2 chroma height` lands on (8,4) and the
17738 // counter reads 0.
17739 (8, 8) => {
17740 hit!(CHROMA422_SQUARE_HITS);
17741 (TxbSet::Chroma8, default_scan(8))
17742 }
17743 // lane-av1-422o: with the `chroma422_pair16` arm above,
17744 // the (2,16) own-strip shape and the 4:4:4 shapes are the
17745 // only residents; anything else is a named-lane gap.
17746 _ => unreachable!("decode_rect4_16_strip chroma shape set is closed"),
17747 };
17748 let mut planes = Vec::with_capacity(2);
17749 for plane in 1..3 {
17750 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
17751 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
17752 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
17753 let (levels, tx_type) = read_chroma_coeffs_rect(
17754 dec,
17755 &mut coding,
17756 chroma_scan,
17757 cw,
17758 ch,
17759 skip_ctx,
17760 dc_sign_ctx(around[plane].2),
17761 default_tx,
17762 fctx,
17763 )?;
17764 planes.push((levels, tx_type));
17765 }
17766 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
17767 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
17768 // CfL averages the luma of the WHOLE pair, the region this one
17769 // chroma transform covers.
17770 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
17771 for (plane, _buf, levels, tx_type) in [
17772 (1usize, &mut *u, &u_levels, u_tx_type),
17773 (2, &mut *v, &v_levels, v_tx_type),
17774 ] {
17775 let residual = dequant_and_inverse_typed_wh(
17776 levels,
17777 cw,
17778 ch,
17779 crate::decode::bit_depth(fctx),
17780 block_q_idx(fctx),
17781 plane_q_delta(plane, fctx).0,
17782 plane_q_delta(plane, fctx).1,
17783 tx_type,
17784 block_iqmatrix(fctx, plane, cw, ch, tx_type),
17785 );
17786 if let Some((ub, vb)) = &palette_uv_bufs {
17787 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
17788 }
17789 push_intra_rect(
17790 plane,
17791 cpx,
17792 cpy,
17793 cw,
17794 ch,
17795 uv_predict_mode,
17796 angle_delta_uv,
17797 pair_reach,
17798 &residual,
17799 alpha
17800 .zip(ac)
17801 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
17802 None,
17803 smooth_neighbor_uv,
17804 fctx,
17805 );
17806 }
17807 (u_levels, v_levels)
17808 };
17809 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
17810 // A lossless pair already stamped each TX_4X4 (`record_mi_chroma`).
17811 // The single-state rewrite below is the non-lossless TX_8X4/TX_4X8.
17812 // lane-av1-422o: the chunked pair's cells are stamped PER UNIT in
17813 // the arm above (libaom's coefficient contexts are per
17814 // 4x4-cell); a pair-wide state would erase the unit boundary the
17815 // next block reads.
17816 if !lossless_pair && !chroma422_pair16 {
17817 // The chroma planes' coefficient context, over the PAIR's mi span
17818 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
17819 // the luma one rounded up to its 4x4 unit).
17820 let u_state = neighbour_state(&u_levels);
17821 let v_state = neighbour_state(&v_levels);
17822 let round_up_even = |n: usize| n.div_ceil(2) * 2;
17823 let bound_h = round_up_even(neighbours.mi_rows);
17824 let bound_w = round_up_even(neighbours.mi_cols);
17825 for cell in 0..(ph / MI) {
17826 if pair_mi.0 + cell < bound_h
17827 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
17828 {
17829 slot[1] = u_state;
17830 slot[2] = v_state;
17831 }
17832 }
17833 for cell in 0..(pw / MI) {
17834 if pair_mi.1 + cell < bound_w
17835 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
17836 {
17837 slot[1] = u_state;
17838 slot[2] = v_state;
17839 }
17840 }
17841 }
17842 last_uv_mode = Some(uv_predict_mode);
17843 }
17844 if horz {
17845 hit!(RECT4_16_HORZ_HITS);
17846 } else {
17847 hit!(RECT4_16_VERT_HITS);
17848 }
17849 let (pal_y_size, pal_y_colors) = palette_y
17850 .as_ref()
17851 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
17852 let (pal_uv_size, pal_uv_colors) = palette_uv
17853 .as_ref()
17854 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
17855 record_strip_palette(
17856 neighbours,
17857 lmi,
17858 bw,
17859 bh,
17860 pal_y_size,
17861 pal_y_colors,
17862 pal_uv_size,
17863 pal_uv_colors,
17864 );
17865 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
17866 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
17867 // frame): the above row records `tx_size_wide` over the block's width and
17868 // the left column `tx_size_high` over its height. This 1:4 strip reader is
17869 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
17870 // and it published neither band -- so the block after a 64x16 strip read
17871 // the row's init value 64 as its left transform height and took
17872 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
17873 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
17874 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
17875 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
17876 Ok((mode, last_uv_mode, (tx_w, tx_h)))
17877}
17878
17879/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
17880/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
17881/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
17882/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
17883/// cap, so LUMA needs the same corner truncation [`decode_block`] already
17884/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
17885/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
17886/// this function's own charter/report), so both strips read a real 32x32
17887/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
17888/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
17889/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
17890/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
17891/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
17892/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
17893/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
17894/// that function, only the single-transform-unit (`tx_depth == 0`) case is
17895/// supported: a split transform refuses by name rather than guess-decode.
17896#[allow(clippy::too_many_arguments)]
17897fn decode_block_rect64(
17898 dec: &mut SymbolDecoder,
17899 cdfs: &mut Cdfs,
17900 neighbours: &mut Neighbours,
17901 at: (usize, usize),
17902 bw: usize,
17903 bh: usize,
17904 y: &mut PlaneBuf<'static>,
17905 u: &mut PlaneBuf<'static>,
17906 v: &mut PlaneBuf<'static>,
17907 enable_filter_intra: bool,
17908 allow_screen_content_tools: bool,
17909 base_q_idx: u8,
17910 tx_select: bool,
17911 reduced_tx_set: bool,
17912 fctx: &crate::decode::FrameCtx,
17913) -> Result<()> {
17914 let (r, c) = at;
17915 let (px, py) = (c * SUB, r * SUB);
17916 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
17917 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
17918 let palette_uv_cache = neighbours.palette_uv_cache(at);
17919 let (
17920 skip,
17921 mode,
17922 angle_delta_y,
17923 uv_mode,
17924 angle_delta_uv,
17925 alpha,
17926 filter_intra,
17927 palette_y,
17928 palette_uv,
17929 intrabc,
17930 ) = read_intra_mode_rect(
17931 dec,
17932 cdfs,
17933 nb_above_mode,
17934 nb_left_mode,
17935 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
17936 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
17937 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
17938 // correct), CFL must never be offered here -- passing `true`
17939 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
17940 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
17941 // from this block's very first symbol (lane-sbpart r3 bisect).
17942 false,
17943 true,
17944 bw,
17945 bh,
17946 enable_filter_intra,
17947 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
17948 allow_screen_content_tools,
17949 Some((palette_ctx, &palette_cache)),
17950 &palette_uv_cache,
17951 r * (SUB / MI),
17952 c * (SUB / MI),
17953 fctx,
17954 )?;
17955 if let Some((dv_row, dv_col)) = intrabc {
17956 return decode_intrabc_owned_rect(
17957 dec,
17958 cdfs,
17959 neighbours,
17960 (r * (SUB / MI), c * (SUB / MI)),
17961 (bw, bh),
17962 skip,
17963 (dv_row, dv_col),
17964 y,
17965 u,
17966 v,
17967 base_q_idx,
17968 tx_select,
17969 reduced_tx_set,
17970 fctx,
17971 );
17972 }
17973 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
17974 // lane-t900 r34: a non-skip palette block on a superblock-level strip
17975 // -- counted so its gate cannot go vacuous (this was a refusal until
17976 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
17977 // decodes_pixel_exact`).
17978 hit!(PALETTE_SB_STRIP_HITS);
17979 }
17980 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
17981 if smooth_neighbor {
17982 hit!(SMOOTH_LUMA_HITS);
17983 }
17984 let smooth_neighbor_uv =
17985 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
17986 if filter_intra.is_some() {
17987 // `filter_intra_size_class_rect` already returns `None` for both
17988 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
17989 // 32 on both axes), so this symbol is never read at this level --
17990 // kept only as the same defensive refusal [`decode_block_rect`] has.
17991 return Err(unsupported(
17992 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
17993 av1_filter_intra_allowed_bsize caps at 32x32)",
17994 ));
17995 }
17996 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
17997 DC_PRED
17998 } else {
17999 uv_mode
18000 };
18001 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
18002 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
18003 // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes
18004 // no depth symbol here either (class sweep of the sub8 leaf's fix).
18005 let depth = if tx_select && !lossless(fctx) {
18006 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
18007 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
18008 // intra-only frame publishes them from every block too
18009 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
18010 // 1920x792 128-superblock stream,
18011 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
18012 // `tx_size_cat2` row 1 where libaom reads row 2.
18013 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
18014 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
18015 // counts `sub_tx_size_map` steps from the block's own max rect
18016 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
18017 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
18018 // steps, so this level's category is 3 (the same one a 64x64 square
18019 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
18020 // here was a wrong-table read of a real symbol.
18021 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
18022 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18023 eprintln!(
18024 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
18025 dec.debug_state().0
18026 );
18027 }
18028 d
18029 } else {
18030 0
18031 };
18032 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
18033 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
18034 publish_txfm_bands_if_in_inter(
18035 neighbours,
18036 (mi_r, mi_c),
18037 depth_to_tx_wh(bw, bh, depth, fctx),
18038 (bw, bh),
18039 fctx,
18040 );
18041 if depth != 0 || lossless(fctx) {
18042 hit!(TX_DEPTH_HITS);
18043 // lane-rectsplit r1/r4: the superblock-level strip splits its
18044 // transform through the very same per-unit path as its 32x32-level
18045 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
18046 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
18047 // measured the old square formula mis-tiling exactly that strip).
18048 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
18049 if bw.max(bh) / bw.min(bh) == 4 {
18050 let which = if depth == 1 {
18051 &RECT4_SPLIT_DEPTH1_HITS
18052 } else {
18053 &RECT4_SPLIT_DEPTH2_HITS
18054 };
18055 hit_do! { which.with(|c| c.set(c.get() + 1)); }
18056 }
18057 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
18058 eprintln!(
18059 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
18060 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
18061 angle_y={angle_delta_y}"
18062 );
18063 }
18064 let modes = RectStripModes {
18065 skip,
18066 mode,
18067 angle_delta_y,
18068 uv_predict_mode,
18069 angle_delta_uv,
18070 alpha,
18071 filter_intra,
18072 smooth_neighbor,
18073 smooth_neighbor_uv,
18074 palette_y: palette_y
18075 .as_ref()
18076 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
18077 palette_uv: palette_uv.as_ref().map(|p| {
18078 (
18079 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
18080 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
18081 )
18082 }),
18083 };
18084 if palette_y.is_some() || palette_uv.is_some() {
18085 hit!(PALETTE_SPLIT_TX_HITS);
18086 }
18087 decode_rect_split(
18088 dec,
18089 cdfs,
18090 neighbours,
18091 (mi_r, mi_c),
18092 bw,
18093 bh,
18094 tx_w,
18095 tx_h,
18096 &modes,
18097 y,
18098 u,
18099 v,
18100 base_q_idx,
18101 reduced_tx_set,
18102 fctx,
18103 )?;
18104 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
18105 // (lane-palette2 r10): this return skips the fn's own tail, so a
18106 // split-tx superblock strip would otherwise leave the above/left
18107 // palette arrays holding a dead block's colours.
18108 let (py_size, py_colors) = palette_y
18109 .as_ref()
18110 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
18111 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
18112 let (puv_size, puv_colors) = palette_uv
18113 .as_ref()
18114 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
18115 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
18116 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
18117 // return skips the fn's own tail, so a SPLIT superblock-level strip
18118 // published no TXFM_CONTEXT band and the next block read the row's init
18119 // value 64 as its left transform height. Measured on the 10-bit
18120 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
18121 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
18122 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
18123 // bands carry the SPLIT unit's size, not the block's.
18124 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
18125 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
18126 hit!(RECT_PARTITION_HITS);
18127 return Ok(());
18128 }
18129 let (tx_w, tx_h) = (bw, bh);
18130 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
18131 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
18132 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
18133 if let Some(ref pyv) = palette_y {
18134 let buf: Vec<u16> = pyv
18135 .map
18136 .iter()
18137 .map(|&idx| pyv.colors[idx as usize])
18138 .collect();
18139 set_palette_pred(buf, fctx);
18140 }
18141 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
18142 (
18143 puv.map
18144 .iter()
18145 .map(|&idx| puv.u_colors[idx as usize])
18146 .collect(),
18147 puv.map
18148 .iter()
18149 .map(|&idx| puv.v_colors[idx as usize])
18150 .collect(),
18151 )
18152 });
18153 if skip {
18154 push_intra_rect(
18155 0,
18156 px,
18157 py,
18158 bw,
18159 bh,
18160 mode,
18161 angle_delta_y,
18162 reach,
18163 &ZERO_RESIDUAL[..bw * bh],
18164 None,
18165 filter_intra,
18166 smooth_neighbor,
18167 fctx,
18168 );
18169 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
18170 if let Some((ub, _)) = &palette_uv_bufs {
18171 set_palette_pred(ub.clone(), fctx);
18172 }
18173 push_intra_rect(
18174 1,
18175 cpx,
18176 cpy,
18177 chroma_w,
18178 chroma_h,
18179 uv_predict_mode,
18180 angle_delta_uv,
18181 reach,
18182 &ZERO_RESIDUAL[..chroma_w * chroma_h],
18183 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
18184 None,
18185 smooth_neighbor_uv,
18186 fctx,
18187 );
18188 if let Some((_, vb)) = &palette_uv_bufs {
18189 set_palette_pred(vb.clone(), fctx);
18190 }
18191 push_intra_rect(
18192 2,
18193 cpx,
18194 cpy,
18195 chroma_w,
18196 chroma_h,
18197 uv_predict_mode,
18198 angle_delta_uv,
18199 reach,
18200 &ZERO_RESIDUAL[..chroma_w * chroma_h],
18201 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
18202 None,
18203 smooth_neighbor_uv,
18204 fctx,
18205 );
18206 neighbours.record_rect(
18207 at,
18208 bw,
18209 bh,
18210 mode,
18211 uv_predict_mode,
18212 &[
18213 &ZERO_RESIDUAL[..bw * bh],
18214 &ZERO_RESIDUAL[..chroma_w * chroma_h],
18215 &ZERO_RESIDUAL[..chroma_w * chroma_h],
18216 ],
18217 );
18218 } else {
18219 let around = neighbours.around_rect(at, bw, bh);
18220 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
18221 // (see this function's own doc comment). A 64-length axis codes only
18222 // its low 32 coefficients, so the corner is `min(bw, 32)` x
18223 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
18224 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
18225 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
18226 let scan32 = default_scan(TX32);
18227 if coeff_trace_on() {
18228 let (rng, _) = dec.debug_state();
18229 eprintln!(
18230 "EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}"
18231 );
18232 }
18233 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
18234 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
18235 read_coeffs(
18236 dec,
18237 &mut luma_coding,
18238 &scan32,
18239 0,
18240 dc_sign_ctx(around[0].2),
18241 TxType::DctDct,
18242 Some((bw, bh)),
18243 )?
18244 } else {
18245 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
18246 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
18247 // (`scan.c`) gives both the very same `default_scan_32x16` /
18248 // `default_scan_16x32` the 2:1 sizes use ("Half of the
18249 // coefficients of tx64 at higher frequencies are set to zeros. So
18250 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
18251 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
18252 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
18253 // 512-position eob group) -- BOTH identical to TX_32X16, so the
18254 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
18255 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
18256 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
18257 // what `base_ctx_rect` computes at (32, 16).
18258 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
18259 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
18260 read_coeffs_rect(
18261 dec,
18262 &mut luma_coding,
18263 luma_scan,
18264 luma_cw,
18265 luma_ch,
18266 0,
18267 dc_sign_ctx(around[0].2),
18268 TxType::DctDct,
18269 )?
18270 };
18271 if coeff_trace_on() {
18272 let (rng, _) = dec.debug_state();
18273 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
18274 }
18275 let mut luma_levels = vec![0i32; bw * bh];
18276 for row in 0..luma_ch {
18277 luma_levels[row * bw..][..luma_cw]
18278 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
18279 }
18280 {
18281 let cur = block_q_idx(fctx);
18282 if cur != i32::from(base_q_idx) {
18283 hit!(RECT64_QIDX_DRIFT_HITS);
18284 }
18285 if crate::envflags::env_flag!("EC_AV1_TRACE") {
18286 eprintln!(
18287 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
18288 );
18289 }
18290 }
18291 let luma_residual = dequant_and_inverse_typed_wh(
18292 &luma_levels,
18293 bw,
18294 bh,
18295 crate::decode::bit_depth(fctx),
18296 block_q_idx(fctx),
18297 plane_q_delta(0, fctx).0,
18298 plane_q_delta(0, fctx).1,
18299 luma_tx_type,
18300 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
18301 );
18302 push_intra_rect(
18303 0,
18304 px,
18305 py,
18306 bw,
18307 bh,
18308 mode,
18309 angle_delta_y,
18310 reach,
18311 &luma_residual,
18312 None,
18313 filter_intra,
18314 smooth_neighbor,
18315 fctx,
18316 );
18317 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
18318 let leftcol: Vec<u16> = if px > 0 {
18319 (py..py + bh)
18320 .map(|row| y.data[row * y.width + px - 1])
18321 .collect()
18322 } else {
18323 vec![]
18324 };
18325 eprintln!(
18326 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
18327 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
18328 luma_corner.iter().any(|&v| v != 0),
18329 &y.data[py * y.width + px..][..bw],
18330 leftcol,
18331 );
18332 }
18333 // CHROMA. At 4:2:0 the plane block is already one adjusted UV
18334 // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma
18335 // is larger than that, so it is tiled into 32-capped units.
18336 let _ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
18337 let (uw, uh) = (chroma_w.min(32), chroma_h.min(32));
18338 let (nw, nh) = (chroma_w / uw, chroma_h / uh);
18339 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (uw, uh) {
18340 (32, 32) => (TxbSet::Chroma32, default_scan(32)),
18341 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
18342 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
18343 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8),
18344 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
18345 _ => {
18346 return Err(unsupported(
18347 "a 64-axis strip whose chroma unit has no coefficient table",
18348 ));
18349 }
18350 };
18351 let bigger = nw * nh > 1;
18352 let mut u_levels = vec![0i32; chroma_w * chroma_h];
18353 let mut v_levels = vec![0i32; chroma_w * chroma_h];
18354 // The tiled units below stamp their own coefficient context
18355 // immediately, then the whole-strip `record_rect` rewrite paints
18356 // every chroma cell with ONE whole-strip state and the per-unit DC
18357 // signs and levels are lost (class `override-slot-on-one-arm`, same
18358 // shape as `decode_rect_split`'s chroma_tiled clobber). Collected
18359 // here and replayed after that record, the c8 `mu_chroma_units` way.
18360 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
18361 for plane_idx in 1..=2 {
18362 for cu_row in 0..nh {
18363 for cu_col in 0..nw {
18364 let cu_around = if nw == 1 && nh == 1 {
18365 around
18366 } else {
18367 let lsx = uw << ss_x(fctx);
18368 let lsy = uh << ss_y(fctx);
18369 let cu_mi = (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI));
18370 neighbours.around_mi_rect(cu_mi, lsx, lsy)
18371 };
18372 let lsx = uw << ss_x(fctx);
18373 let lsy = uh << ss_y(fctx);
18374 let cfl = alpha.map(|(au, av)| {
18375 let a = if plane_idx == 1 { au } else { av };
18376 (
18377 a,
18378 cfl_src_rect(px + cu_col * lsx, py + cu_row * lsy, lsx, lsy),
18379 )
18380 });
18381 let levels = if uw == uh {
18382 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
18383 if let Some((ub, vb)) = &palette_uv_bufs {
18384 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
18385 }
18386 read_plane(
18387 dec,
18388 cdfs,
18389 chroma_set,
18390 chroma_scan,
18391 plane_idx,
18392 cu_around[plane_idx],
18393 mode,
18394 uv_predict_mode,
18395 angle_delta_uv,
18396 reach,
18397 plane,
18398 cpx + cu_col * uw,
18399 cpy + cu_row * uh,
18400 uw,
18401 uw,
18402 base_q_idx,
18403 cfl,
18404 None,
18405 bigger.then_some(3),
18406 smooth_neighbor_uv,
18407 fctx,
18408 )?
18409 } else {
18410 let skip_ctx = usize::from(cu_around[plane_idx].0)
18411 + usize::from(cu_around[plane_idx].1)
18412 + usize::from(bigger) * 3;
18413 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
18414 let (levels, tx_type) = read_chroma_coeffs_rect(
18415 dec,
18416 &mut coding,
18417 chroma_scan,
18418 uw,
18419 uh,
18420 skip_ctx,
18421 dc_sign_ctx(cu_around[plane_idx].2),
18422 TxType::DctDct,
18423 fctx,
18424 )?;
18425 let residual = dequant_and_inverse_typed_wh(
18426 &levels,
18427 uw,
18428 uh,
18429 crate::decode::bit_depth(fctx),
18430 block_q_idx(fctx),
18431 plane_q_delta(plane_idx, fctx).0,
18432 plane_q_delta(plane_idx, fctx).1,
18433 tx_type,
18434 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
18435 );
18436 if let Some((ub, vb)) = &palette_uv_bufs {
18437 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
18438 }
18439 push_intra_rect(
18440 plane_idx,
18441 cpx + cu_col * uw,
18442 cpy + cu_row * uh,
18443 uw,
18444 uh,
18445 uv_predict_mode,
18446 angle_delta_uv,
18447 reach,
18448 &residual,
18449 cfl,
18450 None,
18451 smooth_neighbor_uv,
18452 fctx,
18453 );
18454 levels
18455 };
18456 let dst = if plane_idx == 1 {
18457 &mut u_levels
18458 } else {
18459 &mut v_levels
18460 };
18461 for row in 0..uh {
18462 let d = (cu_row * uh + row) * chroma_w + cu_col * uw;
18463 dst[d..d + uw].copy_from_slice(&levels[row * uw..][..uw]);
18464 }
18465 if bigger {
18466 neighbours.record_mi_chroma(
18467 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
18468 lsx,
18469 lsy,
18470 plane_idx,
18471 &levels,
18472 );
18473 tiled_chroma_units.push((
18474 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
18475 plane_idx,
18476 levels.clone(),
18477 lsx,
18478 lsy,
18479 ));
18480 }
18481 }
18482 }
18483 }
18484 neighbours.record_rect(
18485 at,
18486 bw,
18487 bh,
18488 mode,
18489 uv_predict_mode,
18490 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
18491 );
18492 // The per-unit re-stamp: `record_rect` above wrote the whole strip's
18493 // chroma cells from the assembled grids' one whole-strip state,
18494 // overwriting exactly the stamps the tiled loop just made.
18495 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
18496 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
18497 }
18498 hit!(RECT_COEFF_HITS);
18499 }
18500 let (py_size, py_colors) = palette_y
18501 .as_ref()
18502 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
18503 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
18504 let (puv_size, puv_colors) = palette_uv
18505 .as_ref()
18506 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
18507 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
18508 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
18509 neighbours.fill_lf_grid_rect(
18510 (mi_r, mi_c),
18511 bw / MI,
18512 bh / MI,
18513 tx_w as u8,
18514 tx_h as u8,
18515 0,
18516 fctx,
18517 );
18518 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
18519 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
18520 // frame): the above row records `tx_size_wide` over the block's width and
18521 // the left column `tx_size_high` over its height. This 1:4 strip reader is
18522 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
18523 // and it published neither band -- so the block after a 64x16 strip read
18524 // the row's init value 64 as its left transform height and took
18525 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
18526 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
18527 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
18528 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
18529 hit!(SB_RECT_HITS);
18530 match (bw, bh) {
18531 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
18532 (16, 64) => hit!(SB_RECT4_VERT_HITS),
18533 _ => {}
18534 }
18535 if crate::envflags::env_flag!("EC_AV1_TRACE") {
18536 let (rng, _) = dec.debug_state();
18537 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
18538 }
18539 Ok(())
18540}
18541
18542/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
18543/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
18544/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
18545/// it lands away from zero, for gate tests to prove a real stream fired one.
18546fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
18547 let symbol = dec.symbol(cdf);
18548 if symbol != ANGLE_DELTA_ZERO {
18549 hit!(ANGLE_DELTA_HITS);
18550 }
18551 symbol as i32 - ANGLE_DELTA_ZERO as i32
18552}
18553
18554#[allow(clippy::too_many_arguments)]
18555fn read_intra_mode(
18556 dec: &mut SymbolDecoder,
18557 cdfs: &mut Cdfs,
18558 above_mode: usize,
18559 left_mode: usize,
18560 cfl: bool,
18561 side: usize,
18562 enable_filter_intra: bool,
18563 skip_ctx: usize,
18564 allow_screen_content_tools: bool,
18565 allow_intrabc: bool,
18566 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
18567 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
18568 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
18569 // `None` at the excluded call sites (the 8x8-leaf path), which still read
18570 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
18571 // decoder reads either way -- but refuse by name the moment it fires,
18572 // exactly the old behaviour.
18573 palette: Option<(usize, &[u16])>,
18574 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
18575 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
18576 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
18577 // `use_palette_y`, not a neighbour lookup).
18578 palette_uv_cache: &[u16],
18579 mi_r: usize,
18580 mi_c: usize,
18581 fctx: &crate::decode::FrameCtx,
18582) -> Result<(
18583 bool,
18584 usize,
18585 i32,
18586 usize,
18587 i32,
18588 Option<(i32, i32)>,
18589 Option<usize>,
18590 Option<PaletteY>,
18591 Option<PaletteUv>,
18592)> {
18593 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
18594 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
18595 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
18596 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
18597 // line against the instrumented aomdec, not just `tell()`.
18598 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
18599 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
18600 if ec_istep {
18601 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
18602 // (decodemv.c:818), printed at the same point: before the first
18603 // mode-info symbol of the block, so a cross-decoder range ladder can
18604 // be keyed on the BLOCK, not just on the symbol sequence.
18605 eprintln!(
18606 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}",
18607 dec.debug_state().0
18608 );
18609 }
18610 macro_rules! istep {
18611 ($name:literal, $val:expr) => {
18612 if ec_istep {
18613 let (rng, _) = dec.debug_state();
18614 eprintln!(
18615 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
18616 $name, $val
18617 );
18618 }
18619 };
18620 }
18621 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
18622 // point every square caller routes through (see `read_intra_mode_rect`).
18623 let cfl = if cfl && side > 32 {
18624 hit!(NOCFL_UV_MODE_HITS);
18625 false
18626 } else {
18627 cfl
18628 };
18629 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
18630 // `skip` when `SegIdPreSkip`, and after it otherwise.
18631 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
18632 if seg_id_pre_skip(fctx) {
18633 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
18634 }
18635 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
18636 if trace {
18637 eprintln!(
18638 "TRACE skip value={} rng={}",
18639 skip as i32,
18640 dec.debug_state().0
18641 );
18642 }
18643 istep!("skip", skip as i32);
18644 if !seg_id_pre_skip(fctx) {
18645 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
18646 }
18647 // spec order (see the comment below on `read_intrabc_info`): `skip`,
18648 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
18649 maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
18650 istep!("cdef", 0);
18651 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
18652 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
18653 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
18654 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
18655 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
18656 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
18657 istep!("dq", 0);
18658 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
18659 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
18660 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
18661 // intra frame whose header set `allow_intrabc`. Actual intra block copy
18662 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
18663 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
18664 // draws the line at consuming this one flag symbol and refusing by name
18665 // when it fires, so the arithmetic decoder still resyncs for a stream
18666 // that merely allows (but never uses) intrabc.
18667 if allow_intrabc {
18668 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
18669 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18670 eprintln!(
18671 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
18672 u8::from(use_intrabc),
18673 dec.debug_state().0
18674 );
18675 }
18676 if trace {
18677 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
18678 }
18679 if use_intrabc {
18680 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);
18681 if trace {
18682 eprintln!("TRACE intrabc dv={dv:?}");
18683 }
18684 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
18685 hit!(INTRABC_HITS);
18686 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
18687 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
18688 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
18689 // `DC_PRED` (which is also what the neighbour mode contexts and
18690 // the loop filter then see).
18691 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
18692 }
18693 }
18694 let above_ctx = INTRA_MODE_CTX[above_mode];
18695 let left_ctx = INTRA_MODE_CTX[left_mode];
18696 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
18697 if trace {
18698 eprintln!(
18699 "TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
18700 dec.debug_state().0
18701 );
18702 }
18703 istep!("mode", mode as i32);
18704 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
18705 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
18706 if trace {
18707 eprintln!(
18708 "TRACE angle_delta value={}",
18709 delta + ANGLE_DELTA_ZERO as i32
18710 );
18711 }
18712 delta
18713 } else {
18714 0
18715 };
18716 istep!("angle_y", angle_delta_y);
18717 // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette
18718 // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref`
18719 // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader
18720 // gates its chroma symbols on.
18721 let has_chroma = !mono(fctx);
18722 let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx);
18723 let uv_mode = if !has_chroma {
18724 DC_PRED
18725 } else if cfl {
18726 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
18727 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
18728 } else {
18729 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
18730 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
18731 };
18732 if trace {
18733 eprintln!(
18734 "TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}",
18735 dec.debug_state().0
18736 );
18737 }
18738 istep!("uv_mode", uv_mode as i32);
18739 let alpha = if cfl && uv_mode == UV_CFL_PRED {
18740 Some(read_cfl_alphas(dec, cdfs))
18741 } else {
18742 None
18743 };
18744 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
18745 // from this lane's directional chroma: a corner block with neither
18746 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
18747 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
18748 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
18749 // bug in that fallback this lane's own scope does not cover. Keep it
18750 // refused here rather than ship a silently-wrong decode.
18751 if (9..=12).contains(&uv_mode) {
18752 hit!(SMOOTH_UV_HITS);
18753 }
18754 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
18755 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
18756 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
18757 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
18758 // the `else` branch below and never reads one either way.
18759 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
18760 hit!(DIRECTIONAL_UV_HITS);
18761 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
18762 } else {
18763 0
18764 };
18765 istep!("angle_uv", angle_delta_uv);
18766 if angle_delta_uv != 0 {
18767 hit!(UV_ANGLE_DELTA_HITS);
18768 }
18769 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
18770 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
18771 // gated by `av1_allow_palette` (blockd.h -- size bound only,
18772 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
18773 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
18774 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
18775 // read the same CDF row whenever every neighbour really is non-palette).
18776 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
18777 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
18778 // neighbour lookup at all), so it is exact even at the excluded call
18779 // sites once Y decodes real syntax there too.
18780 //
18781 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
18782 // inline from `read_palette_mode_info` -- it runs later, from
18783 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
18784 // after the WHOLE mode-info read for the block, including UV palette
18785 // mode_info (`read_palette_mode_info`'s own second half, right below)
18786 // and `read_filter_intra_mode_info`. So this branch now only reads
18787 // mode/size/colours for both planes (deferring the two colour-index-map
18788 // decodes to after `filter_intra`, below) -- r6's range trace pinned
18789 // this exact ordering bug (`compare-range-not-tell`: ranges matched
18790 // bit-for-bit through the Y colours, diverged only at the old inline
18791 // `decode_color_index_map` call).
18792 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
18793 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
18794 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) {
18795 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
18796 if mode == DC_PRED {
18797 if trace {
18798 let (rng, _) = dec.debug_state();
18799 eprintln!(
18800 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
18801 );
18802 }
18803 }
18804 let use_palette_y =
18805 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
18806 if mode == DC_PRED && trace {
18807 let (rng, _) = dec.debug_state();
18808 eprintln!(
18809 "TRACE palette_y_mode value={} rng={rng}",
18810 use_palette_y as i32
18811 );
18812 }
18813 if use_palette_y {
18814 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
18815 if trace {
18816 let (rng, _) = dec.debug_state();
18817 eprintln!("TRACE palette_y_size n={n} rng={rng}");
18818 }
18819 let colors = read_palette_colors_y(dec, n, cache, fctx);
18820 if trace {
18821 let (rng, _) = dec.debug_state();
18822 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
18823 }
18824 palette_y_pending = Some((n, colors));
18825 }
18826 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
18827 // unconditionally at this bit position whenever `uv_mode ==
18828 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
18829 // scope always reconstructs chroma alongside luma (`decode_block`
18830 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
18831 // is always true here and does not need threading in.
18832 //
18833 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
18834 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a
18835 // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size`
18836 // symbol even at this chroma-owning square block.
18837 let palette_uv_mode_ctx = usize::from(use_palette_y);
18838 if has_chroma
18839 && uv_mode == DC_PRED
18840 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
18841 {
18842 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
18843 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
18844 palette_uv_pending = Some((n, u_colors, v_colors));
18845 }
18846 }
18847 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
18848 // `use_filter_intra` symbol this decoder never read at all until
18849 // lane-av1real r10 -- silently skipping it left every bit past a
18850 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
18851 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
18852 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
18853 // symbol's bits were never consumed).
18854 let mut filter_intra = None;
18855 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
18856 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
18857 // `use_filter_intra` symbol for a Y-palette block, and reading one here
18858 // desynced every screen-content stream from the first palette block on
18859 // (it surfaced as a bogus "partition below 8x8" refusal further down the
18860 // tile).
18861 if mode == DC_PRED
18862 && enable_filter_intra
18863 && palette_y_pending.is_none()
18864 && let Some(class) = filter_intra_size_class(side)
18865 {
18866 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
18867 if trace {
18868 eprintln!(
18869 "TRACE use_filter_intra side={side} rng={} value={}",
18870 dec.debug_state().0,
18871 use_filter_intra as i32
18872 );
18873 }
18874 istep!("use_filter_intra", use_filter_intra as i32);
18875 if use_filter_intra {
18876 hit!(FILTER_INTRA_HITS);
18877 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
18878 if trace {
18879 eprintln!("TRACE filter_intra_mode value={fi_mode}");
18880 }
18881 istep!("filter_intra_mode", fi_mode as i32);
18882 filter_intra = Some(fi_mode);
18883 }
18884 }
18885 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
18886 // shared U/V map) -- the same order libaom's own loop visits them in.
18887 let palette_y = palette_y_pending.map(|(n, colors)| {
18888 let map = decode_color_index_map(
18889 dec,
18890 cdfs,
18891 n,
18892 side,
18893 palette_onscreen(mi_r, mi_c, side, side, fctx),
18894 false,
18895 );
18896 hit!(PALETTE_HITS);
18897 if trace {
18898 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
18899 }
18900 PaletteY {
18901 size: n,
18902 colors,
18903 map,
18904 }
18905 });
18906 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
18907 let on = palette_onscreen_uv(
18908 (side, side),
18909 palette_onscreen(mi_r, mi_c, side, side, fctx),
18910 (side >> ss_x(fctx), side >> ss_y(fctx)),
18911 (ss_x(fctx), ss_y(fctx)),
18912 );
18913 // lane-av1-422d: the chroma map's extent is the PLANE BLOCK
18914 // `(side >> ss_x) x (side >> ss_y)` -- 4x8 at ss (1,0), not the
18915 // square call's `(side >> ss_x)`-squared (4x4), which left a
18916 // 16-entry map for a 32-sample unit and panicked the reconstruct.
18917 let map = decode_color_index_map_wh(
18918 dec,
18919 cdfs,
18920 n,
18921 side >> ss_x(fctx),
18922 side >> ss_y(fctx),
18923 on,
18924 true,
18925 );
18926 hit!(PALETTE_UV_HITS);
18927 if trace {
18928 eprintln!(
18929 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
18930 &u_colors[..n],
18931 &v_colors[..n]
18932 );
18933 }
18934 PaletteUv {
18935 size: n,
18936 u_colors,
18937 v_colors,
18938 map,
18939 }
18940 });
18941 Ok((
18942 skip,
18943 mode,
18944 angle_delta_y,
18945 uv_mode,
18946 angle_delta_uv,
18947 alpha,
18948 filter_intra,
18949 palette_y,
18950 palette_uv,
18951 ))
18952}
18953
18954/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
18955/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
18956/// intra modes.
18957const UV_CFL_PRED: usize = 13;
18958
18959/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
18960/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
18961/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
18962/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
18963/// joint sign the same way. Returns each plane's final signed `alpha_q3`
18964/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
18965fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
18966 hit!(CFL_BLOCK_HITS);
18967 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
18968 let sign_u = ((joint_sign + 1) * 11) >> 5;
18969 let sign_v = (joint_sign + 1) - 3 * sign_u;
18970 let alpha_u = if sign_u == 0 {
18971 0
18972 } else {
18973 let ctx_u = (joint_sign + 1 - 3) as usize;
18974 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
18975 if sign_u == 2 { mag } else { -mag }
18976 };
18977 let alpha_v = if sign_v == 0 {
18978 0
18979 } else {
18980 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
18981 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
18982 if sign_v == 2 { mag } else { -mag }
18983 };
18984 (alpha_u, alpha_v)
18985}
18986
18987/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
18988/// the reconstructed luma samples under a `side`-square block, subsampled
18989/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
18990/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
18991/// to give the AC values [`cfl_scaled`] scales by alpha.
18992fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
18993 cfl_ac_q3_at(px, py, side, side, |lx, ly| {
18994 i32::from(y.data[ly * y.width + lx])
18995 })
18996}
18997
18998/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
18999/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
19000/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
19001/// reconstruction through THIS function rather than a second transcription of
19002/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
19003/// CfL AC at the frame's subsampling. 4:2:0 keeps the 2x2 average; 4:4:4
19004/// copies each luma sample shifted to Q3 (`cfl_luma_subsampling_444_lbd`).
19005fn cfl_ac_ss(
19006 y: &PlaneBuf<'_>,
19007 px: usize,
19008 py: usize,
19009 bw: usize,
19010 bh: usize,
19011 ss_x: usize,
19012 ss_y: usize,
19013) -> Vec<i32> {
19014 if ss_x == 0 && ss_y == 0 {
19015 let mut ac = vec![0i32; bw * bh];
19016 let mut sum = 0i32;
19017 for row in 0..bh {
19018 for col in 0..bw {
19019 let q3 = i32::from(y.data[(py + row) * y.width + px + col]) << 3;
19020 ac[row * bw + col] = q3;
19021 sum += q3;
19022 }
19023 }
19024 let num_pel = (bw * bh) as i32;
19025 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
19026 ac.iter_mut().for_each(|v| *v -= avg);
19027 ac
19028 } else if ss_x == 1 && ss_y == 0 {
19029 // lane-av1-422: `cfl_luma_subsampling_422_lbd_c` -- each chroma sample
19030 // averages the HORIZONTAL luma pair above it, at full chroma height
19031 // (`(a + b) >> 1` in Q3 is `(a + b) << 2`). A rect luma strip's chroma
19032 // is square here, and the 4:2:0 rect/square helpers below would halve
19033 // the height it must keep.
19034 let (cw, ch) = (bw >> 1, bh);
19035 let mut ac = vec![0i32; cw * ch];
19036 let mut sum = 0i32;
19037 for row in 0..ch {
19038 for col in 0..cw {
19039 let (lx, ly) = (px + col * 2, py + row);
19040 let q3 = (i32::from(y.data[ly * y.width + lx])
19041 + i32::from(y.data[ly * y.width + lx + 1]))
19042 << 2;
19043 ac[row * cw + col] = q3;
19044 sum += q3;
19045 }
19046 }
19047 let num_pel = (cw * ch) as i32;
19048 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
19049 ac.iter_mut().for_each(|v| *v -= avg);
19050 ac
19051 } else if bw == bh {
19052 cfl_ac_q3(y, px, py, bw)
19053 } else {
19054 cfl_ac_q3_rect(y, px, py, bw, bh)
19055 }
19056}
19057
19058pub(crate) fn cfl_ac_q3_at(
19059 px: usize,
19060 py: usize,
19061 bw: usize,
19062 bh: usize,
19063 sample: impl Fn(usize, usize) -> i32,
19064) -> Vec<i32> {
19065 let (cw, ch) = (bw / 2, bh / 2);
19066 let mut ac = vec![0i32; cw * ch];
19067 let mut sum = 0i32;
19068 for cy in 0..ch {
19069 for cx in 0..cw {
19070 let (lx, ly) = (px + cx * 2, py + cy * 2);
19071 let q3 =
19072 (sample(lx, ly) + sample(lx + 1, ly) + sample(lx, ly + 1) + sample(lx + 1, ly + 1))
19073 << 1;
19074 ac[cy * cw + cx] = q3;
19075 sum += q3;
19076 }
19077 }
19078 let num_pel = (cw * ch) as i32;
19079 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
19080 ac.iter_mut().for_each(|v| *v -= avg);
19081 ac
19082}
19083
19084/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
19085/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
19086/// ties away from zero on the shifted-out sign).
19087pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
19088 let v = alpha_q3 * ac_q3;
19089 if v >= 0 {
19090 (v + 32) >> 6
19091 } else {
19092 -((-v + 32) >> 6)
19093 }
19094}
19095
19096/// One plane's reconstruction buffer, `width * height` samples, and the
19097/// prediction/residual reads and writes into it — the decode-side twin of
19098/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
19099/// (own-edge and reach clamps both), passing what it gathers straight to
19100/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
19101/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
19102/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
19103/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
19104/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
19105/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
19106/// lane-mc64 r1: the decode-order index the stage dumps below key their file
19107/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
19108/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
19109/// without this every frame overwrote `.f0` and a per-frame bisection silently
19110/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
19111#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
19112fn stage_dump_idx() -> usize {
19113 PREFILT_PICTURE_IDX
19114 .load(std::sync::atomic::Ordering::SeqCst)
19115 .saturating_sub(1)
19116}
19117
19118fn dump_stage16(
19119 var: &str,
19120 y: &PlaneBuf<'_>,
19121 u: &PlaneBuf<'_>,
19122 v: &PlaneBuf<'_>,
19123 fw: usize,
19124 fh: usize,
19125) {
19126 use std::io::Write;
19127 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
19128 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
19129 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
19130 // not be read out at all.
19131 if let Ok(path) = crate::envflags::var(var)
19132 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
19133 {
19134 for (p, w, h) in [
19135 (y, fw, fh),
19136 (u, fw.div_ceil(2), fh.div_ceil(2)),
19137 (v, fw.div_ceil(2), fh.div_ceil(2)),
19138 ] {
19139 for row in 0..h {
19140 let mut bytes = Vec::with_capacity(w * 2);
19141 for &s in &p.data[row * p.width..][..w] {
19142 bytes.extend_from_slice(&s.to_le_bytes());
19143 }
19144 let _ = f.write_all(&bytes);
19145 }
19146 }
19147 }
19148}
19149
19150/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
19151/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
19152/// every frame overwrote the previous one and only the LAST frame survived,
19153/// which silently defeats any per-frame filter-stage bisection.
19154fn dump_stage_idx(var: &str) -> usize {
19155 use std::collections::HashMap;
19156 use std::sync::{Mutex, OnceLock};
19157 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
19158 let mut m = IDX
19159 .get_or_init(|| Mutex::new(HashMap::new()))
19160 .lock()
19161 .unwrap();
19162 let e = m.entry(var.to_string()).or_insert(0);
19163 let i = *e;
19164 *e += 1;
19165 i
19166}
19167
19168fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
19169 use std::io::Write;
19170 if let Ok(path) = crate::envflags::var(var)
19171 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
19172 {
19173 for p in [y, u, v] {
19174 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
19175 let _ = f.write_all(&narrow);
19176 }
19177 }
19178}
19179
19180/// `EC_AV1_PREFILT_WIDE_DUMP=<prefix>` -> `<prefix>.f<N>`, the pre-loop-filter
19181/// reconstruction cropped to each plane's mi-ALIGNED true extent, byte for
19182/// byte the shape aomdec's own rung 7 writes (`y_width`/`y_height`,
19183/// `uv_width`/`uv_height`), so the two can be diffed directly.
19184///
19185/// lane-av1444edge: this used to be an inline block in the KEY-frame tile path
19186/// only, with a FUNCTION-LOCAL `static IDX2` as its counter. Both facts were
19187/// measurement traps, and the second one is why the first went unnoticed:
19188/// the inter-frame path (`decode_inter_frame_tile_with_cdfs`) had no wide
19189/// prefilter dump at all, so every 4:4:4 lossy divergence localized to an
19190/// inter frame had no pre-filter rung to compare against and got attributed to
19191/// reconstruction when the oracle could not see it. The `static` also restarted
19192/// per monomorphisation, so every frame after the first overwrote `.f0` -- a
19193/// per-frame bisection silently compared the LAST decoded frame. The counter
19194/// is now the shared per-var [`dump_stage_idx`] map, and the call also sits on
19195/// the inter path (skipped when the filter pipeline is active, which has
19196/// already deblocked by the time the tile tail runs -- same condition
19197/// `capture_filter_replay` guards itself with).
19198fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
19199 let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") else {
19200 return;
19201 };
19202 use std::io::Write;
19203 let idx = dump_stage_idx("EC_AV1_PREFILT_WIDE_DUMP");
19204 let crop = |plane: &PlaneBuf<'_>| -> Vec<u8> {
19205 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
19206 for row in 0..plane.true_height {
19207 out.extend(
19208 plane.data[row * plane.width..][..plane.true_width]
19209 .iter()
19210 .map(|&s| s as u8),
19211 );
19212 }
19213 out
19214 };
19215 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
19216 let _ = f.write_all(&crop(y));
19217 let _ = f.write_all(&crop(u));
19218 let _ = f.write_all(&crop(v));
19219 }
19220}
19221
19222/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
19223/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
19224/// at most 4095), so a decode that hashes identically under the flag proves
19225/// the output does not depend on the plane buffer's initial content.
19226const PLANE_SENTINEL: u16 = 0xDEAD;
19227
19228/// A frame plane's own backing store, `n` samples, UNINITIALISED.
19229///
19230/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
19231/// by the tile walk's reconstruction before anything reads it, so the
19232/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
19233/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
19234/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
19235/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
19236/// ways (see the lane report) and the two agree, which is the proof that no
19237/// unwritten sample reaches the output.
19238fn fresh_plane(n: usize) -> Vec<u16> {
19239 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
19240 return vec![PLANE_SENTINEL; n];
19241 }
19242 let mut v: Vec<u16> = Vec::with_capacity(n);
19243 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
19244 // capacity was just reserved, so the vector owns `n` initialised-or-not
19245 // `u16` slots. Every one is written by reconstruction before it is read
19246 // (proven by the sentinel gate above).
19247 #[allow(unsafe_code)]
19248 unsafe {
19249 v.set_len(n);
19250 }
19251 v
19252}
19253
19254#[derive(Clone)]
19255struct PlaneBuf<'a> {
19256 data: std::borrow::Cow<'a, [u16]>,
19257 width: usize,
19258 height: usize,
19259 /// The frame's true, decodable extent in this plane's own units — past
19260 /// this, samples are the padded coding surface's invented tail, never a
19261 /// real decoder's edge or reach reads.
19262 true_width: usize,
19263 true_height: usize,
19264 /// This plane's own tile's top-left pixel origin (spec: intra prediction
19265 /// never reaches across a tile boundary even though an earlier-decoded
19266 /// tile's real pixels sit right there in the shared buffer) — set via
19267 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
19268 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
19269 /// is threaded (the two-tile column-split stage 1 fixture's tile always
19270 /// ends at the frame's own right/bottom edge); a non-last tile's own
19271 /// right/bottom reach bound is still open, tracked in the report.
19272 tile_x0: usize,
19273 tile_y0: usize,
19274 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
19275 /// (exclusive) -- a non-last tile column/row's own reach must stop at
19276 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
19277 /// full padded extent) for the single-tile/last-tile case, matching the
19278 /// old unclipped behaviour exactly.
19279 tile_x1: usize,
19280 tile_y1: usize,
19281}
19282
19283/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
19284/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
19285/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
19286/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
19287/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
19288/// `ALTREF2`/`ALTREF`).
19289
19290impl PlaneBuf<'_> {
19291 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
19292 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
19293 /// are already in this plane's own units (luma pixels for `y`, chroma
19294 /// pixels — halved — for `u`/`v`).
19295 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
19296 self.tile_x0 = x0;
19297 self.tile_y0 = y0;
19298 self.tile_x1 = x1;
19299 self.tile_y1 = y1;
19300 }
19301
19302 fn edges(
19303 &self,
19304 x: usize,
19305 y: usize,
19306 side: usize,
19307 reach: Reach,
19308 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
19309 let own_across = x + side.min(self.true_width.saturating_sub(x));
19310 let across = if reach.above_right {
19311 own_across + side.min(self.true_width.saturating_sub(own_across))
19312 } else {
19313 own_across
19314 }
19315 .min(self.width)
19316 .min(self.tile_x1);
19317 let own_down = y + side.min(self.true_height.saturating_sub(y));
19318 let down = if reach.below_left {
19319 own_down + side.min(self.true_height.saturating_sub(own_down))
19320 } else {
19321 own_down
19322 }
19323 .min(self.height)
19324 .min(self.tile_y1);
19325 let above = (y > self.tile_y0 && across > x)
19326 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
19327 let left = (x > self.tile_x0 && down > y).then(|| {
19328 (y..down)
19329 .map(|row| self.data[row * self.width + x - 1])
19330 .collect::<Vec<_>>()
19331 });
19332 let corner =
19333 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
19334 (above, left, corner)
19335 }
19336
19337 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
19338 /// the above/left reach each extend by their OWN axis (`bw` across,
19339 /// `bh` down), not one shared `side`.
19340 fn edges_rect(
19341 &self,
19342 x: usize,
19343 y: usize,
19344 bw: usize,
19345 bh: usize,
19346 reach: Reach,
19347 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
19348 let own_across = x + bw.min(self.true_width.saturating_sub(x));
19349 let across = if reach.above_right {
19350 own_across + bw.min(self.true_width.saturating_sub(own_across))
19351 } else {
19352 own_across
19353 }
19354 .min(self.width)
19355 .min(self.tile_x1);
19356 let own_down = y + bh.min(self.true_height.saturating_sub(y));
19357 let down = if reach.below_left {
19358 own_down + bh.min(self.true_height.saturating_sub(own_down))
19359 } else {
19360 own_down
19361 }
19362 .min(self.height)
19363 .min(self.tile_y1);
19364 let above = (y > self.tile_y0 && across > x)
19365 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
19366 let left = (x > self.tile_x0 && down > y).then(|| {
19367 (y..down)
19368 .map(|row| self.data[row * self.width + x - 1])
19369 .collect::<Vec<_>>()
19370 });
19371 let corner =
19372 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
19373 if matches!((bw, bh), (16, 8) | (8, 16)) {
19374 hit!(RECT_STRIP_PRED_HITS);
19375 if across > own_across || down > own_down {
19376 hit!(RECT_STRIP_REACH_HITS);
19377 }
19378 }
19379 (above, left, corner)
19380 }
19381
19382 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
19383 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
19384 /// already-rect-capable `(bw, bh)` pair.
19385 #[allow(clippy::too_many_arguments)]
19386 #[track_caller]
19387 fn reconstruct_rect(
19388 &mut self,
19389 x: usize,
19390 y: usize,
19391 bw: usize,
19392 bh: usize,
19393 mode: usize,
19394 angle_delta: i32,
19395 reach: Reach,
19396 residual: &[i32],
19397 cfl: Option<(i32, &[i32])>,
19398 filter_intra: Option<usize>,
19399 smooth_neighbor: bool,
19400 // lane-wave1 step (i): the palette/intrabc prediction override, taken
19401 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
19402 // than by this replay.
19403 pred: Option<Vec<u16>>,
19404 fctx: &crate::decode::FrameCtx,
19405 ) {
19406 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
19407 // (lane-palette2 r4): a palette block's prediction is the
19408 // reconstructed colour-index map, needing no edge pixels at all.
19409 let prediction = if let Some(buf) = pred {
19410 buf
19411 } else {
19412 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
19413 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
19414 eprintln!(
19415 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
19416 above.as_ref().map(|a| (a.len(), a[0])),
19417 left.as_ref().map(|l| l.len()),
19418 left.as_ref().map(|l| l[0]),
19419 self.tile_x0,
19420 self.tile_y0,
19421 self.true_width,
19422 self.true_height
19423 );
19424 }
19425 let mut prediction = vec![0u16; bw * bh];
19426 if let Some(fi_mode) = filter_intra {
19427 crate::intra::predict_filter_intra(
19428 fi_mode,
19429 above.as_deref(),
19430 left.as_deref(),
19431 corner,
19432 bw,
19433 bh,
19434 &mut prediction,
19435 fctx,
19436 );
19437 } else {
19438 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
19439 predict(
19440 mode as u8,
19441 angle_delta,
19442 above.as_deref(),
19443 left.as_deref(),
19444 corner,
19445 bw,
19446 bh,
19447 enable_edge_filter,
19448 smooth_neighbor,
19449 &mut prediction,
19450 fctx,
19451 );
19452 }
19453 prediction
19454 };
19455 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
19456 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
19457 if crate::envflags::env_flag!("EC_PRED") {
19458 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
19459 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
19460 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
19461 eprintln!(
19462 "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
19463 std::panic::Location::caller(),
19464 i32::from(smooth_neighbor)
19465 );
19466 }
19467 let residual = dense_residual(residual, bw * bh);
19468 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
19469 let res0: Vec<i32> = residual[..bw.min(8)].to_vec();
19470 let pred0: Vec<u16> = prediction[..bw.min(8)].to_vec();
19471 eprintln!(
19472 "DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}"
19473 );
19474 }
19475 for row in 0..bh {
19476 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
19477 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
19478 // whose padded width is not superblock aligned hangs past it.
19479 if y + row >= self.height {
19480 break;
19481 }
19482 for col in 0..bw {
19483 if x + col >= self.width {
19484 break;
19485 }
19486 let idx = row * bw + col;
19487 let mut base = i32::from(prediction[idx]);
19488 if let Some((alpha_q3, ac_q3)) = cfl {
19489 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
19490 }
19491 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
19492 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
19493 }
19494 }
19495 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
19496 // -- a block whose prediction matches the oracle's but whose written
19497 // samples do not is either a residual defect or a later overwrite, and
19498 // only this print separates the two.
19499 if crate::envflags::env_flag!("EC_PRED") {
19500 let row0: Vec<u16> = (0..bw.min(8))
19501 .map(|c| self.data[y * self.width + x + c])
19502 .collect();
19503 let col0: Vec<u16> = (0..bh.min(8))
19504 .map(|r| self.data[(y + r) * self.width + x])
19505 .collect();
19506 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
19507 }
19508 }
19509
19510 /// Predicts under `mode` then adds `residual` (side*side, raster),
19511 /// writing the clamped reconstruction back into the plane at `(x, y)`.
19512 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
19513 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
19514 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
19515 /// order (cfl.c).
19516 #[track_caller]
19517 fn reconstruct(
19518 &mut self,
19519 x: usize,
19520 y: usize,
19521 side: usize,
19522 mode: usize,
19523 angle_delta: i32,
19524 reach: Reach,
19525 residual: &[i32],
19526 cfl: Option<(i32, &[i32])>,
19527 filter_intra: Option<usize>,
19528 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
19529 // libaom `get_filt_type`): true when the block's above OR left
19530 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
19531 // Callers pass their own plane's neighbour-mode check
19532 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
19533 // callers until a smooth/paeth `uv_mode` can reach this call at all
19534 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
19535 // keeps `false` exact for chroma without this fn needing to know why.
19536 smooth_neighbor: bool,
19537 // lane-wave1 step (i): the palette/intrabc prediction override, taken
19538 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
19539 // than by this replay.
19540 pred: Option<Vec<u16>>,
19541 fctx: &crate::decode::FrameCtx,
19542 ) {
19543 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
19544 // takes priority over `predict()`/`predict_filter_intra` entirely --
19545 // palette prediction needs no edge pixels at all.
19546 let prediction = if let Some(buf) = pred {
19547 buf
19548 } else {
19549 let (above, left, corner) = self.edges(x, y, side, reach);
19550 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
19551 eprintln!(
19552 "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}",
19553 above.as_deref(),
19554 left.as_deref(),
19555 );
19556 }
19557 let mut prediction = vec![0u16; side * side];
19558 if let Some(fi_mode) = filter_intra {
19559 crate::intra::predict_filter_intra(
19560 fi_mode,
19561 above.as_deref(),
19562 left.as_deref(),
19563 corner,
19564 side,
19565 side,
19566 &mut prediction,
19567 fctx,
19568 );
19569 } else {
19570 // `enable_intra_edge_filter` is the sequence header's own flag
19571 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
19572 // call, never per-block) -- threading it through every
19573 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
19574 // dozen sites for a value that never changes mid-decode, so it
19575 // rides a thread-local instead (this decoder is single-threaded
19576 // per stream).
19577 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
19578 predict(
19579 mode as u8,
19580 angle_delta,
19581 above.as_deref(),
19582 left.as_deref(),
19583 corner,
19584 side,
19585 side,
19586 enable_edge_filter,
19587 smooth_neighbor,
19588 &mut prediction,
19589 fctx,
19590 );
19591 }
19592 prediction
19593 };
19594 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
19595 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
19596 if crate::envflags::env_flag!("EC_PRED") {
19597 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
19598 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
19599 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
19600 eprintln!(
19601 "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
19602 std::panic::Location::caller(),
19603 i32::from(smooth_neighbor)
19604 );
19605 }
19606 let residual = dense_residual(residual, side * side);
19607 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
19608 let res0: Vec<i32> = residual[..side.min(8)].to_vec();
19609 let pred0: Vec<u16> = prediction[..side.min(8)].to_vec();
19610 eprintln!(
19611 "DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}",
19612 cfl.is_some()
19613 );
19614 }
19615 for row in 0..side {
19616 // lane-sb128c r8: libaom's frame buffer is superblock
19617 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
19618 // transform unit of a 128x64 block at the BOTTOM frame edge
19619 // can hang past the last padded row (1920x792: a unit at
19620 // y=768 wants 832 rows of an 800-row buffer, which panicked
19621 // the film's key frames). Those samples are outside the
19622 // frame: never output, and no block below ever references
19623 // them.
19624 if y + row >= self.height {
19625 break;
19626 }
19627 for col in 0..side {
19628 if x + col >= self.width {
19629 break;
19630 }
19631 let idx = row * side + col;
19632 let mut base = i32::from(prediction[idx]);
19633 if let Some((alpha_q3, ac_q3)) = cfl {
19634 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
19635 }
19636 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
19637 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
19638 }
19639 }
19640 }
19641}
19642
19643/// Reads one plane's transform block, reconstructs it into `plane` at
19644/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
19645#[allow(clippy::too_many_arguments)]
19646fn read_plane(
19647 dec: &mut SymbolDecoder,
19648 cdfs: &mut Cdfs,
19649 set: TxbSet,
19650 scan: &[u16],
19651 plane_idx: usize,
19652 around: (bool, bool, i32),
19653 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
19654 // it for every plane's `txb` lookup (it is what an intra transform type's
19655 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
19656 tx_mode: usize,
19657 predict_mode: usize,
19658 angle_delta: i32,
19659 reach: Reach,
19660 // lane-wave1 step (i): unread -- this reader records its write
19661 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
19662 // stays in the signature so every call site still proves the plane is
19663 // exclusively held while its coefficients are parsed.
19664 _plane: &mut PlaneBuf<'static>,
19665 x: usize,
19666 y: usize,
19667 side: usize,
19668 tx_side: usize,
19669 base_q_idx: u8,
19670 cfl: Option<(i32, CflSrc)>,
19671 filter_intra: Option<usize>,
19672 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
19673 // smaller than its own block (spec `get_txb_ctx_general`'s
19674 // `plane_bsize != tx_size` branch), carrying the already-looked-up
19675 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
19676 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
19677 // formula below.
19678 luma_skip_ctx: Option<usize>,
19679 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
19680 smooth_neighbor: bool,
19681 fctx: &crate::decode::FrameCtx,
19682) -> Result<Grid> {
19683 // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's
19684 // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`)
19685 // never reaches a chroma plane -- no u/v coefficient symbol is coded and
19686 // no chroma write is recorded. Return the all-zero grid the caller's
19687 // neighbour bookkeeping reads, without consuming a bit.
19688 if plane_idx > 0 && mono(fctx) {
19689 return Ok(Grid::Zero(side * side));
19690 }
19691 let skip_ctx = if plane_idx == 0 {
19692 luma_skip_ctx.unwrap_or(0)
19693 } else {
19694 // libaom `get_txb_ctx`: a chroma unit's context is
19695 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
19696 // plane block is bigger than the transform. Our chroma tables hold the
19697 // offset-7 rows first, so the caller adds 3 for the bigger-block case
19698 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
19699 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
19700 };
19701 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
19702 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
19703 // not by the block's ordinary `mode` (which is always DC_PRED whenever
19704 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
19705 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
19706 // filter-intra in AV1).
19707 let tx_mode = if plane_idx == 0 {
19708 fi_tx_row(tx_mode, filter_intra)
19709 } else {
19710 tx_mode
19711 };
19712 let mut coding = cdfs.txb(set, tx_mode);
19713 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
19714 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
19715 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
19716 // plane of a lossless block (the residual then goes through the WHT, so
19717 // the type only picks the scan, which is the default one).
19718 if lossless(fctx) {
19719 coding.tx_type = None;
19720 }
19721 // Luma's `default_tx_type` is only a fallback for the sizes whose
19722 // `TxbSet` carries no symbol at all (32-point and up), which the spec
19723 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
19724 // *never* its own coded symbol (`coding.tx_type` is always `None` for
19725 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
19726 // the plane's own predicted mode (`default_intra_tx_type`) -- except
19727 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
19728 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
19729 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
19730 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
19731 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
19732 // narrows there — only `Chroma32` and up do).
19733 let default_tx_type = if plane_idx == 0 || side >= 32 {
19734 TxType::DctDct
19735 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
19736 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
19737 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
19738 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
19739 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
19740 // [`read_inter_plane`]'s own `side < 32` guard).
19741 inherited
19742 } else {
19743 default_intra_tx_type(predict_mode as u8)
19744 };
19745 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
19746 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
19747 let default_tx_type = if lossless(fctx) {
19748 TxType::DctDct
19749 } else {
19750 default_tx_type
19751 };
19752 let (grid, tx_type) = read_coeffs(
19753 dec,
19754 &mut coding,
19755 scan,
19756 skip_ctx,
19757 dc_sign_ctx(around.2),
19758 default_tx_type,
19759 None,
19760 )?;
19761 note_chroma_class1(plane_idx, tx_type);
19762 if plane_idx == 0 {
19763 fctx.luma_tx_type.with(|c| c.set(tx_type));
19764 }
19765 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
19766 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
19767 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
19768 // guard also assumes.
19769 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
19770 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
19771 // keyed by that true size, not the coded corner's -- so the corner
19772 // goes into the top-left of a `side`-sized grid, not the reverse.
19773 let levels = extend_corner(grid, tx_side, tx_side, side, side);
19774 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
19775 let tx = TxParams {
19776 w: side,
19777 h: side,
19778 bit_depth: bit_depth(fctx),
19779 q_idx: block_q_idx(fctx),
19780 dc_delta,
19781 ac_delta,
19782 tx_type,
19783 qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type),
19784 stride: 0,
19785 lossless: lossless(fctx),
19786 };
19787 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19788 let residual = tx.run(&levels);
19789 eprintln!(
19790 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}",
19791 &*levels,
19792 );
19793 }
19794 push_intra_tx(
19795 plane_idx,
19796 x,
19797 y,
19798 side,
19799 side,
19800 false,
19801 predict_mode,
19802 angle_delta,
19803 reach,
19804 tx,
19805 &levels,
19806 cfl,
19807 filter_intra,
19808 smooth_neighbor,
19809 fctx,
19810 );
19811 // `record`'s neighbour state only reads whether *the coded grid* (not the
19812 // residual) has nonzero entries, so the levels this function already
19813 // built are what it wants back -- both arms of the old `tx_side == side`
19814 // branch returned exactly that, one of them through a full `to_vec` copy
19815 // of the grid per intra transform unit (lane-coefbuf).
19816 Ok(levels)
19817}
19818
19819/// [`push_intra`] when the unit is square, [`push_intra_rect`] when it is a
19820/// rect (lane-av1-422f): a 4:2:2 square-block chroma unit is the plane
19821/// block's own rect shape, and the `rect` flag selects
19822/// [`PlaneBuf::reconstruct_rect`]'s two-dimensional loop.
19823#[allow(clippy::too_many_arguments)]
19824fn push_intra_unit(
19825 plane: usize,
19826 x: usize,
19827 y: usize,
19828 w: usize,
19829 h: usize,
19830 mode: usize,
19831 angle_delta: i32,
19832 reach: Reach,
19833 residual: &[i32],
19834 cfl: Option<(i32, CflSrc)>,
19835 filter_intra: Option<usize>,
19836 smooth_neighbor: bool,
19837 fctx: &crate::decode::FrameCtx,
19838) {
19839 if w == h {
19840 push_intra(
19841 plane,
19842 x,
19843 y,
19844 w,
19845 mode,
19846 angle_delta,
19847 reach,
19848 residual,
19849 cfl,
19850 filter_intra,
19851 smooth_neighbor,
19852 fctx,
19853 );
19854 } else {
19855 push_intra_rect(
19856 plane,
19857 x,
19858 y,
19859 w,
19860 h,
19861 mode,
19862 angle_delta,
19863 reach,
19864 residual,
19865 cfl,
19866 filter_intra,
19867 smooth_neighbor,
19868 fctx,
19869 );
19870 }
19871}
19872
19873/// ONE RECT chroma transform unit of a square block's uv plane
19874/// (lane-av1-422f) -- a 4:2:2 frame's plane block is `(side/2, side)` and
19875/// `av1_get_max_uv_txsize` fills it with a single rect unit below side 64
19876/// (TX_4X8 / TX_8X16 / TX_16X32), which the square-shaped [`read_plane`]
19877/// cannot express. Same shape as [`leaf8_chroma422_unit`]'s proven read: the
19878/// [`TxbSet`] whose entropy class the unit squares up to, the unit-shaped
19879/// scan, `txb_skip_ctx` = above + left in the offset-7 rows (the unit covers
19880/// the plane block exactly, so no `+3` bigger-plane term -- that one lives in
19881/// the square multi-unit walks' `chroma_ctx_offset`), and the plane's
19882/// predicted mode supplies the mode-derived default `tx_type` unless an armed
19883/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own -- except at an
19884/// entropy class of 32x32 and up, where the spec forces `DCT_DCT`
19885/// ([`read_plane`]'s `side >= 32` clamp).
19886#[allow(clippy::too_many_arguments)]
19887fn read_rect_chroma_unit(
19888 dec: &mut SymbolDecoder,
19889 cdfs: &mut Cdfs,
19890 set: TxbSet,
19891 scan: &[u16],
19892 w: usize,
19893 h: usize,
19894 plane_idx: usize,
19895 around: (bool, bool, i32),
19896 uv_predict_mode: usize,
19897 angle_delta_uv: i32,
19898 reach: Reach,
19899 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
19900 // the plane exclusively while the unit's coefficients are parsed.
19901 _plane: &mut PlaneBuf<'static>,
19902 x: usize,
19903 y: usize,
19904 // Signature parity with [`read_plane`]; the dequant reads its q index
19905 // off `block_q_idx(fctx)` like every other reader here.
19906 _base_q_idx: u8,
19907 // lane-av1-422p: `get_txb_ctx_general`'s chroma branch
19908 // (txb_common.h) reads `txb_skip_ctx = above + left + ctx_offset`,
19909 // where `ctx_offset` is 10 when the plane block is bigger than the
19910 // transform and 7 otherwise. The port stores the offset-7 rows at
19911 // `txb_skip_chroma_8` rows 0..3 and the offset-10 rows at rows 3..6
19912 // (lane-av1-422b), so a unit SMALLER than its plane block passes
19913 // `Some(3)` to reach the offset-10 rows. Every unit that IS the whole
19914 // plane block stays `None` -- 4:2:2 plane blocks never shrink to a
19915 // rect unit except in the chunk arms.
19916 chroma_skip_offset: Option<usize>,
19917 cfl: Option<(i32, CflSrc)>,
19918 smooth_neighbor_uv: bool,
19919 fctx: &crate::decode::FrameCtx,
19920) -> Result<Grid> {
19921 if ss_x(fctx) == 1 && ss_y(fctx) == 0 && w != h {
19922 hit!(CHROMA422_RECT_HITS);
19923 }
19924 let default_tx = if w.max(h) >= 32 {
19925 TxType::DctDct
19926 } else {
19927 fctx.intrabc_chroma_tx
19928 .with(std::cell::Cell::get)
19929 .unwrap_or_else(|| default_intra_tx_type(uv_predict_mode as u8))
19930 };
19931 let mut coding = cdfs.txb(set, uv_predict_mode);
19932 let (levels, tx_type) = read_coeffs_rect(
19933 dec,
19934 &mut coding,
19935 scan,
19936 w,
19937 h,
19938 usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0),
19939 dc_sign_ctx(around.2),
19940 default_tx,
19941 )?;
19942 let residual = dequant_and_inverse_typed_wh(
19943 &levels,
19944 w,
19945 h,
19946 crate::decode::bit_depth(fctx),
19947 block_q_idx(fctx),
19948 plane_q_delta(plane_idx, fctx).0,
19949 plane_q_delta(plane_idx, fctx).1,
19950 tx_type,
19951 block_iqmatrix(fctx, plane_idx, w, h, tx_type),
19952 );
19953 push_intra_rect(
19954 plane_idx,
19955 x,
19956 y,
19957 w,
19958 h,
19959 uv_predict_mode,
19960 angle_delta_uv,
19961 reach,
19962 &residual,
19963 cfl,
19964 None,
19965 smooth_neighbor_uv,
19966 fctx,
19967 );
19968 Ok(levels)
19969}
19970
19971/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
19972/// three planes, reconstructing them into `y`/`u`/`v` and updating
19973/// `neighbours`.
19974#[allow(clippy::too_many_arguments)]
19975fn decode_block(
19976 dec: &mut SymbolDecoder,
19977 cdfs: &mut Cdfs,
19978 neighbours: &mut Neighbours,
19979 at: (usize, usize),
19980 side: usize,
19981 luma_set: TxbSet,
19982 chroma_set: TxbSet,
19983 luma_tx: usize,
19984 chroma_tx: usize,
19985 scans: (&[u16], &[u16]),
19986 cfl: bool,
19987 y: &mut PlaneBuf<'static>,
19988 u: &mut PlaneBuf<'static>,
19989 v: &mut PlaneBuf<'static>,
19990 base_q_idx: u8,
19991 enable_filter_intra: bool,
19992 allow_screen_content_tools: bool,
19993 allow_intrabc: bool,
19994 scan32: &[u16],
19995 scan16: &[u16],
19996 scan8: &[u16],
19997 scan4: &[u16],
19998 tx_select: bool,
19999 reduced_tx_set: bool,
20000 fctx: &crate::decode::FrameCtx,
20001) -> Result<()> {
20002 let (r, c) = at;
20003 let (px, py) = (c * SUB, r * SUB);
20004 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
20005 let palette_uv_cache = neighbours.palette_uv_cache(at);
20006 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
20007 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
20008 let (
20009 skip,
20010 mode,
20011 angle_delta_y,
20012 uv_mode,
20013 angle_delta_uv,
20014 alpha,
20015 filter_intra,
20016 palette_y,
20017 palette_uv,
20018 ) = read_intra_mode(
20019 dec,
20020 cdfs,
20021 nb_above_mode,
20022 nb_left_mode,
20023 cfl,
20024 side,
20025 enable_filter_intra,
20026 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
20027 allow_screen_content_tools,
20028 allow_intrabc,
20029 Some((palette_ctx, &palette_cache)),
20030 &palette_uv_cache,
20031 r * (SUB / MI),
20032 c * (SUB / MI),
20033 fctx,
20034 )?;
20035 if at_tile_left && palette_y.is_some() {
20036 hit!(PALETTE_TILE_LEFT_HITS);
20037 }
20038 // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane
20039 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
20040 // tables/scans are replaced by the 4x4 ones and the block always takes the
20041 // multi-transform-unit path below. lane-av1mixloss: this rewrite used to
20042 // sit at the TOP of the function -- before `read_intra_mode`, which is
20043 // where the block's own `segment_id` is read -- so a mixed frame resolved
20044 // every block's geometry against the PREVIOUS block's segment (a lossless
20045 // neighbour forced 4x4 units on a lossy block; a lossy one handed the
20046 // lossless TxParams an 8x8 grid). libaom's order is the opposite one:
20047 // `decode_mbmi_block` (segment id included) runs before any tx-size rule.
20048 // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this
20049 // rewrite (which sat above `read_intra_mode`) rides along here -- same
20050 // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own
20051 // segment like the lossless arm above it.
20052 let (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx_h, scans) = if lossless(fctx) {
20053 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, 4, (scan4, scan4))
20054 } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
20055 let tx = if side >= 64 { 32 } else { side };
20056 let (set, scan): (TxbSet, &[u16]) = match tx {
20057 32 => (TxbSet::Chroma32, scan32),
20058 16 => (TxbSet::Chroma16, scan16),
20059 8 => (TxbSet::Chroma8, scan8),
20060 _ => (TxbSet::Chroma4, scan4),
20061 };
20062 (luma_set, set, luma_tx, tx, tx, (scans.0, scan))
20063 } else if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
20064 // lane-av1-422f: the uv plane block is the (side/2, side) rect
20065 // (`ss_size_lookup[..][1][0]`), and `av1_get_max_uv_txsize` is
20066 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[plane_bsize])` --
20067 // the RECT that fills the plane block, NOT the square transform of
20068 // the smaller side (the oracle reads ONE TX_8X16 for a 16x16 block's
20069 // 8x16 plane where the old model read two 8x8 units): 4 -> TX_4X4
20070 // (the 2x4 plane rounds up to BLOCK_4X4), 8 -> TX_4X8, 16 ->
20071 // TX_8X16, 32 -> TX_16X32 (one unit per plane, the whole plane
20072 // block), 64 -> TX_32X64 adjusts to TX_32X32 and 128 -> TX_64X64
20073 // adjusts to TX_32X32 (square units, a 1x2 / 2x4 grid).
20074 // `chroma_tx` is the unit WIDTH, `chroma_tx_h` its HEIGHT; the
20075 // chroma walks below read one (chroma_tx, chroma_tx_h) unit per grid
20076 // cell and key their rect reads on `chroma_tx != chroma_tx_h`.
20077 let (tx_w, tx_h) = match side {
20078 4 => (4, 4),
20079 8 => (4, 8),
20080 16 => (8, 16),
20081 32 => (16, 32),
20082 // 64 and 128: TX_32X64 / TX_64X64 adjust down to TX_32X32.
20083 _ => (32, 32),
20084 };
20085 let (set, scan): (TxbSet, &[u16]) = match side {
20086 4 => (TxbSet::Chroma4, scan4),
20087 8 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
20088 16 => (TxbSet::ChromaRect16x8, &SCAN_8X16[..]),
20089 32 => (TxbSet::ChromaRect32x16, &SCAN_16X32[..]),
20090 _ => (TxbSet::Chroma32, scan32),
20091 };
20092 (luma_set, set, luma_tx, tx_w, tx_h, (scans.0, scan))
20093 } else {
20094 (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx, scans)
20095 };
20096 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
20097 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
20098 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
20099 // actual chroma-from-luma correlation, same as this decoder always did.
20100 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
20101 DC_PRED
20102 } else {
20103 uv_mode
20104 };
20105 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
20106 if smooth_neighbor {
20107 hit!(SMOOTH_LUMA_HITS);
20108 }
20109 let smooth_neighbor_uv =
20110 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
20111 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20112 eprintln!(
20113 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
20114 angle_delta_uv={angle_delta_uv}"
20115 );
20116 }
20117 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
20118 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
20119 // block, skipped or not. `logical_tx` is what the loop filter's edge
20120 // lookup and the next block's own `get_tx_size_context` want (the *nominal*
20121 // transform size -- 64 even for the 64x64 corner-scanned case, spec
20122 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
20123 // which only differs from it at that one corner case.
20124 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
20125 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
20126 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
20127 // intrabc block reads NO tx-size symbol at all -- it takes
20128 // `maxRectTxSize` -- while every ordinary skipped intra block does read
20129 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
20130 // the tile from that block on (class `equal-range-means-unread`).
20131 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
20132 // tree instead (`read_var_tx_size`), the same syntax the inter block path
20133 // has always read -- libaom's `parse_decode_block` dispatches on
20134 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
20135 // intrabc block as inter.
20136 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
20137 // libaom `parse_decode_block`'s var-tx tree condition carries
20138 // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc
20139 // block inside a LOSSLESS segment of a mixed frame reads NO
20140 // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line
20141 // hands back TX_4X4. Invisible while every lossless frame was also
20142 // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which
20143 // is why the mixed frame is the first stream to reach it.
20144 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx);
20145 let intrabc_leaves = if intrabc_vartx {
20146 let max_tx = side.min(64);
20147 // `max_block_wide`/`max_block_high`: the frame's own mi grid
20148 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
20149 // right/bottom edge reads no split symbol for the units outside it.
20150 let mi_cols = 2 * y.true_width.div_ceil(8);
20151 let mi_rows = 2 * y.true_height.div_ceil(8);
20152 let side_mi = side / MI;
20153 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
20154 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
20155 let mut leaves = Vec::new();
20156 for row in (0..side_mi).step_by(max_tx / MI) {
20157 for col in (0..side_mi).step_by(max_tx / MI) {
20158 read_var_tx_size(
20159 dec,
20160 cdfs,
20161 neighbours,
20162 (mi_r, mi_c),
20163 side,
20164 (max_w_mi, max_h_mi),
20165 (max_tx, max_tx),
20166 0,
20167 row,
20168 col,
20169 &mut leaves,
20170 );
20171 }
20172 }
20173 hit!(INTRABC_VARTX_HITS);
20174 // lane-t900 r33 census: the t900 recipes resolved every tree UNIFORM.
20175 // lane-av1-ibcvtx: a tree that resolved to mixed leaf sizes is no
20176 // longer refused -- the luma reconstruct below walks the tree's own
20177 // leaf list per leaf (libaom `decode_token_recon_block`, whose token
20178 // loop reconstructs whatever `read_tx_size_vartx` resolved, per
20179 // transform unit), so mixed sizes reconstruct at their own stride.
20180 // The counter marks the shape so a gate can prove a witness actually
20181 // carries a mixed tree and not merely another uniform one.
20182 let uniform = leaves.first().is_some_and(|f| {
20183 leaves
20184 .iter()
20185 .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)
20186 });
20187 if !uniform {
20188 hit!(INTRABC_VARTX_MIXED_LEAVES_HITS);
20189 if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") {
20190 eprintln!(
20191 "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \
20192 dv={intrabc_dv:?} leaves={leaves:?}"
20193 );
20194 }
20195 }
20196 Some(leaves)
20197 } else {
20198 None
20199 };
20200 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves.as_ref().map(|l| l[0].2) {
20201 (tx, if tx == 64 { 32 } else { tx })
20202 } else if tx_select && !intrabc_skip_tx {
20203 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx);
20204 (resolved, if resolved == 64 { 32 } else { resolved })
20205 } else {
20206 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
20207 // TX_64X64, so a 128x128 block is always FOUR luma transform units
20208 // even with `tx_select` off -- the TU loop below, never the
20209 // single-unit path.
20210 (lossless_tx(side.min(64), fctx), luma_tx)
20211 };
20212 if tx_select && logical_tx < side && uv_mode != DC_PRED {
20213 hit!(SQ_CHROMA_TX_HITS);
20214 }
20215 let luma_set = if tx_select {
20216 txbset_for(logical_tx, reduced_tx_set)
20217 } else {
20218 luma_set
20219 };
20220 let luma_set = if intrabc_dv.is_some() {
20221 inter_txbset_for(logical_tx, reduced_tx_set)
20222 } else {
20223 luma_set
20224 };
20225 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
20226 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
20227 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
20228 let chroma_side = side >> ss_x(fctx);
20229 // lane-av1-422b: chroma extent per axis, `side` at ss_y 0 (4:2:2/4:4:4),
20230 // `side / 2` at 4:2:0.
20231 let chroma_height = side >> ss_y(fctx);
20232 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
20233 // frame's own pre-loop-filter reconstruction (all loop filters are off
20234 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
20235 // block vector, with the BILINEAR kernel libaom forces for intrabc --
20236 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
20237 // odd, which is exactly what the bilinear taps then interpolate.
20238 flush_recon(fctx, y, u, v);
20239 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
20240 let mut yb = vec![0u16; side * side];
20241 mc::predict_with_filter(
20242 &y.data,
20243 y.width,
20244 y.true_width,
20245 y.true_height,
20246 mv_to_q4(px, dv_col, 0),
20247 mv_to_q4(py, dv_row, 0),
20248 side,
20249 side,
20250 mc::InterpFilterKind::Bilinear,
20251 &mut yb,
20252 fctx,
20253 );
20254 let mut ub = vec![0u16; chroma_side * chroma_height];
20255 mc::predict_with_filter(
20256 &u.data,
20257 u.width,
20258 u.true_width,
20259 u.true_height,
20260 mv_to_q4(cpx, dv_col, ss_x(fctx)),
20261 mv_to_q4(cpy, dv_row, ss_y(fctx)),
20262 chroma_side,
20263 chroma_height,
20264 mc::InterpFilterKind::Bilinear,
20265 &mut ub,
20266 fctx,
20267 );
20268 let mut vb = vec![0u16; chroma_side * chroma_height];
20269 mc::predict_with_filter(
20270 &v.data,
20271 v.width,
20272 v.true_width,
20273 v.true_height,
20274 mv_to_q4(cpx, dv_col, ss_x(fctx)),
20275 mv_to_q4(cpy, dv_row, ss_y(fctx)),
20276 chroma_side,
20277 chroma_height,
20278 mc::InterpFilterKind::Bilinear,
20279 &mut vb,
20280 fctx,
20281 );
20282 (yb, ub, vb)
20283 });
20284 // A palette-Y block's own prediction is the reconstructed colour-index
20285 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
20286 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
20287 // parameter through this function's dozen `y.reconstruct`/`read_plane`
20288 // sites. A split luma transform (`tx_select && logical_tx != side`)
20289 // would need the map sliced per-TU -- untested against a real
20290 // `--enable-palette=1` stream this round, so refuse by name rather than
20291 // guess at the slicing (charter's own named-acceptable fallback).
20292 let palette_y_buf: Option<Vec<u16>> = palette_y
20293 .as_ref()
20294 .map(|py| py.map.iter().map(|&idx| py.colors[idx as usize]).collect());
20295 // lane-t900 r32: the intrabc luma prediction rides the very same
20296 // whole-block override slot, so the multi-TU loop below windows it per
20297 // transform unit exactly like a palette map -- setting it once up front
20298 // handed the whole `side`x`side` buffer to the FIRST unit and left every
20299 // later one predicting off block edges (the var-tx tree above is what
20300 // first makes `logical_tx < side` reachable for an intrabc block).
20301 let palette_y_buf = match &intrabc_bufs {
20302 Some((yb, _, _)) => Some(yb.clone()),
20303 None => palette_y_buf,
20304 };
20305 // With one luma transform unit the whole `side`x`side` map is the
20306 // prediction; with several (`logical_tx != side`) each unit takes its own
20307 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
20308 // below (lane-palette2 r7) -- setting the full-block buffer here would be
20309 // taken by the FIRST unit and indexed at the wrong stride.
20310 // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call
20311 // (the `else` arm below -- a palette/intrabc block never takes the per-unit
20312 // `split_tx_skip` walk), so its map must be armed here even when the
20313 // transform is split. Gating the arm on `logical_tx == side` alone left a
20314 // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC
20315 // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen
20316 // key frame; class override-slot-on-one-arm). Neither prediction is
20317 // edge-derived, so the whole-block buffer at the block's own stride is
20318 // exactly what that single call wants.
20319 // Counted on the SHAPE, not on the arm below, so a gate can tell a stream
20320 // that reaches this block apart from one that never does (class
20321 // gate-blind-to-feature).
20322 if palette_y_buf.is_some() && skip && logical_tx < side {
20323 hit!(SKIP_SPLIT_TX_OVERRIDE_HITS);
20324 }
20325 if let Some(buf) = &palette_y_buf
20326 && (logical_tx == side || skip)
20327 {
20328 set_palette_pred(buf.clone(), fctx);
20329 }
20330 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
20331 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
20332 // plane's own `reconstruct`/`read_plane` call below (never both planes at
20333 // once), since Y's own set-then-take already emptied the slot by the time
20334 // either of these run.
20335 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
20336 (
20337 puv.map
20338 .iter()
20339 .map(|&idx| puv.u_colors[idx as usize])
20340 .collect(),
20341 puv.map
20342 .iter()
20343 .map(|&idx| puv.v_colors[idx as usize])
20344 .collect(),
20345 )
20346 });
20347 // The chroma half of the intrabc prediction rides the same per-plane
20348 // override slot the UV-palette buffers do (set fresh before each plane's
20349 // own `reconstruct`/`read_plane` call below).
20350 let palette_uv_bufs = match &intrabc_bufs {
20351 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
20352 None => palette_uv_bufs,
20353 };
20354 if skip {
20355 // A skipped block codes no residual syntax at all (spec 5.11.34):
20356 // straight prediction, on every plane.
20357 //
20358 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
20359 // is skipped (only an INTER skip forces the largest transform), and
20360 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
20361 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
20362 // already written left/above of it inside this same block. Predicting
20363 // the whole `side`x`side` at once gives a different (uniformly off by
20364 // ~1) answer, which is exactly the residue this lane was chasing.
20365 // The palette/intrabc override path keeps the single-call shape (its
20366 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
20367 // untested for skip and unreachable in these streams).
20368 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
20369 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
20370 // per-unit prediction is keyed on the transform being smaller than
20371 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
20372 // narrower meaning (a READ split tx depth).
20373 let split_tx_skip = logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
20374 if split_tx_skip {
20375 if tx_select {
20376 hit!(SKIP_SPLIT_TX_HITS);
20377 }
20378 let n_axis = side / logical_tx;
20379 for tu_row in 0..n_axis {
20380 for tu_col in 0..n_axis {
20381 let tu_px = px + tu_col * logical_tx;
20382 let tu_py = py + tu_row * logical_tx;
20383 if tu_px >= y.true_width || tu_py >= y.true_height {
20384 continue;
20385 }
20386 let tu_reach = tu_reach(
20387 side,
20388 side,
20389 tu_col * logical_tx,
20390 tu_row * logical_tx,
20391 logical_tx,
20392 reach,
20393 px,
20394 py,
20395 y.width,
20396 y.height,
20397 fctx,
20398 );
20399 push_intra(
20400 0,
20401 tu_px,
20402 tu_py,
20403 logical_tx,
20404 mode,
20405 angle_delta_y,
20406 tu_reach,
20407 &ZERO_RESIDUAL[..logical_tx * logical_tx],
20408 None,
20409 filter_intra,
20410 smooth_neighbor,
20411 fctx,
20412 );
20413 }
20414 }
20415 } else {
20416 push_intra(
20417 0,
20418 px,
20419 py,
20420 side,
20421 mode,
20422 angle_delta_y,
20423 reach,
20424 &ZERO_RESIDUAL[..side * side],
20425 None,
20426 filter_intra,
20427 smooth_neighbor,
20428 fctx,
20429 );
20430 }
20431 let ac = alpha.map(|_| cfl_src(px, py, side));
20432 // lane-av1-422b: the chroma unit grid is `cn_cols` x `cn_rows` --
20433 // square at 4:2:0/4:4:4, at 4:2:2 `(side/2)/tx` units wide by
20434 // `side/tx` tall (the plane block is (side/2, side)). A unit's LUMA
20435 // anchor follows the per-axis shifts: `chroma_tx << ss_x` wide,
20436 // `chroma_tx_h << ss_y` tall (lane-av1-422f: the unit itself is the
20437 // (chroma_tx, chroma_tx_h) rect, so a 4:2:2 frame below side 64
20438 // reads ONE unit per plane, the whole plane block).
20439 let cn_cols = (chroma_side / chroma_tx).max(1);
20440 let cn_rows = (chroma_height / chroma_tx_h).max(1);
20441 let luma_span_x = chroma_tx << ss_x(fctx);
20442 let luma_span_y = chroma_tx_h << ss_y(fctx);
20443 for cu_row in 0..cn_rows {
20444 for cu_col in 0..cn_cols {
20445 let cu_r = if cn_rows == 1 && cn_cols == 1 {
20446 reach
20447 } else {
20448 tu_reach_rect(
20449 side,
20450 side,
20451 cu_col * luma_span_x,
20452 cu_row * luma_span_y,
20453 luma_span_x,
20454 luma_span_y,
20455 reach,
20456 px,
20457 py,
20458 y.width,
20459 y.height,
20460 fctx,
20461 )
20462 };
20463 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
20464 if let Some((ub, _)) = &palette_uv_bufs {
20465 set_palette_pred(ub.clone(), fctx);
20466 }
20467 push_intra_unit(
20468 1,
20469 cu_x,
20470 cu_y,
20471 chroma_tx,
20472 chroma_tx_h,
20473 uv_predict_mode,
20474 angle_delta_uv,
20475 cu_r,
20476 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
20477 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
20478 None,
20479 smooth_neighbor_uv,
20480 fctx,
20481 );
20482 if let Some((_, vb)) = &palette_uv_bufs {
20483 set_palette_pred(vb.clone(), fctx);
20484 }
20485 push_intra_unit(
20486 2,
20487 cu_x,
20488 cu_y,
20489 chroma_tx,
20490 chroma_tx_h,
20491 uv_predict_mode,
20492 angle_delta_uv,
20493 cu_r,
20494 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
20495 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
20496 None,
20497 smooth_neighbor_uv,
20498 fctx,
20499 );
20500 }
20501 }
20502 let luma_grid = vec![0i32; side * side];
20503 let u_grid = vec![0i32; chroma_side * chroma_side];
20504 let v_grid = vec![0i32; chroma_side * chroma_side];
20505 neighbours.record(
20506 at,
20507 side,
20508 mode,
20509 uv_predict_mode,
20510 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
20511 );
20512 } else if logical_tx == side {
20513 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
20514 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
20515 // that arm was redundant -- and wrong at 128, where
20516 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
20517 // block is four units whether or not `tx_select` is on.
20518 // A single luma transform unit -- the old path, unchanged (including
20519 // the 64x64 corner case, `logical_tx == side == 64` with
20520 // `coeff_tx_side == 32`).
20521 let around = neighbours.around(at, side);
20522 let luma_grid = read_plane(
20523 dec,
20524 cdfs,
20525 luma_set,
20526 luma_scan,
20527 0,
20528 around[0],
20529 mode,
20530 mode,
20531 angle_delta_y,
20532 reach,
20533 y,
20534 px,
20535 py,
20536 side,
20537 coeff_tx_side,
20538 base_q_idx,
20539 None,
20540 filter_intra,
20541 None,
20542 smooth_neighbor,
20543 fctx,
20544 )?;
20545 let ac = alpha.map(|_| cfl_src(px, py, side));
20546 // Armed for exactly this block's two chroma reads (see
20547 // [`INTRABC_CHROMA_TX`]); the luma call above just set
20548 // [`LUMA_TX_TYPE`] to the type it coded.
20549 if intrabc_dv.is_some() {
20550 fctx.intrabc_chroma_tx
20551 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
20552 }
20553 // lane-av1-444: this arm is one luma TU (`logical_tx == side`), including
20554 // the 64x64 case whose coefficient grid is 32. At 4:4:4 the chroma plane
20555 // is the same size as luma and `av1_get_max_uv_txsize` caps it at
20556 // TX_32X32, so a 64x64 block codes four chroma units, plane-major
20557 // (every U, then every V) — the same loop the multi-TU arm runs.
20558 // At 4:2:0 `chroma_side == chroma_tx`, so it stays one read.
20559 // lane-av1-422b: 4:2:2 never collapses to one read above a 4x4 luma
20560 // block -- the unit grid is `(side/2)/tx` wide by `side/tx` tall.
20561 // lane-av1-422f: `chroma_tx` is the unit WIDTH and `chroma_tx_h` its
20562 // HEIGHT, so below side 64 a 4:2:2 frame's grid is 1x1 and the one
20563 // unit is the plane block's own rect.
20564 let cn_cols = (chroma_side / chroma_tx).max(1);
20565 let cn_rows = (chroma_height / chroma_tx_h).max(1);
20566 let luma_span_x = chroma_tx << ss_x(fctx);
20567 let luma_span_y = chroma_tx_h << ss_y(fctx);
20568 let (u_grid, v_grid, chroma_units) = if cn_rows == 1 && cn_cols == 1 {
20569 if chroma_tx == chroma_tx_h {
20570 if let Some((ub, _)) = &palette_uv_bufs {
20571 set_palette_pred(ub.clone(), fctx);
20572 }
20573 let u_grid = read_plane(
20574 dec,
20575 cdfs,
20576 chroma_set,
20577 scans.1,
20578 1,
20579 around[1],
20580 mode,
20581 uv_predict_mode,
20582 angle_delta_uv,
20583 reach,
20584 u,
20585 cpx,
20586 cpy,
20587 chroma_side,
20588 chroma_tx,
20589 base_q_idx,
20590 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
20591 None,
20592 None,
20593 smooth_neighbor_uv,
20594 fctx,
20595 )?;
20596 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20597 eprintln!(
20598 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
20599 &u.data[cpy * u.width + cpx..][..chroma_side]
20600 );
20601 }
20602 if let Some((_, vb)) = &palette_uv_bufs {
20603 set_palette_pred(vb.clone(), fctx);
20604 }
20605 let v_grid = read_plane(
20606 dec,
20607 cdfs,
20608 chroma_set,
20609 scans.1,
20610 2,
20611 around[2],
20612 mode,
20613 uv_predict_mode,
20614 angle_delta_uv,
20615 reach,
20616 v,
20617 cpx,
20618 cpy,
20619 chroma_side,
20620 chroma_tx,
20621 base_q_idx,
20622 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
20623 None,
20624 None,
20625 smooth_neighbor_uv,
20626 fctx,
20627 )?;
20628 (u_grid, v_grid, Vec::new())
20629 } else {
20630 // lane-av1-422f: the one unit is a RECT filling the plane
20631 // block -- the square-shaped [`read_plane`] cannot express
20632 // it, so both planes go through [`read_rect_chroma_unit`]
20633 // (U, then V, the same order the square arm reads). The
20634 // chroma context reads per chroma 4-px cell (see
20635 // [`Neighbours::around_mi_422_chroma`]).
20636 let chroma_around = neighbours.around_mi_422_chroma((mi_r, mi_c), side, side);
20637 if let Some((ub, _)) = &palette_uv_bufs {
20638 set_palette_pred(ub.clone(), fctx);
20639 }
20640 let u_grid = read_rect_chroma_unit(
20641 dec,
20642 cdfs,
20643 chroma_set,
20644 scans.1,
20645 chroma_tx,
20646 chroma_tx_h,
20647 1,
20648 chroma_around[1],
20649 uv_predict_mode,
20650 angle_delta_uv,
20651 reach,
20652 u,
20653 cpx,
20654 cpy,
20655 base_q_idx,
20656 None,
20657 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
20658 smooth_neighbor_uv,
20659 fctx,
20660 )?;
20661 if let Some((_, vb)) = &palette_uv_bufs {
20662 set_palette_pred(vb.clone(), fctx);
20663 }
20664 let v_grid = read_rect_chroma_unit(
20665 dec,
20666 cdfs,
20667 chroma_set,
20668 scans.1,
20669 chroma_tx,
20670 chroma_tx_h,
20671 2,
20672 chroma_around[2],
20673 uv_predict_mode,
20674 angle_delta_uv,
20675 reach,
20676 v,
20677 cpx,
20678 cpy,
20679 base_q_idx,
20680 None,
20681 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
20682 smooth_neighbor_uv,
20683 fctx,
20684 )?;
20685 (u_grid, v_grid, Vec::new())
20686 }
20687 } else {
20688 let chroma_ctx_offset = Some(3);
20689 let mut u_pass: Vec<Grid> = Vec::new();
20690 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
20691 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
20692 for plane_pass in 1..=2usize {
20693 let mut pass_idx = 0usize;
20694 for cu_row in 0..cn_rows {
20695 for cu_col in 0..cn_cols {
20696 let cu_mi = (
20697 mi_r + cu_row * (luma_span_y / MI),
20698 mi_c + cu_col * (luma_span_x / MI),
20699 );
20700 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
20701 // lane-av1-422f: chroma-only loop; per-chroma-cell
20702 // above votes (see [`Neighbours::around_mi_422_chroma`]).
20703 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
20704 } else {
20705 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
20706 };
20707 let cu_reach = tu_reach_rect(
20708 side,
20709 side,
20710 cu_col * luma_span_x,
20711 cu_row * luma_span_y,
20712 luma_span_x,
20713 luma_span_y,
20714 reach,
20715 px,
20716 py,
20717 y.width,
20718 y.height,
20719 fctx,
20720 );
20721 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
20722 if let Some((ub, vb)) = &palette_uv_bufs {
20723 let pbuf = if plane_pass == 1 { ub } else { vb };
20724 set_palette_pred(
20725 palette_window(
20726 pbuf,
20727 chroma_side,
20728 cu_col * chroma_tx,
20729 cu_row * chroma_tx_h,
20730 chroma_tx,
20731 chroma_tx_h,
20732 ),
20733 fctx,
20734 );
20735 }
20736 let buf: &mut PlaneBuf<'static> =
20737 if plane_pass == 1 { &mut *u } else { &mut *v };
20738 let cu_grid = read_plane(
20739 dec,
20740 cdfs,
20741 chroma_set,
20742 scans.1,
20743 plane_pass,
20744 cu_around[plane_pass],
20745 mode,
20746 uv_predict_mode,
20747 angle_delta_uv,
20748 cu_reach,
20749 buf,
20750 cu_x,
20751 cu_y,
20752 chroma_tx,
20753 chroma_tx,
20754 base_q_idx,
20755 alpha
20756 .zip(ac)
20757 .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)),
20758 None,
20759 chroma_ctx_offset,
20760 smooth_neighbor_uv,
20761 fctx,
20762 )?;
20763 hit!(CHROMA_SPLIT_TX_HITS);
20764 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
20765 hit!(CHROMA422_SQUARE_HITS);
20766 }
20767 // Immediately, so the next unit of this block reads this
20768 // one's coefficient context. `record` below stamps one
20769 // chroma state across the whole block; the replay after
20770 // it puts the per-unit state back.
20771 neighbours.record_mi_chroma(
20772 cu_mi,
20773 luma_span_x,
20774 luma_span_y,
20775 plane_pass,
20776 &cu_grid,
20777 );
20778 if plane_pass == 1 {
20779 u_pass.push(cu_grid);
20780 } else {
20781 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
20782 units.push((
20783 cu_mi,
20784 luma_span_x,
20785 luma_span_y,
20786 u_grid.clone(),
20787 cu_grid.clone(),
20788 ));
20789 last_grids = [u_grid, cu_grid];
20790 }
20791 pass_idx += 1;
20792 }
20793 }
20794 }
20795 (last_grids[0].clone(), last_grids[1].clone(), units)
20796 };
20797 fctx.intrabc_chroma_tx.with(|c| c.set(None));
20798 neighbours.record(
20799 at,
20800 side,
20801 mode,
20802 uv_predict_mode,
20803 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
20804 );
20805 for (cu_mi, sw, sh, u_unit, v_unit) in &chroma_units {
20806 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_unit);
20807 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_unit);
20808 }
20809 } else {
20810 // Several luma transform units, raster order (spec
20811 // `transform_block`'s loop): the block's resolved transform is
20812 // genuinely smaller than its own side, so each tile of it predicts
20813 // and codes independently, its own context read fresh off whatever
20814 // the earlier tiles in this same block already wrote -- the same
20815 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
20816 let n_axis = side / logical_tx;
20817 // lane-av1-422f: unit width/height per axis, like walk 2 above --
20818 // a 4:2:2 frame below side 64 reads ONE rect unit per plane per
20819 // chunk, the whole plane block.
20820 let cn_cols = (chroma_side / chroma_tx).max(1);
20821 let cn_rows = (chroma_height / chroma_tx_h).max(1);
20822 let luma_span_x = chroma_tx << ss_x(fctx);
20823 let luma_span_y = chroma_tx_h << ss_y(fctx);
20824 // libaom's transform-block loop is over 64x64 luma "mu" chunks
20825 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
20826 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
20827 // before moving to the next one. Below 128 a block is a single chunk,
20828 // so this is byte-for-byte the all-luma-then-all-chroma order that has
20829 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
20830 // and reading all four luma units first desyncs the tile at the second
20831 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
20832 let nchunk = (side / 64).max(1);
20833 // `cn > 1` means the uv plane block is larger than the uv transform,
20834 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
20835 let chroma_ctx_offset = if cn_rows * cn_cols > 1 { Some(3) } else { None };
20836 let tpc = (n_axis / nchunk).max(1);
20837 let cpc_rows = (cn_rows / nchunk).max(1);
20838 let cpc_cols = (cn_cols / nchunk).max(1);
20839 // The block's luma transform units, raster order inside each mu
20840 // chunk. lane-av1-ibcvtx: an intrabc block's units are the var-tx
20841 // tree's own leaf list -- mixed sizes included, exactly what libaom's
20842 // `decode_token_recon_block` token loop reconstructs (one
20843 // `av1_read_coeffs_txb` + inverse transform per resolved unit) --
20844 // while every other block's list is the uniform `logical_tx` grid
20845 // this loop has always walked, generated here in the same order.
20846 let mut chunk_tus: Vec<Vec<(usize, usize, usize)>> = vec![Vec::new(); nchunk * nchunk];
20847 if let Some(leaves) = &intrabc_leaves {
20848 for &(lr, lc, tw, _th) in leaves {
20849 let (off_y, off_x) = (lr * MI, lc * MI);
20850 chunk_tus[(off_y / 64) * nchunk + (off_x / 64)].push((off_y, off_x, tw));
20851 }
20852 } else {
20853 for tu_row in 0..n_axis {
20854 for tu_col in 0..n_axis {
20855 chunk_tus[(tu_row / tpc) * nchunk + (tu_col / tpc)].push((
20856 tu_row * logical_tx,
20857 tu_col * logical_tx,
20858 logical_tx,
20859 ));
20860 }
20861 }
20862 }
20863 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
20864 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
20865 for ch_row in 0..nchunk {
20866 for ch_col in 0..nchunk {
20867 // lane-av1-ibcvtx: the chunk's chroma units inherit the CHROMA tx
20868 // type of the co-located luma position (`av1_get_tx_type`,
20869 // blockd.h:1278: a non-Y plane of an inter-classified block -- and
20870 // intrabc is one -- reads `tx_type_map`, i.e. the coded type of the
20871 // luma unit covering it). Inside a mu chunk that is the chunk's
20872 // FIRST luma unit in raster order (the chunk origin is always the
20873 // first leaf's own origin). Captured right after that unit's read;
20874 // the single-TU arm below does the same for a whole-block unit.
20875 let mut first_leaf_tx: Option<TxType> = None;
20876 for &(tu_off_y, tu_off_x, tu_tx) in &chunk_tus[ch_row * nchunk + ch_col] {
20877 let tu_mi = (mi_r + tu_off_y / MI, mi_c + tu_off_x / MI);
20878 let tu_px = px + tu_off_x;
20879 let tu_py = py + tu_off_y;
20880 // Same libaom clip as `decode_rect_split`'s loop above; a
20881 // square block only hangs off the frame when the frame's mi
20882 // dimensions are odd at the block's own level.
20883 if tu_px >= y.true_width || tu_py >= y.true_height {
20884 continue;
20885 }
20886 let tu_around = neighbours.around_mi(tu_mi, tu_tx)[0];
20887 // A transform unit inside a block is NOT a block at that
20888 // position (lane-palette2 r12): `Reach::of` granted the
20889 // top-right 8x8 unit of a 16x16 D203 block bottom-left
20890 // pixels libaom refuses outright (`col_off > 0`), which is
20891 // the diagonal wedge seed 46 reconstructed wrong.
20892 let tu_reach = tu_reach(
20893 side, side, tu_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height,
20894 fctx,
20895 );
20896 // This transform unit's own bsize (`tu_tx`) is smaller
20897 // than the block it sits in (`side`), so `txb_skip_ctx` is
20898 // the neighbour-magnitude table, not the lone-TU 0 (spec
20899 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
20900 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tu_tx / MI);
20901 // An intrabc unit's CDF set and scan follow the unit's OWN
20902 // resolved size (`get_txsize_entropy_ctx` /
20903 // `av1_get_scan` per `av1_read_coeffs_txb` call); the
20904 // uniform grid's precomputed pair already matches because
20905 // `tu_tx == logical_tx` there.
20906 let (tu_set, tu_scan) = if intrabc_dv.is_some() {
20907 (
20908 inter_txbset_for(tu_tx, reduced_tx_set),
20909 scan_for(
20910 if tu_tx == 64 { 32 } else { tu_tx },
20911 scan32,
20912 scan16,
20913 scan8,
20914 scan4,
20915 ),
20916 )
20917 } else {
20918 (luma_set, luma_scan)
20919 };
20920 if let Some(buf) = &palette_y_buf {
20921 hit!(PALETTE_SPLIT_TX_HITS);
20922 let mut window = vec![0u16; tu_tx * tu_tx];
20923 for row in 0..tu_tx {
20924 let src = (tu_off_y + row) * side + tu_off_x;
20925 window[row * tu_tx..][..tu_tx].copy_from_slice(&buf[src..][..tu_tx]);
20926 }
20927 set_palette_pred(window, fctx);
20928 }
20929 let tu_grid = read_plane(
20930 dec,
20931 cdfs,
20932 tu_set,
20933 tu_scan,
20934 0,
20935 tu_around,
20936 mode,
20937 mode,
20938 angle_delta_y,
20939 tu_reach,
20940 y,
20941 tu_px,
20942 tu_py,
20943 tu_tx,
20944 // The unit's own COEFFICIENT grid, half its side at
20945 // TX_64X64 (a 64-point transform codes nothing past 32);
20946 // identical to `tu_tx` at every smaller size
20947 // (lane-sb128b r1).
20948 if tu_tx == 64 { 32 } else { tu_tx },
20949 base_q_idx,
20950 None,
20951 filter_intra,
20952 Some(tu_skip_ctx),
20953 smooth_neighbor,
20954 fctx,
20955 )?;
20956 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20957 eprintln!(
20958 "TRACE tu_bitpos mi=({},{}) tell={}",
20959 tu_mi.0,
20960 tu_mi.1,
20961 dec.debug_bitpos()
20962 );
20963 }
20964 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);
20965 if first_leaf_tx.is_none() {
20966 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
20967 }
20968 }
20969 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
20970 // this still runs after every luma unit of the block.
20971 let ac = alpha.map(|_| cfl_src(px, py, side));
20972 // lane-av1-ibcvtx: an intrabc block's chroma rides the luma's coded
20973 // tx type (see `first_leaf_tx` above) -- the same arm the single-TU
20974 // branch sets before its own chroma reads.
20975 if intrabc_dv.is_some() {
20976 if let Some(t) = first_leaf_tx {
20977 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
20978 }
20979 }
20980 // The block's uv plane block is `chroma_side` across but its uv
20981 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
20982 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
20983 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
20984 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
20985 // FOUR units (lane-sb128b r2) -- one per mu chunk.
20986 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
20987 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
20988 // the chunk, then every V unit. At one unit per plane per chunk --
20989 // every non-lossless case this decoder reaches -- that is the same
20990 // symbol order as the interleaved pair this loop used to read; a
20991 // lossless frame's 4x4 chroma units are the case where it differs
20992 // (lane-lossless2).
20993 let mut u_pass: Vec<Grid> = Vec::new();
20994 for plane_pass in 1..=2usize {
20995 let mut pass_idx = 0usize;
20996 for cu_row in ch_row * cpc_rows..(ch_row + 1) * cpc_rows {
20997 for cu_col in ch_col * cpc_cols..(ch_col + 1) * cpc_cols {
20998 // libaom `decode_reconstruct_tx`'s frame-edge clip
20999 // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col
21000 // >= max_blocks_wide` returns before ANY symbol is read): a
21001 // transform unit whose 4x4 origin sits outside the frame's mi
21002 // grid is not coded at all. The luma loop above carries the
21003 // same clip; its absence here read `txb_skip` (+coeffs) for
21004 // chroma units libaom never wrote -- the lossless 64x64 block
21005 // at mi(48,0) of a 320x240 frame overhangs the bottom edge by
21006 // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not
21007 // eight (lane-av1-loss64; 48 chroma units per plane in
21008 // aomdec's EC_COEFF census vs the 64 this loop read).
21009 // `max_block_wide/high` (av1_common_int.h:1565): the plane
21010 // block's pixel span (4:2:0 halves the luma span, clamped to
21011 // 4 by `set_plane_n4`) plus the negative overhang
21012 // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4
21013 // units.
21014 let span_mi = side / MI;
21015 let over_w_mi = (2 * y.true_width.div_ceil(8)) as i32
21016 - mi_c as i32
21017 - span_mi as i32;
21018 let over_h_mi = (2 * y.true_height.div_ceil(8)) as i32
21019 - mi_r as i32
21020 - span_mi as i32;
21021 // `max_block_wide/high` in chroma pixels: the plane block's
21022 // own span (`side` at 4:4:4, `side / 2` at 4:2:0 -- the old
21023 // hardcoded `span_mi * 2` clipped three quarters of a 4:4:4
21024 // block's coded units and desynced the tile) plus the
21025 // negative overhang (`mb_to_*_edge >> (3 + ss)`), whose
21026 // chroma-px scale is `MI >> ss` per mi.
21027 let plane_px = (((span_mi * MI) >> ss_x(fctx)).max(4)) as i32;
21028 let over_w_px = over_w_mi.min(0) * (MI >> ss_x(fctx)) as i32;
21029 let over_h_px = over_h_mi.min(0) * (MI >> ss_y(fctx)) as i32;
21030 let max_units_w = ((plane_px + over_w_px) >> 2).max(0) as usize;
21031 // lane-av1-422f: the shared halved formula in the `else` counts
21032 // the plane span in 4-px units through the 2-px-per-mi
21033 // subsampled height, which a 4:2:2 plane does not have (ss_y
21034 // 0) -- its span is the full luma mi count, so a keyed
21035 // formula clips the same units libaom's `max_block_high`
21036 // does. 4:2:0 and 4:4:4 keep the proven shared rows (at 4:2:0
21037 // `MI >> ss_y` is 2, the same `2 * over_h_mi.min(0)` the
21038 // pre-ss form spelled).
21039 let max_units_h = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21040 (span_mi as i32 + over_h_mi.min(0)).max(0) as usize
21041 } else {
21042 ((plane_px + over_h_px) >> 2).max(0) as usize
21043 };
21044 let (unit_w, unit_h) = (chroma_tx / 4, chroma_tx_h / 4);
21045 if cu_col * unit_w >= max_units_w || cu_row * unit_h >= max_units_h {
21046 hit!(CHROMA_EDGE_TU_CLIP_HITS);
21047 continue;
21048 }
21049 // The chroma context arrays are indexed in LUMA mi, so this
21050 // unit's anchor is its own luma quadrant (lane-av1-422b: the
21051 // quadrant spans `chroma_tx << ss_x` luma px wide by
21052 // `chroma_tx_h << ss_y` tall -- at 4:2:2 below side 64 the
21053 // one unit's quadrant is the whole block).
21054 let cu_mi = (
21055 mi_r + cu_row * (luma_span_y / MI),
21056 mi_c + cu_col * (luma_span_x / MI),
21057 );
21058 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21059 // lane-av1-422f: chroma-only loop; per-chroma-cell above
21060 // votes (see [`Neighbours::around_mi_422_chroma`]).
21061 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
21062 } else {
21063 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
21064 };
21065 let cu_reach = if cn_rows == 1 && cn_cols == 1 {
21066 reach
21067 } else {
21068 tu_reach_rect(
21069 side,
21070 side,
21071 cu_col * luma_span_x,
21072 cu_row * luma_span_y,
21073 luma_span_x,
21074 luma_span_y,
21075 reach,
21076 px,
21077 py,
21078 y.width,
21079 y.height,
21080 fctx,
21081 )
21082 };
21083 let (cu_x, cu_y) =
21084 (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
21085 if let Some((ub, vb)) = &palette_uv_bufs {
21086 let pbuf = if plane_pass == 1 { ub } else { vb };
21087 set_palette_pred(
21088 palette_window(
21089 pbuf,
21090 chroma_side,
21091 cu_col * chroma_tx,
21092 cu_row * chroma_tx_h,
21093 chroma_tx,
21094 chroma_tx_h,
21095 ),
21096 fctx,
21097 );
21098 }
21099 let buf: &mut PlaneBuf<'static> =
21100 if plane_pass == 1 { &mut *u } else { &mut *v };
21101 let cu_grid = if chroma_tx == chroma_tx_h {
21102 read_plane(
21103 dec,
21104 cdfs,
21105 chroma_set,
21106 scans.1,
21107 plane_pass,
21108 cu_around[plane_pass],
21109 mode,
21110 uv_predict_mode,
21111 angle_delta_uv,
21112 cu_reach,
21113 buf,
21114 cu_x,
21115 cu_y,
21116 chroma_tx,
21117 chroma_tx,
21118 base_q_idx,
21119 alpha.zip(ac).map(|((au, av), ac)| {
21120 (if plane_pass == 1 { au } else { av }, ac)
21121 }),
21122 None,
21123 chroma_ctx_offset,
21124 smooth_neighbor_uv,
21125 fctx,
21126 )?
21127 } else {
21128 // lane-av1-422f: the whole plane block as one rect unit;
21129 // `chroma_ctx_offset` is `None` there (the unit covers
21130 // the plane block, so the offset-7 skip rows are right).
21131 read_rect_chroma_unit(
21132 dec,
21133 cdfs,
21134 chroma_set,
21135 scans.1,
21136 chroma_tx,
21137 chroma_tx_h,
21138 plane_pass,
21139 cu_around[plane_pass],
21140 uv_predict_mode,
21141 angle_delta_uv,
21142 cu_reach,
21143 buf,
21144 cu_x,
21145 cu_y,
21146 base_q_idx,
21147 None,
21148 alpha.zip(ac).map(|((au, av), ac)| {
21149 (if plane_pass == 1 { au } else { av }, ac)
21150 }),
21151 smooth_neighbor_uv,
21152 fctx,
21153 )?
21154 };
21155 if cn_rows * cn_cols > 1 {
21156 hit!(CHROMA_SPLIT_TX_HITS);
21157 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21158 hit!(CHROMA422_SQUARE_HITS);
21159 }
21160 // Immediately, so the NEXT unit of this same block reads
21161 // this one's coefficient context (libaom's chroma
21162 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
21163 // 1 from this left neighbour -- measured against aomdec).
21164 // The same writes are replayed after `record_split_luma`
21165 // below, which would otherwise clobber them whole-block.
21166 neighbours.record_mi_chroma(
21167 cu_mi,
21168 luma_span_x,
21169 luma_span_y,
21170 plane_pass,
21171 &cu_grid,
21172 );
21173 }
21174 if plane_pass == 1 {
21175 u_pass.push(cu_grid);
21176 } else {
21177 let u_grid =
21178 std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
21179 if cn_rows * cn_cols > 1 {
21180 units.push((
21181 cu_mi,
21182 luma_span_x,
21183 luma_span_y,
21184 u_grid.clone(),
21185 cu_grid.clone(),
21186 ));
21187 }
21188 last_grids = [u_grid, cu_grid];
21189 }
21190 pass_idx += 1;
21191 }
21192 }
21193 }
21194 }
21195 if intrabc_dv.is_some() {
21196 fctx.intrabc_chroma_tx.with(|c| c.set(None));
21197 }
21198 }
21199 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
21200 // context write; at `cn > 1` the per-unit writes above are what the
21201 // next block reads, so they run after this (last writer wins).
21202 neighbours.record_split_luma(
21203 at,
21204 side,
21205 mode,
21206 uv_predict_mode,
21207 [&last_grids[0], &last_grids[1]],
21208 );
21209 for (cu_mi, sw, sh, u_grid, v_grid) in &units {
21210 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_grid);
21211 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_grid);
21212 }
21213 }
21214 // Unconditional, `size == 0` for a non-palette block: clears any stale
21215 // neighbour palette state the same way [`Neighbours::record`] always
21216 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
21217 // (the split-luma-TU branch above always refuses before reaching here
21218 // when `palette_y` is `Some`, so it is never live for that branch).
21219 let (py_size, py_colors) = palette_y
21220 .as_ref()
21221 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
21222 neighbours.record_palette_y(at, side, py_size, py_colors);
21223 let (puv_size, puv_colors) = palette_uv
21224 .as_ref()
21225 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
21226 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
21227 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
21228 neighbours.fill_lf_grid(
21229 (r * (SUB / MI), c * (SUB / MI)),
21230 side / MI,
21231 logical_tx as u8,
21232 0,
21233 fctx,
21234 );
21235 // lane-t900 r32 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size,
21236 // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY
21237 // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM
21238 // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express
21239 // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED
21240 // intrabc block publish its BLOCK size instead, intrabc being the only
21241 // "inter" block an intra-only frame codes (`blockd.h:373`). So this call
21242 // stays the authority wherever one can appear; with `allow_intrabc` unset
21243 // it writes exactly what the grid already did.
21244 if allow_intrabc {
21245 set_txfm_ctxs(
21246 neighbours,
21247 (mi_r, mi_c),
21248 logical_tx,
21249 side / MI,
21250 side / MI,
21251 skip && intrabc_dv.is_some(),
21252 );
21253 }
21254 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, neighbours, fctx);
21255 Ok(())
21256}
21257
21258thread_local! {
21259 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
21260 /// root's HORZ arm, and 64x128 ones at its VERT arm.
21261 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21262 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21263 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
21264 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
21265 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
21266 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
21267 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
21268 /// inter frame) -- (128x64, 64x128).
21269 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
21270 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
21271 /// handed back var-tx leaves, so the per-transform-unit luma publication
21272 /// loop never ran and the block has to clear its own luma coefficient
21273 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
21274 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
21275 /// non-vacuous.
21276 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21277 /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded
21278 /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the
21279 /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this
21280 /// shape non-vacuous -- a stream that never codes one reads 0.
21281 pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21282 /// lane-av1-128rectspan: chroma transform units of a 128-root HORZ/VERT
21283 /// intra block re-stamped by the end-of-block replay
21284 /// (`record_split_luma_rect` clobbers the per-unit contexts the chroma
21285 /// walk published, so every unit replays its own state after it). A
21286 /// non-skip 128x64/64x128 block codes `nch_x * cn * 2 + nch_y * cn_h * 2`
21287 /// of them, so this reads 0 on any stream that never codes one -- the
21288 /// non-vacuity anchor for the replay's own gate.
21289 pub(crate) static SB128RECT_CHROMA_REPLAY_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21290 /// ... and the number of non-skip 128-root rect BLOCKS whose replay
21291 /// height differs from the unit's own LUMA-MI height -- the signature of the
21292 /// width passed to both axes (`luma_span` where the in-loop stamp used
21293 /// `luma_span_h`). Zero on every stream this decoder admits: both
21294 /// supported chroma formats have `ss_x == ss_y` (4:2:0 and 4:4:4), and
21295 /// 4:2:2 -- the one format whose two spans differ -- is refused by name
21296 /// at the sequence header (`stream::decode_frame`), so the arm is
21297 /// defensive until that format is ported. The counter turns a future
21298 /// 4:2:2 admission (or any hardcoded span) into a named red gate instead
21299 /// of silent mi-state corruption.
21300 pub(crate) static SB128RECT_REPLAY_SPAN_MISMATCH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21301}
21302
21303/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
21304pub fn skip_vartx_luma_reset_hits() -> usize {
21305 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
21306}
21307
21308/// [`INTRA128_LOSSLESS_HITS`], for a gate's own before/after delta.
21309pub(crate) fn intra128_lossless_hits() -> usize {
21310 INTRA128_LOSSLESS_HITS.with(std::cell::Cell::get)
21311}
21312
21313/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
21314pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
21315 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
21316}
21317
21318/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
21319/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
21320pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
21321 (
21322 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
21323 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
21324 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
21325 )
21326}
21327
21328/// [`SB128RECT_CHROMA_REPLAY_HITS`] (chroma units re-stamped by
21329/// `decode_block_128rect`'s end-of-block replay) and
21330/// [`SB128RECT_REPLAY_SPAN_MISMATCH_HITS`] (replays whose stamped height was
21331/// not the unit's own), for a gate's own before/after delta.
21332pub(crate) fn sb128rect_chroma_replay_hits() -> (usize, usize) {
21333 (
21334 SB128RECT_CHROMA_REPLAY_HITS.with(std::cell::Cell::get),
21335 SB128RECT_REPLAY_SPAN_MISMATCH_HITS.with(std::cell::Cell::get),
21336 )
21337}
21338
21339/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
21340/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
21341/// `decode_inter_block`'s own rect path).
21342///
21343/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
21344/// transform unit, with the 128-specific geometry:
21345/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
21346/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
21347/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
21348/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
21349/// same CDF a 64x64 square block reads).
21350/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
21351/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
21352/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
21353/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
21354/// a chunk before moving to the next (the interleave lane-sb128b r3
21355/// measured at the 128x128 NONE root).
21356/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
21357/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
21358/// No CfL, no filter intra (both cap at 32x32) and no palette
21359/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
21360/// reader's own size gates already say so, and the guard below is defensive.
21361///
21362/// lane-lossless128: on a LOSSLESS frame every one of those sizes collapses to
21363/// TX_4X4 -- `read_tx_mode` returns `ONLY_4X4` before the frame codes a tx-size
21364/// symbol and `read_tx_size` returns `TX_4X4` before it looks at anything
21365/// (`decodeframe.c:141`, `:1183`) -- so the block is tiled into 4x4 luma units
21366/// and (because a lossless frame forces `TX_4X4` on CHROMA too) 4x4 chroma
21367/// units, plane-major inside each 64x64 mu chunk exactly as
21368/// `decode_token_recon_block` codes them. Reading the 64-point geometry there
21369/// reconstructs into a `side`-sized plane with a 16-sample residual (the panic
21370/// this lane closed); the geometry and the unit walks below are normalized on
21371/// `lossless_frame`.
21372#[allow(clippy::too_many_arguments)]
21373fn decode_block_128rect(
21374 dec: &mut SymbolDecoder,
21375 cdfs: &mut Cdfs,
21376 neighbours: &mut Neighbours,
21377 at: (usize, usize),
21378 bw: usize,
21379 bh: usize,
21380 y: &mut PlaneBuf<'static>,
21381 u: &mut PlaneBuf<'static>,
21382 v: &mut PlaneBuf<'static>,
21383 base_q_idx: u8,
21384 enable_filter_intra: bool,
21385 allow_screen_content_tools: bool,
21386 tx_select: bool,
21387 reduced_tx_set: bool,
21388 fctx: &crate::decode::FrameCtx,
21389) -> Result<()> {
21390 let (r, c) = at;
21391 let (px, py) = (c * SUB, r * SUB);
21392 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
21393 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
21394 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
21395 let palette_uv_cache = neighbours.palette_uv_cache(at);
21396 let (
21397 skip,
21398 mode,
21399 angle_delta_y,
21400 uv_mode,
21401 angle_delta_uv,
21402 alpha,
21403 filter_intra,
21404 palette_y,
21405 palette_uv,
21406 intrabc,
21407 ) = read_intra_mode_rect(
21408 dec,
21409 cdfs,
21410 nb_above_mode,
21411 nb_left_mode,
21412 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
21413 // 13-symbol no-CFL CDF here, never the 14-symbol one.
21414 false,
21415 true,
21416 bw,
21417 bh,
21418 enable_filter_intra,
21419 neighbours.skip_txfm_ctx(mi_r, mi_c),
21420 allow_screen_content_tools,
21421 Some((palette_ctx, &palette_cache)),
21422 &palette_uv_cache,
21423 mi_r,
21424 mi_c,
21425 fctx,
21426 )?;
21427 if let Some((dv_row, dv_col)) = intrabc {
21428 // lane-av1-ibcrect: the reconstruction is ported -- an intrabc block
21429 // is is_inter_block, so libaom predicts the whole 128x64/64x128 strip
21430 // from this frame's own reconstruction and runs the INTER residual
21431 // walk (`decode_token_recon_block`'s else arm) over it.
21432 return decode_intrabc_128rect(
21433 dec,
21434 cdfs,
21435 neighbours,
21436 (mi_r, mi_c),
21437 (bw, bh),
21438 skip,
21439 (dv_row, dv_col),
21440 y,
21441 u,
21442 v,
21443 base_q_idx,
21444 fctx,
21445 );
21446 }
21447 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
21448 return Err(unsupported(
21449 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
21450 their size gates caps at 64x64 or below, so none of these symbols exists there)",
21451 ));
21452 }
21453 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
21454 DC_PRED
21455 } else {
21456 uv_mode
21457 };
21458 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
21459 if smooth_neighbor {
21460 hit!(SMOOTH_LUMA_HITS);
21461 }
21462 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
21463 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
21464 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
21465 // lane-lossless128: a LOSSLESS frame codes no tx-size symbol at all --
21466 // libaom's `read_tx_mode` returns `ONLY_4X4` for a `coded_lossless` frame
21467 // before the symbol is even considered (`decodeframe.c:141`) and
21468 // `read_tx_size` returns `TX_4X4` before it looks at anything
21469 // (`decodeframe.c:1183`). So `tx_select` is off, every plane is walked as
21470 // TX_4X4 transform units, and no `tx_size_cat3` symbol may be consumed.
21471 let lossless_frame = lossless(fctx);
21472 let in_inter = fctx
21473 .intra_in_inter_mode
21474 .with(std::cell::Cell::get)
21475 .is_some();
21476 let depth = if tx_select && !lossless_frame {
21477 // lane-inter128intra r1: `get_tx_size_context` compares the bands
21478 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --
21479 // TX_64X64 for every 128-axis block, hence the `min(64)`.
21480 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
21481 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
21482 } else {
21483 0
21484 };
21485 if depth != 0 {
21486 hit!(TX_DEPTH_HITS);
21487 }
21488 hit_do! {
21489 INTRA_SB128_DEPTH_HITS.with(|c| {
21490 let mut h = c.get();
21491 h[depth.min(2)] += 1;
21492 c.set(h);
21493 });
21494 }
21495 let logical_tx = if lossless_frame { 4 } else { 64 >> depth };
21496 if lossless_frame {
21497 hit!(INTRA128_LOSSLESS_HITS);
21498 }
21499 // A 64-point transform codes nothing past its low 32 coefficients.
21500 let coeff_tx_side = logical_tx.min(32);
21501 let luma_set = if lossless_frame {
21502 TxbSet::Luma4
21503 } else {
21504 txbset_for(logical_tx, reduced_tx_set)
21505 };
21506 let luma_scan = default_scan(coeff_tx_side);
21507 // `av1_get_max_uv_txsize` caps at TX_32X32 normally; a lossless frame
21508 // forces every plane to TX_4X4 (its own `Chroma4` set and 4x4 scan).
21509 let chroma_tx = if lossless_frame { 4 } else { 32 };
21510 let chroma_set = if lossless_frame {
21511 TxbSet::Chroma4
21512 } else {
21513 TxbSet::Chroma32
21514 };
21515 let chroma_scan = default_scan(chroma_tx);
21516 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
21517 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
21518 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
21519 let (nch_x, nch_y) = (bw / 64, bh / 64);
21520 // The frame's own mi grid (`av1_calc_mi_size`, 8-px aligned): libaom's
21521 // `decode_token_recon_block` clips each vector's walk to
21522 // `max_block_wide/high`, so a chroma unit whose top-left is off the frame
21523 // codes nothing.
21524 let mi_cols = 2 * y.true_width.div_ceil(8);
21525 let mi_rows = 2 * y.true_height.div_ceil(8);
21526 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
21527 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
21528 // Non-lossless: per mu chunk, `(64 >> ss) / chroma_tx` chroma units per
21529 // axis -- one 32x32 at 4:2:0, two stacked on the tall axis at 4:2:2
21530 // (lane-av1-422bigblock: the chunk's chroma plane block is 32x64 there),
21531 // four at 4:4:4 (lane-av1-444sb's own finding on this same walk).
21532 debug_assert!(
21533 lossless_frame
21534 || (chroma_w / chroma_tx, chroma_h / chroma_tx)
21535 == (
21536 nch_x * ((64 >> ss_x(fctx)) / chroma_tx),
21537 nch_y * ((64 >> ss_y(fctx)) / chroma_tx)
21538 )
21539 );
21540 let tpc = 64 / logical_tx;
21541 let zero_tu = vec![0i32; logical_tx * logical_tx];
21542 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
21543 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
21544 let mut units: Vec<(usize, (usize, usize), Grid)> = Vec::new();
21545 // The chroma context arrays are indexed in LUMA mi; every chroma unit of
21546 // every chunk shares this luma span (2 chroma pixels per luma unit).
21547 let luma_span = chroma_tx << ss_x(fctx);
21548 let luma_span_h = chroma_tx << ss_y(fctx);
21549 for ch_row in 0..nch_y {
21550 for ch_col in 0..nch_x {
21551 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
21552 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
21553 let tu_mi = (
21554 mi_r + tu_row * (logical_tx / MI),
21555 mi_c + tu_col * (logical_tx / MI),
21556 );
21557 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
21558 // libaom clips the transform loop to
21559 // `max_blocks_wide/high`: a unit whose top-left sample is
21560 // outside the frame is never coded.
21561 if tu_px >= y.true_width || tu_py >= y.true_height {
21562 continue;
21563 }
21564 // Edge availability of a unit INSIDE a block, with the
21565 // 128 geometry -- `has_top_right` is false for a block
21566 // whose largest side is > 64, which [`Reach::of_rect`]
21567 // already answered for the block and [`tu_reach`] carries
21568 // down to the units on its own top row.
21569 let tu_r = tu_reach(
21570 bw,
21571 bh,
21572 tu_col * logical_tx,
21573 tu_row * logical_tx,
21574 logical_tx,
21575 reach,
21576 px,
21577 py,
21578 y.width,
21579 y.height,
21580 fctx,
21581 );
21582 if skip {
21583 push_intra(
21584 0,
21585 tu_px,
21586 tu_py,
21587 logical_tx,
21588 mode,
21589 angle_delta_y,
21590 tu_r,
21591 &zero_tu,
21592 None,
21593 None,
21594 smooth_neighbor,
21595 fctx,
21596 );
21597 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
21598 continue;
21599 }
21600 // The unit is smaller than its block, so `txb_skip_ctx`
21601 // is the neighbour-magnitude table, never the lone-TU 0.
21602 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
21603 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
21604 let tu_grid = read_plane(
21605 dec,
21606 cdfs,
21607 luma_set,
21608 &luma_scan,
21609 0,
21610 tu_around,
21611 mode,
21612 mode,
21613 angle_delta_y,
21614 tu_r,
21615 y,
21616 tu_px,
21617 tu_py,
21618 logical_tx,
21619 coeff_tx_side,
21620 base_q_idx,
21621 None,
21622 None,
21623 Some(tu_skip_ctx),
21624 smooth_neighbor,
21625 fctx,
21626 )?;
21627 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
21628 }
21629 }
21630 // Transform units per axis inside this mu chunk's chroma span:
21631 // a 64x64 luma chunk covers `64 >> ss` chroma pixels per axis,
21632 // so it holds `(64 >> ss) / chroma_tx` units -- one 32x32 at
21633 // 4:2:0, four at 4:4:4 (lane-av1-444sb), TWO STACKED TX_32X32 on
21634 // the tall axis at 4:2:2 (lane-av1-422bigblock: the chunk's
21635 // chroma plane block is 32x64 there, so the two axes' counts
21636 // part ways -- 1 x 2); 8x8 TX_4X4 units when lossless.
21637 let cn = ((64 >> ss_x(fctx)) / chroma_tx).max(1);
21638 let cn_h = ((64 >> ss_y(fctx)) / chroma_tx).max(1);
21639 // libaom's per-chunk `unit_width/height` (plane-mi units of the
21640 // luma mi grid): `min(mu_blocks + col, max_blocks) >> ss`.
21641 let unit_w = ((ch_col + 1) * 16).min(max_w_mi) >> ss_x(fctx);
21642 let unit_h = ((ch_row + 1) * 16).min(max_h_mi) >> ss_y(fctx);
21643 let stepc = (chroma_tx / 4).max(1);
21644 // `decode_token_recon_block` codes a mu chunk PLANE-MAJOR: every U
21645 // unit of the chunk, then every V unit. At one unit per plane per
21646 // chunk (every non-lossless 128-axis block) that is the same
21647 // symbol order the interleaved pair used to read; a lossless
21648 // frame's 4x4 chroma units are where it becomes observable.
21649 for plane_pass in 1..=2usize {
21650 for ci_row in 0..cn_h {
21651 for ci_col in 0..cn {
21652 // The clamp strides are the CHUNK's chroma mi extent
21653 // per axis: 16 luma mi >> the axis's own ss.
21654 if ch_col * (16 >> ss_x(fctx)) + ci_col * stepc >= unit_w
21655 || ch_row * (16 >> ss_y(fctx)) + ci_row * stepc >= unit_h
21656 {
21657 continue;
21658 }
21659 let cu_x = cpx + ch_col * (64 >> ss_x(fctx)) + ci_col * chroma_tx;
21660 let cu_y = cpy + ch_row * (64 >> ss_y(fctx)) + ci_row * chroma_tx;
21661 let cu_mi = (
21662 mi_r + ch_row * 16 + ci_row * ((chroma_tx << ss_y(fctx)) / 4),
21663 mi_c + ch_col * 16 + ci_col * ((chroma_tx << ss_x(fctx)) / 4),
21664 );
21665 let cu_r = tu_reach_rect(
21666 bw,
21667 bh,
21668 ch_col * 64 + ci_col * luma_span,
21669 ch_row * 64 + ci_row * luma_span_h,
21670 luma_span,
21671 luma_span_h,
21672 reach,
21673 px,
21674 py,
21675 y.width,
21676 y.height,
21677 fctx,
21678 );
21679 if skip {
21680 push_intra(
21681 plane_pass,
21682 cu_x,
21683 cu_y,
21684 chroma_tx,
21685 uv_predict_mode,
21686 angle_delta_uv,
21687 cu_r,
21688 &zero_cu,
21689 None,
21690 None,
21691 smooth_neighbor_uv,
21692 fctx,
21693 );
21694 continue;
21695 }
21696 let cu_around = neighbours.around_mi_rect(cu_mi, luma_span, luma_span_h);
21697 let buf: &mut PlaneBuf<'static> =
21698 if plane_pass == 1 { &mut *u } else { &mut *v };
21699 let grid = read_plane(
21700 dec,
21701 cdfs,
21702 chroma_set,
21703 &chroma_scan,
21704 plane_pass,
21705 cu_around[plane_pass],
21706 mode,
21707 uv_predict_mode,
21708 angle_delta_uv,
21709 cu_r,
21710 buf,
21711 cu_x,
21712 cu_y,
21713 chroma_tx,
21714 chroma_tx,
21715 base_q_idx,
21716 None,
21717 None,
21718 Some(3),
21719 smooth_neighbor_uv,
21720 fctx,
21721 )?;
21722 last_grids[plane_pass - 1] = grid.clone();
21723 // Immediately, so the NEXT unit of this same block
21724 // reads this one's coefficient context; replayed after
21725 // `record_split_luma_rect` below, which would otherwise
21726 // clobber them whole-block.
21727 neighbours.record_mi_chroma(
21728 cu_mi,
21729 luma_span,
21730 luma_span_h,
21731 plane_pass,
21732 &grid,
21733 );
21734 units.push((plane_pass, cu_mi, grid));
21735 }
21736 }
21737 }
21738 if !skip {
21739 hit!(CHROMA_SPLIT_TX_HITS);
21740 }
21741 }
21742 }
21743 if skip {
21744 neighbours.record_rect(
21745 at,
21746 bw,
21747 bh,
21748 mode,
21749 uv_predict_mode,
21750 &[
21751 &ZERO_RESIDUAL[..bw * bh],
21752 &ZERO_RESIDUAL[..chroma_w * chroma_h],
21753 &ZERO_RESIDUAL[..chroma_w * chroma_h],
21754 ],
21755 );
21756 } else {
21757 neighbours.record_split_luma_rect(
21758 at,
21759 bw,
21760 bh,
21761 mode,
21762 uv_predict_mode,
21763 [&last_grids[0], &last_grids[1]],
21764 );
21765 // lane-av1-128rectspan: the replay must re-stamp each unit over the
21766 // SAME cells the walk above stamped it over -- `record_mi_chroma`'s
21767 // height drives `left[]` and its width `above[]`, and the walk used
21768 // the per-axis `luma_span_h`. Passing the width on both axes doubled
21769 // the `left[]` run wherever the two differ (4:2:2), reaching 8 mi
21770 // rows below the block on the last unit of a 128x64/64x128 strip and
21771 // smearing a neighbour chunk's unit over its neighbour's rows.
21772 //
21773 // DEFENSIVE at the decoder's current capability set: both admitted
21774 // chroma formats have `ss_x == ss_y` (4:2:0 ss (1,1), 4:4:4 ss
21775 // (0,0)), so the two spans are equal and this line is a no-op on
21776 // every stream `decode_stream` accepts; 4:2:2 (ss (1,0)) -- the one
21777 // format where they differ -- is refused by name at the sequence
21778 // header, so the arm is unreachable there. It stays per-axis because
21779 // the walk it replays is per-axis, and a 4:2:2 port must not have to
21780 // re-derive this. `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` names the
21781 // day that changes.
21782 if luma_span != luma_span_h {
21783 hit!(SB128RECT_REPLAY_SPAN_MISMATCH_HITS);
21784 }
21785 for (plane, cu_mi, grid) in &units {
21786 neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span_h, *plane, grid);
21787 hit!(SB128RECT_CHROMA_REPLAY_HITS);
21788 }
21789 }
21790 // No palette exists at this size; the unconditional stamp clears any
21791 // stale neighbour palette state, as every other block path does.
21792 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
21793 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
21794 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
21795 neighbours.fill_lf_grid_rect(
21796 (mi_r, mi_c),
21797 bw / MI,
21798 bh / MI,
21799 logical_tx as u8,
21800 logical_tx as u8,
21801 0,
21802 fctx,
21803 );
21804 if in_inter || allow_intrabc_frame(fctx) {
21805 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
21806 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
21807 // inter frame, intra ones included: an intra block stamps its
21808 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
21809 // A key frame reads those bands only when it allows intrabc
21810 // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom
21811 // stamps here too -- lane-av1-intrabc r3.
21812 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (logical_tx, logical_tx), (bw, bh));
21813 }
21814 if in_inter {
21815 hit_do! {
21816 INTRA128_IN_INTER_HITS.with(|c| {
21817 let mut h = c.get();
21818 h[usize::from(bw < bh)] += 1;
21819 c.set(h);
21820 });
21821 }
21822 } else if bw > bh {
21823 hit!(INTRA_SB128_HORZ_HITS);
21824 } else {
21825 hit!(INTRA_SB128_VERT_HITS);
21826 }
21827 Ok(())
21828}
21829
21830/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
21831/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
21832/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
21833/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
21834/// just-decoded mode, not the enclosing slot's stale one, is the true
21835/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
21836/// units, which is what its coefficient context (finer than [`SUB`]) is read
21837/// at. Returns the mode this leaf decoded, for the caller's own
21838/// `prev_leaf`/final mode-writeback bookkeeping.
21839#[allow(clippy::too_many_arguments)]
21840/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
21841/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
21842/// `above_mode[col]`, and its true above neighbour is the mi directly above
21843/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
21844/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
21845/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
21846/// (bottom-right) into both, as this path did, is right only when all four
21847/// leaves happen to share a mode. `done` may be short at the true frame edge
21848/// (the straddle caller filters positions off the frame), so each side falls
21849/// back to the last leaf actually decoded.
21850fn write_back_split_modes(
21851 neighbours: &mut Neighbours,
21852 done: &[((usize, usize), usize)],
21853 parent_mi: (usize, usize),
21854 slot: (usize, usize),
21855) {
21856 let (sr, sc) = slot;
21857 let Some(&(_, last)) = done.last() else {
21858 return;
21859 };
21860 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
21861 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
21862 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
21863}
21864
21865fn decode_leaf8(
21866 dec: &mut SymbolDecoder,
21867 cdfs: &mut Cdfs,
21868 neighbours: &mut Neighbours,
21869 outer_at: (usize, usize),
21870 leaf_mi: (usize, usize),
21871 scans: (&[u16], &[u16]),
21872 prev_leaf: Option<((usize, usize), usize)>,
21873 y: &mut PlaneBuf<'static>,
21874 u: &mut PlaneBuf<'static>,
21875 v: &mut PlaneBuf<'static>,
21876 base_q_idx: u8,
21877 enable_filter_intra: bool,
21878 allow_screen_content_tools: bool,
21879 allow_intrabc: bool,
21880 tx_select: bool,
21881 reduced_tx_set: bool,
21882 fctx: &crate::decode::FrameCtx,
21883) -> Result<usize> {
21884 let (r, c) = outer_at;
21885 // lane-modectx r1: the group's own availability-correct fallback pair, not
21886 // the raw coarse bands (which leak across a tile edge -- see
21887 // `modes_above_left`).
21888 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
21889 if let Some(((pr, pc), pmode)) = prev_leaf {
21890 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
21891 above_mode = pmode;
21892 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
21893 left_mode = pmode;
21894 }
21895 }
21896 // The mi-exact neighbour wins over both the coarse 16x16 slot and
21897 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
21898 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
21899 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
21900 // lane-rectsplitx r2 swept this arm into
21901 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
21902 // "no neighbour" at a tile edge, where the coarse cell holds the block
21903 // above/left of it inside the same 16x16.
21904 let (above_mode, left_mode) =
21905 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
21906 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
21907 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
21908 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
21909 // this leaf's `smooth_neighbor` is built from -- passing `false` here
21910 // filtered a directional chroma block's edge at the wrong strength
21911 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
21912 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
21913 // with the coarse [`SUB`] slot as the fallback when no block recorded
21914 // that exact mi cell.
21915 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
21916 if smooth_neighbor {
21917 hit!(SMOOTH_LUMA_HITS);
21918 }
21919 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
21920 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
21921 // `decode_block` caller at 16x16 and up.
21922 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
21923 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
21924 // `read_palette_mode_info`), at its REAL mi position -- passing
21925 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
21926 // moment a real 8x8 palette block fired, which is where every 8-bit
21927 // `--tune-content=screen --min-partition-size=8` stream stopped.
21928 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
21929 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
21930 let (
21931 skip,
21932 mode,
21933 angle_delta_y,
21934 uv_mode,
21935 angle_delta_uv,
21936 alpha,
21937 filter_intra,
21938 palette_y,
21939 palette_uv,
21940 ) = read_intra_mode(
21941 dec,
21942 cdfs,
21943 above_mode,
21944 left_mode,
21945 true,
21946 8,
21947 enable_filter_intra,
21948 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
21949 allow_screen_content_tools,
21950 allow_intrabc,
21951 Some((palette_ctx, &palette_cache)),
21952 &palette_uv_cache,
21953 leaf_mi.0,
21954 leaf_mi.1,
21955 fctx,
21956 )?;
21957 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
21958 // `read_intra_mode` and then decoded the block as if it were ordinary
21959 // intra. libaom's `is_inter_block` counts an intrabc block
21960 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
21961 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
21962 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
21963 // same value with a different interval, so the tile desynced at the very
21964 // next symbol (class `wrong-alphabet-same-value`). Everything below
21965 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
21966 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
21967 if intrabc_dv.is_some() {
21968 hit!(LEAF8_INTRABC_HITS);
21969 }
21970 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
21971 // index map, mapped through the base colours, IS the block's prediction --
21972 // carried to the next `reconstruct`/`read_plane` through the same
21973 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
21974 let palette_y_buf: Option<Vec<u16>> = palette_y
21975 .as_ref()
21976 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
21977 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
21978 (
21979 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
21980 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
21981 )
21982 });
21983 let (pal_y_size, pal_y_colors) = palette_y
21984 .as_ref()
21985 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
21986 let (pal_uv_size, pal_uv_colors) = palette_uv
21987 .as_ref()
21988 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
21989 if palette_y.is_some() || palette_uv.is_some() {
21990 hit!(PALETTE_LEAF8_HITS);
21991 }
21992 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
21993 DC_PRED
21994 } else {
21995 uv_mode
21996 };
21997 neighbours.above_uv_mode[c] = uv_predict_mode;
21998 neighbours.left_uv_mode[r] = uv_predict_mode;
21999 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
22000 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
22001 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
22002 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
22003 // transform units, same raster-order per-TU pattern `decode_block`'s
22004 // multi-TU branch runs).
22005 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
22006 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
22007 // intrabc block, so a SKIPPED one takes the largest transform and an
22008 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
22009 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
22010 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
22011 // `parse_decode_block`'s tree condition carries
22012 // `!xd->lossless[mbmi->segment_id]` (see [`decode_block`]'s own copy):
22013 // a lossless segment's intrabc leaf reads no tree, TX_4X4 via
22014 // `read_tx_size`'s first line (lane-av1mixloss).
22015 let resolved = if tx_select && intrabc_dv.is_some() && !skip && !lossless(fctx) {
22016 let mut leaves = Vec::new();
22017 let mi_cols = 2 * y.true_width.div_ceil(8);
22018 let mi_rows = 2 * y.true_height.div_ceil(8);
22019 read_var_tx_size(
22020 dec,
22021 cdfs,
22022 neighbours,
22023 leaf_mi,
22024 8,
22025 (
22026 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
22027 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
22028 ),
22029 (8, 8),
22030 0,
22031 0,
22032 0,
22033 &mut leaves,
22034 );
22035 hit!(INTRABC_VARTX_HITS);
22036 leaves.first().map_or(8, |l| l.2)
22037 } else if tx_select && intrabc_dv.is_none() {
22038 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, fctx)
22039 } else {
22040 // lane-lossless: TX_4X4 on a lossless frame, no symbol
22041 // (libaom `read_tx_size`).
22042 lossless_tx(8, fctx)
22043 };
22044 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
22045 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
22046 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
22047 // 4:4:4: this 8x8 block's chroma plane block is 8x8 (same scan as luma,
22048 // `scans.0`). 4:2:0 stays the 4x4 unit this leaf was written for.
22049 // lane-av1-422d: 4:2:2 (ss 1/0) halves only the width, so the plane block
22050 // is 4x8 -- ONE rect transform unit per plane (`av1_get_max_uv_txsize(
22051 // BLOCK_8X8)` at ss (1,0) is `max_txsize_rect_lookup[BLOCK_4X8]` ==
22052 // TX_4X8): one txb_skip + one scan per plane in the
22053 // [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the
22054 // shape, read through [`leaf8_chroma422_unit`] in each arm below. The
22055 // `(csz, cset, cscan)` selection keeps serving the square arms (444's
22056 // 8x8, 420's 4x4); the rect arms branch on [`chroma_422`] instead.
22057 let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
22058 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
22059 let (csz, cset, cscan) = if chroma_444 {
22060 (8usize, TxbSet::Chroma8, scans.0)
22061 } else {
22062 (4usize, TxbSet::Chroma4, scans.1)
22063 };
22064 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
22065 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
22066 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
22067 // the full-pel block vector, with the BILINEAR kernel libaom forces.
22068 flush_recon(fctx, y, u, v);
22069 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
22070 let mut yb = vec![0u16; 8 * 8];
22071 mc::predict_with_filter(
22072 &y.data,
22073 y.width,
22074 y.true_width,
22075 y.true_height,
22076 mv_to_q4(px, dv_col, 0),
22077 mv_to_q4(py, dv_row, 0),
22078 8,
22079 8,
22080 mc::InterpFilterKind::Bilinear,
22081 &mut yb,
22082 fctx,
22083 );
22084 // The chroma extent is THIS frame's subsampled size of the 8x8 luma
22085 // leaf (`get_plane_block_size`): 4x4 at 4:2:0, 4x8 at 4:2:2, 8x8 at
22086 // 4:4:4. The literal 4x4 this replaces hardcoded the 4:2:0 halving --
22087 // at 4:4:4 the 16-sample override fed this leaf's own 8x8 chroma
22088 // reconstruct, which indexed `prediction[16]` of a 16-sample buffer
22089 // (len 16, index 16 at `PlaneBuf::reconstruct`), and at 4:2:2 it
22090 // covered half the leaf's 4x8 chroma plane block (lane-av1-422d's
22091 // `if chroma_422 { (4, 8) }` arm, which the ss-derived form subsumes:
22092 // `8 >> ss_x` is 4 and `8 >> ss_y` is 8 there). The same buffers
22093 // are windowed at stride 8 by `read_intra_chroma_lossless` (the TX4
22094 // 4:4:4-lossless arm) and consumed whole by the TX8 and skip arms,
22095 // so all three heal with this one sizing.
22096 let (cw, ch) = (8 >> ss_x(fctx), 8 >> ss_y(fctx));
22097 let mut ub = vec![0u16; cw * ch];
22098 mc::predict_with_filter(
22099 &u.data,
22100 u.width,
22101 u.true_width,
22102 u.true_height,
22103 mv_to_q4(cpx, dv_col, ss_x(fctx)),
22104 mv_to_q4(cpy, dv_row, ss_y(fctx)),
22105 cw,
22106 ch,
22107 mc::InterpFilterKind::Bilinear,
22108 &mut ub,
22109 fctx,
22110 );
22111 let mut vb = vec![0u16; cw * ch];
22112 mc::predict_with_filter(
22113 &v.data,
22114 v.width,
22115 v.true_width,
22116 v.true_height,
22117 mv_to_q4(cpx, dv_col, ss_x(fctx)),
22118 mv_to_q4(cpy, dv_row, ss_y(fctx)),
22119 cw,
22120 ch,
22121 mc::InterpFilterKind::Bilinear,
22122 &mut vb,
22123 fctx,
22124 );
22125 (yb, ub, vb)
22126 });
22127 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
22128 // `decode_block` uses: set fresh right before each plane's own
22129 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
22130 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
22131 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
22132 // first shape that reaches that loop with an override set).
22133 let palette_y_buf = match &intrabc_bufs {
22134 Some((yb, _, _)) => Some(yb.clone()),
22135 None => palette_y_buf,
22136 };
22137 // lane-av1intrapred: the chroma twin of the `palette_y_buf` wrap above --
22138 // `decode_block` does the same for its own `palette_uv_bufs`
22139 // (decode.rs's single-TU and multi-TU chroma reads). Without it, an
22140 // intrabc leaf whose var-tx tree split to TX_4X4 reached the TX4 arm's
22141 // chroma reads with the override unset: the unit predicted INTRA from
22142 // the UV mode (intrabc's is DC) instead of copying the frame at the DV,
22143 // R5 first differing pixel U(184,4), block mi (2,92).
22144 let palette_uv_bufs = match &intrabc_bufs {
22145 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
22146 None => palette_uv_bufs,
22147 };
22148 let (luma_grid, u_grid, v_grid);
22149 if skip {
22150 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
22151 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
22152 // transform units, each off the units already written left/above of
22153 // it inside this same leaf -- an intra block's transform size is read
22154 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
22155 // A palette block's prediction is the whole-block index map, never
22156 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
22157 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
22158 // even when `tx_depth` resolved to TX_4X4.
22159 if resolved == 4 && palette_y_buf.is_none() {
22160 hit!(SKIP_SPLIT_TX_HITS);
22161 for tu_row in 0..2 {
22162 for tu_col in 0..2 {
22163 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
22164 if tu_px >= y.true_width || tu_py >= y.true_height {
22165 continue;
22166 }
22167 let tu_reach = tu_reach(
22168 8,
22169 8,
22170 tu_col * 4,
22171 tu_row * 4,
22172 4,
22173 reach,
22174 px,
22175 py,
22176 y.width,
22177 y.height,
22178 fctx,
22179 );
22180 push_intra(
22181 0,
22182 tu_px,
22183 tu_py,
22184 4,
22185 mode,
22186 angle_delta_y,
22187 tu_reach,
22188 &ZERO_RESIDUAL[..16],
22189 None,
22190 filter_intra,
22191 smooth_neighbor,
22192 fctx,
22193 );
22194 }
22195 }
22196 } else {
22197 if let Some(buf) = &palette_y_buf {
22198 set_palette_pred(buf.clone(), fctx);
22199 }
22200 push_intra(
22201 0,
22202 px,
22203 py,
22204 8,
22205 mode,
22206 angle_delta_y,
22207 reach,
22208 &ZERO_RESIDUAL[..64],
22209 None,
22210 filter_intra,
22211 smooth_neighbor,
22212 fctx,
22213 );
22214 }
22215 let ac = alpha.map(|_| cfl_src(px, py, 8));
22216 // Three skip-arm shapes, dispatched on THIS frame's subsampling.
22217 // lane-av1-422d: at 4:2:2 a skipped leaf still predicts its 4x8 rect
22218 // unit per plane (CfL keeps its contribution, [`decode_block`]'s own
22219 // skip-arm rule); no coefficient symbol exists, so the entropy
22220 // context never enters the rect read.
22221 if chroma_422 {
22222 u_grid = leaf8_chroma422_unit(
22223 dec,
22224 cdfs,
22225 (false, false, 0),
22226 uv_predict_mode,
22227 angle_delta_uv,
22228 reach,
22229 1,
22230 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22231 true,
22232 intrabc_bufs
22233 .as_ref()
22234 .map(|(_, ub, _)| ub.clone())
22235 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
22236 u,
22237 cpx,
22238 cpy,
22239 smooth_neighbor_uv,
22240 fctx,
22241 )?;
22242 v_grid = leaf8_chroma422_unit(
22243 dec,
22244 cdfs,
22245 (false, false, 0),
22246 uv_predict_mode,
22247 angle_delta_uv,
22248 reach,
22249 2,
22250 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22251 true,
22252 intrabc_bufs
22253 .as_ref()
22254 .map(|(_, _, vb)| vb.clone())
22255 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
22256 v,
22257 cpx,
22258 cpy,
22259 smooth_neighbor_uv,
22260 fctx,
22261 )?;
22262 luma_grid = Grid::Zero(64);
22263 } else {
22264 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster of
22265 // TX_4X4 units (`av1_get_tx_size`: lossless forces TX_4X4 on EVERY
22266 // plane), so a skipped leaf predicts per unit -- each from its own
22267 // edges -- like the luma `SKIP_SPLIT_TX` loop above. CfL never fires
22268 // here (`is_cfl_allowed` at lossless needs plane_bsize == 4x4; this
22269 // chroma plane block is 8x8), and intrabc/palette keep the
22270 // whole-plane-block prediction they already run. The guard also
22271 // requires `chroma_444`, so it can never reach the 4:2:2 arm above.
22272 let chroma_units_444 =
22273 chroma_444 && lossless(fctx) && intrabc_bufs.is_none() && palette_uv_bufs.is_none();
22274 if let Some((_, ub, _)) = &intrabc_bufs {
22275 set_palette_pred(ub.clone(), fctx);
22276 } else if let Some((ub, _)) = &palette_uv_bufs {
22277 set_palette_pred(ub.clone(), fctx);
22278 }
22279 if chroma_units_444 {
22280 for cu_row in 0..2 {
22281 for cu_col in 0..2 {
22282 let cu_reach = tu_reach(
22283 8,
22284 8,
22285 cu_col * 4,
22286 cu_row * 4,
22287 4,
22288 reach,
22289 px,
22290 py,
22291 y.width,
22292 y.height,
22293 fctx,
22294 );
22295 push_intra(
22296 1,
22297 cpx + cu_col * 4,
22298 cpy + cu_row * 4,
22299 4,
22300 uv_predict_mode,
22301 angle_delta_uv,
22302 cu_reach,
22303 &ZERO_RESIDUAL[..16],
22304 None,
22305 None,
22306 smooth_neighbor_uv,
22307 fctx,
22308 );
22309 }
22310 }
22311 } else {
22312 push_intra(
22313 1,
22314 cpx,
22315 cpy,
22316 csz,
22317 uv_predict_mode,
22318 angle_delta_uv,
22319 reach,
22320 &ZERO_RESIDUAL[..csz * csz],
22321 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22322 None,
22323 smooth_neighbor_uv,
22324 fctx,
22325 );
22326 }
22327 if let Some((_, _, vb)) = &intrabc_bufs {
22328 set_palette_pred(vb.clone(), fctx);
22329 } else if let Some((_, vb)) = &palette_uv_bufs {
22330 set_palette_pred(vb.clone(), fctx);
22331 }
22332 if chroma_units_444 {
22333 for cu_row in 0..2 {
22334 for cu_col in 0..2 {
22335 let cu_reach = tu_reach(
22336 8,
22337 8,
22338 cu_col * 4,
22339 cu_row * 4,
22340 4,
22341 reach,
22342 px,
22343 py,
22344 y.width,
22345 y.height,
22346 fctx,
22347 );
22348 push_intra(
22349 2,
22350 cpx + cu_col * 4,
22351 cpy + cu_row * 4,
22352 4,
22353 uv_predict_mode,
22354 angle_delta_uv,
22355 cu_reach,
22356 &ZERO_RESIDUAL[..16],
22357 None,
22358 None,
22359 smooth_neighbor_uv,
22360 fctx,
22361 );
22362 }
22363 }
22364 } else {
22365 push_intra(
22366 2,
22367 cpx,
22368 cpy,
22369 csz,
22370 uv_predict_mode,
22371 angle_delta_uv,
22372 reach,
22373 &ZERO_RESIDUAL[..csz * csz],
22374 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22375 None,
22376 smooth_neighbor_uv,
22377 fctx,
22378 );
22379 }
22380 luma_grid = Grid::Zero(64);
22381 u_grid = Grid::Zero(csz * csz);
22382 v_grid = Grid::Zero(csz * csz);
22383 }
22384 } else if resolved != 4 {
22385 let around = neighbours.around_mi(leaf_mi, 8);
22386 // lane-av1-422h: the 4:2:2 chroma rect unit's `get_txb_ctx_general`
22387 // reads its above votes over CHROMA 4-px cells -- at ss_x 1 one chroma
22388 // cell spans TWO luma mi columns, so the per-luma-mi sum counts each
22389 // above chroma column twice and `dc_sign_ctx`'s signum flips whenever
22390 // the doubled sum crosses zero (the same class
22391 // [`Neighbours::around_mi_422_chroma`] fixes for the rect readers;
22392 // measured at mi(2,24) plane 2: ours dc_sign row 0, oracle row 2).
22393 // The left extent is unsubsquared at ss_y 0 and stays one-to-one.
22394 let chroma_around = if chroma_422 {
22395 neighbours.around_mi_422_chroma(leaf_mi, 8, 8)
22396 } else {
22397 around
22398 };
22399 if let Some(buf) = &palette_y_buf {
22400 set_palette_pred(buf.clone(), fctx);
22401 }
22402 luma_grid = read_plane(
22403 dec,
22404 cdfs,
22405 if intrabc_dv.is_some() {
22406 inter_txbset_for(8, reduced_tx_set)
22407 } else if reduced_tx_set {
22408 TxbSet::Luma8
22409 } else {
22410 TxbSet::Luma8Set1
22411 },
22412 scans.0,
22413 0,
22414 around[0],
22415 mode,
22416 mode,
22417 angle_delta_y,
22418 reach,
22419 y,
22420 px,
22421 py,
22422 8,
22423 TX8,
22424 base_q_idx,
22425 None,
22426 filter_intra,
22427 None,
22428 smooth_neighbor,
22429 fctx,
22430 )?;
22431 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
22432 // an intrabc block's chroma tx_type is the colocated LUMA transform's
22433 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
22434 if intrabc_dv.is_some() {
22435 fctx.intrabc_chroma_tx
22436 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
22437 }
22438 let ac = alpha.map(|_| cfl_src(px, py, 8));
22439 if chroma_422 {
22440 // lane-av1-422d: ONE 4x8 rect unit per plane (`av1_get_max_uv_txsize`
22441 // at ss (1,0) == TX_4X8), covering the plane block exactly, off the
22442 // leaf's own 8x8-span entropy context (`chroma_tiled`'s convention).
22443 u_grid = leaf8_chroma422_unit(
22444 dec,
22445 cdfs,
22446 chroma_around[1],
22447 uv_predict_mode,
22448 angle_delta_uv,
22449 reach,
22450 1,
22451 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22452 false,
22453 intrabc_bufs
22454 .as_ref()
22455 .map(|(_, ub, _)| ub.clone())
22456 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
22457 u,
22458 cpx,
22459 cpy,
22460 smooth_neighbor_uv,
22461 fctx,
22462 )?;
22463 v_grid = leaf8_chroma422_unit(
22464 dec,
22465 cdfs,
22466 chroma_around[2],
22467 uv_predict_mode,
22468 angle_delta_uv,
22469 reach,
22470 2,
22471 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22472 false,
22473 intrabc_bufs
22474 .as_ref()
22475 .map(|(_, _, vb)| vb.clone())
22476 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
22477 v,
22478 cpx,
22479 cpy,
22480 smooth_neighbor_uv,
22481 fctx,
22482 )?;
22483 } else {
22484 if let Some((_, ub, _)) = &intrabc_bufs {
22485 set_palette_pred(ub.clone(), fctx);
22486 } else if let Some((ub, _)) = &palette_uv_bufs {
22487 set_palette_pred(ub.clone(), fctx);
22488 }
22489 u_grid = read_plane(
22490 dec,
22491 cdfs,
22492 cset,
22493 cscan,
22494 1,
22495 around[1],
22496 mode,
22497 uv_predict_mode,
22498 angle_delta_uv,
22499 reach,
22500 u,
22501 cpx,
22502 cpy,
22503 csz,
22504 csz,
22505 base_q_idx,
22506 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22507 None,
22508 None,
22509 smooth_neighbor_uv,
22510 fctx,
22511 )?;
22512 if let Some((_, _, vb)) = &intrabc_bufs {
22513 set_palette_pred(vb.clone(), fctx);
22514 } else if let Some((_, vb)) = &palette_uv_bufs {
22515 set_palette_pred(vb.clone(), fctx);
22516 }
22517 v_grid = read_plane(
22518 dec,
22519 cdfs,
22520 cset,
22521 cscan,
22522 2,
22523 around[2],
22524 mode,
22525 uv_predict_mode,
22526 angle_delta_uv,
22527 reach,
22528 v,
22529 cpx,
22530 cpy,
22531 csz,
22532 csz,
22533 base_q_idx,
22534 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22535 None,
22536 None,
22537 smooth_neighbor_uv,
22538 fctx,
22539 )?;
22540 }
22541 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
22542 // two chroma reads (`decode_block`'s own tail does the same) -- left
22543 // set, every later chroma block would inherit this luma tx_type,
22544 // which picks the scan and the inverse transform.
22545 fctx.intrabc_chroma_tx.with(|c| c.set(None));
22546 } else {
22547 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
22548 // grid of 4x4 transform units, each predicted from the leaf's own
22549 // 8x8 `mode` and reading its own fresh context off the earlier
22550 // units in this same leaf (the same per-TU pattern `decode_block`'s
22551 // multi-TU branch runs at bigger blocks).
22552 let mut first_leaf_tx: Option<TxType> = None;
22553 for tu_row in 0..2 {
22554 for tu_col in 0..2 {
22555 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
22556 let tu_px = px + tu_col * 4;
22557 let tu_py = py + tu_row * 4;
22558 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
22559 if crate::encode::Reach::in_vert_ab() {
22560 hit!(VERT_AB_TX4_HITS);
22561 }
22562 let tu_reach = tu_reach(
22563 8,
22564 8,
22565 tu_col * 4,
22566 tu_row * 4,
22567 4,
22568 reach,
22569 px,
22570 py,
22571 y.width,
22572 y.height,
22573 fctx,
22574 );
22575 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
22576 // Each 4x4 unit predicts from its own window of the block's
22577 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
22578 // 16x16 and up) -- the whole-block buffer would be taken by
22579 // the FIRST unit and indexed at the wrong stride.
22580 if let Some(buf) = &palette_y_buf {
22581 hit!(PALETTE_SPLIT_TX_HITS);
22582 let mut window = vec![0u16; 16];
22583 for row in 0..4 {
22584 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
22585 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
22586 }
22587 set_palette_pred(window, fctx);
22588 }
22589 let tu_grid = read_plane(
22590 dec,
22591 cdfs,
22592 if intrabc_dv.is_some() {
22593 inter_txbset_for(4, reduced_tx_set)
22594 } else if reduced_tx_set {
22595 TxbSet::Luma4
22596 } else {
22597 TxbSet::Luma4Set1
22598 },
22599 scans.1,
22600 0,
22601 tu_around,
22602 mode,
22603 mode,
22604 angle_delta_y,
22605 tu_reach,
22606 y,
22607 tu_px,
22608 tu_py,
22609 4,
22610 4,
22611 base_q_idx,
22612 None,
22613 filter_intra,
22614 Some(tu_skip_ctx),
22615 smooth_neighbor,
22616 fctx,
22617 )?;
22618 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22619 eprintln!(
22620 "TRACE tu_bitpos mi=({},{}) tell={}",
22621 tu_mi.0,
22622 tu_mi.1,
22623 dec.debug_bitpos()
22624 );
22625 }
22626 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
22627 // The FIRST (top-left, co-located with this group's chroma)
22628 // TU's coded tx_type is what the group's chroma inherits --
22629 // the same capture [`decode_block`]'s multi-TU branch makes
22630 // for `first_leaf_tx` (libaom `av1_get_tx_type`, blockd.h:
22631 // an inter-classified block's `PLANE_TYPE_UV` reads
22632 // `tx_type_map`, and intrabc is inter-classified).
22633 if first_leaf_tx.is_none() {
22634 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
22635 }
22636 }
22637 }
22638 // lane-av1intrapred: an intrabc leaf whose var-tx tree split to
22639 // TX_4X4 never armed [`INTRABC_CHROMA_TX`], so its chroma reads fell
22640 // back to `default_intra_tx_type(DC_PRED)` = `DCT_DCT` and took the
22641 // 2D scan, the 2D eob row and the 2D nz contexts where libaom takes
22642 // the inherited luma type's (R5's first fork: mi (36,66), luma
22643 // (0,0) coded `H_ADST` off the 16-symbol inter set, chroma U then
22644 // decoded its `eob` from the wrong CDF row). Same arm the
22645 // `resolved != 4` branch above runs for its whole-leaf unit.
22646 if intrabc_dv.is_some() {
22647 if let Some(t) = first_leaf_tx {
22648 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
22649 }
22650 }
22651 let ac = alpha.map(|_| cfl_src(px, py, 8));
22652 // lane-av1-422h: same ss_x-1 dc-vote sampling as the whole-leaf arm
22653 // above -- the doubled above sum crosses zero at mi(2,24) plane 2.
22654 let chroma_around = if chroma_422 {
22655 neighbours.around_mi_422_chroma(leaf_mi, 8, 8)
22656 } else {
22657 neighbours.around_mi(leaf_mi, 8)
22658 };
22659 // lane-av1intrapred: the non-vacuity counter -- armed slot consulted
22660 // by this arm's chroma reads means the frame-copy + inherited-type
22661 // route ran; zero at gate time means the fixture stopped reaching it.
22662 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
22663 hit!(INTRABC_TX4_CHROMA_COPY_HITS);
22664 }
22665 if chroma_422 {
22666 // lane-av1-422d: the chroma unit does NOT follow the luma var-tx
22667 // split -- `uv_txsize` is `av1_get_max_uv_txsize` of the block,
22668 // still the one 4x8 rect unit per plane at ss (1,0).
22669 u_grid = leaf8_chroma422_unit(
22670 dec,
22671 cdfs,
22672 chroma_around[1],
22673 uv_predict_mode,
22674 angle_delta_uv,
22675 reach,
22676 1,
22677 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22678 false,
22679 intrabc_bufs
22680 .as_ref()
22681 .map(|(_, ub, _)| ub.clone())
22682 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
22683 u,
22684 cpx,
22685 cpy,
22686 smooth_neighbor_uv,
22687 fctx,
22688 )?;
22689 v_grid = leaf8_chroma422_unit(
22690 dec,
22691 cdfs,
22692 chroma_around[2],
22693 uv_predict_mode,
22694 angle_delta_uv,
22695 reach,
22696 2,
22697 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22698 false,
22699 intrabc_bufs
22700 .as_ref()
22701 .map(|(_, _, vb)| vb.clone())
22702 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
22703 v,
22704 cpx,
22705 cpy,
22706 smooth_neighbor_uv,
22707 fctx,
22708 )?;
22709 } else if chroma_444 && lossless(fctx) {
22710 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster
22711 // of TX_4X4 units per plane, PLANE-MAJOR (`av1_get_tx_size`:
22712 // lossless forces TX_4X4 on EVERY plane) -- the same walk
22713 // `read_intra_chroma_lossless` runs for whole blocks. Reading one
22714 // TX_8X8 unit here panicked before: the lossless inverse is the
22715 // 4x4-only WHT (`TxParams::run`'s own `(w, h) == (4, 4)`
22716 // invariant), and the unit count desyncs the tile either way.
22717 // Per-unit `record_mi_chroma` calls stamp the neighbour bands
22718 // inside, which is why the tail's whole-leaf chroma stamp below
22719 // is skipped for this shape.
22720 let (mut uo, mut vo) = (Vec::new(), Vec::new());
22721 read_intra_chroma_lossless(
22722 dec,
22723 cdfs,
22724 neighbours,
22725 u,
22726 v,
22727 leaf_mi,
22728 (px, py),
22729 (cpx, cpy),
22730 8,
22731 (8, 8),
22732 (0, 0),
22733 (8, 8),
22734 8,
22735 reach,
22736 (y.width, y.height),
22737 mode,
22738 uv_predict_mode,
22739 angle_delta_uv,
22740 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
22741 smooth_neighbor_uv,
22742 base_q_idx,
22743 &mut uo,
22744 &mut vo,
22745 fctx,
22746 )?;
22747 u_grid = if uo.is_empty() {
22748 Grid::Zero(64)
22749 } else {
22750 Grid::Own(uo)
22751 };
22752 v_grid = if vo.is_empty() {
22753 Grid::Zero(64)
22754 } else {
22755 Grid::Own(vo)
22756 };
22757 } else {
22758 if let Some((ub, _)) = &palette_uv_bufs {
22759 set_palette_pred(ub.clone(), fctx);
22760 }
22761 u_grid = read_plane(
22762 dec,
22763 cdfs,
22764 cset,
22765 cscan,
22766 1,
22767 chroma_around[1],
22768 mode,
22769 uv_predict_mode,
22770 angle_delta_uv,
22771 reach,
22772 u,
22773 cpx,
22774 cpy,
22775 csz,
22776 csz,
22777 base_q_idx,
22778 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22779 None,
22780 None,
22781 smooth_neighbor_uv,
22782 fctx,
22783 )?;
22784 if let Some((_, vb)) = &palette_uv_bufs {
22785 set_palette_pred(vb.clone(), fctx);
22786 }
22787 v_grid = read_plane(
22788 dec,
22789 cdfs,
22790 cset,
22791 cscan,
22792 2,
22793 chroma_around[2],
22794 mode,
22795 uv_predict_mode,
22796 angle_delta_uv,
22797 reach,
22798 v,
22799 cpx,
22800 cpy,
22801 csz,
22802 csz,
22803 base_q_idx,
22804 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22805 None,
22806 None,
22807 smooth_neighbor_uv,
22808 fctx,
22809 )?;
22810 }
22811 // The two chroma reads above are the only consulters of this leaf's
22812 // armed [`INTRABC_CHROMA_TX`]; leaving it set would make the NEXT
22813 // leaf's chroma inherit this leaf's luma type instead of its own
22814 // derivation (class armed-slot-leak-into-next-leaf, seen live: the
22815 // regular-intra leaf after an intrabc TX4 leaf took the intrabc
22816 // luma's `V_ADST` for its chroma eob row).
22817 if intrabc_dv.is_some() {
22818 fctx.intrabc_chroma_tx.with(|c| c.set(None));
22819 }
22820 // `record_split_luma` expects a `record`-style `(r, c)` position in
22821 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
22822 // already in mi units, so calling it here double-scaled the
22823 // position. Plane 0 is already correct per-TU from the
22824 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
22825 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
22826 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
22827 // leaf's own 8x8 side over `MI`).
22828 let side_mi = 2;
22829 for cell in 0..side_mi {
22830 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
22831 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
22832 }
22833 let round_up_even = |n: usize| n.div_ceil(2) * 2;
22834 let bound_h = round_up_even(neighbours.mi_rows);
22835 let bound_w = round_up_even(neighbours.mi_cols);
22836 let u_state = neighbour_state(&u_grid);
22837 let v_state = neighbour_state(&v_grid);
22838 // The 4:4:4 lossless walk above already stamped these bands PER UNIT
22839 // (its raster-order last writer per cell is exactly libaom's
22840 // per-entry last update); this whole-leaf aggregate would clobber
22841 // four distinct unit states with one, so it runs only for the shapes
22842 // whose chroma really is one unit.
22843 if !(chroma_444 && lossless(fctx)) {
22844 for cell in 0..side_mi {
22845 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
22846 neighbours.left[leaf_mi.0 + cell][1] = u_state;
22847 neighbours.left[leaf_mi.0 + cell][2] = v_state;
22848 }
22849 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
22850 neighbours.above[leaf_mi.1 + cell][1] = u_state;
22851 neighbours.above[leaf_mi.1 + cell][2] = v_state;
22852 }
22853 }
22854 }
22855 // This leaf's own palette state into the mi-granular above/left bands
22856 // (sizes 0 when it used none, which is what clears a previous block's
22857 // palette out of the next block's ctx and colour cache).
22858 {
22859 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
22860 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
22861 }
22862 neighbours.fill_skip_grid(leaf_mi, 2, skip);
22863 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
22864 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
22865 // own copy; only an intrabc var-tx read consumes these bands on the intra
22866 // path, so the write is armed by `allow_intrabc`.
22867 if allow_intrabc {
22868 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
22869 }
22870 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
22871 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
22872 return Ok(mode);
22873 }
22874 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
22875 // This leaf's own palette state into the mi-granular above/left bands
22876 // (sizes 0 when it used none, which is what clears a previous block's
22877 // palette out of the next block's ctx and colour cache).
22878 {
22879 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
22880 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
22881 }
22882 hit!(INTER8_SKIP_BAND_HITS);
22883 neighbours.fill_skip_grid(leaf_mi, 2, skip);
22884 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
22885 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
22886 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
22887 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
22888 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
22889 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
22890 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
22891 // wrong CDF row, so the msac range diverged mid-frame with no refusal
22892 // (class `wrong-alphabet-same-value`; the ReelB key frame at
22893 // -ss 900, first bad luma sample row 186 col 1803).
22894 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
22895 // lane-t900 r32 / lane-av1txbands: `set_txfm_ctxs` for an 8x8 leaf -- see
22896 // `decode_block`'s own copy for why this stays beside
22897 // [`Neighbours::fill_lf_grid_rect`]'s publish (the skipped-intrabc
22898 // BLOCK-size term).
22899 if allow_intrabc {
22900 set_txfm_ctxs(
22901 neighbours,
22902 leaf_mi,
22903 resolved,
22904 2,
22905 2,
22906 skip && intrabc_dv.is_some(),
22907 );
22908 }
22909 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
22910 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
22911 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
22912 // publish its own cells exactly like `decode_block` does.
22913 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
22914 Ok(mode)
22915}
22916
22917/// lane-av1-422d: ONE 4:2:2 chroma transform unit of an 8x8 leaf
22918/// ([`decode_leaf8`]). At ss (1,0) the plane block is 4x8 and
22919/// `av1_get_max_uv_txsize(BLOCK_8X8)` resolves to
22920/// `max_txsize_rect_lookup[BLOCK_4X8]` == TX_4X8, so the WHOLE plane block is
22921/// a single rect unit -- one txb_skip + one scan per plane in the
22922/// [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the
22923/// shape. Mirrors [`sub8_leaf_chroma444`]'s rect arm at the leaf's halved
22924/// position: the entropy context is the leaf's own 8x8 luma-span
22925/// above/left state (the `chroma_tiled` arm's convention; no `+3`
22926/// plane-block-bigger term -- the unit covers the plane block exactly), the
22927/// CFL source is the leaf's whole 8x8 luma block, and the plane's predicted
22928/// mode supplies the mode-derived default `tx_type` unless an armed
22929/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own (the caller
22930/// arms and disarms it, exactly as it does around its square reads).
22931#[allow(clippy::too_many_arguments)]
22932fn leaf8_chroma422_unit(
22933 dec: &mut SymbolDecoder,
22934 cdfs: &mut Cdfs,
22935 around: (bool, bool, i32),
22936 uv_predict_mode: usize,
22937 angle_delta_uv: i32,
22938 reach: Reach,
22939 plane_idx: usize,
22940 cfl: Option<(i32, CflSrc)>,
22941 skip: bool,
22942 // The prediction override the square arms feed through
22943 // `set_palette_pred`: an intrabc leaf's frame copy at the DV takes
22944 // priority over a palette block's colour-index map.
22945 pred_override: Option<Vec<u16>>,
22946 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
22947 // the plane exclusively while the unit's coefficients are parsed.
22948 _plane: &mut PlaneBuf<'static>,
22949 cpx: usize,
22950 cpy: usize,
22951 smooth_neighbor_uv: bool,
22952 fctx: &crate::decode::FrameCtx,
22953) -> Result<Grid> {
22954 // The unit's prediction runs whether or not a residual follows it -- a
22955 // skipped leaf still predicts (the CfL contribution survives a skip),
22956 // and a skipped intrabc leaf still copies the frame at its DV.
22957 if let Some(buf) = pred_override {
22958 set_palette_pred(buf, fctx);
22959 }
22960 if skip {
22961 push_intra_rect(
22962 plane_idx,
22963 cpx,
22964 cpy,
22965 4,
22966 8,
22967 uv_predict_mode,
22968 angle_delta_uv,
22969 reach,
22970 &ZERO_RESIDUAL[..4 * 8],
22971 cfl,
22972 None,
22973 smooth_neighbor_uv,
22974 fctx,
22975 );
22976 return Ok(Grid::Zero(4 * 8));
22977 }
22978 let default_tx = fctx
22979 .intrabc_chroma_tx
22980 .with(std::cell::Cell::get)
22981 .unwrap_or_else(|| default_intra_tx_type(uv_predict_mode as u8));
22982 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
22983 let (levels, tx_type) = read_coeffs_rect(
22984 dec,
22985 &mut coding,
22986 &SCAN_4X8,
22987 4,
22988 8,
22989 usize::from(around.0) + usize::from(around.1),
22990 dc_sign_ctx(around.2),
22991 default_tx,
22992 )?;
22993 let residual = dequant_and_inverse_typed_wh(
22994 &levels,
22995 4,
22996 8,
22997 crate::decode::bit_depth(fctx),
22998 block_q_idx(fctx),
22999 plane_q_delta(plane_idx, fctx).0,
23000 plane_q_delta(plane_idx, fctx).1,
23001 tx_type,
23002 block_iqmatrix(fctx, plane_idx, 4, 8, tx_type),
23003 );
23004 push_intra_rect(
23005 plane_idx,
23006 cpx,
23007 cpy,
23008 4,
23009 8,
23010 uv_predict_mode,
23011 angle_delta_uv,
23012 reach,
23013 &residual,
23014 cfl,
23015 None,
23016 smooth_neighbor_uv,
23017 fctx,
23018 );
23019 Ok(levels)
23020}
23021
23022/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
23023/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
23024/// bottom, where no partition symbol is read at all -- `decode_block` runs
23025/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
23026/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
23027/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
23028/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
23029/// of the 2x2 4x4 group carries chroma syntax at all.
23030#[allow(clippy::too_many_arguments)]
23031fn read_intra_mode_sub8(
23032 dec: &mut SymbolDecoder,
23033 cdfs: &mut Cdfs,
23034 above_mode: usize,
23035 left_mode: usize,
23036 has_chroma: bool,
23037 enable_filter_intra: bool,
23038 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
23039 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
23040 // from the wrong row is the same VALUE with a different interval, so it
23041 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
23042 fi_class: usize,
23043 skip_ctx: usize,
23044 allow_intrabc: bool,
23045 mi_r: usize,
23046 mi_c: usize,
23047 // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4`
23048 // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf
23049 // left the second mi column at segment 0, which reads back as a
23050 // neighbour's `cdf_index`/prediction two blocks later.
23051 seg_w_mi: usize,
23052 seg_h_mi: usize,
23053 fctx: &crate::decode::FrameCtx,
23054) -> Result<(
23055 bool,
23056 usize,
23057 i32,
23058 Option<(usize, i32, Option<(i32, i32)>)>,
23059 Option<usize>,
23060 Option<(i32, i32)>,
23061)> {
23062 // lane-av1mono: a monochrome leaf codes no chroma mode (libaom
23063 // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`.
23064 let has_chroma = has_chroma && !mono(fctx);
23065 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
23066 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
23067 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
23068 if ec_istep {
23069 eprintln!(
23070 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}",
23071 dec.debug_state().0
23072 );
23073 }
23074 // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder
23075 // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block.
23076 macro_rules! istep {
23077 ($name:literal, $val:expr) => {
23078 if ec_istep {
23079 eprintln!(
23080 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}",
23081 $name,
23082 $val,
23083 dec.debug_state().0
23084 );
23085 }
23086 };
23087 }
23088 // lane-seg2: same `intra_segment_id` placement as the square and rect
23089 // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id`
23090 // like any other block, over its own 1x1 mi footprint. Dropping it here
23091 // both ate a symbol (the tile desynced at the frame's first sub-8x8
23092 // split) and left `cur_segment_id` on the previous block, so the leaf
23093 // dequantized with a neighbour's `SEG_LVL_ALT_Q`.
23094 if seg_id_pre_skip(fctx) {
23095 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
23096 }
23097 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
23098 if trace {
23099 eprintln!(
23100 "TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}",
23101 skip as i32,
23102 dec.debug_state().0
23103 );
23104 }
23105 istep!("skip", skip as i32);
23106 if !seg_id_pre_skip(fctx) {
23107 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
23108 }
23109 maybe_read_cdef_idx(dec, mi_r, mi_c, (2, 2), skip, fctx);
23110 istep!("cdef", 0);
23111 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
23112 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
23113 istep!("dq", 0);
23114 if allow_intrabc {
23115 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
23116 if ec_istep {
23117 eprintln!(
23118 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
23119 u8::from(use_intrabc),
23120 dec.debug_state().0
23121 );
23122 }
23123 if use_intrabc {
23124 // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block
23125 // vector right after the flag and RETURNS -- no y/uv mode, angle
23126 // delta, palette, CfL or filter-intra syntax follows, and the
23127 // block is reconstructed by the INTER path (libaom's
23128 // `is_inter_block` counts an intrabc block), so the caller takes
23129 // the frame-copy prediction + inter residual.
23130 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (seg_w_mi, seg_h_mi), fctx);
23131 // lane-av1txr: the DV travels back in the RETURN value -- it is
23132 // NOT published through `FrameCtx::intrabc_dv`. That slot is the
23133 // SQUARE paths' handoff (`decode_block`/`decode_leaf8` arm it,
23134 // then `take()` it in the same call), so a sub-8x8 leaf that
23135 // armed it left the vector standing for the NEXT >=8x8 block:
23136 // `warped.obu`'s (38,60) 8x8 intra block took it as its own
23137 // intrabc and read an inter var-tx `txfm_split` where libaom read
23138 // an intra `tx_depth` (class `stale-slot-handoff`).
23139 hit!(INTRABC_HITS);
23140 return Ok((skip, DC_PRED, 0, None, None, Some(dv)));
23141 }
23142 }
23143 let above_ctx = INTRA_MODE_CTX[above_mode];
23144 let left_ctx = INTRA_MODE_CTX[left_mode];
23145 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
23146 istep!("mode", mode);
23147 if trace {
23148 eprintln!(
23149 "TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
23150 dec.debug_state().0
23151 );
23152 }
23153 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
23154 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
23155 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
23156 // symbol. Reading one consumed a symbol the encoder never wrote and
23157 // desynced the tile at the very next element.
23158 let angle_delta_y = 0;
23159 let chroma = if has_chroma {
23160 // `is_cfl_allowed` (blockd.h): at lossless CfL needs the CHROMA plane
23161 // block to be a single TX_4X4 (`cfl_allowed_px`). True for this leaf
23162 // at 4:2:0 (the group's plane block is 4x4) and for a 4:4:4
23163 // `BLOCK_4X4` split leaf, but FALSE for a 4:4:4 `BLOCK_8X4`/`BLOCK_4X8`
23164 // rect leaf, whose plane block is the rect itself -- that shape reads
23165 // the 13-symbol `uv_mode_no_cfl` CDF, and reading the CFL alphabet
23166 // there desynced the tile at the rect leaf's own uv_mode symbol (measured:
23167 // ours consumed the 14-symbol interval where the oracle read 13, first
23168 // divergence at the rect leaf mi (8,16) of `ll444.obu`; class
23169 // `wrong-alphabet-same-value`, lane-av1-llsub8).
23170 let uv_mode = if cfl_allowed_px(seg_w_mi * MI, seg_h_mi * MI, fctx) {
23171 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
23172 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
23173 } else {
23174 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
23175 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
23176 };
23177 if trace {
23178 eprintln!(
23179 "TRACE sub8 uv_mode value={uv_mode} rng={}",
23180 dec.debug_state().0
23181 );
23182 }
23183 if (9..=12).contains(&uv_mode) {
23184 hit!(SMOOTH_UV_HITS);
23185 }
23186 let alpha = if uv_mode == UV_CFL_PRED {
23187 Some(read_cfl_alphas(dec, cdfs))
23188 } else {
23189 None
23190 };
23191 if (V_PRED..=D67_PRED).contains(&uv_mode) {
23192 hit!(DIRECTIONAL_UV_HITS);
23193 }
23194 // See the luma comment above: no angle delta below 8x8.
23195 let angle_delta_uv = 0;
23196 Some((uv_mode, angle_delta_uv, alpha))
23197 } else {
23198 None
23199 };
23200 let mut filter_intra = None;
23201 if mode == DC_PRED && enable_filter_intra {
23202 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
23203 if trace {
23204 eprintln!(
23205 "TRACE sub8 use_filter_intra value={}",
23206 use_filter_intra as i32
23207 );
23208 }
23209 if use_filter_intra {
23210 hit!(FILTER_INTRA_HITS);
23211 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
23212 filter_intra = Some(fi_mode);
23213 }
23214 }
23215 Ok((skip, mode, angle_delta_y, chroma, filter_intra, None))
23216}
23217/// 4:4:4 sub-8x8 key-frame leaf chroma (lane-av1-444). At subsampling 0/0
23218/// `is_chroma_reference` (av1_common_int.h:1459) is unconditional, so EVERY
23219/// 4x4 / 4x8 / 8x4 leaf codes its own full-resolution chroma unit right
23220/// after its own luma (`read_intra_mode_sub8` already read this leaf's own
23221/// `uv_mode`), not the one shared 4x4 unit [`decode_leaf_split4`] /
23222/// [`decode_leaf_rect8`]'s group tails decode at 4:2:0. Mirrors those tails
23223/// arm for arm at leaf scale: a skipped leaf keeps its CfL contribution, an
23224/// intrabc leaf predicts a frame copy at its DV with the luma `tx_type`
23225/// inherited through [`INTRABC_CHROMA_TX`] (the caller arms it right after
23226/// the luma read) -- and a SKIPPED intrabc leaf is still the DV copy, never
23227/// an intra prediction (lane-av1-ibcskip2: libaom's
23228/// `av1_build_inter_predictors_sb` runs for an intrabc block regardless of
23229/// `skip`). The chroma position, reach and entropy-context span are
23230/// the leaf's own (ss 0/0); the 4x8/8x4 unit reads the same
23231/// `ChromaRect8x4` tables [`decode_rect_split`] proves for that shape.
23232/// Records the leaf's own `uv_mode` map entry and chroma above/left state,
23233/// and returns the (u, v) grids for the caller's coarse slots.
23234#[allow(clippy::too_many_arguments)]
23235fn sub8_leaf_chroma444(
23236 dec: &mut SymbolDecoder,
23237 cdfs: &mut Cdfs,
23238 neighbours: &mut Neighbours,
23239 lmi: (usize, usize),
23240 bw: usize,
23241 bh: usize,
23242 uv_mode: usize,
23243 alpha: Option<(i32, i32)>,
23244 skip: bool,
23245 intrabc_dv: Option<(i32, i32)>,
23246 y: &PlaneBuf<'static>,
23247 u: &mut PlaneBuf<'static>,
23248 v: &mut PlaneBuf<'static>,
23249 scan4: &[u16],
23250 base_q_idx: u8,
23251 smooth_neighbor_uv: bool,
23252 fctx: &crate::decode::FrameCtx,
23253) -> Result<(Grid, Grid, usize, usize)> {
23254 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
23255 DC_PRED
23256 } else {
23257 uv_mode
23258 };
23259 let (w_mi, h_mi) = (bw / MI, bh / MI);
23260 neighbours.record_uv_mode_mi(lmi.0, lmi.1, w_mi, h_mi, uv_predict_mode);
23261 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
23262 let square = (bw, bh) == (4, 4);
23263 // `Reach::of_rect` has no 4x4 table (`rect_reach_tables` starts at 4x8);
23264 // the square unit takes the leaf's own `Reach::of`, as its luma does.
23265 let reach = if square {
23266 Reach::of(4, px, py, y.width, y.height, fctx)
23267 } else {
23268 Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx)
23269 };
23270 let grids = if let Some(dv) = intrabc_dv.filter(|_| skip) {
23271 // lane-av1-ibcskip2: a SKIPPED intrabc leaf still predicts the frame
23272 // copy at its DV -- libaom's `av1_build_inter_predictors_sb` runs for
23273 // an intrabc block regardless of `skip` (only the residual read is
23274 // dropped), so the reconstruction is the bare DV copy. The intra push
23275 // in the next arm is the NON-intrabc route; predicting DC there
23276 // decoded flat cells where this fixture's oracle copies frame bytes
23277 // (class skipped-intrabc-predicts-intra,
23278 // lanes/av1ibcskip2.report.md). Same armed-palette-slot route the
23279 // leaf's own luma skip arm uses (`decode_leaf_split4` /
23280 // `decode_leaf_rect8`); the caller already flushed the recon queue
23281 // before its luma DV copy, so the source samples are current.
23282 let mut ub = vec![0u16; bw * bh];
23283 mc::predict_with_filter(
23284 &u.data,
23285 u.width,
23286 u.true_width,
23287 u.true_height,
23288 mv_to_q4(px, dv.1, 0),
23289 mv_to_q4(py, dv.0, 0),
23290 bw,
23291 bh,
23292 mc::InterpFilterKind::Bilinear,
23293 &mut ub,
23294 fctx,
23295 );
23296 let mut vb = vec![0u16; bw * bh];
23297 mc::predict_with_filter(
23298 &v.data,
23299 v.width,
23300 v.true_width,
23301 v.true_height,
23302 mv_to_q4(px, dv.1, 0),
23303 mv_to_q4(py, dv.0, 0),
23304 bw,
23305 bh,
23306 mc::InterpFilterKind::Bilinear,
23307 &mut vb,
23308 fctx,
23309 );
23310 hit!(SKIPPED_INTRABC_DV_COPY_HITS);
23311 let zeros = &ZERO_RESIDUAL[..bw * bh];
23312 if square {
23313 set_palette_pred(ub, fctx);
23314 push_intra(
23315 1,
23316 px,
23317 py,
23318 4,
23319 DC_PRED,
23320 0,
23321 reach,
23322 zeros,
23323 None,
23324 None,
23325 smooth_neighbor_uv,
23326 fctx,
23327 );
23328 set_palette_pred(vb, fctx);
23329 push_intra(
23330 2,
23331 px,
23332 py,
23333 4,
23334 DC_PRED,
23335 0,
23336 reach,
23337 zeros,
23338 None,
23339 None,
23340 smooth_neighbor_uv,
23341 fctx,
23342 );
23343 } else {
23344 set_palette_pred(ub, fctx);
23345 push_intra_rect(
23346 1,
23347 px,
23348 py,
23349 bw,
23350 bh,
23351 DC_PRED,
23352 0,
23353 reach,
23354 zeros,
23355 None,
23356 None,
23357 smooth_neighbor_uv,
23358 fctx,
23359 );
23360 set_palette_pred(vb, fctx);
23361 push_intra_rect(
23362 2,
23363 px,
23364 py,
23365 bw,
23366 bh,
23367 DC_PRED,
23368 0,
23369 reach,
23370 zeros,
23371 None,
23372 None,
23373 smooth_neighbor_uv,
23374 fctx,
23375 );
23376 }
23377 // The same arm-without-clear route the 4:2:0 tails count: a skipped
23378 // leaf reads no coefficient, so the inherited chroma `tx_type` is
23379 // dropped unconsumed.
23380 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
23381 fctx.intrabc_chroma_tx.with(|c| c.set(None));
23382 (Grid::Zero(bw * bh), Grid::Zero(bw * bh), 4, 4)
23383 } else if skip {
23384 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
23385 if square {
23386 push_intra(
23387 1,
23388 px,
23389 py,
23390 4,
23391 uv_predict_mode,
23392 0,
23393 reach,
23394 &ZERO_RESIDUAL[..16],
23395 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23396 None,
23397 smooth_neighbor_uv,
23398 fctx,
23399 );
23400 push_intra(
23401 2,
23402 px,
23403 py,
23404 4,
23405 uv_predict_mode,
23406 0,
23407 reach,
23408 &ZERO_RESIDUAL[..16],
23409 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23410 None,
23411 smooth_neighbor_uv,
23412 fctx,
23413 );
23414 } else {
23415 push_intra_rect(
23416 1,
23417 px,
23418 py,
23419 bw,
23420 bh,
23421 uv_predict_mode,
23422 0,
23423 reach,
23424 &ZERO_RESIDUAL[..bw * bh],
23425 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23426 None,
23427 smooth_neighbor_uv,
23428 fctx,
23429 );
23430 push_intra_rect(
23431 2,
23432 px,
23433 py,
23434 bw,
23435 bh,
23436 uv_predict_mode,
23437 0,
23438 reach,
23439 &ZERO_RESIDUAL[..bw * bh],
23440 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23441 None,
23442 smooth_neighbor_uv,
23443 fctx,
23444 );
23445 }
23446 // The same arm-without-clear route the 4:2:0 tails count: a skipped
23447 // leaf reads no coefficient, so an armed intrabc slot is dropped.
23448 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
23449 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
23450 fctx.intrabc_chroma_tx.with(|c| c.set(None));
23451 }
23452 (Grid::Zero(bw * bh), Grid::Zero(bw * bh), 4, 4)
23453 } else if let Some(dv) = intrabc_dv {
23454 // Frame copy at the DV; the residual still reads the ordinary chroma
23455 // tables with the inherited luma `tx_type` (see the 4:2:0 tails).
23456 let mut ub = vec![0u16; bw * bh];
23457 mc::predict_with_filter(
23458 &u.data,
23459 u.width,
23460 u.true_width,
23461 u.true_height,
23462 mv_to_q4(px, dv.1, 0),
23463 mv_to_q4(py, dv.0, 0),
23464 bw,
23465 bh,
23466 mc::InterpFilterKind::Bilinear,
23467 &mut ub,
23468 fctx,
23469 );
23470 let mut vb = vec![0u16; bw * bh];
23471 mc::predict_with_filter(
23472 &v.data,
23473 v.width,
23474 v.true_width,
23475 v.true_height,
23476 mv_to_q4(px, dv.1, 0),
23477 mv_to_q4(py, dv.0, 0),
23478 bw,
23479 bh,
23480 mc::InterpFilterKind::Bilinear,
23481 &mut vb,
23482 fctx,
23483 );
23484 let around = neighbours.around_mi_rect(lmi, bw, bh);
23485 let pair = if square {
23486 set_palette_pred(ub, fctx);
23487 let ug = read_plane(
23488 dec,
23489 cdfs,
23490 TxbSet::Chroma4,
23491 scan4,
23492 1,
23493 around[1],
23494 DC_PRED,
23495 DC_PRED,
23496 0,
23497 reach,
23498 u,
23499 px,
23500 py,
23501 4,
23502 TX4,
23503 base_q_idx,
23504 None,
23505 None,
23506 None,
23507 smooth_neighbor_uv,
23508 fctx,
23509 )?;
23510 set_palette_pred(vb, fctx);
23511 let vg = read_plane(
23512 dec,
23513 cdfs,
23514 TxbSet::Chroma4,
23515 scan4,
23516 2,
23517 around[2],
23518 DC_PRED,
23519 DC_PRED,
23520 0,
23521 reach,
23522 v,
23523 px,
23524 py,
23525 4,
23526 TX4,
23527 base_q_idx,
23528 None,
23529 None,
23530 None,
23531 smooth_neighbor_uv,
23532 fctx,
23533 )?;
23534 (ug, vg, 4, 4)
23535 } else {
23536 // lane-av1-ibc444rect: the unskipped lossless chroma walk this
23537 // lane fixes (one rect unit -> per-4x4 Chroma4 units).
23538 if lossless(fctx) {
23539 hit!(INTRABC_RECT8_LOSSLESS_CHROMA_HITS);
23540 }
23541 if lossless(fctx) {
23542 // lane-av1-ibc444rect: at lossless `read_tx_size` forces
23543 // TX_4X4 on EVERY plane (`av1_get_tx_size`'s lossless
23544 // first line), so this rect leaf's chroma is (bw/4)*(bh/4)
23545 // TX_4X4 units at their own 4x4 origins -- not the single
23546 // `ChromaRect8x4` rect unit the non-lossless arm below reads
23547 // (`av1_get_max_uv_txsize(BLOCK_8X4)`'s rect, unreachable at
23548 // lossless). Same walk the leaf's own non-intrabc lossless
23549 // arm runs (lane-av1-llsub8's fix), plane-major per libaom
23550 // `decode_token_recon_block`, with the intra predictor
23551 // swapped for the CURRENT frame at the DV; CFL is never
23552 // allowed at lossless and no alpha rides an intrabc leaf.
23553 let mut out_u = Grid::Own(vec![0i32; bw * bh]);
23554 let mut out_v = Grid::Own(vec![0i32; bw * bh]);
23555 for (plane_idx, buf) in [(1usize, u), (2usize, v)] {
23556 for ur in 0..bh / 4usize {
23557 for uc in 0..bw / 4usize {
23558 let (umi_r, umi_c) = (lmi.0 + ur, lmi.1 + uc);
23559 let (upx, upy) = (px + uc * 4, py + ur * 4);
23560 let mut pb = vec![0u16; 16];
23561 mc::predict_with_filter(
23562 &buf.data,
23563 buf.width,
23564 buf.true_width,
23565 buf.true_height,
23566 mv_to_q4(upx, dv.1, 0),
23567 mv_to_q4(upy, dv.0, 0),
23568 4,
23569 4,
23570 mc::InterpFilterKind::Bilinear,
23571 &mut pb,
23572 fctx,
23573 );
23574 set_palette_pred(pb, fctx);
23575 let unit_around = neighbours.around_mi_rect((umi_r, umi_c), 4, 4);
23576 let unit_reach = Reach::of(4, upx, upy, y.width, y.height, fctx);
23577 let grid = read_plane(
23578 dec,
23579 cdfs,
23580 TxbSet::Chroma4,
23581 scan4,
23582 plane_idx,
23583 unit_around[plane_idx],
23584 DC_PRED,
23585 DC_PRED,
23586 0,
23587 unit_reach,
23588 buf,
23589 upx,
23590 upy,
23591 4,
23592 TX4,
23593 base_q_idx,
23594 None,
23595 None,
23596 Some(3),
23597 smooth_neighbor_uv,
23598 fctx,
23599 )?;
23600 let cell = grid_unit_state(&grid, 4, 0, 0, 4, 4);
23601 if umi_r < neighbours.mi_rows {
23602 neighbours.left[umi_r][plane_idx] = cell;
23603 }
23604 if umi_c < neighbours.mi_cols {
23605 neighbours.above[umi_c][plane_idx] = cell;
23606 }
23607 let out = if plane_idx == 1 {
23608 &mut out_u
23609 } else {
23610 &mut out_v
23611 };
23612 if let Grid::Own(v) = out {
23613 for r in 0..4usize {
23614 v[(ur * 4 + r) * bw + uc * 4..][..4]
23615 .copy_from_slice(&grid[r * 4..][..4]);
23616 }
23617 }
23618 }
23619 }
23620 }
23621 (out_u, out_v, 4, 4)
23622 } else {
23623 let scan: &[u16] = if bw > bh { &SCAN_8X4 } else { &SCAN_4X8 };
23624 let default_tx = fctx
23625 .intrabc_chroma_tx
23626 .with(std::cell::Cell::get)
23627 .unwrap_or(TxType::DctDct);
23628 let mut out = (Grid::Zero(bw * bh), Grid::Zero(bw * bh), bw, bh);
23629 for (plane_idx, buf) in [(1usize, ub), (2usize, vb)] {
23630 let skip_ctx =
23631 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
23632 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, DC_PRED);
23633 let (levels, tx_type) = read_coeffs_rect(
23634 dec,
23635 &mut coding,
23636 scan,
23637 bw,
23638 bh,
23639 skip_ctx,
23640 dc_sign_ctx(around[plane_idx].2),
23641 default_tx,
23642 )?;
23643 let residual = dequant_and_inverse_typed_wh(
23644 &levels,
23645 bw,
23646 bh,
23647 crate::decode::bit_depth(fctx),
23648 block_q_idx(fctx),
23649 plane_q_delta(plane_idx, fctx).0,
23650 plane_q_delta(plane_idx, fctx).1,
23651 tx_type,
23652 block_iqmatrix(fctx, plane_idx, bw, bh, tx_type),
23653 );
23654 set_palette_pred(buf, fctx);
23655 push_intra_rect(
23656 plane_idx,
23657 px,
23658 py,
23659 bw,
23660 bh,
23661 DC_PRED,
23662 0,
23663 reach,
23664 &residual,
23665 None,
23666 None,
23667 smooth_neighbor_uv,
23668 fctx,
23669 );
23670 if plane_idx == 1 {
23671 out.0 = levels;
23672 } else {
23673 out.1 = levels;
23674 }
23675 }
23676 out
23677 }
23678 };
23679 fctx.intrabc_chroma_tx.with(|c| c.set(None));
23680 pair
23681 } else {
23682 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
23683 let around = neighbours.around_mi_rect(lmi, bw, bh);
23684 if square {
23685 let ug = read_plane(
23686 dec,
23687 cdfs,
23688 TxbSet::Chroma4,
23689 scan4,
23690 1,
23691 around[1],
23692 uv_mode,
23693 uv_predict_mode,
23694 0,
23695 reach,
23696 u,
23697 px,
23698 py,
23699 4,
23700 TX4,
23701 base_q_idx,
23702 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23703 None,
23704 None,
23705 smooth_neighbor_uv,
23706 fctx,
23707 )?;
23708 let vg = read_plane(
23709 dec,
23710 cdfs,
23711 TxbSet::Chroma4,
23712 scan4,
23713 2,
23714 around[2],
23715 uv_mode,
23716 uv_predict_mode,
23717 0,
23718 reach,
23719 v,
23720 px,
23721 py,
23722 4,
23723 TX4,
23724 base_q_idx,
23725 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23726 None,
23727 None,
23728 smooth_neighbor_uv,
23729 fctx,
23730 )?;
23731 (ug, vg, 4, 4)
23732 } else if lossless(fctx) {
23733 // lane-av1-llsub8: `read_tx_size` answers TX_4X4 for EVERY plane of
23734 // a lossless block, so this rect leaf's chroma is (bw/4)*(bh/4)
23735 // TX_4X4 units at their own 4x4 origins -- not the single
23736 // TX_8X4/TX_4X8 rect unit the non-lossless arm below reads (that
23737 // one is `av1_get_max_uv_txsize(BLOCK_8X4)`'s rect transform, which
23738 // lossless never reaches). Measured on `ll444.obu`'s HORZ leaf at
23739 // mi (8,16): the oracle codes U units at bc 0,1 with
23740 // `get_txb_ctx`'s +10 rows (`txb_skip_cdf[0][10..12]`,
23741 // plane pels 32 > tx pels 16) where the rect-unit read consumed
23742 // `txb_skip_cdf[1][0]` -- the tile desynced at that U unit's
23743 // all_zero symbol. Walk is plane-major like libaom
23744 // `decode_token_recon_block`'s plane/row/col loop; each unit adds
23745 // 3 to the chroma context (Chroma4's `big` rows, the same fold
23746 // [`read_plane`]'s 128x128 caller uses); CFL is never allowed at
23747 // lossless, so no alpha rides along.
23748 let mut out_u = Grid::Own(vec![0i32; bw * bh]);
23749 let mut out_v = Grid::Own(vec![0i32; bw * bh]);
23750 for (plane_idx, buf) in [(1usize, u), (2usize, v)] {
23751 for ur in 0..bh / 4usize {
23752 for uc in 0..bw / 4usize {
23753 let (umi_r, umi_c) = (lmi.0 + ur, lmi.1 + uc);
23754 let (upx, upy) = (px + uc * 4, py + ur * 4);
23755 let unit_around = neighbours.around_mi_rect((umi_r, umi_c), 4, 4);
23756 let unit_reach = Reach::of(4, upx, upy, y.width, y.height, fctx);
23757 let grid = read_plane(
23758 dec,
23759 cdfs,
23760 TxbSet::Chroma4,
23761 scan4,
23762 plane_idx,
23763 unit_around[plane_idx],
23764 uv_mode,
23765 uv_predict_mode,
23766 0,
23767 unit_reach,
23768 buf,
23769 upx,
23770 upy,
23771 4,
23772 TX4,
23773 base_q_idx,
23774 None,
23775 None,
23776 Some(3),
23777 smooth_neighbor_uv,
23778 fctx,
23779 )?;
23780 let cell = grid_unit_state(&grid, 4, 0, 0, 4, 4);
23781 if umi_r < neighbours.mi_rows {
23782 neighbours.left[umi_r][plane_idx] = cell;
23783 }
23784 if umi_c < neighbours.mi_cols {
23785 neighbours.above[umi_c][plane_idx] = cell;
23786 }
23787 let out = if plane_idx == 1 {
23788 &mut out_u
23789 } else {
23790 &mut out_v
23791 };
23792 if let Grid::Own(v) = out {
23793 for r in 0..4usize {
23794 v[(ur * 4 + r) * bw + uc * 4..][..4]
23795 .copy_from_slice(&grid[r * 4..][..4]);
23796 }
23797 }
23798 }
23799 }
23800 }
23801 (out_u, out_v, 4, 4)
23802 } else {
23803 // `av1_get_max_uv_txsize(BLOCK_4X8/8X4)` at ss 0/0 is the rect
23804 // transform itself; its `tx_type` is mode-derived with the
23805 // <32 set (`decode_rect_split`'s own rule for this shape).
23806 let scan: &[u16] = if bw > bh { &SCAN_8X4 } else { &SCAN_4X8 };
23807 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
23808 let mut out = (Grid::Zero(bw * bh), Grid::Zero(bw * bh), bw, bh);
23809 for plane_idx in 1..=2usize {
23810 let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
23811 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
23812 let (levels, tx_type) = read_coeffs_rect(
23813 dec,
23814 &mut coding,
23815 scan,
23816 bw,
23817 bh,
23818 skip_ctx,
23819 dc_sign_ctx(around[plane_idx].2),
23820 default_tx,
23821 )?;
23822 let residual = dequant_and_inverse_typed_wh(
23823 &levels,
23824 bw,
23825 bh,
23826 crate::decode::bit_depth(fctx),
23827 block_q_idx(fctx),
23828 plane_q_delta(plane_idx, fctx).0,
23829 plane_q_delta(plane_idx, fctx).1,
23830 tx_type,
23831 block_iqmatrix(fctx, plane_idx, bw, bh, tx_type),
23832 );
23833 let cfl = alpha
23834 .zip(ac)
23835 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
23836 push_intra_rect(
23837 plane_idx,
23838 px,
23839 py,
23840 bw,
23841 bh,
23842 uv_predict_mode,
23843 0,
23844 reach,
23845 &residual,
23846 cfl,
23847 None,
23848 smooth_neighbor_uv,
23849 fctx,
23850 );
23851 if plane_idx == 1 {
23852 out.0 = levels;
23853 } else {
23854 out.1 = levels;
23855 }
23856 }
23857 out
23858 }
23859 };
23860 // libaom `av1_set_entropy_contexts` stamps above/left PER TRANSFORM UNIT:
23861 // the leaf's own chroma span, not the 8x8 group's. A rect leaf's lossless
23862 // units (4x4) each carry their own state -- a 4:2:0-style whole-leaf smear
23863 // gave one unit's state to its neighbour's cells (lane-av1-llsub8).
23864 let (u_grid, v_grid, unit_w, unit_h) = grids;
23865 // One unit covers `unit_w/MI` mi columns and `unit_h/MI` mi rows (a 4x4
23866 // unit: one cell each; the non-lossless rect unit: the whole leaf).
23867 let (uw_cells, uh_cells) = ((unit_w / MI).max(1), (unit_h / MI).max(1));
23868 for ur in 0..h_mi / uh_cells {
23869 for uc in 0..w_mi / uw_cells {
23870 let (x0, y0) = (uc * unit_w, ur * unit_h);
23871 let us = grid_unit_state(&u_grid, bw, x0, y0, unit_w, unit_h);
23872 let vs = grid_unit_state(&v_grid, bw, x0, y0, unit_w, unit_h);
23873 for cell in 0..uh_cells {
23874 if lmi.0 + ur * uh_cells + cell < neighbours.mi_rows {
23875 neighbours.left[lmi.0 + ur * uh_cells + cell][1] = us;
23876 neighbours.left[lmi.0 + ur * uh_cells + cell][2] = vs;
23877 }
23878 }
23879 for cell in 0..uw_cells {
23880 if lmi.1 + uc * uw_cells + cell < neighbours.mi_cols {
23881 neighbours.above[lmi.1 + uc * uw_cells + cell][1] = us;
23882 neighbours.above[lmi.1 + uc * uw_cells + cell][2] = vs;
23883 }
23884 }
23885 }
23886 }
23887 Ok((u_grid, v_grid, unit_w, unit_h))
23888}
23889
23890/// [`neighbour_state`] over one `(unit_w x unit_h)` transform unit at offset
23891/// `(x0, y0)` inside a `bw`-wide assembled chroma grid -- the per-unit stamp
23892/// the rect arms need when a leaf carries more than one unit.
23893fn grid_unit_state(
23894 grid: &Grid,
23895 bw: usize,
23896 x0: usize,
23897 y0: usize,
23898 unit_w: usize,
23899 unit_h: usize,
23900) -> Neighbour {
23901 let mut cul = 0u32;
23902 let mut dc = None;
23903 for r in 0..unit_h {
23904 for c in 0..unit_w {
23905 let v = grid[(y0 + r) * bw + x0 + c];
23906 cul += v.unsigned_abs();
23907 if r == 0 && c == 0 && v != 0 {
23908 dc = Some(v < 0);
23909 }
23910 }
23911 }
23912 if cul == 0 {
23913 return Neighbour::default();
23914 }
23915 Neighbour {
23916 level: cul.min(7) as u8,
23917 dc,
23918 }
23919}
23920
23921/// [`sub8_leaf_chroma444`] for 4:2:2 (lane-av1-422g): an even-mi-column 4x4
23922/// leaf is its plane's own chroma reference (`is_chroma_reference`'s
23923/// `!(mi_col & ss_x)` at ss_x 1 -- every even-column leaf, not 4:2:0's single
23924/// bottom-right one) and codes ONE TX_4X4 chroma unit per plane right after
23925/// its luma: `ss_size_lookup[BLOCK_4X4][1][0]` is BLOCK_4X4, so the (2, 4)
23926/// plane area rounds up to the square 4x4 read. The unit sits at the chroma
23927/// position (`px >> ss_x`), and its 4 chroma-px width spans TWO luma mi
23928/// columns, so the context reads go through
23929/// [`Neighbours::around_mi_422_chroma`] and the entropy stamp covers both
23930/// columns with the unit's whole-unit state.
23931#[allow(clippy::too_many_arguments)]
23932fn sub8_leaf_chroma422(
23933 dec: &mut SymbolDecoder,
23934 cdfs: &mut Cdfs,
23935 neighbours: &mut Neighbours,
23936 lmi: (usize, usize),
23937 uv_mode: usize,
23938 angle_delta_uv: i32,
23939 alpha: Option<(i32, i32)>,
23940 skip: bool,
23941 intrabc_dv: Option<(i32, i32)>,
23942 y: &PlaneBuf<'static>,
23943 u: &mut PlaneBuf<'static>,
23944 v: &mut PlaneBuf<'static>,
23945 scan4: &[u16],
23946 base_q_idx: u8,
23947 smooth_neighbor_uv: bool,
23948 // The owning luma leaf's own shape (`(4, 4)` for a split leaf, `(8, 4)` /
23949 // `(4, 8)` for a rect pair's strip): libaom's `has_top_right` /
23950 // `has_bottom_left` answer for this chroma TX_4X4 unit comes from the
23951 // LEAF's own rect table row at the leaf's mi (`bsize` is the leaf, the
23952 // unit covers it whole), never the standalone square-4x4 table the old
23953 // `Reach::of(4, ..)` lookup used -- that said 1 where `has_tr_8x4` says 0
23954 // at mi(27,44) (the oracle's own EC_PRED prints `n_tr=0` there), so the
23955 // D45 unit read undecoded pixels to its upper right.
23956 leaf_shape: (usize, usize),
23957 fctx: &crate::decode::FrameCtx,
23958) -> Result<(Grid, Grid)> {
23959 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
23960 DC_PRED
23961 } else {
23962 uv_mode
23963 };
23964 // lane-av1-422kf2: libaom writes one MB_MODE_INFO per mi cell the LEAF
23965 // covers, and `chroma_left_mbmi`/`chroma_above_mbmi` read whichever of
23966 // those cells the next block's snap lands on -- an 8x4 strip's SM_V
23967 // uv_mode must therefore be visible at BOTH of its mi columns, or the
23968 // block to its right (mi (30,50): left neighbour cell (30,49)) missed the
23969 // smooth neighbour and skipped libaom's strength-1 intra edge filter
23970 // (class context-read-from-one-cell, the 4:2:2 sub-8 twin of the
23971 // lane-kf900 snap fix).
23972 neighbours.record_uv_mode_mi(
23973 lmi.0,
23974 lmi.1,
23975 (leaf_shape.0 / MI).max(1),
23976 (leaf_shape.1 / MI).max(1),
23977 uv_predict_mode,
23978 );
23979 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
23980 // lane-av1-422kf2: the unit's WRITE/PREDICTION anchor is the same floored
23981 // chroma cell as the entropy anchor below -- libaom positions the sub-8
23982 // chroma plane block at `av1_setup_dst_planes`' mi-exact floor
23983 // (`(mi_col & !1) * MI >> ss_x`), NOT at the odd leaf's own chroma x:
23984 // the oracle's mi(18,55) TX_4X4 unit reconstructed chroma px 108..111
23985 // (a pure V-copy of the row above at 108..111), while the leaf's own
23986 // chroma x is 110 -- anchoring there left px 108..109 unwritten (zeros)
23987 // and stepped px 112..113 with the unit's right columns.
23988 let (cpx, cpy) = (((lmi.1 & !1) * MI) >> ss_x(fctx), py >> ss_y(fctx));
23989 // lane-av1-422h: the entropy-context anchor is the unit's FLOOR chroma
23990 // cell (`pd->above_entropy_context + (mi_col >> ss_x)`): an ODD-column
23991 // leaf's 4-px unit starts at a chroma px that is NOT cell aligned, and
23992 // both its ctx read and its ctx write live in the cell containing that
23993 // start -- one luma mi column to the LEFT of the leaf's own. Even-column
23994 // (cell-aligned) leaves keep their own column. The state write spans the
23995 // anchor's two luma mi columns, so the second (odd) leaf of a split group
23996 // overwrites exactly the cell the first one wrote, as libaom's
23997 // `av1_set_entropy_contexts` per-TU writes do.
23998 let ctx_mi = (lmi.0, lmi.1 & !1);
23999 // lane-av1-422kf2: the square unit takes the leaf's OWN reach: a split
24000 // leaf is a standalone BLOCK_4X4 (square table), a rect pair's strip is
24001 // `of_rect` on the strip's true (8x4 / 4x8) shape -- libaom passes the
24002 // LEAF's bsize to `has_top_right`/`has_bottom_left`, so a rect strip's
24003 // answer comes from `has_tr_8x4`/`has_tr_4x8` at the strip's mi, not
24004 // from a 4x4-block lookup.
24005 let reach = if leaf_shape == (4, 4) {
24006 Reach::of(4, px, py, y.width, y.height, fctx)
24007 } else {
24008 Reach::of_rect(leaf_shape.0, leaf_shape.1, px, py, y.width, y.height, fctx)
24009 };
24010 let chroma_around = neighbours.around_mi_422_chroma(ctx_mi, 8, 4);
24011 // lane-av1422sub8pix: the CfL AC signal spans the UNIT's luma footprint,
24012 // anchored at the same FLOORED luma x the write/prediction anchor below
24013 // uses -- `px` (the odd leaf's own luma x) steps half the span into the
24014 // RIGHT neighbour group (t422 frame-1 leaf (1,23): the unit reconstructs
24015 // chroma px 44..47 from luma 88..95, while a `px`-anchored source
24016 // averaged luma 92..99 and every CFL unit of the group mismatched).
24017 let ac = alpha.map(|_| cfl_src_rect((lmi.1 & !1) * MI, py, 8, 4));
24018 let grids: (Grid, Grid) = if skip {
24019 // A skipped chroma-reference leaf still predicts (the CfL contribution
24020 // survives a skip); no coefficient symbol exists.
24021 if alpha.is_some() {
24022 hit!(CHROMA_SKIP_CFL_HITS);
24023 hit!(SKIP_CFL_HITS);
24024 }
24025 push_intra(
24026 1,
24027 cpx,
24028 cpy,
24029 4,
24030 uv_predict_mode,
24031 angle_delta_uv,
24032 reach,
24033 &ZERO_RESIDUAL[..16],
24034 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
24035 None,
24036 smooth_neighbor_uv,
24037 fctx,
24038 );
24039 push_intra(
24040 2,
24041 cpx,
24042 cpy,
24043 4,
24044 uv_predict_mode,
24045 angle_delta_uv,
24046 reach,
24047 &ZERO_RESIDUAL[..16],
24048 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
24049 None,
24050 smooth_neighbor_uv,
24051 fctx,
24052 );
24053 // The same arm-without-clear route the 4:2:0 tails count: a skipped
24054 // leaf reads no coefficient, so an armed intrabc slot is dropped.
24055 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
24056 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
24057 fctx.intrabc_chroma_tx.with(|c| c.set(None));
24058 }
24059 (Grid::Zero(16), Grid::Zero(16))
24060 } else if let Some(dv) = intrabc_dv {
24061 hit!(CHROMA422_SUB8_HITS);
24062 // Frame copy at the DV; the residual still reads the ordinary chroma
24063 // tables with the inherited luma `tx_type` (see the 4:2:0 tails).
24064 let mut ub = vec![0u16; 16];
24065 mc::predict_with_filter(
24066 &u.data,
24067 u.width,
24068 u.true_width,
24069 u.true_height,
24070 mv_to_q4(cpx, dv.1, ss_x(fctx)),
24071 mv_to_q4(cpy, dv.0, ss_y(fctx)),
24072 4,
24073 4,
24074 mc::InterpFilterKind::Bilinear,
24075 &mut ub,
24076 fctx,
24077 );
24078 let mut vb = vec![0u16; 16];
24079 mc::predict_with_filter(
24080 &v.data,
24081 v.width,
24082 v.true_width,
24083 v.true_height,
24084 mv_to_q4(cpx, dv.1, ss_x(fctx)),
24085 mv_to_q4(cpy, dv.0, ss_y(fctx)),
24086 4,
24087 4,
24088 mc::InterpFilterKind::Bilinear,
24089 &mut vb,
24090 fctx,
24091 );
24092 set_palette_pred(ub, fctx);
24093 let ug = read_plane(
24094 dec,
24095 cdfs,
24096 TxbSet::Chroma4,
24097 scan4,
24098 1,
24099 chroma_around[1],
24100 DC_PRED,
24101 DC_PRED,
24102 0,
24103 reach,
24104 u,
24105 cpx,
24106 cpy,
24107 4,
24108 TX4,
24109 base_q_idx,
24110 None,
24111 None,
24112 None,
24113 smooth_neighbor_uv,
24114 fctx,
24115 )?;
24116 set_palette_pred(vb, fctx);
24117 let vg = read_plane(
24118 dec,
24119 cdfs,
24120 TxbSet::Chroma4,
24121 scan4,
24122 2,
24123 chroma_around[2],
24124 DC_PRED,
24125 DC_PRED,
24126 0,
24127 reach,
24128 v,
24129 cpx,
24130 cpy,
24131 4,
24132 TX4,
24133 base_q_idx,
24134 None,
24135 None,
24136 None,
24137 smooth_neighbor_uv,
24138 fctx,
24139 )?;
24140 fctx.intrabc_chroma_tx.with(|c| c.set(None));
24141 (ug, vg)
24142 } else {
24143 hit!(CHROMA422_SUB8_HITS);
24144 let ug = read_plane(
24145 dec,
24146 cdfs,
24147 TxbSet::Chroma4,
24148 scan4,
24149 1,
24150 chroma_around[1],
24151 uv_mode,
24152 uv_predict_mode,
24153 angle_delta_uv,
24154 reach,
24155 u,
24156 cpx,
24157 cpy,
24158 4,
24159 TX4,
24160 base_q_idx,
24161 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
24162 None,
24163 None,
24164 smooth_neighbor_uv,
24165 fctx,
24166 )?;
24167 let vg = read_plane(
24168 dec,
24169 cdfs,
24170 TxbSet::Chroma4,
24171 scan4,
24172 2,
24173 chroma_around[2],
24174 uv_mode,
24175 uv_predict_mode,
24176 angle_delta_uv,
24177 reach,
24178 v,
24179 cpx,
24180 cpy,
24181 4,
24182 TX4,
24183 base_q_idx,
24184 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
24185 None,
24186 None,
24187 smooth_neighbor_uv,
24188 fctx,
24189 )?;
24190 (ug, vg)
24191 };
24192 // libaom `av1_set_entropy_contexts` stamps above/left PER TRANSFORM UNIT:
24193 // the unit's own chroma span -- 1 mi row tall, TWO luma mi columns wide
24194 // (one chroma column) -- not the 8x8 group's.
24195 let (u_grid, v_grid) = grids;
24196 let u_state = neighbour_state(&u_grid);
24197 let v_state = neighbour_state(&v_grid);
24198 if lmi.0 < neighbours.mi_rows {
24199 neighbours.left[ctx_mi.0][1] = u_state;
24200 neighbours.left[ctx_mi.0][2] = v_state;
24201 }
24202 for cell in 0..2 {
24203 if ctx_mi.1 + cell < neighbours.mi_cols {
24204 neighbours.above[ctx_mi.1 + cell][1] = u_state;
24205 neighbours.above[ctx_mi.1 + cell][2] = v_state;
24206 }
24207 }
24208 Ok((u_grid, v_grid))
24209}
24210
24211/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
24212/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
24213/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
24214/// bookkeeping needs no change. Each leaf reads its own luma mode info,
24215/// neighboured off the *previously decoded leaf in this same group* on
24216/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
24217/// pattern, one level deeper); chroma is read and reconstructed exactly
24218/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
24219/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
24220/// derivation.
24221#[allow(clippy::too_many_arguments)]
24222fn decode_leaf_split4(
24223 dec: &mut SymbolDecoder,
24224 cdfs: &mut Cdfs,
24225 neighbours: &mut Neighbours,
24226 outer_at: (usize, usize),
24227 leaf_mi: (usize, usize),
24228 scan4: &[u16],
24229 prev_leaf: Option<((usize, usize), usize)>,
24230 y: &mut PlaneBuf<'static>,
24231 u: &mut PlaneBuf<'static>,
24232 v: &mut PlaneBuf<'static>,
24233 base_q_idx: u8,
24234 enable_filter_intra: bool,
24235 allow_intrabc: bool,
24236 reduced_tx_set: bool,
24237 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
24238 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
24239 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx
24240 fctx: &crate::decode::FrameCtx,
24241) -> Result<(usize, usize)> {
24242 hit!(SUB8_SPLIT_HITS);
24243 let (r, c) = outer_at;
24244 let mut above_mode = neighbours.above_mode[c];
24245 let mut left_mode = neighbours.left_mode[r];
24246 if let Some(((pr, pc), pmode)) = prev_leaf {
24247 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
24248 above_mode = pmode;
24249 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
24250 left_mode = pmode;
24251 }
24252 }
24253 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
24254 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
24255 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
24256 let mut leaf_modes = [0usize; 4];
24257 let mut leaf_skips = [false; 4];
24258 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
24259 // lane-av1txr: the chroma-reference (i==3) leaf's block vector when that
24260 // leaf is an intrabc block -- its prediction/reconstruction below is a
24261 // frame copy at this DV, not an intra one.
24262 let mut last_intrabc: Option<(i32, i32)> = None;
24263 // 4:4:4 (lane-av1-444): `is_chroma_reference` (av1_common_int.h:1459) is
24264 // unconditional at subsampling 0/0, so EVERY 4x4 leaf reads its own
24265 // `uv_mode` and codes its own full-resolution 4x4 chroma unit right
24266 // after its luma -- there is no shared group unit at all.
24267 let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
24268 // lane-av1-422g: at ss (1,0) every even-mi-column leaf is its plane's own
24269 // chroma reference (`is_chroma_reference`'s `!(mi_col & ss_x)`) and codes
24270 // one TX_4X4 chroma unit per plane; odd-column leaves read no chroma.
24271 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
24272 // The last leaf's own `uv_predict_mode`, for the coarse above/left slots
24273 // the 4:2:0 tail fills from the group's single unit.
24274 let mut last_uv444 = DC_PRED;
24275 let mut last_uv422 = DC_PRED;
24276 for i in 0..4usize {
24277 let (dr, dc) = (i / 2, i % 2);
24278 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
24279 // Neighbour modes at real mi granularity: inside the group the
24280 // sibling leaf, outside it the split-leaf map when the adjacent mi
24281 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
24282 // `sub8_mode_col`'s doc).
24283 let leaf_above = if dr == 0 {
24284 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
24285 } else {
24286 leaf_modes[i - 2]
24287 };
24288 let leaf_left = if dc == 0 {
24289 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
24290 } else {
24291 leaf_modes[i - 1]
24292 };
24293 let has_chroma = if chroma_444 {
24294 true
24295 } else if chroma_422 {
24296 // lane-av1-422h: `is_chroma_reference`'s column clause at ss_x 1 is
24297 // `(mi_col & 1)` for a BLOCK_4X4 leaf -- the ODD-column leaf is the
24298 // chroma reference (oracle, mi(30,42) split group: uv_mode read at
24299 // mi(30,43) and mi(31,43) only). The even-column rule this
24300 // replaces came from 422f's pre-partition-trace misreading.
24301 (lmi.1 & 1) == 1
24302 } else {
24303 i == 3
24304 };
24305 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
24306 let (skip, mode, angle_delta_y, chroma, filter_intra, intrabc) = read_intra_mode_sub8(
24307 dec,
24308 cdfs,
24309 leaf_above,
24310 leaf_left,
24311 has_chroma,
24312 enable_filter_intra,
24313 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
24314 skip_ctx,
24315 allow_intrabc,
24316 lmi.0,
24317 lmi.1,
24318 1,
24319 1,
24320 fctx,
24321 )?;
24322 leaf_modes[i] = mode;
24323 leaf_skips[i] = skip;
24324 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
24325 // lane-av1txr: libaom `parse_decode_block`'s `set_txfm_ctxs` for this
24326 // `BLOCK_4X4` leaf -- EVERY block publishes its transform size into
24327 // the TXFM context bands, and an intrabc block's later `txfm_split`
24328 // context is read off them (`txfm_partition_context`). A 4x4 never
24329 // signals a tx size, so it is always TX_4X4 (`set_txfm_ctxs`'s
24330 // `skip && is_inter` branch writes the block's own 4 pixels -- the
24331 // same value).
24332 set_txfm_ctxs(neighbours, lmi, 4, 1, 1, false);
24333 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
24334 if smooth_neighbor {
24335 hit!(SMOOTH_LUMA_HITS);
24336 }
24337 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
24338 let reach = Reach::of(4, px, py, y.width, y.height, fctx);
24339 if let Some(dv) = intrabc {
24340 // lane-av1txr: an intrabc `BLOCK_4X4` leaf -- prediction is the
24341 // CURRENT frame at the block vector (`predict_inter_block`'s
24342 // intrabc arm, spec 7.11.3.4), residual the INTER coefficient set
24343 // (libaom reads `tx_type` off `inter_ext_tx_cdf` for
24344 // `is_inter_block`, which counts intrabc). Published into
24345 // `intrabc_dv` so the group's chroma arm (below, when the
24346 // chroma-reference leaf is the intrabc one) and
24347 // [`record_intrabc_mi`] see it.
24348 flush_recon(fctx, y, u, v);
24349 let mut yb = vec![0u16; 16];
24350 mc::predict_with_filter(
24351 &y.data,
24352 y.width,
24353 y.true_width,
24354 y.true_height,
24355 mv_to_q4(px, dv.1, 0),
24356 mv_to_q4(py, dv.0, 0),
24357 4,
24358 4,
24359 mc::InterpFilterKind::Bilinear,
24360 &mut yb,
24361 fctx,
24362 );
24363 set_palette_pred(yb.clone(), fctx);
24364 if skip {
24365 push_intra(
24366 0,
24367 px,
24368 py,
24369 4,
24370 DC_PRED,
24371 0,
24372 reach,
24373 &ZERO_RESIDUAL[..16],
24374 None,
24375 None,
24376 smooth_neighbor,
24377 fctx,
24378 );
24379 neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]);
24380 } else {
24381 let tu_around = neighbours.around_mi(lmi, 4)[0];
24382 let tu_grid = read_plane(
24383 dec,
24384 cdfs,
24385 if reduced_tx_set {
24386 TxbSet::Luma4Inter
24387 } else {
24388 TxbSet::Luma4InterSet1
24389 },
24390 scan4,
24391 0,
24392 tu_around,
24393 DC_PRED,
24394 DC_PRED,
24395 0,
24396 reach,
24397 y,
24398 px,
24399 py,
24400 4,
24401 4,
24402 base_q_idx,
24403 None,
24404 None,
24405 None,
24406 smooth_neighbor,
24407 fctx,
24408 )?;
24409 neighbours.record_mi_luma(lmi, 4, &tu_grid);
24410 }
24411 neighbours.fill_skip_grid(lmi, 1, skip);
24412 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
24413 record_intrabc_mi(lmi.0, lmi.1, 1, Some(dv), neighbours, fctx);
24414 if has_chroma {
24415 // An intrabc block is an INTER block for `av1_get_tx_type`, so
24416 // the chroma inherits the LUMA's coded transform type
24417 // (`xd->tx_type_map` at the co-located luma position) -- the
24418 // luma `read_plane` above just set [`LUMA_TX_TYPE`]. Armed for
24419 // exactly this leaf's two chroma reads.
24420 fctx.intrabc_chroma_tx
24421 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
24422 if chroma_444 {
24423 // lane-av1-444: this leaf codes its OWN 4x4 chroma unit
24424 // right here (frame copy at the DV); no group tail.
24425 sub8_leaf_chroma444(
24426 dec,
24427 cdfs,
24428 neighbours,
24429 lmi,
24430 4,
24431 4,
24432 DC_PRED,
24433 None,
24434 skip,
24435 Some(dv),
24436 y,
24437 u,
24438 v,
24439 scan4,
24440 base_q_idx,
24441 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
24442 fctx,
24443 )?;
24444 last_uv444 = DC_PRED;
24445 } else if chroma_422 {
24446 sub8_leaf_chroma422(
24447 dec,
24448 cdfs,
24449 neighbours,
24450 lmi,
24451 DC_PRED,
24452 0,
24453 None,
24454 skip,
24455 Some(dv),
24456 y,
24457 u,
24458 v,
24459 scan4,
24460 base_q_idx,
24461 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
24462 (4, 4),
24463 fctx,
24464 )?;
24465 last_uv422 = DC_PRED;
24466 } else {
24467 last_uv = Some((DC_PRED, 0, None));
24468 // lane-av1txbands: the group's chroma is the CHROMA-REFERENCE
24469 // leaf's own block -- libaom codes one chroma unit under the
24470 // last sub-block only (`is_chroma_reference`), so its prediction
24471 // is that leaf's `uv_mode` (CfL alpha and all) unless THAT leaf
24472 // is the intrabc one. Arming this from a non-chroma-reference
24473 // leaf's DV made `warped.obu`'s 8x8 group at mi(40,62) copy
24474 // frame bytes at mi(41,62)'s vector where aomdec predicts
24475 // `uv_mode=UV_CFL_PRED`: luma stayed byte-exact and only chroma
24476 // moved (class chroma-keyed-at-a-non-chroma-leaf). Mirrors
24477 // [`decode_leaf_rect8`]'s own placement.
24478 last_intrabc = Some(dv);
24479 }
24480 }
24481 continue;
24482 }
24483 if skip {
24484 push_intra(
24485 0,
24486 px,
24487 py,
24488 4,
24489 mode,
24490 angle_delta_y,
24491 reach,
24492 &ZERO_RESIDUAL[..16],
24493 None,
24494 filter_intra,
24495 smooth_neighbor,
24496 fctx,
24497 );
24498 neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]);
24499 } else {
24500 let tu_around = neighbours.around_mi(lmi, 4)[0];
24501 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
24502 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
24503 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
24504 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
24505 // off the wrong CDF on the very first leaf and desynced the tile.
24506 let tu_grid = read_plane(
24507 dec,
24508 cdfs,
24509 if reduced_tx_set {
24510 TxbSet::Luma4
24511 } else {
24512 TxbSet::Luma4Set1
24513 },
24514 scan4,
24515 0,
24516 tu_around,
24517 mode,
24518 mode,
24519 angle_delta_y,
24520 reach,
24521 y,
24522 px,
24523 py,
24524 4,
24525 4,
24526 base_q_idx,
24527 None,
24528 filter_intra,
24529 None,
24530 smooth_neighbor,
24531 fctx,
24532 )?;
24533 neighbours.record_mi_luma(lmi, 4, &tu_grid);
24534 }
24535 neighbours.fill_skip_grid(lmi, 1, skip);
24536 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
24537 if has_chroma {
24538 if chroma_444 {
24539 // lane-av1-444: the leaf's own 4x4 chroma unit, coded right
24540 // after its luma (no shared group unit at ss 0/0).
24541 let (uv_mode, _, alpha) = chroma.expect("4:4:4 reads uv_mode on every leaf");
24542 sub8_leaf_chroma444(
24543 dec,
24544 cdfs,
24545 neighbours,
24546 lmi,
24547 4,
24548 4,
24549 uv_mode,
24550 alpha,
24551 skip,
24552 None,
24553 y,
24554 u,
24555 v,
24556 scan4,
24557 base_q_idx,
24558 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
24559 fctx,
24560 )?;
24561 last_uv444 = if uv_mode == UV_CFL_PRED {
24562 DC_PRED
24563 } else {
24564 uv_mode
24565 };
24566 } else if chroma_422 {
24567 let (uv_mode, angle_delta_uv, alpha) =
24568 chroma.expect("4:2:2 reads uv_mode on even-column leaves");
24569 sub8_leaf_chroma422(
24570 dec,
24571 cdfs,
24572 neighbours,
24573 lmi,
24574 uv_mode,
24575 angle_delta_uv,
24576 alpha,
24577 skip,
24578 None,
24579 y,
24580 u,
24581 v,
24582 scan4,
24583 base_q_idx,
24584 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
24585 (4, 4),
24586 fctx,
24587 )?;
24588 last_uv422 = if uv_mode == UV_CFL_PRED {
24589 DC_PRED
24590 } else {
24591 uv_mode
24592 };
24593 } else {
24594 last_uv = chroma;
24595 }
24596 }
24597 }
24598 // lane-av1mono: as [`decode_leaf_rect8`] -- a monochrome frame has no
24599 // chroma to reconstruct and no uv_mode was read.
24600 let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) {
24601 (Grid::Zero(16), Grid::Zero(16))
24602 } else if chroma_444 {
24603 // lane-av1-444: every leaf coded and reconstructed its own chroma in
24604 // the loop above ([`sub8_leaf_chroma444`] stamped the mi-exact maps
24605 // and per-leaf entropy state); only the coarse slots remain, filled
24606 // from the bottom-right leaf like the 4:2:0 tail's single unit.
24607 neighbours.above_uv_mode[c] = last_uv444;
24608 neighbours.left_uv_mode[r] = last_uv444;
24609 (Grid::Zero(16), Grid::Zero(16))
24610 } else if chroma_422 {
24611 // lane-av1-422g: each even-column leaf coded and reconstructed its
24612 // own TX_4X4 chroma unit in the loop above (sub8_leaf_chroma422
24613 // stamped the per-leaf entropy state); only the coarse slots remain,
24614 // filled from the group's last chroma-reference leaf (bottom-left).
24615 neighbours.above_uv_mode[c] = last_uv422;
24616 neighbours.left_uv_mode[r] = last_uv422;
24617 (Grid::Zero(16), Grid::Zero(16))
24618 } else {
24619 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
24620 let (cpx, cpy) = (gpx >> ss_x(fctx), gpy >> ss_y(fctx));
24621 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
24622 let (uv_mode, angle_delta_uv, alpha) =
24623 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
24624 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
24625 DC_PRED
24626 } else {
24627 uv_mode
24628 };
24629 neighbours.above_uv_mode[c] = uv_predict_mode;
24630 neighbours.left_uv_mode[r] = uv_predict_mode;
24631 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
24632 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[3] {
24633 // A skipped chroma block still gets its CfL contribution: libaom's
24634 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
24635 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
24636 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
24637 // added -- `skip_txfm` only drops the residual, never the alpha.
24638 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
24639 // merge keeps one fix and feeds both lanes' counters so neither of
24640 // their gates goes vacuous.
24641 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
24642 if alpha.is_some() {
24643 hit!(CHROMA_SKIP_CFL_HITS);
24644 hit!(SKIP_CFL_HITS);
24645 }
24646 push_intra(
24647 1,
24648 cpx,
24649 cpy,
24650 4,
24651 uv_predict_mode,
24652 angle_delta_uv,
24653 group_reach,
24654 &ZERO_RESIDUAL[..16],
24655 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
24656 None,
24657 smooth_neighbor_uv,
24658 fctx,
24659 );
24660 push_intra(
24661 2,
24662 cpx,
24663 cpy,
24664 4,
24665 uv_predict_mode,
24666 angle_delta_uv,
24667 group_reach,
24668 &ZERO_RESIDUAL[..16],
24669 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
24670 None,
24671 smooth_neighbor_uv,
24672 fctx,
24673 );
24674 // lane-av1txbands: a SKIPPED chroma-reference leaf reads no chroma
24675 // coefficient, so it never consults the inherited luma transform type
24676 // -- but an intrabc chroma-reference leaf did arm
24677 // [`INTRABC_CHROMA_TX`] above (`has_chroma`), and the two coefficient
24678 // branches below are the only ones that disarm it. Left armed, the slot
24679 // picks the NEXT block's chroma scan and inverse transform (class
24680 //

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