forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB052d1d3Tahinli2 months ago3627 commits

decode.rs24228 lines, 2.4 MiBHistoryRawDownload
1//! Software decoder for this crate's own key-frame tile payloads (spec 5.11),
2//! the reader half of [`crate::tile`]'s writer.
3//!
4//! `tile.rs` is another lane's territory this round (`lane-av1-rect` is
5//! touching its partition search), so nothing here imports its private
6//! helpers: the handful of `pub(crate)` items it already exposes
7//! ([`crate::tile::block_grid`], [`crate::tile::has_half`],
8//! [`crate::tile::INTRA_MODE_CTX`], [`crate::tile::write_golomb`]) are reused,
9//! and everything else (the partition/coefficient context arithmetic, the
10//! scan table) is a from-spec reimplementation kept in step with the writer by
11//! the gate tests below rather than by sharing code with it.
12//!
13//! # Scope (round 1)
14//! Key frames only, and only the shapes the encoder actually still needs to
15//! prove itself against: every coded block is `DC_PRED` (this crate's mode
16//! search names other intra modes, but a decoder for those needs the
17//! directional-prediction edge-reach plumbing [`crate::intra::predict`]
18//! already carries; wiring it up is round 2), never skipped, and every
19//! superblock is a whole number of 64x64 units (a frame whose true edge falls
20//! inside one, forcing the gathered-CDF partial-superblock path, is round 2
21//! too). Anything outside that refuses with [`Error::unsupported`] rather than
22//! silently miscoding.
23use crate::hits::{hit, hit_do};
24
25use ec_av1_syntax::{
26 CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, MAX_SEGMENTS,
27 SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo,
28};
29use ec_core::{Error, Result};
30
31// lane-av112bit: the 12-bit warp refusal that used to stand at all three
32// warp decision sites (compound, 16x16+, 8x8 leaf) was an inline literal
33// (refusal_inventory.rs extracts refusal strings from the decode source);
34// it named the real gap: warp's reduce bits inherited the 12-bit
35// `conv_params->round_0` (warped_motion.c:295, convolve.h:81..86) and no
36// witness existed.
37// lane-av112bitw lifted it from all three sites: `warp::warp_round_0`
38// implements the bump (`round_0 += max(bd + FILTER_BITS - round_0 - 14, 0)`,
39// 5 at 12 bits), and the single-ref witness plus the rotating-mandelbrot
40// compound-warp witness are both byte-exact vs ffmpeg. Compound inter
41// itself was lifted by lane-av112bitc before that (the combines absorb the
42// CONV_BUF gain drop, `INTER_POST_ROUND - delta`, see `mc::combine_compound`).
43
44/// Per-frame decode state, one instance per decoded stream (lane-thread1).
45///
46/// Every field here used to be a `thread_local!` static, which made a decode a
47/// function of the calling THREAD's history rather than of the bitstream alone
48/// -- and made frame-parallel decoding impossible, since a worker thread sees
49/// empty state. The cells keep exactly the interior mutability the statics
50/// had, so every read/write site is byte-identical; what changes is WHERE the
51/// state lives: `stream.rs` owns one `FrameCtx` and threads `&FrameCtx` down
52/// the decode call graph.
53///
54/// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to
55/// exactly one thread's decode, and is never shared between workers.
56/// One frame's in-loop filter intermediates, as [`FrameCtx::capture_stages`]
57/// asks for them: each plane's post-deblock (pre-CDEF) and post-CDEF
58/// (pre-restoration) samples, at the decoder's own plane stride.
59pub(crate) struct FilterStages {
60 /// Post-deblock, pre-CDEF planes (Y, U, V).
61 pub(crate) deblocked: [Vec<u16>; 3],
62 /// Post-CDEF, pre-restoration planes (Y, U, V).
63 pub(crate) cdefed: [Vec<u16>; 3],
64 /// Each plane's stride (and so its width in the buffers above).
65 pub(crate) stride: [usize; 3],
66}
67
68/// Takes whatever the last capturing decode left (see
69/// [`FrameCtx::capture_stages`]).
70#[allow(dead_code)] // read from the encoder's loop restoration search
71pub(crate) fn take_filter_stages(fctx: &FrameCtx) -> Option<FilterStages> {
72 fctx.stages.borrow_mut().take()
73}
74
75pub(crate) struct FrameCtx {
76 /// lane-av1lr: when set, the frame filter chain leaves its post-deblock
77 /// and post-CDEF planes in [`FrameCtx::stages`] for the ENCODER's loop
78 /// restoration search (spec 7.17 reads both: the stripe interior from
79 /// the post-CDEF plane, its 3-row border from the post-deblock one).
80 /// Off for every decode but that search, and off it costs one bool read
81 /// per frame and not a single copy.
82 pub(crate) capture_stages: std::cell::Cell<bool>,
83 pub(crate) stages: std::cell::RefCell<Option<FilterStages>>,
84 pub(crate) sb128_flag: std::cell::Cell<bool>,
85 /// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every
86 /// motion compensation of THIS frame runs, already resolved to a kernel.
87 /// `mc::predict` used to hardwire `Regular`, so the encoder's search,
88 /// trial and recon could only ever build a REGULAR prediction whatever
89 /// the frame header said; it lives here (and is copied by
90 /// [`filter_ctx_copy`]) so a tile-search worker thread reads the same
91 /// kernel the frame header wrote instead of the default.
92 pub(crate) interp_filter: std::cell::Cell<crate::mc::InterpFilterKind>,
93 /// lane-lossless: this frame's per-segment lossless table -- libaom's
94 /// `xd->lossless[MAX_SEGMENTS]`, computed ONCE per frame in the header
95 /// (spec 5.9.12 `CodedLossless`: each segment at `qindex == 0` with zero
96 /// plane deltas, `get_qindex` applying that segment's own `SEG_LVL_ALT_Q`).
97 /// Every block-decoder rule that reads [`decode::lossless`] resolves it
98 /// through the BLOCK's own `segment_id`: TX_4X4 with the Walsh-Hadamard
99 /// transform on every plane, the dropped `tx_type` symbol and the narrowed
100 /// `is_cfl_allowed` (libaom `read_tx_size` (`decodeframe.c`),
101 /// `read_tx_type` (`decodetxb.c`), `is_cfl_allowed` (`blockd.h`)) follow
102 /// the SEGMENT, so a frame whose segments disagree codes lossless and
103 /// lossy blocks side by side.
104 pub(crate) lossless_per_seg: std::cell::Cell<[bool; MAX_SEGMENTS]>,
105 /// lane-av1txr: this frame header's `disable_cdf_update` (spec 5.9.2).
106 /// When set, the tile reader must not adapt any CDF it reads, or its
107 /// tables drift away from the encoder's and the frame desyncs mid-tile
108 /// (libaom: `allow_update_cdf = allow_update_cdf &&
109 /// !cm->features.disable_cdf_update`, `decodeframe.c:2909`).
110 pub(crate) disable_cdf_update: std::cell::Cell<bool>,
111 pub(crate) cdef_bits: std::cell::Cell<u8>,
112 pub(crate) bit_depth: std::cell::Cell<u8>,
113 /// lane-av1mono: the sequence header's `color_config.mono_chrome` (spec
114 /// 5.5.2), i.e. `NumPlanes == 1`. libaom threads this as
115 /// `av1_num_planes(cm)` and every chroma read site is guarded by
116 /// `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`,
117 /// `:1208`) or bounded by `plane < num_planes`; a monochrome frame codes
118 /// NO `uv_mode`/`cfl`/`angle_delta_uv`/`palette_uv` symbol and NO chroma
119 /// coefficients on any block. Set once per frame from the sequence header
120 /// (like [`FrameCtx::bit_depth`]), so a mono frame decoded on a thread
121 /// that last saw a 4:2:0 one never inherits the wrong plane count.
122 pub(crate) mono_chrome: std::cell::Cell<bool>,
123 /// lane-av1-444: sequence subsampling_x/y. 1,1 is 4:2:0; 0,0 is 4:4:4.
124 pub(crate) subsampling_x: std::cell::Cell<u8>,
125 pub(crate) subsampling_y: std::cell::Cell<u8>,
126 pub(crate) superres: std::cell::Cell<(u32, u32)>,
127 pub(crate) cdef_transmitted: std::cell::Cell<bool>,
128 pub(crate) cdef_sb_cols: std::cell::Cell<usize>,
129 pub(crate) cdef_idx_grid: std::cell::RefCell<Vec<u8>>,
130 pub(crate) delta_q_present: std::cell::Cell<bool>,
131 pub(crate) delta_q_res: std::cell::Cell<i32>,
132 pub(crate) current_q_idx: std::cell::Cell<i32>,
133 pub(crate) quant_deltas: std::cell::Cell<crate::quant::QuantDeltas>,
134 /// lane-av1-qmatrix: this frame's quantisation-matrix LEVEL per plane,
135 /// straight from spec 5.9.12's `qm_y`/`qm_u`/`qm_v` (the parsed 4-bit
136 /// value IS the table level -- libaom `quant_params->qmatrix_level_y/u/v`,
137 /// decodeframe.c:1902-1917; the `aom_get_qmlevel` formula that maps
138 /// base_q_idx onto a level is encoder-side only). 15 is libaom's flat
139 /// sentinel (`NUM_QM_LEVELS - 1`, stored as NULL tables) and the default
140 /// every `using_qmatrix == 0` frame keeps, so a matrix-free stream
141 /// selects no matrix.
142 pub(crate) qm_levels: std::cell::Cell<[u8; 3]>,
143 pub(crate) delta_lf_present: std::cell::Cell<bool>,
144 pub(crate) delta_lf_res: std::cell::Cell<i32>,
145 pub(crate) delta_lf_multi: std::cell::Cell<bool>,
146 pub(crate) current_delta_lf: std::cell::Cell<[i32; 4]>,
147 pub(crate) seg: std::cell::RefCell<SegmentationParams>,
148 pub(crate) seg_ids: std::cell::RefCell<Vec<u8>>,
149 pub(crate) prev_seg_ids: std::cell::RefCell<Vec<u8>>,
150 pub(crate) seg_mi_dims: std::cell::Cell<(usize, usize)>,
151 pub(crate) above_seg_pred: std::cell::RefCell<Vec<u8>>,
152 pub(crate) left_seg_pred: std::cell::RefCell<Vec<u8>>,
153 pub(crate) cur_segment_id: std::cell::Cell<u8>,
154 pub(crate) seg_tile_origin: std::cell::Cell<(usize, usize)>,
155 pub(crate) tx_select_inter: std::cell::Cell<bool>,
156 /// Whether the tile being decoded is an INTRA-ONLY frame's (key/intra-only
157 /// frame). libaom runs `set_txfm_ctxs` for EVERY block of EVERY frame
158 /// (`decodeframe.c` `parse_decode_block`), so an intra-only frame
159 /// maintains the `TXFM_CONTEXT` bands exactly like an inter one; only this
160 /// decoder's inter-side publishing was wired. See
161 /// [`Neighbours::fill_lf_grid_rect`]'s band publish.
162 pub(crate) intra_only: std::cell::Cell<bool>,
163 /// This FRAME's own `tx_mode == TxMode::Select`, set for EVERY frame
164 /// (intra included). [`Self::tx_select_inter`] cannot stand in for it:
165 /// an intrabc block rides an INTRA frame, but libaom still reads its
166 /// var-tx `txfm_partition` tree under the frame's `TxMode::Select`.
167 pub(crate) tx_select_frame: std::cell::Cell<bool>,
168 pub(crate) reduced_tx_set_inter: std::cell::Cell<bool>,
169 pub(crate) enable_filter_intra_inter: std::cell::Cell<bool>,
170 pub(crate) palette_pred: std::cell::RefCell<Option<Vec<u16>>>,
171 pub(crate) intrabc_mi_grid: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>>,
172 pub(crate) intrabc_dv: std::cell::Cell<Option<(i32, i32)>>,
173 pub(crate) luma_tx_type: std::cell::Cell<TxType>,
174 pub(crate) intrabc_chroma_tx: std::cell::Cell<Option<TxType>>,
175 pub(crate) intra_in_inter_mode: std::cell::Cell<Option<(usize, bool)>>,
176 pub(crate) inter_strip_chroma: std::cell::Cell<Option<InterStripChroma>>,
177 pub(crate) inter_last_mc:
178 std::cell::Cell<Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>>,
179 pub(crate) enable_edge_filter: std::cell::Cell<bool>,
180 pub(crate) last_frame_wide_margin: std::cell::RefCell<Option<Picture>>,
181 pub(crate) reach_sb_px: std::cell::Cell<usize>,
182 pub(crate) grain_bit_depth: std::cell::Cell<u32>,
183 /// lane-wave1 step (i): this superblock's recorded pixel writes, see
184 /// [`ReconOp`]. Pushed by parse, replayed by [`flush_recon`].
185 pub(crate) recon_ops: std::cell::RefCell<Vec<ReconOp>>,
186 /// The queue buffer [`flush_recon`] just drained, kept for its capacity
187 /// so a superblock's records do not regrow the vector from nothing.
188 pub(crate) recon_spare: std::cell::RefCell<Vec<ReconOp>>,
189 /// lane-recoparse: the coefficient grids of the recorded ops above, one
190 /// buffer instead of a `Vec` per transform unit -- a recorded unit is
191 /// `(offset, len)` into it ([`Residual::Coeffs`]). Written by parse
192 /// before the op is published, read only by whoever replays that op, and
193 /// handed over WITH the ops at every drain point ([`wave_submit`],
194 /// [`flush_recon`]), so offsets are always relative to the live arena.
195 pub(crate) coeff_arena: std::cell::RefCell<Vec<i32>>,
196 /// [`recon_spare`](Self::recon_spare) for the arena, on the inline drain
197 /// path (a submitted job's arena travels to its worker instead).
198 pub(crate) coeff_spare: std::cell::RefCell<Vec<i32>>,
199 /// [`coeff_arena`](Self::coeff_arena) for the recorded PREDICTIONS
200 /// ([`PredSrc::Owned`]): same lifetime, same drain points.
201 pub(crate) pred_arena: std::cell::RefCell<Vec<u16>>,
202 pub(crate) pred_spare: std::cell::RefCell<Vec<u16>>,
203 /// lane-wave1 step (ii): the tile decoder's own planes, registered by
204 /// [`ReconInline`] while reconstruction runs INLINE (one recon thread).
205 /// `None` while the queue is in use (wavefront workers) and outside a
206 /// tile. See [`push_op`].
207 pub(crate) recon_planes: std::cell::Cell<Option<ReconPlanes>>,
208 /// lane-wave1 step (ii): the superblock wavefront this tile's recorded
209 /// writes are handed to, at more than one reconstruction thread.
210 pub(crate) wave: std::cell::RefCell<Option<std::sync::Arc<WaveState>>>,
211 /// lane-wave5 instrumentation only (`EC_AV1_WAVE_STATS`): when the parse
212 /// thread last handed a superblock to the wavefront.
213 pub(crate) wave_mark: std::cell::Cell<Option<std::time::Instant>>,
214}
215
216impl std::fmt::Debug for FrameCtx {
217 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218 f.write_str("FrameCtx")
219 }
220}
221
222impl FrameCtx {
223 /// A fresh context, every field at the default its thread-local
224 /// predecessor was born with.
225 pub(crate) fn new() -> Self {
226 Self {
227 // A DECODER context is seeded from the stream alone: every real
228 // decode overwrites this from the parsed sequence header
229 // (`set_sb128`, stream.rs). The encoder's own contexts start at
230 // the size this process encodes -- see [`FrameCtx::for_encoder`].
231 sb128_flag: std::cell::Cell::new(false),
232 interp_filter: std::cell::Cell::new(crate::mc::InterpFilterKind::Regular),
233 lossless_per_seg: std::cell::Cell::new([false; MAX_SEGMENTS]),
234 disable_cdf_update: std::cell::Cell::new(false),
235 cdef_bits: std::cell::Cell::new(0),
236 bit_depth: std::cell::Cell::new(8),
237 mono_chrome: std::cell::Cell::new(false),
238 subsampling_x: std::cell::Cell::new(1),
239 subsampling_y: std::cell::Cell::new(1),
240 superres: std::cell::Cell::new((0, 8)),
241 cdef_transmitted: std::cell::Cell::new(false),
242 cdef_sb_cols: std::cell::Cell::new(0),
243 capture_stages: std::cell::Cell::new(false),
244 stages: std::cell::RefCell::new(None),
245 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
246 delta_q_present: std::cell::Cell::new(false),
247 delta_q_res: std::cell::Cell::new(1),
248 current_q_idx: std::cell::Cell::new(0),
249 quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas {
250 y_dc: 0,
251 u_dc: 0,
252 u_ac: 0,
253 v_dc: 0,
254 v_ac: 0,
255 }),
256 qm_levels: std::cell::Cell::new([crate::qm::NUM_QM_LEVELS as u8 - 1; 3]),
257 delta_lf_present: std::cell::Cell::new(false),
258 delta_lf_res: std::cell::Cell::new(1),
259 delta_lf_multi: std::cell::Cell::new(false),
260 current_delta_lf: std::cell::Cell::new([0; 4]),
261 seg: std::cell::RefCell::new(SegmentationParams::default()),
262 seg_ids: std::cell::RefCell::new(Vec::new()),
263 prev_seg_ids: std::cell::RefCell::new(Vec::new()),
264 seg_mi_dims: std::cell::Cell::new((0, 0)),
265 above_seg_pred: std::cell::RefCell::new(Vec::new()),
266 left_seg_pred: std::cell::RefCell::new(Vec::new()),
267 cur_segment_id: std::cell::Cell::new(0),
268 seg_tile_origin: std::cell::Cell::new((0, 0)),
269 tx_select_inter: std::cell::Cell::new(false),
270 tx_select_frame: std::cell::Cell::new(false),
271 intra_only: std::cell::Cell::new(false),
272 reduced_tx_set_inter: std::cell::Cell::new(false),
273 enable_filter_intra_inter: std::cell::Cell::new(false),
274 palette_pred: std::cell::RefCell::new(None),
275 intrabc_mi_grid: std::cell::RefCell::new(None),
276 intrabc_dv: std::cell::Cell::new(None),
277 luma_tx_type: std::cell::Cell::new(TxType::DctDct),
278 intrabc_chroma_tx: std::cell::Cell::new(None),
279 intra_in_inter_mode: std::cell::Cell::new(None),
280 inter_strip_chroma: std::cell::Cell::new(None),
281 inter_last_mc: std::cell::Cell::new(None),
282 enable_edge_filter: std::cell::Cell::new(false),
283 last_frame_wide_margin: std::cell::RefCell::new(None),
284 reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK),
285 grain_bit_depth: std::cell::Cell::new(8),
286 recon_ops: std::cell::RefCell::new(Vec::new()),
287 recon_spare: std::cell::RefCell::new(Vec::new()),
288 coeff_arena: std::cell::RefCell::new(Vec::new()),
289 coeff_spare: std::cell::RefCell::new(Vec::new()),
290 pred_arena: std::cell::RefCell::new(Vec::new()),
291 pred_spare: std::cell::RefCell::new(Vec::new()),
292 recon_planes: std::cell::Cell::new(None),
293 wave: std::cell::RefCell::new(None),
294 wave_mark: std::cell::Cell::new(None),
295 }
296 }
297
298 /// A context for the ENCODER's own trial decodes: it starts at the
299 /// superblock size this process encodes (`crate::encode::sb128_on`) so
300 /// the mode search's `Reach` and the filter search's internal decodes
301 /// agree with the tile writer. A decoder never reads that knob -- doing
302 /// so coupled every decode to the encoder's process-global and raced the
303 /// 128-superblock decode gates against the encoder witness.
304 pub(crate) fn for_encoder() -> Self {
305 let ctx = Self::new();
306 let on = crate::encode::sb128_on();
307 ctx.sb128_flag.set(on);
308 ctx.reach_sb_px
309 .set(if on { 128 } else { crate::encode::SUPERBLOCK });
310 ctx
311 }
312}
313
314/// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)`
315/// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent
316/// `with` still wins for the scratch pools and gate counters that stay
317/// thread-local.
318pub(crate) trait WithRef {
319 fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
320 f(self)
321 }
322}
323impl<T: ?Sized> WithRef for T {}
324
325/// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads.
326///
327/// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread),
328/// and the post-decode filter chain reads exactly these fields: the bit depth
329/// (every kernel's clamp and threshold shift), the segmentation table
330/// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state
331/// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s
332/// default -- a field that turns out to be read after all shows up as a hash
333/// mismatch in
334/// `a_real_stream_filters_identically_with_one_and_four_filter_threads`.
335pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
336 let out = FrameCtx::new();
337 out.bit_depth.set(fctx.bit_depth.get());
338 out.mono_chrome.set(fctx.mono_chrome.get());
339 out.subsampling_x.set(fctx.subsampling_x.get());
340 out.subsampling_y.set(fctx.subsampling_y.get());
341 out.interp_filter.set(fctx.interp_filter.get());
342 out.grain_bit_depth.set(fctx.grain_bit_depth.get());
343 out.superres.set(fctx.superres.get());
344 out.seg_mi_dims.set(fctx.seg_mi_dims.get());
345 out.seg.replace(fctx.seg.borrow().clone());
346 out.seg_ids.replace(fctx.seg_ids.borrow().clone());
347 // lane-b128m: the superblock size travels with the copy. A tile SEARCH
348 // worker (`encode::search_tiles`) gets its context from here, so dropping
349 // it made every worker search at 64 while the calling thread searched at
350 // 128 -- the bytes a frame came out as then depended on the tile thread
351 // count under `EC_AV1_SB128`.
352 out.sb128_flag.set(fctx.sb128_flag.get());
353 out.reach_sb_px.set(fctx.reach_sb_px.get());
354 out
355}
356
357use crate::cdf;
358use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
359use crate::encode::{Picture, Reach};
360use crate::intra::predict;
361use crate::mc;
362use crate::msac::SymbolDecoder;
363use crate::mvstack::{
364 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
365 MiGrid, MiInfo, NO_REF1, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
366 find_mv_stack_with_sign_bias, mv16, mv32, reference_mode_ctx, single_ref_p1_ctx,
367 single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
368 uni_comp_ref_p1_ctx,
369};
370use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
371use crate::transform::{TxType, dequant_and_inverse_typed_wh};
372
373const PARTITION_NONE: usize = 0;
374const PARTITION_HORZ: usize = 1;
375const PARTITION_VERT: usize = 2;
376const PARTITION_SPLIT: usize = 3;
377const PARTITION_HORZ_A: usize = 4;
378const PARTITION_HORZ_B: usize = 5;
379const PARTITION_VERT_A: usize = 6;
380const PARTITION_VERT_B: usize = 7;
381const PARTITION_HORZ_4: usize = 8;
382const PARTITION_VERT_4: usize = 9;
383const SB_MI: u32 = 16;
384const BLOCK_MI: u32 = 8;
385
386// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
387// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
388// superblock's own top-left mi?", the loop-restoration read's unit span, the
389// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
390// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
391// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
392// inside a 128 superblock).
393thread_local! {
394 /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the
395 /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream
396 /// prints gigabytes otherwise). Unset = every frame, as before.
397 static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
398 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
399}
400
401/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
402/// that frame's DECODE-order index.
403pub fn set_coeff_trace_frame(idx: usize) {
404 COEFF_TRACE_FRAME.with(|c| {
405 if c.get().is_none() {
406 let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
407 Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
408 // unset: keep tracing every frame, as before this rung existed
409 Err(_) => usize::MAX - 1,
410 };
411 c.set(Some(want));
412 }
413 });
414 COEFF_TRACE_CUR.with(|c| c.set(idx));
415 if crate::envflags::env_flag!("EC_TRACE_COEFF") {
416 eprintln!("EC_COEFF_FRAME decode_idx={idx}");
417 }
418}
419
420pub(crate) fn coeff_trace_on() -> bool {
421 if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
422 return false;
423 }
424 match COEFF_TRACE_FRAME.with(|c| c.get()) {
425 // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
426 // env var unset: trace every frame.
427 None => true,
428 Some(w) if w >= usize::MAX - 1 => true,
429 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
430 }
431}
432
433/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
434pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
435 fctx.sb128_flag.with(|c| c.set(v));
436 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
437}
438
439/// lane-av1mixloss: sets [`FrameCtx::lossless_per_seg`] (called once per frame
440/// from `stream.rs`).
441pub(crate) fn set_lossless_per_seg(table: [bool; MAX_SEGMENTS], fctx: &crate::decode::FrameCtx) {
442 fctx.lossless_per_seg.with(|c| c.set(table));
443}
444
445/// The BLOCK's own lossless bit: libaom's `xd->lossless[mbmi->segment_id]`.
446/// The table is computed once per frame (libaom `decodeframe.c:5205`:
447/// `qindex == 0` with every plane delta 0, `av1_get_qindex` applying the
448/// segment's `SEG_LVL_ALT_Q`), but the frame never carries ONE lossless rule
449/// -- `read_tx_size`, `read_tx_type` and `is_cfl_allowed` all index it by the
450/// BLOCK's own segment id, which the spec-order `segment_id` read sets before
451/// any mode/transform symbol of the block. A frame whose segments disagree
452/// codes TX_4X4/WHT blocks and normal blocks side by side.
453pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool {
454 let seg_id = usize::from(fctx.cur_segment_id.with(|c| c.get()));
455 fctx.lossless_per_seg.with(|c| c.get())[seg_id]
456}
457
458/// Sets [`FrameCtx::disable_cdf_update`] (called once per frame from
459/// `stream.rs`).
460pub(crate) fn set_disable_cdf_update(v: bool, fctx: &crate::decode::FrameCtx) {
461 fctx.disable_cdf_update.with(|c| c.set(v));
462}
463
464/// This frame's `disable_cdf_update`, for the tile readers --
465/// [`msac::SymbolDecoder::set_cdf_update`](crate::msac::SymbolDecoder::set_cdf_update).
466pub(crate) fn cdf_update_disabled(fctx: &crate::decode::FrameCtx) -> bool {
467 fctx.disable_cdf_update.with(|c| c.get())
468}
469
470/// The transform side a block of `side` pixels codes: its own (capped at the
471/// caller's own largest) normally, 4 on a lossless BLOCK, where libaom's
472/// `read_tx_size` returns TX_4X4 before it looks at anything else
473/// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return
474/// TX_4X4;`).
475pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize {
476 if lossless(fctx) { 4 } else { px }
477}
478
479/// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to
480/// 32x32 -- but on a LOSSLESS BLOCK only when the block's CHROMA plane block
481/// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller.
482/// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom
483/// picks the 13-symbol one (class `wrong-alphabet-same-value`).
484pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool {
485 if lossless(fctx) {
486 // `is_cfl_allowed`: at lossless CfL is available only when the
487 // partition size equals the transform size -- the CHROMA plane block
488 // must be a single TX_4X4. True for an 8x8 partition at 4:2:0 (its
489 // plane block is 4x4) and for 4x4 partitions; FALSE for an 8x8
490 // partition at 4:4:4, whose plane block is 8x8 -- that partition
491 // reads the 13-symbol uv_mode CDF, and reading the CFL alphabet
492 // there desynced the tile from the leaf's own uv_mode symbol (class
493 // `wrong-alphabet-same-value`).
494 (bw >> ss_x(fctx)).max(4) == 4 && (bh >> ss_y(fctx)).max(4) == 4
495 } else {
496 bw <= 32 && bh <= 32
497 }
498}
499
500fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
501 fctx.sb128_flag.with(|c| c.get())
502}
503
504/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
505pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
506 if sb128(fctx) { SB_MI * 2 } else { SB_MI }
507}
508
509// How many real 128-level partition symbols this decoder has read, and how
510// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
511// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
512thread_local! {
513 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
514 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
515 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
516}
517
518/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
519/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
520/// 5.11.4), which this decoder used to read and throw away.
521#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
522pub(crate) fn part128_gathered_symbols() -> usize {
523 PART128_GATHERED_SYMBOLS.with(|c| c.get())
524}
525
526/// Current value of [`PART128_SYMBOLS`].
527#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
528pub(crate) fn part128_symbols() -> usize {
529 PART128_SYMBOLS.with(|c| c.get())
530}
531
532/// Current value of [`PART128_SPLIT_HITS`].
533#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
534pub(crate) fn part128_split_hits() -> usize {
535 PART128_SPLIT_HITS.with(|c| c.get())
536}
537
538/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
539/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
540/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
541/// the 64/32 levels sum 6.
542pub(crate) fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
543 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
544 [32768 - split, 32768, 0]
545}
546
547/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
548pub(crate) const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
549pub(crate) const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
550
551// How many `use_filter_intra` symbols this decoder has read as `1`, across
552// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
553// tests read (before/after, not the absolute value) to prove a stream
554// actually exercised the filter-intra predictor rather than silently
555// skipping it.
556thread_local! {
557 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
558 const { std::cell::Cell::new(0) };
559}
560
561/// Current value of [`FILTER_INTRA_HITS`].
562#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
563pub(crate) fn filter_intra_hits() -> usize {
564 FILTER_INTRA_HITS.with(|c| c.get())
565}
566
567// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
568// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
569// `read_filter_intra_mode_info` call), which no gate exercised before this
570// round -- every inter gate recipe passed `--enable-filter-intra=0`.
571thread_local! {
572 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
573 const { std::cell::Cell::new(0) };
574}
575
576/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
577#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
578pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
579 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
580}
581
582// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a
583// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both
584// arms refused a nonzero luma delta before this round, and no inter gate
585// enabled `--enable-angle-delta` (aomenc's own default is 1).
586thread_local! {
587 static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> =
588 const { std::cell::Cell::new(0) };
589 static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> =
590 const { std::cell::Cell::new(0) };
591}
592
593/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`].
594#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
595pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize {
596 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get())
597}
598
599/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`].
600#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
601pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize {
602 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get())
603}
604
605// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside
606// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm
607// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and
608// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block.
609thread_local! {
610 static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
611 static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
612 static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
613}
614
615thread_local! {
616 static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
617}
618
619/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame
620/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm.
621#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
622pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize {
623 INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get())
624}
625
626/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
627/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
628#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
629pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
630 (
631 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
632 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
633 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
634 )
635}
636
637// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
638// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
639// frame-level flag through the recursive block decode -- `0` (the default)
640// makes every call a true no-op, matching every existing gate stream's
641// `cdef_bits == 0` behaviour exactly.
642// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
643// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
644// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
645// blocks every non-8-bit stream from reaching a decode call, so this is `8`
646// on every path that runs today -- threading it now (rather than the literal
647// `8`) is stage 1 of widening past that refusal without re-deriving every
648// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
649// depth (this decoder's own internal choice, matches dav1d/libaom).
650/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
651/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
652pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
653 (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
654}
655/// The current stream's bit depth, for callers (e.g. dequant) that need the
656/// raw value rather than the derived clamp bound.
657pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
658 fctx.bit_depth.with(std::cell::Cell::get)
659}
660/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
661/// [`crate::stream`]'s decode loop.
662pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
663 fctx.bit_depth.with(|c| c.set(bit_depth));
664}
665
666/// This stream's `mono_chrome` (see [`FrameCtx::mono_chrome`]): a
667/// monochrome frame has `NumPlanes == 1`, so no block codes any chroma
668/// symbol or chroma coefficient and the output picture is luma only.
669pub(crate) fn mono(fctx: &crate::decode::FrameCtx) -> bool {
670 fctx.mono_chrome.with(std::cell::Cell::get)
671}
672
673/// Sets [`mono`] for the current thread, called once per frame from
674/// [`crate::stream`]'s decode loop like [`set_bit_depth`].
675pub(crate) fn set_mono(mono_chrome: bool, fctx: &crate::decode::FrameCtx) {
676 fctx.mono_chrome.with(|c| c.set(mono_chrome));
677}
678
679/// Sequence subsampling. Set once per frame from stream.rs, like set_mono.
680pub(crate) fn set_subsampling(ss_x: u8, ss_y: u8, fctx: &crate::decode::FrameCtx) {
681 fctx.subsampling_x.set(ss_x);
682 fctx.subsampling_y.set(ss_y);
683}
684
685#[inline]
686pub(crate) fn ss_x(fctx: &crate::decode::FrameCtx) -> usize {
687 fctx.subsampling_x.get() as usize
688}
689
690#[inline]
691pub(crate) fn ss_y(fctx: &crate::decode::FrameCtx) -> usize {
692 fctx.subsampling_y.get() as usize
693}
694
695/// libaom ROUND_POWER_OF_TWO. At ss=1 equals div_ceil(dim, 2); at ss=0 is dim.
696#[inline]
697pub(crate) fn round_ss(dim: usize, ss: usize) -> usize {
698 (dim + ((1usize << ss) >> 1)) >> ss
699}
700
701/// This frame's superres state: `(upscaled_width, superres_denom)`, or
702/// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
703/// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
704/// `read_lr`'s unit corners and the pixel filters themselves -- works in
705/// UPSCALED coordinates while deblock and CDEF work in downscaled ones
706/// (libaom `av1_superres_upscale` in `decodeframe.c`, and
707/// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x`
708/// superres arms). Set once per frame from [`crate::stream`]'s decode
709/// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
710/// so a later frame never inherits it.
711
712/// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
713/// `denom` 8) for a frame that is not superres-scaled.
714pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
715 fctx.superres.with(|c| c.set((upscaled_width, denom)));
716}
717
718/// `(upscaled_width, superres_denom)` when this frame is superres-scaled
719/// (libaom `av1_superres_scaled`), else `None`.
720pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
721 let (w, d) = fctx.superres.with(std::cell::Cell::get);
722 (w > 0 && d != 8).then_some((w, d))
723}
724// Whether this superblock's single CDEF unit (this decoder has no 128x128
725// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
726// read -- reset to `false` at the top of each superblock in the two tile
727// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
728// Number of superblock columns in the current tile's grid, so
729// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
730// [`CDEF_IDX_GRID`].
731// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
732// which of the header's `1 << cdef.bits` strength pairs applies to that
733// superblock's samples.
734// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
735// has read, across every call on the current thread -- the gate's proof that a
736// `cdef_bits > 0` stream actually reached the new reader rather than every
737// superblock coincidentally being all-skip.
738thread_local! {
739 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
740}
741
742// How many times a warp was suppressed for one PLANE because that plane's own
743// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out,
744// reconinter.c) -- the gate's proof that a stream really carries the shape,
745// since the square `side`/`chroma_side` can be 8 or more while the plane's
746// true block is 4 wide (an 8x16 luma block's 4x8 chroma).
747thread_local! {
748 static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
749}
750
751/// Current value of [`WARP_PLANE_SUPPRESS_HITS`].
752#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
753pub(crate) fn warp_plane_suppress_hits() -> usize {
754 WARP_PLANE_SUPPRESS_HITS.with(|c| c.get())
755}
756
757/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
758/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
759/// block dimensions decide it -- never the square `side`/`chroma_side`, which
760/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
761/// bigger than the real block in one axis.
762pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool {
763 if w >= 8 && h >= 8 {
764 return true;
765 }
766 hit!(WARP_PLANE_SUPPRESS_HITS);
767 false
768}
769
770/// Current value of [`CDEF_IDX_HITS`].
771#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
772pub(crate) fn cdef_idx_hits() -> usize {
773 CDEF_IDX_HITS.with(|c| c.get())
774}
775
776// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no
777// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the
778// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient
779// contexts alone, and the intra-edge filter neighbour pair taken mi-exact
780// instead of from the coarse 16x16 cell.
781thread_local! {
782 static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
783 static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
784 static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
785}
786
787/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`].
788#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
789pub(crate) fn intra_in_inter_txctx_hits() -> usize {
790 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get())
791}
792
793/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`].
794#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
795pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize {
796 NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get())
797}
798
799/// Current value of [`EDGE_FILTER_MI_FIX_HITS`].
800#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
801pub(crate) fn edge_filter_mi_fix_hits() -> usize {
802 EDGE_FILTER_MI_FIX_HITS.with(|c| c.get())
803}
804
805// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
806// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
807// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
808// true no-op, matching every existing gate stream's `delta_q_present == 0`
809// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
810// The running quantizer index (spec `CurrentQIndex`, libaom
811// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
812// top of every tile (spec `decode_tile`), carried across superblocks within
813// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
814// dequantization call sites instead of the frame-constant `base_q_idx`.
815// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
816// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
817// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
818// back at every dequantization call site keyed on which plane it is doing.
819// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
820// read, across every call on the current thread -- the gate's proof that a
821// `delta_q_present` stream actually reached the new reader.
822thread_local! {
823 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
824}
825
826/// Current value of [`DELTA_Q_HITS`].
827#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
828pub(crate) fn delta_q_hits() -> usize {
829 DELTA_Q_HITS.with(|c| c.get())
830}
831
832/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
833/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
834/// one), so it is always `0` here.
835fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
836 let d = fctx.quant_deltas.with(|c| c.get());
837 match plane_idx {
838 0 => (d.y_dc, 0),
839 1 => (d.u_dc, d.u_ac),
840 _ => (d.v_dc, d.v_ac),
841 }
842}
843
844/// lane-av1-qmatrix: records this FRAME's quantisation-matrix levels
845/// ([`crate::decode::FrameCtx::qm_levels`]) from the parsed
846/// `quantization_params`. Called from `stream.rs` at the frame header, where
847/// the refusal this lane lifted used to sit.
848pub(crate) fn set_qm_levels(levels: [u8; 3], fctx: &crate::decode::FrameCtx) {
849 fctx.qm_levels.with(|c| c.set(levels));
850}
851
852/// This block's inverse quantisation matrix -- libaom `av1_get_iqmatrix`
853/// (`av1/common/quant_common.c:243`) plus `setup_segmentation_dequant`'s
854/// `av1_use_qmatrix` gate, evaluated per dequantisation call site the same
855/// way the site already evaluates its quantizer index. `None` dequantises
856/// flat (the only behaviour before lane-av1-qmatrix):
857/// - a level of 15, which is both libaom's flat sentinel and what every
858/// `using_qmatrix == 0` frame's levels are parked at;
859/// - a 1D/identity transform (`is_2d_transform` false: libaom's
860/// `av1_get_iqmatrix` reads the NULL slot for those);
861/// - a LOSSLESS block (libaom `av1_use_qmatrix`'s `!xd->lossless[seg]`: the
862/// segment-adjusted quantizer index clamped to 0 with all five plane
863/// deltas zero -- the same `block_q_idx` every other dequant site reads).
864fn block_iqmatrix(
865 fctx: &crate::decode::FrameCtx,
866 plane_idx: usize,
867 w: usize,
868 h: usize,
869 tx_type: TxType,
870) -> Option<crate::qm::Iqm> {
871 let levels = fctx.qm_levels.with(|c| c.get());
872 let level = levels[plane_idx.min(2)];
873 if usize::from(level) >= crate::qm::NUM_QM_LEVELS - 1 {
874 return None;
875 }
876 if !tx_type.is_2d_transform() {
877 return None;
878 }
879 let d = fctx.quant_deltas.with(|c| c.get());
880 if block_q_idx(fctx) == 0
881 && d.y_dc == 0
882 && d.u_dc == 0
883 && d.u_ac == 0
884 && d.v_dc == 0
885 && d.v_ac == 0
886 {
887 return None;
888 }
889 crate::qm::iwt_matrix(usize::from(level), plane_idx != 0, w, h)
890}
891
892/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
893/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
894/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
895/// A no-op when `delta_q_present` is unset, or when this block is not at the
896/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
897/// libaom, collapsed here to a position check since a partition tree's
898/// top-left leaf is the only block that can ever land there), or when that
899/// leaf both *is* the whole superblock and is `skip` (the one case libaom
900/// itself skips the read, state carrying over unchanged).
901fn maybe_read_delta_q(
902 dec: &mut SymbolDecoder,
903 cdfs: &mut Cdfs,
904 mi_r: usize,
905 mi_c: usize,
906 is_whole_sb: bool,
907 skip: bool,
908 fctx: &crate::decode::FrameCtx,
909) {
910 if !fctx.delta_q_present.with(|c| c.get()) {
911 return;
912 }
913 let sb_mi = sb_mi_cur(fctx) as usize;
914 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
915 return;
916 }
917 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
918 // computed against the sequence's own superblock size (lane-sb128b r1:
919 // it used to be hardcoded against 64 and disabled under `sb128`, which a
920 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
921 // wrong).
922 if is_whole_sb && skip {
923 return;
924 }
925 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
926 const DELTA_Q_SMALL: i32 = 3;
927 if abs >= DELTA_Q_SMALL {
928 let rem_bits = dec.literal(3) + 1;
929 let thr = (1i32 << rem_bits) + 1;
930 abs = dec.literal(rem_bits) as i32 + thr;
931 }
932 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
933 let reduced = if sign_negative { -abs } else { abs };
934 hit!(DELTA_Q_HITS);
935 let res = fctx.delta_q_res.with(|c| c.get());
936 fctx.current_q_idx
937 .with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
938}
939
940// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
941// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
942// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
943// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
944// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
945// updates index 0 and every reader treats that as the value for all 4
946// indices (spec `read_delta_lf_params`'s own single-cdf branch).
947// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
948// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
949thread_local! {
950 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
951}
952
953/// Current value of [`DELTA_LF_HITS`].
954#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
955pub(crate) fn delta_lf_hits() -> usize {
956 DELTA_LF_HITS.with(|c| c.get())
957}
958
959/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
960/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
961/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
962/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
963/// read once into index 0 otherwise.
964fn maybe_read_delta_lf(
965 dec: &mut SymbolDecoder,
966 cdfs: &mut Cdfs,
967 mi_r: usize,
968 mi_c: usize,
969 is_whole_sb: bool,
970 skip: bool,
971 fctx: &crate::decode::FrameCtx,
972) {
973 if !fctx.delta_lf_present.with(|c| c.get()) {
974 return;
975 }
976 let sb_mi = sb_mi_cur(fctx) as usize;
977 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
978 return;
979 }
980 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
981 // computed against the sequence's own superblock size (lane-sb128b r1:
982 // it used to be hardcoded against 64 and disabled under `sb128`, which a
983 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
984 // wrong).
985 if is_whole_sb && skip {
986 return;
987 }
988 let multi = fctx.delta_lf_multi.with(|c| c.get());
989 let res = fctx.delta_lf_res.with(|c| c.get());
990 let count = if multi { 4 } else { 1 };
991 let mut cur = fctx.current_delta_lf.with(|c| c.get());
992 for i in 0..count {
993 let mut abs = if multi {
994 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
995 } else {
996 dec.symbol(&mut cdfs.delta_lf) as i32
997 };
998 const DELTA_LF_SMALL: i32 = 3;
999 if abs >= DELTA_LF_SMALL {
1000 let rem_bits = dec.literal(3) + 1;
1001 let thr = (1i32 << rem_bits) + 1;
1002 abs = dec.literal(rem_bits) as i32 + thr;
1003 }
1004 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
1005 let reduced = if sign_negative { -abs } else { abs };
1006 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
1007 hit!(DELTA_LF_HITS);
1008 }
1009 fctx.current_delta_lf.with(|c| c.set(cur));
1010}
1011
1012/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
1013/// after `skip` is known at every block-decode call site. A no-op at
1014/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
1015/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
1016/// `allow_intrabc`, so neither needs a separate check here. Reads once per
1017/// superblock, at the first non-skip block.
1018fn maybe_read_cdef_idx(
1019 dec: &mut SymbolDecoder,
1020 mi_r: usize,
1021 mi_c: usize,
1022 // The reading BLOCK's own span in 4x4 mode-info units: a block wider or
1023 // taller than one 64x64 CDEF unit is the first non-skip block of EVERY
1024 // unit it covers, so its one literal drives all of them (lane-b128r).
1025 (w_mi, h_mi): (usize, usize),
1026 skip: bool,
1027 fctx: &crate::decode::FrameCtx,
1028) {
1029 let bits = fctx.cdef_bits.with(|c| c.get());
1030 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
1031 return;
1032 }
1033 let idx = dec.literal(u32::from(bits)) as u8;
1034 fctx.cdef_transmitted.with(|c| c.set(true));
1035 hit!(CDEF_IDX_HITS);
1036 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
1037 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
1038 if sb_cols > 0 {
1039 // lane-b128r: libaom's four CDEF units of a 128 superblock all read
1040 // their strength off the MB_MODE_INFO of the first non-skip block in
1041 // their own unit -- and a block that COVERS several units (the 128
1042 // root's own 128x128 block, the only one there is) is that block for
1043 // every unit it covers, so one literal drives all four. This grid is
1044 // per 64x64 unit, so the read stamps every unit the block covers; one
1045 // that is smaller than a unit stamps exactly the cell it always did.
1046 let (rows, cols) = (
1047 (h_mi / SB_MI as usize).max(1),
1048 (w_mi / SB_MI as usize).max(1),
1049 );
1050 fctx.cdef_idx_grid.with(|g| {
1051 let mut g = g.borrow_mut();
1052 for dr in 0..rows {
1053 for dc in 0..cols {
1054 let i = (sb_r + dr) * sb_cols + sb_c + dc;
1055 if sb_c + dc < sb_cols && i < g.len() {
1056 g[i] = idx;
1057 }
1058 }
1059 }
1060 });
1061 }
1062}
1063
1064// ---------------------------------------------------------------------------
1065// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
1066// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
1067// the two consumers a real stream exercises: the per-segment quantizer index
1068// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
1069// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
1070// `read_intra_segment_id`/`read_inter_segment_id` and
1071// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
1072// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
1073// is what the oracle every gate here compares against actually does.
1074thread_local! {
1075 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
1076 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
1077 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
1078 /// this frame has no primary reference (spec `load_previous_segment_ids`).
1079 /// `(mi_rows, mi_cols)` for both maps above.
1080 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
1081 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
1082 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
1083 /// The block currently being decoded -- read back by [`block_q_idx`].
1084 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
1085 /// How many real `segment_id` symbols were read, and the set of segment
1086 /// ids any block ended up with -- the gate's proof the feature fired.
1087 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1088 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
1089 /// lane-golomb2: the (lowest, highest) quantizer index any block has been
1090 /// dequantized with, i.e. `block_q_idx`'s own span. A gate that means to
1091 /// exercise `SEG_LVL_ALT_Q` needs a stream where this span is WIDER than
1092 /// zero (class `gate-blind-to-feature`): segmentation being enabled says
1093 /// nothing about the segments carrying distinct quantizers.
1094 static BLOCK_Q_SPAN: std::cell::Cell<(i32, i32)> = const { std::cell::Cell::new((i32::MAX, i32::MIN)) };
1095 /// How many `seg_id_predicted` symbols were read (temporal update).
1096 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1097}
1098
1099/// Installs this frame's segmentation parameters and allocates its map, with
1100/// `prev` the primary reference frame's saved map (spec
1101/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
1102/// slot). Called once per frame, whether or not segmentation is enabled.
1103pub(crate) fn set_segmentation(
1104 seg: SegmentationParams,
1105 mi_rows: usize,
1106 mi_cols: usize,
1107 prev: Option<&[u8]>,
1108 fctx: &crate::decode::FrameCtx,
1109) {
1110 if crate::envflags::env_flag!("EC_HDR") {
1111 eprintln!(
1112 "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}",
1113 seg.enabled,
1114 seg.update_map,
1115 seg.temporal_update,
1116 seg.seg_id_pre_skip,
1117 seg.last_active_seg_id,
1118 seg.feature_data
1119 );
1120 }
1121 fctx.seg.with(|s| *s.borrow_mut() = seg);
1122 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
1123 fctx.seg_ids
1124 .with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
1125 fctx.prev_seg_ids.with(|m| {
1126 let mut m = m.borrow_mut();
1127 m.clear();
1128 if let Some(p) = prev {
1129 if p.len() == mi_rows * mi_cols {
1130 m.extend_from_slice(p);
1131 }
1132 }
1133 });
1134 fctx.above_seg_pred
1135 .with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
1136 fctx.left_seg_pred
1137 .with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
1138 fctx.cur_segment_id.with(|c| c.set(0));
1139}
1140
1141/// This frame's decoded segment map, to be stored into whichever reference
1142/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
1143pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
1144 fctx.seg_ids.with(|m| m.borrow().clone())
1145}
1146
1147/// How many `segment_id` symbols have been read (never reset per frame).
1148#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1149pub(crate) fn segment_id_hits() -> usize {
1150 SEG_ID_HITS.with(|c| c.get())
1151}
1152
1153/// How many distinct segment ids any decoded block has carried.
1154#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1155pub(crate) fn segment_ids_seen() -> usize {
1156 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
1157}
1158
1159/// The lowest and highest quantizer index any decoded block was dequantized
1160/// with (`(i32::MAX, i32::MIN)` when nothing decoded).
1161#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1162pub(crate) fn block_q_span() -> (i32, i32) {
1163 BLOCK_Q_SPAN.with(|c| c.get())
1164}
1165
1166/// How many `seg_id_predicted` symbols have been read (temporal update).
1167#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1168pub(crate) fn segment_pred_hits() -> usize {
1169 SEG_PRED_HITS.with(|c| c.get())
1170}
1171
1172/// Resets the segmentation hit counters (gate setup).
1173#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1174pub(crate) fn reset_segment_hits() {
1175 SEG_ID_HITS.with(|c| c.set(0));
1176 SEG_IDS_SEEN.with(|c| c.set(0));
1177 SEG_PRED_HITS.with(|c| c.set(0));
1178 BLOCK_Q_SPAN.with(|c| c.set((i32::MAX, i32::MIN)));
1179}
1180
1181/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
1182/// being decoded, with its `FeatureData` value.
1183fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
1184 fctx.seg.with(|s| {
1185 let s = s.borrow();
1186 s.feature_active(segment_id, feature)
1187 .then(|| i32::from(s.feature_data[segment_id][feature]))
1188 })
1189}
1190
1191/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
1192/// `av1_get_qindex`) for the block currently being decoded: the running
1193/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
1194/// Every dequant call site reads the block's quantizer through here.
1195fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
1196 let base = fctx.current_q_idx.with(|c| c.get());
1197 let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
1198 let q = match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
1199 Some(data) => (base + data).clamp(0, 255),
1200 None => base,
1201 };
1202 // lane-d792: which SEGMENT a block's quantizer came out of, beside the
1203 // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels
1204 // already proven equal is a segment-id defect, not a quantizer one.
1205 if crate::envflags::env_flag!("EC_DQCOEFF") {
1206 eprintln!("OUR_Q base={base} seg={seg_id} q={q}");
1207 }
1208 hit_do!(BLOCK_Q_SPAN.with(|c| {
1209 let (lo, hi) = c.get();
1210 c.set((lo.min(q), hi.max(q)));
1211 }););
1212 q
1213}
1214
1215/// The segment id recorded for one mi cell of the current frame's map.
1216fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
1217 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1218 if mi_r >= mi_rows || mi_c >= mi_cols {
1219 return 0;
1220 }
1221 fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
1222}
1223
1224/// `set_segment_id`: stamps `id` over every mi cell this block covers.
1225fn write_segment_id(
1226 mi_r: usize,
1227 mi_c: usize,
1228 w_mi: usize,
1229 h_mi: usize,
1230 id: u8,
1231 fctx: &crate::decode::FrameCtx,
1232) {
1233 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1234 let (x_mis, y_mis) = (
1235 w_mi.min(mi_cols.saturating_sub(mi_c)),
1236 h_mi.min(mi_rows.saturating_sub(mi_r)),
1237 );
1238 fctx.seg_ids.with(|m| {
1239 let mut m = m.borrow_mut();
1240 for y in 0..y_mis {
1241 for x in 0..x_mis {
1242 m[(mi_r + y) * mi_cols + mi_c + x] = id;
1243 }
1244 }
1245 });
1246 fctx.cur_segment_id.with(|c| c.set(id));
1247 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1248}
1249
1250/// `copy_segment_id` (libaom `decodemv.c:342`): the previous frame's map is
1251/// inherited VERBATIM over this block's own mi footprint -- per-cell copies,
1252/// not the minified id [`predicted_segment_id`] hands the block. Without a
1253/// previous map the footprint is zeroed, exactly as the C NULL branch does.
1254fn copy_segment_ids(
1255 mi_r: usize,
1256 mi_c: usize,
1257 w_mi: usize,
1258 h_mi: usize,
1259 fctx: &crate::decode::FrameCtx,
1260) {
1261 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1262 let (x_mis, y_mis) = (
1263 w_mi.min(mi_cols.saturating_sub(mi_c)),
1264 h_mi.min(mi_rows.saturating_sub(mi_r)),
1265 );
1266 fctx.seg_ids.with(|m| {
1267 let mut m = m.borrow_mut();
1268 fctx.prev_seg_ids.with(|p| {
1269 let p = p.borrow();
1270 for y in 0..y_mis {
1271 for x in 0..x_mis {
1272 let idx = (mi_r + y) * mi_cols + mi_c + x;
1273 m[idx] = p.get(idx).copied().unwrap_or(0);
1274 }
1275 }
1276 });
1277 });
1278}
1279
1280/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
1281/// `last_frame_seg_map`): the minimum previous-frame segment id over the
1282/// block's own mi footprint. `0` when there is no previous map.
1283fn predicted_segment_id(
1284 mi_r: usize,
1285 mi_c: usize,
1286 w_mi: usize,
1287 h_mi: usize,
1288 fctx: &crate::decode::FrameCtx,
1289) -> u8 {
1290 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1291 fctx.prev_seg_ids.with(|m| {
1292 let m = m.borrow();
1293 if m.is_empty() {
1294 return 0;
1295 }
1296 let (x_mis, y_mis) = (
1297 w_mi.min(mi_cols.saturating_sub(mi_c)),
1298 h_mi.min(mi_rows.saturating_sub(mi_r)),
1299 );
1300 let mut id = u8::MAX;
1301 for y in 0..y_mis {
1302 for x in 0..x_mis {
1303 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
1304 }
1305 }
1306 if id == u8::MAX { 0 } else { id }
1307 })
1308}
1309
1310/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
1311fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
1312 if reference == 0 {
1313 return diff;
1314 }
1315 if reference >= max - 1 {
1316 return max - diff - 1;
1317 }
1318 let half = if 2 * reference < max {
1319 diff <= 2 * reference
1320 } else {
1321 diff <= 2 * (max - reference - 1)
1322 };
1323 if half {
1324 return if diff & 1 != 0 {
1325 reference + ((diff + 1) >> 1)
1326 } else {
1327 reference - (diff >> 1)
1328 };
1329 }
1330 if 2 * reference < max {
1331 diff
1332 } else {
1333 max - (diff + 1)
1334 }
1335}
1336
1337/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
1338/// frame's already-decoded above/left/above-left neighbours.
1339fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
1340 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1341 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
1342 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
1343 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
1344 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
1345 let ctx = match prev_ul {
1346 None => 0,
1347 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
1348 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
1349 Some(_) => 0,
1350 };
1351 let pred = match (prev_u, prev_l) {
1352 (None, l) => l.unwrap_or(0),
1353 (Some(u), None) => u,
1354 (Some(u), Some(l)) => {
1355 if prev_ul == Some(u) {
1356 u
1357 } else {
1358 l
1359 }
1360 }
1361 };
1362 (pred, ctx)
1363}
1364
1365/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
1366/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
1367/// that prediction. Does NOT write the map -- callers do.
1368fn read_segment_id(
1369 dec: &mut SymbolDecoder,
1370 cdfs: &mut Cdfs,
1371 mi_r: usize,
1372 mi_c: usize,
1373 skip: bool,
1374 fctx: &crate::decode::FrameCtx,
1375) -> u8 {
1376 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
1377 if skip {
1378 return pred as u8;
1379 }
1380 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
1381 hit!(SEG_ID_HITS);
1382 let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
1383 let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active);
1384 // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..`
1385 // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff.
1386 if crate::envflags::env_flag!("EC_TRACE_SEG") {
1387 eprintln!(
1388 "EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}",
1389 dec.debug_state().0
1390 );
1391 }
1392 id as u8
1393}
1394
1395/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
1396/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
1397/// caller decides which by passing `pre_skip`).
1398fn intra_segment_id(
1399 dec: &mut SymbolDecoder,
1400 cdfs: &mut Cdfs,
1401 mi_r: usize,
1402 mi_c: usize,
1403 w_mi: usize,
1404 h_mi: usize,
1405 skip: bool,
1406 fctx: &crate::decode::FrameCtx,
1407) {
1408 if !fctx.seg.with(|s| s.borrow().enabled) {
1409 return;
1410 }
1411 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
1412 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1413}
1414
1415/// Whether this frame's intra blocks read their `segment_id` before `skip`
1416/// (`SegIdPreSkip`); `false` also when segmentation is off.
1417fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
1418 fctx.seg.with(|s| {
1419 let s = s.borrow();
1420 s.enabled && s.seg_id_pre_skip
1421 })
1422}
1423
1424/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
1425/// Called at both spec positions of an inter frame's block: `pre_skip = true`
1426/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
1427fn inter_segment_id(
1428 dec: &mut SymbolDecoder,
1429 cdfs: &mut Cdfs,
1430 mi_r: usize,
1431 mi_c: usize,
1432 w_mi: usize,
1433 h_mi: usize,
1434 skip: bool,
1435 pre_skip: bool,
1436 fctx: &crate::decode::FrameCtx,
1437) {
1438 let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
1439 let s = s.borrow();
1440 (
1441 s.enabled,
1442 s.update_map,
1443 s.temporal_update,
1444 s.seg_id_pre_skip,
1445 )
1446 });
1447 if !enabled {
1448 return;
1449 }
1450 if !update_map {
1451 // The map is inherited from the previous frame, and libaom's
1452 // `copy_segment_id` (decodemv.c:342) does that VERBATIM -- a memcpy of
1453 // the previous map over the block's own footprint, mixed ids intact --
1454 // while the id the BLOCK itself carries is the min over that footprint
1455 // (`get_predicted_segment_id`). Stamping the min here flattened mixed
1456 // footprints into the saved map, and every later frame whose
1457 // `update_map == 0` copy or temporal prediction read that position
1458 // dequantized with the wrong segment's `SEG_LVL_ALT_Q` (class
1459 // `simplified-inheritance`).
1460 copy_segment_ids(mi_r, mi_c, w_mi, h_mi, fctx);
1461 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
1462 fctx.cur_segment_id.with(|c| c.set(id));
1463 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1464 return;
1465 }
1466 if pre_skip && !pre_skip_frame {
1467 return;
1468 }
1469 if !pre_skip && skip {
1470 // libaom: a skipped block never codes `seg_id_predicted`, and its
1471 // segment id is the spatial prediction.
1472 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
1473 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
1474 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1475 return;
1476 }
1477 let id = if temporal_update {
1478 let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
1479 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
1480 hit!(SEG_PRED_HITS);
1481 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
1482 if predicted {
1483 predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
1484 } else {
1485 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1486 }
1487 } else {
1488 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1489 };
1490 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1491}
1492
1493/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
1494fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
1495 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
1496 // so contribute 0) outside the tile -- the availability check here is
1497 // what keeps a previous tile's stamps out of this tile's context.
1498 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1499 let above = if mi_r > row0 {
1500 fctx.above_seg_pred
1501 .with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
1502 } else {
1503 0
1504 };
1505 let left = if mi_c > col0 {
1506 fctx.left_seg_pred
1507 .with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
1508 } else {
1509 0
1510 };
1511 usize::from(above + left)
1512}
1513
1514/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
1515fn stamp_seg_pred(
1516 mi_r: usize,
1517 mi_c: usize,
1518 w_mi: usize,
1519 h_mi: usize,
1520 value: u8,
1521 fctx: &crate::decode::FrameCtx,
1522) {
1523 fctx.above_seg_pred.with(|m| {
1524 let mut m = m.borrow_mut();
1525 for i in 0..w_mi {
1526 if let Some(cell) = m.get_mut(mi_c + i) {
1527 *cell = value;
1528 }
1529 }
1530 });
1531 fctx.left_seg_pred.with(|m| {
1532 let mut m = m.borrow_mut();
1533 for i in 0..h_mi {
1534 if let Some(cell) = m.get_mut(mi_r + i) {
1535 *cell = value;
1536 }
1537 }
1538 });
1539}
1540
1541// How many key-frame luma blocks resolved `smooth_neighbor` (spec
1542// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
1543// counter, proving a stream actually put a directional block next to a
1544// smooth-predicted neighbour rather than every block reading the (previously
1545// hardcoded `false`) edge-filter strength bucket unchanged.
1546thread_local! {
1547 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
1548 const { std::cell::Cell::new(0) };
1549}
1550
1551/// Current value of [`SMOOTH_LUMA_HITS`].
1552#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1553pub(crate) fn smooth_luma_hits() -> usize {
1554 SMOOTH_LUMA_HITS.with(|c| c.get())
1555}
1556
1557thread_local! {
1558 /// lane-band46 r1: how many split-transform units answered their intra
1559 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
1560 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
1561 /// apply to them (class reach-is-per-transform-unit). Every hit is a
1562 /// transform unit whose above-right / below-left reference samples would
1563 /// be wrong without that fix.
1564 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
1565 const { std::cell::Cell::new(0) };
1566}
1567
1568/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
1569#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1570pub(crate) fn split_tu_reach_fix_hits() -> usize {
1571 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
1572}
1573
1574/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
1575/// answer differs from the standalone-block answer the call sites used before
1576/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
1577/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
1578/// block's top-left `(px, py)`.
1579#[allow(clippy::too_many_arguments)]
1580fn tu_reach(
1581 bw: usize,
1582 bh: usize,
1583 col_off: usize,
1584 row_off: usize,
1585 tx: usize,
1586 block: Reach,
1587 px: usize,
1588 py: usize,
1589 width: usize,
1590 height: usize,
1591 fctx: &crate::decode::FrameCtx,
1592) -> Reach {
1593 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
1594 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
1595 if fixed != standalone {
1596 hit!(SPLIT_TU_REACH_FIX_HITS);
1597 }
1598 fixed
1599}
1600
1601/// [`tu_reach`] for a unit whose LUMA footprint is a `tx_w` x `tx_h` rect
1602/// (lane-av1-422b: a 4:2:2 chroma unit is square in chroma pixels, but its
1603/// luma anchor is `(chroma_tx << ss_x, chroma_tx << ss_y)` -- at ss (1,0)
1604/// twice as wide as it is tall). Same predicate as [`tu_reach`]; the
1605/// square mismatch counter only means anything when the footprint actually
1606/// is square.
1607#[allow(clippy::too_many_arguments)]
1608fn tu_reach_rect(
1609 bw: usize,
1610 bh: usize,
1611 col_off: usize,
1612 row_off: usize,
1613 tx_w: usize,
1614 tx_h: usize,
1615 block: Reach,
1616 px: usize,
1617 py: usize,
1618 width: usize,
1619 height: usize,
1620 fctx: &crate::decode::FrameCtx,
1621) -> Reach {
1622 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block);
1623 if tx_w == tx_h {
1624 let standalone = Reach::of(tx_w, px + col_off, py + row_off, width, height, fctx);
1625 if fixed != standalone {
1626 hit!(SPLIT_TU_REACH_FIX_HITS);
1627 }
1628 }
1629 fixed
1630}
1631
1632// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
1633// across every call on the current thread -- lane-chroma r3's own before/after
1634// counter, proving a stream actually exercised chroma's smooth/paeth
1635// predictor (the previously-refused round-2 gap) rather than every block
1636// landing on DC/CFL/directional.
1637thread_local! {
1638 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
1639 const { std::cell::Cell::new(0) };
1640}
1641
1642/// Current value of [`SMOOTH_UV_HITS`].
1643#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1644pub(crate) fn smooth_uv_hits() -> usize {
1645 SMOOTH_UV_HITS.with(|c| c.get())
1646}
1647
1648// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
1649// full superblock walk over, across every call on the current thread --
1650// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
1651// multi-tile stream must prove more than one tile actually fired, not just
1652// that the stream carried tile_info.cols > 1.
1653thread_local! {
1654 static TILE_HITS: std::cell::Cell<usize> =
1655 const { std::cell::Cell::new(0) };
1656}
1657/// Current value of [`TILE_HITS`].
1658#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1659pub(crate) fn tile_hits() -> usize {
1660 TILE_HITS.with(|c| c.get())
1661}
1662
1663// How many 4-pixel deblocking edge groups [`edge_params`] has actually
1664// selected for filtering, across every call on the current thread -- the same
1665// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1666// exercised `apply_deblock` rather than every edge landing on level 0.
1667thread_local! {
1668 static DEBLOCK_HITS: std::cell::Cell<usize> =
1669 const { std::cell::Cell::new(0) };
1670}
1671/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1672/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1673/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1674static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1675
1676/// Current value of [`DEBLOCK_HITS`].
1677#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1678pub(crate) fn deblock_hits() -> usize {
1679 DEBLOCK_HITS.with(|c| c.get())
1680}
1681
1682// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1683// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1684// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1685// stream built with `--enable-onesided-comp=1` really exercised the
1686// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1687thread_local! {
1688 static UNI_COMP_HITS: std::cell::Cell<usize> =
1689 const { std::cell::Cell::new(0) };
1690}
1691
1692/// Current value of [`UNI_COMP_HITS`].
1693#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1694pub(crate) fn uni_comp_hits() -> usize {
1695 UNI_COMP_HITS.with(|c| c.get())
1696}
1697
1698// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1699// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1700// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1701// blend and not only the wedge arm.
1702thread_local! {
1703 static DIFFWTD_HITS: std::cell::Cell<usize> =
1704 const { std::cell::Cell::new(0) };
1705}
1706
1707/// Current value of [`DIFFWTD_HITS`].
1708#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1709pub(crate) fn diffwtd_hits() -> usize {
1710 DIFFWTD_HITS.with(|c| c.get())
1711}
1712
1713// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1714// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1715// this decoder's square inter path reaches), so no `compound_type` symbol is
1716// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1717// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1718thread_local! {
1719 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1720 const { std::cell::Cell::new(0) };
1721}
1722
1723/// Current value of [`DIFFWTD_INFERRED_HITS`].
1724#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1725pub(crate) fn diffwtd_inferred_hits() -> usize {
1726 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1727}
1728
1729// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1730// with `show_frame == 0`, output later by a `show_existing_frame` header
1731// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1732// `stream::decode_stream`, which is where the frame header is consumed; the
1733// gate's proof that the on-value really reached the bitstream rather than
1734// being dropped by the rate control.
1735thread_local! {
1736 static FWD_KF_HITS: std::cell::Cell<usize> =
1737 const { std::cell::Cell::new(0) };
1738}
1739
1740/// Current value of [`FWD_KF_HITS`].
1741#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1742pub(crate) fn fwd_kf_hits() -> usize {
1743 FWD_KF_HITS.with(|c| c.get())
1744}
1745
1746/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1747pub(crate) fn note_fwd_kf() {
1748 hit!(FWD_KF_HITS);
1749}
1750
1751// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1752// the block's own side, across every call on the current thread -- the same
1753// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1754// actually exercised a *split* transform under `TxMode::Select` rather than
1755// every block coincidentally resolving `depth=0` (indistinguishable from
1756// `TxMode::Largest` pixel-wise).
1757thread_local! {
1758 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1759 const { std::cell::Cell::new(0) };
1760}
1761
1762// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1763// transform smaller than their own side (`tx_depth != 0`) while coding a
1764// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1765// only exercises with aomenc's tx-size search left ON (its default), which
1766// every older recipe in this file pins off. Counted at the block, so a stream
1767// where RD happened to give every split-transform block a DC chroma mode
1768// reads as zero rather than silently passing for free.
1769thread_local! {
1770 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1771 const { std::cell::Cell::new(0) };
1772}
1773
1774/// Current value of [`SQ_CHROMA_TX_HITS`].
1775#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1776pub(crate) fn sq_chroma_tx_hits() -> usize {
1777 SQ_CHROMA_TX_HITS.with(|c| c.get())
1778}
1779
1780/// Current value of [`TX_DEPTH_HITS`].
1781#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1782pub(crate) fn tx_depth_hits() -> usize {
1783 TX_DEPTH_HITS.with(|c| c.get())
1784}
1785
1786// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1787// read, and how many of those actually took the split, on the current thread
1788// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1789// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1790// coincidentally coding one whole-block transform.
1791thread_local! {
1792 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1793 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1794 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1795 // strips coded one whole-block rect transform unit, and how many split
1796 // their rect max transform into square sub-transforms.
1797 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1798 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1799 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1800 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1801 // truncated low-32 corner.
1802 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1803 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1804 // inter strip, `[32x8, 8x32]`.
1805 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1806 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1807 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1808 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1809 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1810 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1811 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1812 // frame -- 16x8 and 8x16 inter leaves.
1813 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1814 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1815 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1816 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1817 // `decode_inter_block` already carries forty parameters and both are
1818 // frame-constant.
1819 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1820 // frame-constant like the two above and stashed the same way -- an intra
1821 // block inside an inter frame reads `use_filter_intra` under it.
1822}
1823
1824/// Current value of [`TXFM_SPLIT_READS`].
1825#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1826pub(crate) fn txfm_split_reads() -> usize {
1827 TXFM_SPLIT_READS.with(|c| c.get())
1828}
1829
1830/// Current value of [`TXFM_SPLIT_HITS`].
1831#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1832pub(crate) fn txfm_split_hits() -> usize {
1833 TXFM_SPLIT_HITS.with(|c| c.get())
1834}
1835
1836/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1837#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1838pub(crate) fn inter_leaf16_horz_hits() -> usize {
1839 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1840}
1841
1842/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1843#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1844pub(crate) fn inter_leaf16_vert_hits() -> usize {
1845 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1846}
1847
1848/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1849pub(crate) fn rect_inter_tu_hits() -> usize {
1850 RECT_INTER_TU_HITS.with(|c| c.get())
1851}
1852
1853/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1854pub(crate) fn rect_inter_txsplit_hits() -> usize {
1855 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1856}
1857
1858/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1859pub(crate) fn rect64_inter_tu_hits() -> usize {
1860 RECT64_INTER_TU_HITS.with(|c| c.get())
1861}
1862
1863/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1864/// whole-block luma units of a 32x32-level 1:4 inter strip.
1865pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1866 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1867}
1868
1869/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1870/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1871pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1872 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1873}
1874
1875/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1876/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1877pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1878 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1879}
1880
1881/// Records one rectangular var-tx leaf.
1882fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1883 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1884 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1885 }
1886 let cell = if tw.min(th) == 4 {
1887 &VARTX_RECT_LEAF4_HITS
1888 } else {
1889 &VARTX_RECT_LEAF_HITS
1890 };
1891 cell.with(|c| {
1892 let mut h = c.get();
1893 h[usize::from(th > tw)] += 1;
1894 c.set(h);
1895 });
1896}
1897
1898/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1899/// [`ENABLE_FILTER_INTRA_INTER`].
1900pub(crate) fn set_inter_tx_mode(
1901 tx_select: bool,
1902 reduced_tx_set: bool,
1903 enable_filter_intra: bool,
1904 fctx: &crate::decode::FrameCtx,
1905) {
1906 fctx.tx_select_inter.with(|c| c.set(tx_select));
1907 fctx.intra_only.with(|c| c.set(false));
1908 fctx.tx_select_frame.with(|c| c.set(tx_select));
1909 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1910 fctx.enable_filter_intra_inter
1911 .with(|c| c.set(enable_filter_intra));
1912}
1913
1914// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1915// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1916// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1917// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1918// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1919// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1920// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1921// path above).
1922thread_local! {
1923 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1924 const { std::cell::Cell::new(0) };
1925}
1926
1927/// Current value of [`VERT_B_INTRA_HITS`].
1928#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1929pub(crate) fn vert_b_intra_hits() -> usize {
1930 VERT_B_INTRA_HITS.with(|c| c.get())
1931}
1932
1933// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1934// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1935// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1936// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1937// every arm separately so a run where aomenc's RD only picked one cannot
1938// pass as proof of four.
1939thread_local! {
1940 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1941}
1942
1943// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1944thread_local! {
1945 /// 4x4 transform units decoded inside an 8x8 square of a
1946 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1947 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1948 /// a real `--enable-tx-size-search=1` stream reaches it.
1949 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1950}
1951
1952#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1953pub(crate) fn vert_ab_tx4_hits() -> usize {
1954 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1955}
1956
1957#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1958pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1959 AB16_HITS.with(std::cell::Cell::get)
1960}
1961
1962fn bump_ab16(arm: usize) {
1963 hit_do! {
1964 AB16_HITS.with(|c| {
1965 let mut v = c.get();
1966 v[arm] += 1;
1967 c.set(v);
1968 });
1969 }
1970}
1971
1972// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1973// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1974// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1975// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1976// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1977// superblock's z-order recursion, not raster mi position).
1978thread_local! {
1979 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1980 const { std::cell::Cell::new(0) };
1981}
1982
1983/// Current value of [`HORZ_VERT_INTRA_HITS`].
1984#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1985pub(crate) fn horz_vert_intra_hits() -> usize {
1986 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1987}
1988
1989// How many blocks were decoded as a frame-edge rect strip -- the single
1990// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1991// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1992// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1993// paths share the counter.
1994thread_local! {
1995 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1996 const { std::cell::Cell::new(0) };
1997}
1998
1999/// Current value of [`EDGE_RECT_STRIP_HITS`].
2000#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
2001pub(crate) fn edge_rect_strip_hits() -> usize {
2002 EDGE_RECT_STRIP_HITS.with(|c| c.get())
2003}
2004
2005// lane-interedge r1: frame-edge half strips on the INTER path, per partition
2006// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
2007// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
2008// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
2009// are height mod 16 == 8, so every inter frame crosses these nodes.
2010thread_local! {
2011 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
2012 const { std::cell::Cell::new([0; 6]) };
2013}
2014
2015/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
2016pub(crate) fn bump_inter_edge_strip(idx: usize) {
2017 hit_do! {
2018 INTER_EDGE_STRIP_HITS.with(|c| {
2019 let mut v = c.get();
2020 v[idx] += 1;
2021 c.set(v);
2022 });
2023 }
2024}
2025
2026// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
2027// forced split -- libaom `decode_partition` (decodeframe.c):
2028// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
2029// straddle case that reads NO symbol at all. Indexed by level:
2030// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
2031thread_local! {
2032 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
2033 const { std::cell::Cell::new([0; 4]) };
2034}
2035
2036fn bump_edge_both_cut(level: usize) {
2037 hit_do! {
2038 EDGE_BOTH_CUT_HITS.with(|c| {
2039 let mut v = c.get();
2040 v[level] += 1;
2041 c.set(v);
2042 });
2043 }
2044}
2045
2046/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
2047pub fn inter_edge_strip_hits() -> [usize; 6] {
2048 INTER_EDGE_STRIP_HITS.with(|c| c.get())
2049}
2050
2051/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
2052/// into the next one (class `counter-from-refused-stream`).
2053pub fn reset_inter_edge_strip_hits() {
2054 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
2055}
2056
2057/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
2058#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2059pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
2060 EDGE_BOTH_CUT_HITS.with(|c| c.get())
2061}
2062
2063/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
2064#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2065pub(crate) fn reset_edge_both_cut_hits() {
2066 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
2067}
2068
2069// How many HORZ/VERT intra strips resolved a SPLIT luma transform
2070// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
2071// the case every rect path here refused by name before, and the first
2072// refusal the user's ReelB extract (600s in) stops at.
2073thread_local! {
2074 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
2075 const { std::cell::Cell::new(0) };
2076}
2077
2078/// Current value of [`RECT_SPLIT_TX_HITS`].
2079#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2080pub(crate) fn rect_split_tx_hits() -> usize {
2081 RECT_SPLIT_TX_HITS.with(|c| c.get())
2082}
2083
2084// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
2085// side 64) AND split past the first depth, i.e. tiled more than one unit in
2086// each axis -- the only shape with a transform unit that has neighbours on
2087// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
2088// no gate fired before lane-rectsplit r2 (the shared counter above also
2089// counts 32x32-level and depth-1 strips, so it cannot prove this case).
2090thread_local! {
2091 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
2092 const { std::cell::Cell::new(0) };
2093}
2094
2095/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
2096#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2097pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
2098 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
2099}
2100
2101// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
2102// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
2103// chroma half takes that had no coefficient tables before (index order:
2104// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
2105// proves the pair it happens to hit cannot catch a transposed scan/context
2106// table (class scan-weights-cross-axis).
2107thread_local! {
2108 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
2109 const { std::cell::Cell::new([0; 4]) };
2110}
2111
2112/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
2113#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2114pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
2115 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
2116}
2117
2118// lane-av1-422: how many SQUARE chroma coefficient units the strip path read
2119// on a 4:2:2 frame (ss 1,0) -- the half-width, unhalved-height shape whose
2120// tables only exist because of the square rows in the chroma_tiled arm. A
2121// 4:2:0 or 4:4:4 frame can never increment it (their rect strips' chroma is
2122// itself rect), and a restored `/2 chroma height` diverts 4:2:2 squares onto
2123// the rect rows, so the witness gate reads 0 there and fails.
2124thread_local! {
2125 static CHROMA422_SQUARE_HITS: std::cell::Cell<usize> =
2126 const { std::cell::Cell::new(0) };
2127}
2128
2129/// Current value of [`CHROMA422_SQUARE_HITS`].
2130// lane-av1-422b: `pub` so `examples/decode_probe.rs` can census it the way
2131// it does every other capability counter.
2132pub fn chroma422_square_hits() -> usize {
2133 CHROMA422_SQUARE_HITS.with(|c| c.get())
2134}
2135
2136// lane-av1-422f: how many RECT chroma coefficient units the square-block
2137// path read on a 4:2:2 frame (ss 1,0) -- TX_4X8 / TX_8X16 / TX_16X32, the
2138// plane block's own half-width, unhalved-height shape. A 4:2:0 or 4:4:4
2139// frame never takes the rect branch (their units are square
2140// `chroma_tx == chroma_tx_h`), so a witness gate reading 0 here proves the
2141// model reverted to squares.
2142thread_local! {
2143 static CHROMA422_RECT_HITS: std::cell::Cell<usize> =
2144 const { std::cell::Cell::new(0) };
2145}
2146
2147/// Current value of [`CHROMA422_RECT_HITS`].
2148pub fn chroma422_rect_hits() -> usize {
2149 CHROMA422_RECT_HITS.with(|c| c.get())
2150}
2151
2152// lane-av1-422g: how many PER-LEAF TX_4X4 chroma coefficient units the
2153// sub-8x8 split4 path read on a 4:2:2 frame (ss 1,0) -- one per even-column
2154// leaf per plane (`is_chroma_reference`'s `!(mi_col & ss_x)`). A 4:2:0 frame
2155// codes no sub-8 chroma at all and 4:4:4 goes through `sub8_leaf_chroma444`,
2156// so a witness gate reading 0 here proves the per-leaf 4:2:2 arm never ran.
2157thread_local! {
2158 static CHROMA422_SUB8_HITS: std::cell::Cell<usize> =
2159 const { std::cell::Cell::new(0) };
2160}
2161
2162/// Current value of [`CHROMA422_SUB8_HITS`].
2163pub fn chroma422_sub8_hits() -> usize {
2164 CHROMA422_SUB8_HITS.with(|c| c.get())
2165}
2166
2167// lane-av1-422sub8rect: how many PER-PIECE TX_4X4 chroma coefficient units
2168// the INTER sub-8x8 split4 path read on a 4:2:2 frame (ss 1,0) -- one per
2169// non-skipped odd-column piece per plane (`is_chroma_reference`'s
2170// `mi_col & 0x01` at ss_x 1). 4:2:0 goes through the shared group unit and
2171// 4:4:4 through [`sub8_leaf_chroma444`]'s own per-piece twin, so a witness
2172// gate reading 0 here proves the inter 4:2:2 per-piece arm never ran.
2173thread_local! {
2174 static CHROMA422_INTER_SUB8_HITS: std::cell::Cell<usize> =
2175 const { std::cell::Cell::new(0) };
2176}
2177
2178/// Current value of [`CHROMA422_INTER_SUB8_HITS`].
2179pub fn chroma422_inter_sub8_hits() -> usize {
2180 CHROMA422_INTER_SUB8_HITS.with(|c| c.get())
2181}
2182
2183// lane-av1-422m: how many TX_4X4 chunk units the invalid-ss-size chroma arm
2184// read (the 8x32 luma block whose 4:2:2 plane has no `ss_size_lookup` block).
2185// A 4:2:0 or 4:4:4 frame cannot increment it, so a non-zero read proves the
2186// chunked 4:2:2 chroma really decoded.
2187thread_local! {
2188 static CHROMA422_CHUNK_HITS: std::cell::Cell<usize> =
2189 const { std::cell::Cell::new(0) };
2190}
2191
2192/// Current value of [`CHROMA422_CHUNK_HITS`].
2193pub fn chroma422_chunk_hits() -> usize {
2194 CHROMA422_CHUNK_HITS.with(|c| c.get())
2195}
2196
2197// lane-av1-422stripanchor: how many 4-wide-strip PAIR chroma units
2198// ([`decode_rect_split`]'s ported floored-pair anchor) decoded. A 4:2:0 or
2199// 4:4:4 frame cannot increment it (the arm is keyed to a 2-px-wide chroma
2200// block, which only a 1-mi-wide strip at ss (1, 0) produces), so a non-zero
2201// read proves a stream routed a 4-wide strip through the split path.
2202thread_local! {
2203 static CHROMA422_PAIR_WIDE_HITS: std::cell::Cell<usize> =
2204 const { std::cell::Cell::new(0) };
2205}
2206
2207/// Current value of [`CHROMA422_PAIR_WIDE_HITS`].
2208pub fn chroma422_pair_wide_hits() -> usize {
2209 CHROMA422_PAIR_WIDE_HITS.with(|c| c.get())
2210}
2211
2212// How many HORZ/VERT intra strips actually predicted with filter intra
2213// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
2214// ("this decoder predicts square-only") until `predict_filter_intra` took
2215// `bw`x`bh`.
2216thread_local! {
2217 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
2218 const { std::cell::Cell::new(0) };
2219}
2220
2221/// Current value of [`FILTER_INTRA_RECT_HITS`].
2222#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2223pub(crate) fn filter_intra_rect_hits() -> usize {
2224 FILTER_INTRA_RECT_HITS.with(|c| c.get())
2225}
2226
2227// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
2228// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
2229// was never read at all before that round, so a gate needs to prove the flag
2230// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
2231// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
2232// carry different probabilities (18101 vs 20229), so a transposed pair is
2233// only caught by a gate that sees the flag fire on BOTH shapes (class
2234// scan-weights-cross-axis).
2235thread_local! {
2236 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
2237 const { std::cell::Cell::new(0) };
2238 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
2239 const { std::cell::Cell::new(0) };
2240}
2241
2242/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
2243#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2244pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
2245 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
2246}
2247
2248/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
2249#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2250pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
2251 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
2252}
2253
2254// How many rectangular transform units actually coded coefficients through
2255// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
2256// exercised the rect coefficient reader at all rather than passing on
2257// all-skip blocks.
2258thread_local! {
2259 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2260 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2261}
2262
2263/// Current value of [`RECT_COEFF_TU_HITS`].
2264#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2265pub(crate) fn rect_coeff_tu_hits() -> usize {
2266 RECT_COEFF_TU_HITS.with(|c| c.get())
2267}
2268
2269/// Rectangular transform units whose resolved `tx_type` is a 1D class
2270/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
2271/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
2272/// for the square reader's own 1D types.
2273#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2274pub(crate) fn rect_class1_hits() -> usize {
2275 RECT_CLASS1_HITS.with(|c| c.get())
2276}
2277
2278// lane-av1readcensus: the PER-UNIT coefficient census -- one unit counted
2279// per `read_coeffs`/`read_coeffs_rect` call, i.e. per object this decoder
2280// actually walks, which is the unit the round-4 `av1444rect` count measured
2281// (636 square chroma reads against the oracle's 1086). The counters are
2282// 4:4:4-ONLY (`CENSUS_444`, set per frame beside `set_subsampling`), so a
2283// 4:2:0 control reads `(0, 0, 0)` -- a walk-shape change at 4:2:0 is another
2284// lane's business, and this census must not fire there.
2285thread_local! {
2286 /// Per-plane unit counts, `[luma, u, v]`, at 4:4:4 only.
2287 static CENSUS_444_UNITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
2288 /// Of [`CENSUS_444_UNITS`], the units that coded at least one coefficient
2289 /// (`txb_skip == 0`) -- the per-plane split is only comparable against
2290 /// the oracle's when both sides count all-zero units the same way.
2291 static CENSUS_444_CODED: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
2292 /// Sequential unit index, so a trace line names its own position in the
2293 /// frame's walk rather than relying on line order alone.
2294 static CENSUS_UNIT_N: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2295 /// The plane the units read from here on belong to. A thread-local rather
2296 /// than a `read_coeffs` parameter because the three luma call sites
2297 /// (`decode_rect_split`, `decode_block_rect64`, `read_inter_plane_rect`)
2298 /// are not this lane's to edit and would each grow an argument; the
2299 /// plane-owning readers stamp it once on entry instead.
2300 static CENSUS_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2301 /// 4:4:4 (`subsampling_x == 0 && subsampling_y == 0`) for the frame being
2302 /// decoded, set per frame from [`crate::stream`].
2303 static CENSUS_444: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2304}
2305
2306/// Current `[luma, u, v]` 4:4:4 coefficient-unit counts.
2307#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2308pub(crate) fn census_444_units() -> [usize; 3] {
2309 CENSUS_444_UNITS.with(|c| c.get())
2310}
2311
2312/// Current `[luma, u, v]` 4:4:4 counts of units that coded coefficients.
2313#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2314pub(crate) fn census_444_coded() -> [usize; 3] {
2315 CENSUS_444_CODED.with(|c| c.get())
2316}
2317
2318/// lane-av1readcensus: arms the 4:4:4 census for the frame about to decode,
2319/// called once per frame from [`crate::stream`]'s decode loop beside
2320/// [`set_subsampling`]. At 4:2:0 (or 4:2:2) every census counter stays zero --
2321/// the walk-shape question this census answers is a 4:4:4 one.
2322pub(crate) fn set_census_444(ss_x: u8, ss_y: u8) {
2323 CENSUS_444.with(|c| c.set(ss_x == 0 && ss_y == 0));
2324}
2325
2326/// lane-av1readcensus: the plane the units read from here on belong to,
2327/// stamped by the plane-owning readers ([`read_plane`], [`read_inter_plane`],
2328/// [`read_inter_plane_rect`]) on entry.
2329pub(crate) fn set_census_plane(plane: usize) {
2330 CENSUS_PLANE.with(|c| c.set(plane));
2331}
2332
2333/// lane-av1readcensus: is the per-unit census trace on? Shares
2334/// [`coeff_trace_on`]'s per-frame narrowing so one frame's walk can be
2335/// dumped without the rest of the stream.
2336fn census_trace_on() -> bool {
2337 if !crate::envflags::env_flag!("EC_CENSUS_UNIT") {
2338 return false;
2339 }
2340 match COEFF_TRACE_FRAME.with(|c| c.get()) {
2341 None => true,
2342 Some(w) if w >= usize::MAX - 1 => true,
2343 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
2344 }
2345}
2346
2347/// lane-av1readcensus: one line per coefficient unit this decoder walks, the
2348/// twin of the oracle's `EC_COEFF` / `EC_COEFF_VAL` bracket around each
2349/// `av1_read_coeffs_txb` call. Pair the two sides by `post_rng` (or by `n`),
2350/// never by plane label or by walk position -- the walk order is exactly what
2351/// the census is measuring.
2352fn census_unit(
2353 w: usize,
2354 h: usize,
2355 tx_type: TxType,
2356 eob: usize,
2357 all_zero: bool,
2358 entry_rng: u32,
2359 dec: &SymbolDecoder,
2360) {
2361 let plane = CENSUS_PLANE.with(|c| c.get()).min(2);
2362 let coded = usize::from(!all_zero);
2363 CENSUS_UNIT_N.with(|c| c.set(c.get() + 1));
2364 hit_do! {
2365 CENSUS_444_UNITS.with(|c| {
2366 if CENSUS_444.with(|on| on.get()) {
2367 let mut v = c.get();
2368 v[plane] += 1;
2369 c.set(v);
2370 }
2371 });
2372 CENSUS_444_CODED.with(|c| {
2373 if CENSUS_444.with(|on| on.get()) {
2374 let mut v = c.get();
2375 v[plane] += coded;
2376 c.set(v);
2377 }
2378 });
2379 }
2380 if !census_trace_on() {
2381 return;
2382 }
2383 let n = CENSUS_UNIT_N.with(|c| c.get()) - 1;
2384 let post_rng = dec.debug_state().0;
2385 eprintln!(
2386 "EC_CENSUS_UNIT side=ours n={n} plane={plane} w={w} h={h} tx={tx_type:?} eob={eob} \
2387 all_zero={all_zero} entry_rng={entry_rng} post_rng={post_rng}"
2388 );
2389}
2390
2391/// lane-av1ibcfork: this decoder's half of the per-unit BIT INTERVAL -- the
2392/// exact mirror of the oracle's `EC_ECDUMP_IN` / `EC_ECDUMP_OUT` /
2393/// `EC_ECDUMP_END` triple (`aom-oracle2/src/av1/decoder/decodetxb.c`: one
2394/// print in `read_coeffs_txb` before and after its `aom_read_symbol`, one in
2395/// the single caller `av1_read_coeffs_txb` after the whole unit).
2396///
2397/// Why three prints and not one `EC_CENSUS_UNIT`: a COUNT is not a key. The
2398/// two sides can walk a different NUMBER of units and still be paired, because
2399/// the interval is what a unit CONSUMED. Entry position alone drifts the moment
2400/// one side consumes a different number of bits, and list index is invalid the
2401/// moment one side misses a unit -- both were measured here and both
2402/// mis-attribute. `post_bit` after the `txb_skip` read is the same
2403/// `aom_reader_tell` the oracle prints there; `end_bit` is the end of the whole
2404/// unit including the optional luma `tx_type`, the eob, the base/BR passes and
2405/// the sign/Golomb loop, so a unit that reads the right symbols in the wrong
2406/// ORDER is caught too.
2407///
2408/// `bit` counts the bits this decoder has pulled out of its window, so it sits
2409/// at a CONSTANT offset from the oracle's tell (the OBU header libaom counts
2410/// before `aom_reader_init`). The offset is measured per fixture, never
2411/// assumed: +14 on `444_intrabc_rect4_witness.obu`.
2412#[inline]
2413fn unit_iv_on() -> bool {
2414 crate::envflags::env_flag!("EC_UNITIV")
2415}
2416
2417/// The unit's ENTRY position. Returns it so the caller can pass the same value
2418/// to [`unit_iv_skip`] and [`unit_iv_end`] without reading the decoder again.
2419#[inline]
2420#[track_caller]
2421fn unit_iv_in(plane: usize, w: usize, h: usize, ctx: usize, dec: &SymbolDecoder) -> usize {
2422 if !unit_iv_on() {
2423 return 0;
2424 }
2425 let bit = dec.debug_bitpos();
2426 let (mi_r, mi_c) = SymbolDecoder::symr_mi();
2427 eprintln!(
2428 "EC_UNITIV_IN side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} bit={bit} at {}",
2429 std::panic::Location::caller()
2430 );
2431 bit
2432}
2433
2434/// The position immediately after this unit's `txb_skip` read. `bit_in ==
2435/// post_bit` means the read consumed ZERO bits (a CDF row already at a
2436/// boundary), so this is also the real-read filter: the reader logs a step
2437/// either way, and counting raw lines overstates the symbol count ~2x (measured
2438/// on `444_intrabc_rect4_witness.obu`: 2395 lines, 512 real reads, against the
2439/// oracle's 513 -- not the "~1069 fewer" an earlier round reported).
2440#[inline]
2441fn unit_iv_skip(
2442 dec: &SymbolDecoder,
2443 bit_in: usize,
2444 plane: usize,
2445 w: usize,
2446 h: usize,
2447 ctx: usize,
2448 all_zero: bool,
2449) {
2450 if !unit_iv_on() {
2451 return;
2452 }
2453 let (mi_r, mi_c) = SymbolDecoder::symr_mi();
2454 eprintln!(
2455 "EC_UNITIV_SKIP side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} az={} bit={bit_in} post_bit={}",
2456 all_zero as i32,
2457 dec.debug_bitpos()
2458 );
2459}
2460
2461/// The position after the WHOLE unit. One call per successful read, on both
2462/// the all-zero early return and the full coefficient walk.
2463#[inline]
2464fn unit_iv_end(dec: &SymbolDecoder, plane: usize, w: usize, h: usize, ctx: usize) {
2465 if !unit_iv_on() {
2466 return;
2467 }
2468 let (mi_r, mi_c) = SymbolDecoder::symr_mi();
2469 eprintln!(
2470 "EC_UNITIV_END side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} end_bit={}",
2471 dec.debug_bitpos()
2472 );
2473}
2474
2475// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
2476// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
2477// shapes whose `use_filter_intra` symbol had no CDF class before this round.
2478// A gate asserting the wider counter would be satisfied by a 32x16 strip and
2479// prove nothing about the new shapes.
2480thread_local! {
2481 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
2482 const { std::cell::Cell::new(0) };
2483}
2484
2485/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
2486#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2487pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
2488 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
2489}
2490
2491// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
2492// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
2493// counter would be satisfied by a 16x8 strip and prove nothing here.
2494thread_local! {
2495 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
2496 const { std::cell::Cell::new(0) };
2497}
2498
2499/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
2500#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2501pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
2502 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
2503}
2504
2505// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
2506// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
2507// call on the current thread -- the same before/after counter pattern as
2508// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
2509// `eob_pt`/1D-neighbour context path rather than every block coincidentally
2510// landing on `DCT_DCT`.
2511thread_local! {
2512 static TX_CLASS1_HITS: std::cell::Cell<usize> =
2513 const { std::cell::Cell::new(0) };
2514}
2515
2516// How many `uv_mode` reads resolved to a directional chroma mode (neither
2517// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
2518// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
2519// actually exercised chroma's own directional predictor.
2520thread_local! {
2521 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
2522 const { std::cell::Cell::new(0) };
2523}
2524
2525/// Current value of [`DIRECTIONAL_UV_HITS`].
2526#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2527pub(crate) fn directional_uv_hits() -> usize {
2528 DIRECTIONAL_UV_HITS.with(|c| c.get())
2529}
2530
2531// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
2532// something other than [`ANGLE_DELTA_ZERO`], across every call in the
2533// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
2534// proving a stream actually exercised a nonzero angle delta.
2535thread_local! {
2536 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
2537 const { std::cell::Cell::new(0) };
2538}
2539
2540// How many [`read_single_ref`] reads resolved to a reference other than
2541// `LAST_FRAME`, across every call on the current thread -- the same before/after
2542// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
2543// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
2544// only other supported one so far) rather than every block coincidentally
2545// resolving `LAST_FRAME`.
2546thread_local! {
2547 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
2548 const { std::cell::Cell::new(0) };
2549}
2550
2551/// Current value of [`NON_LAST_REF_HITS`].
2552#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2553pub(crate) fn non_last_ref_hits() -> usize {
2554 NON_LAST_REF_HITS.with(|c| c.get())
2555}
2556
2557// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
2558// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
2559// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
2560// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
2561// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
2562// `GOLDEN_FRAME` draw it did not ask for.
2563thread_local! {
2564 static LAST2_HITS: std::cell::Cell<usize> =
2565 const { std::cell::Cell::new(0) };
2566}
2567thread_local! {
2568 static LAST3_HITS: std::cell::Cell<usize> =
2569 const { std::cell::Cell::new(0) };
2570}
2571thread_local! {
2572 static GOLDEN_HITS: std::cell::Cell<usize> =
2573 const { std::cell::Cell::new(0) };
2574}
2575thread_local! {
2576 static BWDREF_HITS: std::cell::Cell<usize> =
2577 const { std::cell::Cell::new(0) };
2578}
2579thread_local! {
2580 static ALTREF2_HITS: std::cell::Cell<usize> =
2581 const { std::cell::Cell::new(0) };
2582}
2583thread_local! {
2584 static ALTREF_HITS: std::cell::Cell<usize> =
2585 const { std::cell::Cell::new(0) };
2586}
2587
2588// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
2589// -- proves a `reference_select` stream actually reached a block that picked
2590// compound, not just that the header bit was set. Every such block is
2591// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
2592// so this only ever counts attempted reads, never a completed decode.
2593thread_local! {
2594 static COMP_MODE_HITS: std::cell::Cell<usize> =
2595 const { std::cell::Cell::new(0) };
2596}
2597
2598/// Current value of [`COMP_MODE_HITS`].
2599#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2600pub(crate) fn comp_mode_hits() -> usize {
2601 COMP_MODE_HITS.with(|c| c.get())
2602}
2603
2604// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
2605// use for, across every call on the current thread -- the same before/after
2606// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
2607// exercised palette reconstruction rather than only reading and refusing the
2608// `palette_y_mode` symbol.
2609thread_local! {
2610 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2611}
2612
2613/// Current value of [`PALETTE_HITS`].
2614#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2615pub(crate) fn palette_hits() -> usize {
2616 PALETTE_HITS.with(|c| c.get())
2617}
2618
2619// lane-tiles r12: of those, how many sat at their own TILE's left column --
2620// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
2621// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
2622// palette gate that never hits one proves nothing about the tile guard.
2623thread_local! {
2624 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2625}
2626
2627/// Current value of [`PALETTE_TILE_LEFT_HITS`].
2628#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2629pub(crate) fn palette_tile_left_hits() -> usize {
2630 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
2631}
2632
2633// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
2634// palette use -- proves a stream actually reconstructed UV palette pixels,
2635// not just read and refused the `palette_uv_mode` symbol.
2636thread_local! {
2637 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2638}
2639
2640/// Current value of [`PALETTE_UV_HITS`].
2641#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2642pub(crate) fn palette_uv_hits() -> usize {
2643 PALETTE_UV_HITS.with(|c| c.get())
2644}
2645
2646// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
2647// decoded a real palette-Y use -- proves the rect strip's own palette syntax
2648// (not just the square path's) actually fired.
2649thread_local! {
2650 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2651}
2652
2653/// Current value of [`PALETTE_RECT_HITS`].
2654#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2655pub(crate) fn palette_rect_hits() -> usize {
2656 PALETTE_RECT_HITS.with(|c| c.get())
2657}
2658
2659// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
2660// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
2661// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
2662// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
2663// RD, almost always refused-on-use because the block doesn't end up USING a
2664// palette -- see r5's report). This is the site the removed refusal
2665// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
2666// fired here whether or not the block picked a palette, so this is the
2667// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
2668// never observes.
2669thread_local! {
2670 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2671}
2672
2673/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
2674#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2675pub(crate) fn rect_screen_content_hits() -> usize {
2676 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
2677}
2678
2679// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
2680// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
2681// windowing actually ran, not just that the whole-block path stayed exact.
2682// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
2683// first actually incremented in r7, when the refusal it guarded was lifted.
2684thread_local! {
2685 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2686}
2687
2688thread_local! {
2689 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
2690 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
2691 /// (16x8/8x16), the two shapes the lifted refusals named.
2692 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2693}
2694
2695/// Current value of [`RECT4_PALETTE_HITS`].
2696#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2697pub(crate) fn rect4_palette_hits() -> usize {
2698 RECT4_PALETTE_HITS.with(|c| c.get())
2699}
2700
2701/// Current value of [`PALETTE_SPLIT_TX_HITS`].
2702#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2703pub(crate) fn palette_split_tx_hits() -> usize {
2704 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
2705}
2706
2707thread_local! {
2708 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
2709 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
2710 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
2711 /// `--min-partition-size=8` puts them on this leaf path.
2712 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2713}
2714
2715/// Current value of [`PALETTE_LEAF8_HITS`].
2716#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2717pub(crate) fn palette_leaf8_hits() -> usize {
2718 PALETTE_LEAF8_HITS.with(|c| c.get())
2719}
2720
2721/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
2722#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2723pub(crate) fn reset_palette_leaf8_hits() {
2724 PALETTE_LEAF8_HITS.with(|c| c.set(0));
2725}
2726
2727thread_local! {
2728 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
2729 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
2730 /// block that also carries a real, corner-cropped luma transform.
2731 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2732}
2733
2734/// Current value of [`PALETTE_SB_STRIP_HITS`].
2735#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2736pub(crate) fn palette_sb_strip_hits() -> usize {
2737 PALETTE_SB_STRIP_HITS.with(|c| c.get())
2738}
2739
2740/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
2741#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2742pub(crate) fn reset_palette_sb_strip_hits() {
2743 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
2744}
2745
2746thread_local! {
2747 /// lane-av1rectreach: units of `decode_rect_split`'s `chroma_tiled` walk
2748 /// whose PER-UNIT reach ([`tu_reach_rect`], libaom's per-unit
2749 /// `has_top_right` / `has_bottom_left`) DIFFERS from the block-level
2750 /// `reach` this walk used to hand every unit -- i.e. units for which the
2751 /// two answers are not interchangeable. This is what a gate needs before
2752 /// it compares the walk byte-exactly: if the two agreed everywhere, the
2753 /// substitution could not change a single predicted sample and the
2754 /// exactness assert would be measuring a witness the fix cannot touch.
2755 ///
2756 /// What it does NOT prove is that the argument handed to the unit reader
2757 /// is the per-unit one -- the count is taken from the same expression
2758 /// either way, so deleting the substitution reds the exactness assert
2759 /// rather than this counter. That is the right way round: the assert is
2760 /// the claim, this is only the floor under it.
2761 static RECT_TILED_CHROMA_UNIT_REACH_HITS: std::cell::Cell<usize> =
2762 const { std::cell::Cell::new(0) };
2763 /// Chroma units of the same walk whose grid is exactly 2x1 (a 4:4:4
2764 /// 64x32 chroma plane block as two 32x32 units).
2765 static RECT_TILED_CHROMA_2X1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2766 /// Chroma units of the same walk whose grid is exactly 1x2 (4:4:4 32x64,
2767 /// or 16x64 as two 16x32s).
2768 static RECT_TILED_CHROMA_1X2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2769 /// Chroma units of the same walk in any other multi-unit grid (2x2 and up
2770 /// -- only reachable at 4:2:2, which is refused, so this stays 0 on
2771 /// every admitted stream; kept so the match above is exhaustive).
2772 static RECT_TILED_CHROMA_NXN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2773}
2774
2775/// Current values of the four `RECT_TILED_CHROMA_*` counters, in the order
2776/// `(unit_reach_differs, 2x1, 1x2, other multi-unit)`.
2777#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2778pub(crate) fn rect_tiled_chroma_grid_hits() -> (usize, usize, usize, usize) {
2779 (
2780 RECT_TILED_CHROMA_UNIT_REACH_HITS.with(|c| c.get()),
2781 RECT_TILED_CHROMA_2X1_HITS.with(|c| c.get()),
2782 RECT_TILED_CHROMA_1X2_HITS.with(|c| c.get()),
2783 RECT_TILED_CHROMA_NXN_HITS.with(|c| c.get()),
2784 )
2785}
2786
2787/// Zeroes the four `RECT_TILED_CHROMA_*` counters (gate tests call this
2788/// before their own decode).
2789#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2790pub(crate) fn reset_rect_tiled_chroma_grid_hits() {
2791 RECT_TILED_CHROMA_UNIT_REACH_HITS.with(|c| c.set(0));
2792 RECT_TILED_CHROMA_2X1_HITS.with(|c| c.set(0));
2793 RECT_TILED_CHROMA_1X2_HITS.with(|c| c.set(0));
2794 RECT_TILED_CHROMA_NXN_HITS.with(|c| c.set(0));
2795}
2796
2797// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
2798// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
2799// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
2800// capability rather than the key frame's, which every screen stream also
2801// carries.
2802thread_local! {
2803 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2804 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2805}
2806
2807// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
2808// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
2809// shared counter too, so only this one proves a gate really reached the leaf
2810// where the refusal used to sit.
2811thread_local! {
2812 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
2813 const { std::cell::Cell::new((0, 0)) };
2814}
2815
2816/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
2817pub(crate) fn inter8_palette_hits() -> (usize, usize) {
2818 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
2819}
2820
2821/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
2822pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
2823 (
2824 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
2825 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
2826 )
2827}
2828
2829// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
2830// and which are therefore predicted one transform unit at a time (a skipped
2831// block codes no coefficients, so nothing else in the stream witnesses this
2832// path -- only the pixels do).
2833thread_local! {
2834 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2835}
2836
2837/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
2838pub fn skip_split_tx_hits() -> usize {
2839 SKIP_SPLIT_TX_HITS.with(|c| c.get())
2840}
2841
2842// lane-svt1: SKIPPED square blocks carrying a palette/intrabc prediction whose
2843// `tx_depth` split the luma transform -- the arm that predicted DC off the
2844// block edges before the fix. Like [`SKIP_SPLIT_TX_HITS`] only the pixels
2845// witness this path, so a gate that wants it needs the counter.
2846thread_local! {
2847 static SKIP_SPLIT_TX_OVERRIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2848 /// lane-av1chromadc: chroma units of a skipped block whose intra-BC /
2849 /// UV-palette override had to be WINDOWED to the unit's own extent --
2850 /// i.e. `cn_cols * cn_rows > 1`, which at 4:2:0 never happens (the chroma
2851 /// plane block is one 32x32 unit) and at 4:4:4 is every block of 64 and
2852 /// above. Counts UNITS, not blocks. EXCLUSIVE to this walk: the other two
2853 /// override sites (the luma slot and `decode_intrabc_owned_rect`) have
2854 /// their own windows.
2855 static SKIP_CHROMA_OVERRIDE_WINDOW_HITS: std::cell::Cell<usize> =
2856 const { std::cell::Cell::new(0) };
2857}
2858
2859/// Current value of [`SKIP_SPLIT_TX_OVERRIDE_HITS`] (blocks).
2860pub fn skip_split_tx_override_hits() -> usize {
2861 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.get())
2862}
2863
2864/// lane-av1chromadc: [`SKIP_CHROMA_OVERRIDE_WINDOW_HITS`].
2865#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2866pub fn skip_chroma_override_window_hits() -> usize {
2867 SKIP_CHROMA_OVERRIDE_WINDOW_HITS.with(|c| c.get())
2868}
2869
2870/// Zeroes [`SKIP_CHROMA_OVERRIDE_WINDOW_HITS`] before a gate's own decode.
2871#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2872pub fn reset_skip_chroma_override_window_hits() {
2873 SKIP_CHROMA_OVERRIDE_WINDOW_HITS.with(|c| c.set(0));
2874}
2875
2876/// Zeroes [`SKIP_SPLIT_TX_OVERRIDE_HITS`] before a gate's own decode attempt.
2877pub fn reset_skip_split_tx_override_hits() {
2878 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.set(0));
2879}
2880
2881// lane-svtinter: palette colour-index maps whose block is cut by the frame's
2882// bottom/right mi edge, so spec 5.11.50's `onscreenWidth`/`onscreenHeight`
2883// really are smaller than the block and FEWER symbols are read than the
2884// block has cells (class map-read-past-frame-edge).
2885thread_local! {
2886 static PALETTE_ONSCREEN_CUT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2887}
2888
2889/// Current value of [`PALETTE_ONSCREEN_CUT_HITS`] (colour-index maps).
2890pub fn palette_onscreen_cut_hits() -> usize {
2891 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.get())
2892}
2893
2894/// Zeroes [`PALETTE_ONSCREEN_CUT_HITS`] before a gate's own decode attempt.
2895pub fn reset_palette_onscreen_cut_hits() {
2896 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.set(0));
2897}
2898
2899/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
2900pub fn reset_skip_split_tx_hits() {
2901 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
2902}
2903
2904// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
2905// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
2906// the gate's proof that the lifted path actually ran, per size.
2907thread_local! {
2908 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
2909 const { std::cell::Cell::new([0; 4]) };
2910}
2911
2912/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
2913#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2914pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
2915 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2916}
2917
2918/// A just-decoded palette-Y block's own predicted pixels
2919/// (`side*side`, row-major, `colors[map[i]]`), consumed by
2920/// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
2921/// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
2922/// per-block override through `read_plane`'s two dozen call sites is the
2923/// alternative this avoids). Always empty again once that call consumes
2924/// it (`.take()`), so a non-palette block's own `reconstruct` call never
2925/// sees stale state.
2926
2927/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
2928/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
2929/// site whose reconstruct never runs would be picked up by the NEXT block's
2930/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
2931/// lane-lossless2: one transform unit's window on a block-sized palette
2932/// prediction buffer. A unit reads its prediction at ITS OWN stride, so
2933/// handing it the whole-block buffer makes every unit reconstruct the block's
2934/// top-left corner (the luma split-transform paths already window; the chroma
2935/// ones did not, which is invisible until a lossless frame codes a palette
2936/// block as 4x4 chroma units).
2937fn palette_window(
2938 buf: &[u16],
2939 stride: usize,
2940 ox: usize,
2941 oy: usize,
2942 w: usize,
2943 h: usize,
2944) -> Vec<u16> {
2945 (0..h)
2946 .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied())
2947 .collect()
2948}
2949
2950/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
2951#[track_caller]
2952fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
2953 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2954 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
2955 eprintln!(
2956 "PALSET len={} stale={stale} at {}",
2957 buf.len(),
2958 std::panic::Location::caller()
2959 );
2960 }
2961 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
2962}
2963
2964#[track_caller]
2965fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
2966 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
2967 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2968 eprintln!(
2969 "PALTAKE len={:?} at {}",
2970 got.as_ref().map(Vec::len),
2971 std::panic::Location::caller()
2972 );
2973 }
2974 got
2975}
2976
2977/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
2978/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
2979/// pixels, because at parse time this block's own luma is still queued.
2980#[derive(Clone, Copy, Debug)]
2981pub(crate) struct CflSrc {
2982 px: usize,
2983 py: usize,
2984 bw: usize,
2985 bh: usize,
2986}
2987
2988fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
2989 CflSrc {
2990 px,
2991 py,
2992 bw: side,
2993 bh: side,
2994 }
2995}
2996
2997fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
2998 CflSrc { px, py, bw, bh }
2999}
3000
3001/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
3002/// instead of executed. Each variant is the resolved argument tuple of the
3003/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
3004/// order performs exactly the same writes in exactly the same order --
3005/// entropy parsing no longer touches the frame's own planes (except the two
3006/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
3007/// the replay on a superblock-row wavefront worker.
3008/// The dequantization + inverse transform of one transform unit, kept as its
3009/// INPUTS so that a recorded write carries the work instead of its result
3010/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
3011/// recon worker, not on the parsing thread. `stride == 0` means the dense
3012/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
3013/// `reconstruct_mc_rect` reads both of its buffers at.
3014#[derive(Clone, Copy)]
3015pub(crate) struct TxParams {
3016 pub(crate) w: usize,
3017 pub(crate) h: usize,
3018 pub(crate) bit_depth: u8,
3019 pub(crate) q_idx: i32,
3020 pub(crate) dc_delta: i32,
3021 pub(crate) ac_delta: i32,
3022 pub(crate) tx_type: TxType,
3023 /// lane-av1-qmatrix: this unit's inverse quantisation matrix, selected
3024 /// on the parse thread by [`block_iqmatrix`] and captured here so the
3025 /// recon worker scales identically without touching frame state.
3026 pub(crate) qm: Option<crate::qm::Iqm>,
3027 pub(crate) stride: usize,
3028 /// lane-lossless: this transform unit belongs to a lossless BLOCK (its
3029 /// segment's `xd->lossless[segment_id]` bit), so the residual comes off
3030 /// the 4x4 Walsh-Hadamard
3031 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
3032 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
3033 pub(crate) lossless: bool,
3034}
3035
3036/// lane-av1mixloss: Walsh-Hadamard transform units actually reconstructed.
3037/// The mixed-lossless witness's proof the per-segment lossless path really
3038/// ran on a frame that is NOT `CodedLossless`. Atomic because the wavefront
3039/// workers run this on their own threads.
3040static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
3041
3042/// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after
3043/// delta around one decode.
3044#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3045pub(crate) fn lossless_wht_units() -> usize {
3046 LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
3047}
3048
3049/// lane-whtshape: 4x4 Walsh-Hadamard units reconstructed as part of a LOSSLESS
3050/// transform unit that was itself NOT 4x4 -- a shape libaom cannot code.
3051/// `read_tx_mode` (`av1/decoder/decodeframe.c:140`) returns `ONLY_4X4` for a
3052/// `coded_lossless` frame before it looks at the `tx_mode` symbol,
3053/// `read_tx_size` (`:1117`) returns `TX_4X4` before it looks at a tree,
3054/// `get_vartx_max_txsize` (`av1/common/blockd.h:1447`) returns `TX_4X4` for
3055/// EVERY plane of a lossless block, and of `av1/common/idct.c`'s
3056/// `highbd_inv_txfm_add_*_c` only `highbd_inv_txfm_add_4x4_c` carries a
3057/// `lossless` branch -- every other size falls through to the IDCT, because
3058/// there is no non-4x4 lossless inverse transform to dispatch to. So one of
3059/// these is a CALLER sizing a lossless unit wrongly, not a bitstream shape;
3060/// read as a before/after delta around one decode it names the caller. Must
3061/// read 0 on a stream whose lossless unit geometry is right. Atomic: the
3062/// wavefront workers run the transform on their own threads.
3063static LOSSLESS_WHT_SPLIT_UNITS: std::sync::atomic::AtomicUsize =
3064 std::sync::atomic::AtomicUsize::new(0);
3065
3066/// [`LOSSLESS_WHT_SPLIT_UNITS`] -- total over the process, read as a
3067/// before/after delta around one decode.
3068#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3069pub(crate) fn lossless_wht_split_units() -> usize {
3070 LOSSLESS_WHT_SPLIT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
3071}
3072
3073impl TxParams {
3074 /// The one copy of the produce-the-residual code: the inline path calls it
3075 /// on the parse thread, the wavefront worker calls it on its own, so both
3076 /// are the same function on the same inputs and byte-identical.
3077 fn run(self, grid: &[i32]) -> Vec<i32> {
3078 let residual = if self.lossless {
3079 LOSSLESS_WHT_UNITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3080 // lane-whtshape: a non-4x4 unit here is this decoder's own
3081 // transform-unit geometry being wrong (see
3082 // [`LOSSLESS_WHT_SPLIT_UNITS`] for the libaom evidence). It used
3083 // to be stopped by a `debug_assert_eq!` that RELEASE never ran:
3084 // the 4x4 WHT returned 16 values for a `w * h` block and the
3085 // release build died one frame later in the strided copy with an
3086 // opaque `range end index 8 out of range for slice of length 0`
3087 // that never named lossless or the transform. Counted, and
3088 // reconstructed as the raster of 4x4 WHT units
3089 // ([`crate::transform::dequant_and_inverse_wht`]) instead: total,
3090 // the same in both profiles, and the 4x4 fast path is the same
3091 // single call it always was. The old
3092 // `debug_assert_eq!(self.tx_type, TxType::DctDct)` is gone with
3093 // it: the WHT takes no tx_type (libaom's `av1_iwht4x4_add` does
3094 // not either), and `av1_get_tx_type` already answers `DCT_DCT` on
3095 // every plane of a lossless block, so asserting an argument
3096 // nothing reads was a debug-only panic on a value release
3097 // ignores.
3098 if self.w != 4 || self.h != 4 {
3099 LOSSLESS_WHT_SPLIT_UNITS.fetch_add(
3100 self.w.div_ceil(4) * self.h.div_ceil(4),
3101 std::sync::atomic::Ordering::Relaxed,
3102 );
3103 }
3104 crate::transform::dequant_and_inverse_wht(
3105 grid,
3106 self.w,
3107 self.h,
3108 self.bit_depth,
3109 self.q_idx,
3110 self.dc_delta,
3111 self.ac_delta,
3112 )
3113 } else {
3114 dequant_and_inverse_typed_wh(
3115 grid,
3116 self.w,
3117 self.h,
3118 self.bit_depth,
3119 self.q_idx,
3120 self.dc_delta,
3121 self.ac_delta,
3122 self.tx_type,
3123 self.qm,
3124 )
3125 };
3126 // An all-zero grid transforms to the empty marker, and a strided copy
3127 // of zeros is still zeros: the marker passes straight through.
3128 if residual.is_empty() {
3129 return residual;
3130 }
3131 if self.stride == 0 {
3132 return residual;
3133 }
3134 // lane-av1-422sub8rect: `h` rows of `stride` -- a rect unit whose
3135 // height exceeds its (narrow) prediction stride needs the full
3136 // stride * h; every square caller has h == stride and is unchanged.
3137 let mut strided = vec![0i32; self.stride * self.h];
3138 for row in 0..self.h {
3139 strided[row * self.stride..][..self.w]
3140 .copy_from_slice(&residual[row * self.w..][..self.w]);
3141 }
3142 strided
3143 }
3144}
3145
3146/// A recorded write's residual: already transformed, or the coefficients and
3147/// [`TxParams`] the worker transforms itself.
3148pub(crate) enum Residual {
3149 /// An already-transformed residual in the arena, `(offset, len)`; a zero
3150 /// `len` is the all-zero marker [`dense_residual`] expands.
3151 Done(u32, u32),
3152 /// The coefficients live in the pushing tile's arena
3153 /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
3154 /// len)` in it.
3155 Coeffs(TxParams, u32, u32),
3156}
3157
3158impl Residual {
3159 /// The record for a transform unit whose coefficient grid is all zero:
3160 /// the empty marker, so neither the grid nor the residual is cloned and
3161 /// the worker never runs the transform (60% of the 4K segment's units).
3162 fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
3163 if is_zero_grid(grid) {
3164 return Self::Done(0, 0);
3165 }
3166 Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
3167 }
3168
3169 /// A residual the parse thread already transformed, kept in the arena
3170 /// instead of its own `Vec`.
3171 fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
3172 // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself,
3173 // which is exactly the all-zero marker -- one pointer compare instead
3174 // of copying up to 64 KB of zeros into the arena per block.
3175 if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) {
3176 return Self::Done(0, 0);
3177 }
3178 Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
3179 }
3180
3181 /// The residual to reconstruct with; `scratch` is where a transform run
3182 /// on this thread lands, so the caller owns that buffer.
3183 fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
3184 match self {
3185 Self::Done(off, len) => &arena[off as usize..][..len as usize],
3186 Self::Coeffs(p, off, len) => {
3187 *scratch = p.run(&arena[off as usize..][..len as usize]);
3188 scratch
3189 }
3190 }
3191 }
3192}
3193
3194/// Appends to the tile's coefficient arena, returning the offset the record
3195/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
3196fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
3197 fctx.coeff_arena.with(|a| {
3198 let mut a = a.borrow_mut();
3199 let off = a.len();
3200 a.extend_from_slice(v);
3201 off as u32
3202 })
3203}
3204
3205/// [`push_coeffs`] for a recorded prediction.
3206fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
3207 fctx.pred_arena.with(|a| {
3208 let mut a = a.borrow_mut();
3209 let off = a.len();
3210 a.extend_from_slice(v);
3211 off as u32
3212 })
3213}
3214
3215/// An all-zero residual, for the transform units that code no coefficient:
3216/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
3217/// and the reconstruction loops below read this instead of a per-unit
3218/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
3219/// (a 128-wide inter block's prediction stride).
3220pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
3221
3222/// lane-blockscratch: one plane's coefficient levels as the block-tail
3223/// neighbour writes want them. A plane that coded nothing (a skipped block, a
3224/// strip with no chroma, luma under a var-tx split whose units already wrote
3225/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
3226/// zeroing up to 64 KB of its own per block.
3227#[derive(Clone)]
3228enum Grid {
3229 Zero(usize),
3230 Own(Vec<i32>),
3231}
3232
3233/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
3234/// unit that writes into it. Only a block wider or taller than 64 px codes its
3235/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
3236/// collectors per block and then drop them untouched.
3237fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
3238 if v.is_empty() {
3239 *v = vec![0i32; n];
3240 }
3241 v
3242}
3243
3244impl std::ops::Deref for Grid {
3245 type Target = [i32];
3246 fn deref(&self) -> &[i32] {
3247 match self {
3248 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
3249 Grid::Own(v) => v,
3250 }
3251 }
3252}
3253
3254/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
3255/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
3256/// transform units that code no coefficient without the scan (lane-coefgrid).
3257pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
3258 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
3259}
3260
3261/// `residual`, or `n` zeros when it is the empty all-zero marker.
3262fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
3263 if residual.is_empty() {
3264 &ZERO_RESIDUAL[..n]
3265 } else {
3266 residual
3267 }
3268}
3269
3270/// Where a recorded motion-compensated write reads its prediction from.
3271///
3272/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
3273/// the parse thread's single biggest reconstruction cost, so at
3274/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
3275/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
3276/// runs it into its own three-plane slot, and every transform unit of that
3277/// block then reads its window out of that slot ([`Pred::Cur`]).
3278#[derive(Clone, Copy)]
3279pub(crate) enum Pred<'a> {
3280 /// A prediction the parse thread already built, at its own stride
3281 /// (`stride == 0` means "the reader's own `stride` argument").
3282 Inline(&'a [u16], usize),
3283 /// The current block's deferred prediction: plane, its stride, and this
3284 /// unit's offset into it.
3285 Cur {
3286 plane: usize,
3287 stride: usize,
3288 off: usize,
3289 },
3290}
3291
3292impl<'a> Pred<'a> {
3293 /// The same prediction read at an explicit stride.
3294 fn view(self, stride: usize) -> Self {
3295 match self {
3296 Self::Inline(b, _) => Self::Inline(b, stride),
3297 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
3298 }
3299 }
3300 /// The materialised buffer and the stride to read it at (`stride` is the
3301 /// reader's own when this prediction was built dense); `None` for a
3302 /// deferred prediction, which only a recorded op can carry.
3303 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
3304 match self {
3305 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
3306 Self::Cur { .. } => None,
3307 }
3308 }
3309 /// This prediction's window starting `n` samples in.
3310 fn offset(self, n: usize) -> Self {
3311 match self {
3312 Self::Inline(b, s) => Self::Inline(&b[n..], s),
3313 Self::Cur { plane, stride, off } => Self::Cur {
3314 plane,
3315 stride,
3316 off: off + n,
3317 },
3318 }
3319 }
3320}
3321
3322/// [`Pred`], resolved into what a recorded op carries.
3323pub(crate) enum PredSrc {
3324 /// A prediction window in the tile's prediction arena, `(offset, len)`.
3325 Owned(u32, u32),
3326 /// A window of the block prediction: its plane, its offset, and the
3327 /// stride it is read at -- which is the block's, not necessarily the
3328 /// op's (a transform unit's residual stays dense, so the worker takes
3329 /// its window out of the block prediction itself).
3330 Cur {
3331 plane: usize,
3332 off: usize,
3333 src: usize,
3334 },
3335}
3336
3337/// One block's whole-block prediction build, deferred to a recon worker.
3338///
3339/// The closure borrows the tile's reference pictures and its own frame-level
3340/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
3341/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
3342/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
3343pub(crate) struct PredBuild(
3344 Box<
3345 dyn FnOnce(
3346 &mut PlaneBuf<'static>,
3347 &mut PlaneBuf<'static>,
3348 &mut PlaneBuf<'static>,
3349 &crate::decode::FrameCtx,
3350 // lane-blockmem: the previous block's three prediction buffers,
3351 // refilled in place -- the build used to return three fresh
3352 // `Vec`s per block and drop these.
3353 &mut [Vec<u16>; 3],
3354 ),
3355 >,
3356);
3357
3358// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
3359// pictures and frame tables, and the closure runs on exactly one worker.
3360#[allow(unsafe_code)]
3361unsafe impl Send for PredBuild {}
3362
3363/// `true` when this tile's writes are recorded for the wavefront instead of
3364/// performed at the push site, i.e. when a prediction may be deferred.
3365fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
3366 fctx.recon_planes.with(std::cell::Cell::get).is_none()
3367}
3368
3369/// The previous block's prediction buffer, cleared and zero-filled to `n`
3370/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
3371/// without the per-block allocation and free.
3372fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
3373 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
3374 // than resized element by element -- which is every block on the inline
3375 // path, where there is no previous buffer to reuse.
3376 if v.capacity() < n {
3377 return vec![0u16; n];
3378 }
3379 v.clear();
3380 v.resize(n, 0);
3381 v
3382}
3383
3384/// Records one block's prediction build for the worker that reconstructs it.
3385#[allow(unsafe_code)]
3386fn push_pred<'a>(
3387 fctx: &crate::decode::FrameCtx,
3388 f: impl FnOnce(
3389 &mut PlaneBuf<'static>,
3390 &mut PlaneBuf<'static>,
3391 &mut PlaneBuf<'static>,
3392 &crate::decode::FrameCtx,
3393 &mut [Vec<u16>; 3],
3394 ) + 'a,
3395) {
3396 type Dyn<'x> = dyn FnOnce(
3397 &mut PlaneBuf<'static>,
3398 &mut PlaneBuf<'static>,
3399 &mut PlaneBuf<'static>,
3400 &crate::decode::FrameCtx,
3401 &mut [Vec<u16>; 3],
3402 ) + 'x;
3403 let boxed: Box<Dyn<'a>> = Box::new(f);
3404 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
3405 // before the borrows the closure holds go out of scope.
3406 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
3407 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
3408}
3409
3410/// One superblock's recorded writes plus the two arenas they index -- the
3411/// unit a wavefront worker takes off the queue (lane-recoparse).
3412pub(crate) struct ReconJob {
3413 ops: Vec<ReconOp>,
3414 coeffs: Vec<i32>,
3415 preds: Vec<u16>,
3416}
3417
3418pub(crate) enum ReconOp {
3419 /// lane-wave4: build this block's prediction into the worker's slot.
3420 Pred(PredBuild),
3421 Intra {
3422 plane: usize,
3423 x: usize,
3424 y: usize,
3425 bw: usize,
3426 bh: usize,
3427 /// `true` when the parse site called `reconstruct_rect` (whose
3428 /// `edges_rect` differs from `edges` even at `bw == bh`).
3429 rect: bool,
3430 mode: usize,
3431 angle_delta: i32,
3432 reach: Reach,
3433 residual: Residual,
3434 cfl: Option<(i32, CflSrc)>,
3435 filter_intra: Option<usize>,
3436 smooth_neighbor: bool,
3437 /// The palette/intrabc prediction override, taken off
3438 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
3439 /// from that slot by the replay.
3440 pred: Option<Vec<u16>>,
3441 },
3442 Mc {
3443 plane: usize,
3444 x: usize,
3445 y: usize,
3446 stride: usize,
3447 w: usize,
3448 h: usize,
3449 prediction: PredSrc,
3450 residual: Residual,
3451 },
3452}
3453
3454/// The three planes of the tile currently being decoded, as raw pointers.
3455///
3456/// corner-cut: at one reconstruction thread a recorded write must cost
3457/// nothing -- deferring it to the end of the superblock is +1.2%
3458/// instructions and +4.5% wall on 4K, because the residual is written at
3459/// parse and read back cache-cold at replay. So the recorded op is performed
3460/// at the push site instead, through the pointers the tile decoder registers
3461/// once ([`ReconInline`]), which is the same thread, the same order and the
3462/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
3463/// stack still holds aliases them, exactly the [`crate::par::Shared`]
3464/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
3465/// threading the three planes down every `read_plane`/`read_inter_plane`
3466/// call site (~40) so the push site owns the borrow it writes through.
3467#[derive(Clone, Copy)]
3468pub(crate) struct ReconPlanes(
3469 *mut PlaneBuf<'static>,
3470 *mut PlaneBuf<'static>,
3471 *mut PlaneBuf<'static>,
3472);
3473
3474// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
3475// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
3476// value travelling is `None`; the pointers never leave the tile decoder's
3477// own thread.
3478#[allow(unsafe_code)]
3479unsafe impl Send for ReconPlanes {}
3480// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
3481// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
3482// contract, one superblock per band instead of one row band.
3483#[allow(unsafe_code)]
3484unsafe impl Sync for ReconPlanes {}
3485
3486/// Registers the tile's planes for inline reconstruction and unregisters them
3487/// on every exit from the tile decoder, including the `?` ones -- a stale
3488/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
3489/// tile.
3490pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
3491
3492#[allow(unsafe_code)]
3493impl<'a> ReconInline<'a> {
3494 /// Installs the guard for this tile when reconstruction is inline
3495 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
3496 /// to the queue instead, for the wavefront workers to replay.
3497 fn install(
3498 fctx: &'a crate::decode::FrameCtx,
3499 y: &mut PlaneBuf<'static>,
3500 u: &mut PlaneBuf<'static>,
3501 v: &mut PlaneBuf<'static>,
3502 ) -> Option<Self> {
3503 if crate::par::recon_threads() != 1 {
3504 return None;
3505 }
3506 // SAFETY: the planes are locals of the tile decoder and outlive the
3507 // guard, which is dropped on every exit from it (including `?`); see
3508 // [`ReconPlanes`] for the aliasing trade-off.
3509 let planes = ReconPlanes(
3510 std::ptr::from_mut(y),
3511 std::ptr::from_mut(u),
3512 std::ptr::from_mut(v),
3513 );
3514 fctx.recon_planes.with(|c| c.set(Some(planes)));
3515 Some(Self(fctx))
3516 }
3517}
3518
3519impl Drop for ReconInline<'_> {
3520 fn drop(&mut self) {
3521 self.0.recon_planes.with(|c| c.set(None));
3522 }
3523}
3524
3525#[allow(unsafe_code)]
3526fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
3527 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
3528 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
3529 // the parse site would have performed itself before lane-wave1.
3530 // The inline path never records coefficients (the transform runs at
3531 // the push site), so the arena is not read here.
3532 unsafe {
3533 exec_op(
3534 op,
3535 &mut *y,
3536 &mut *u,
3537 &mut *v,
3538 &mut Default::default(),
3539 &[],
3540 &[],
3541 fctx,
3542 )
3543 };
3544 return;
3545 }
3546 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
3547}
3548
3549/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
3550/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
3551///
3552/// The parser keeps parsing and never touches the planes; each superblock's
3553/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
3554/// `(row, column)` inside the tile (128x128 superblocks are one job for all
3555/// four of their 64x64 visits, since a 128 block writes across quadrants).
3556/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
3557/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
3558/// every pixel an intra predictor can read (its edges reach one block right
3559/// along the row above and one block down the column to the left, both
3560/// inside those two neighbours) and every CfL AC read (this block's own
3561/// luma, written by this same job). Jobs are handed out in raster order, so
3562/// the oldest outstanding one always has its dependencies met: no deadlock.
3563///
3564/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
3565/// `thread_local!` and miss every worker, which is why the default is 1.
3566pub(crate) struct WaveState {
3567 q: std::sync::Mutex<WaveQueue>,
3568 cv: std::sync::Condvar,
3569 planes: ReconPlanes,
3570 /// The [`FrameCtx`] fields reconstruction reads (`sample_max` is
3571 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
3572 bit_depth: u8,
3573 enable_edge_filter: bool,
3574 /// lane-av1wavefront: the sequence's chroma subsampling. The replay-side
3575 /// readers -- the deferred chroma builds' `mv_to_q4(.., ss_x(fctx))`
3576 /// positions and `exec_intra`'s CfL AC signal -- must see the FRAME's
3577 /// pair, not [`FrameCtx::new`]'s 4:2:0 default: on a 4:4:4 stream the
3578 /// default halved every worker's chroma reference position and lost the
3579 /// chroma planes (the 444_sb128rect witness, U 17504 / V 3 at PREFILT on
3580 /// frame 1) while every 4:2:0 gate stream stayed accidentally exact.
3581 subsampling: (u8, u8),
3582 last_col: usize,
3583}
3584
3585struct WaveQueue {
3586 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
3587 /// row's front job can ever be runnable -- a job waits on its own left
3588 /// neighbour -- so a worker takes the lowest row whose front job's
3589 /// dependencies are met. Popping the raster-oldest job instead (what
3590 /// this replaced) put every worker on the SAME row, where the wavefront
3591 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
3592 rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
3593 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
3594 /// walking it.
3595 queued: usize,
3596 /// Per superblock row, the last column reconstructed (-1 = none yet).
3597 done: Vec<isize>,
3598 /// Per superblock row, the last column PARSED (submitted, whether or not
3599 /// it recorded any write) and the last column actually pushed as a job
3600 /// (-1 = none). A row is fully reconstructed once it has been parsed to
3601 /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
3602 /// reads that to release the row's filters (see [`wave_rows_complete`]).
3603 last_sub: Vec<isize>,
3604 last_push: Vec<isize>,
3605 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
3606 active: usize,
3607 closed: bool,
3608 /// lane-sballoc: the three per-superblock buffers a finished job hands
3609 /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no
3610 /// first-touch page faults) instead of the `Vec::with_capacity` it used
3611 /// to make per superblock -- 3 allocations and 3 frees per superblock,
3612 /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives
3613 /// inside the queue's own mutex, which both sides already take.
3614 free: Vec<JobBufs>,
3615 free_cap: usize,
3616}
3617
3618/// One recycled set of [`ReconJob`] buffers (lane-sballoc).
3619type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>);
3620
3621impl WaveQueue {
3622 /// The lowest-row queued job whose wavefront dependencies are satisfied,
3623 /// or `None` (with the blocking condition counted when instrumented).
3624 fn take_runnable(&mut self, last_col: usize, stats: bool) -> Option<(usize, usize, ReconJob)> {
3625 let mut blocked: Option<bool> = None;
3626 for r in 0..self.rows.len() {
3627 let Some(front) = self.rows[r].front() else {
3628 continue;
3629 };
3630 let c = front.0;
3631 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
3632 let left = c == 0 || self.done[r] >= c as isize - 1;
3633 if above && left {
3634 let (c, job) = self.rows[r].pop_front().expect("front checked above");
3635 self.queued -= 1;
3636 return Some((r, c, job));
3637 }
3638 if blocked.is_none() {
3639 blocked = Some(above);
3640 }
3641 }
3642 if stats {
3643 match blocked {
3644 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
3645 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
3646 None => 0,
3647 };
3648 }
3649 None
3650 }
3651}
3652
3653/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
3654/// worker's time goes (busy replaying, waiting for a dependency, idle on an
3655/// empty queue), how far ahead the parse thread is, and how often the two
3656/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
3657/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
3658/// whole run.
3659const WS_SLOTS: usize = 16;
3660use std::sync::atomic::AtomicU64;
3661use std::sync::atomic::Ordering::Relaxed;
3662static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3663static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3664static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3665static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3666static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
3667static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
3668/// Parse-thread time between two submits, i.e. everything parse still does
3669/// itself (symbol decode plus the predictions not deferred).
3670static WS_PARSE: AtomicU64 = AtomicU64::new(0);
3671/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
3672/// (the intrabc/interintra reads) and at the tile's end.
3673static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
3674static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
3675static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
3676static WS_TILES: AtomicU64 = AtomicU64::new(0);
3677
3678fn wave_stats() -> bool {
3679 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
3680 match ON.load(Relaxed) {
3681 0 => {
3682 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
3683 .map(|v| v.trim() == "1")
3684 .unwrap_or(false);
3685 ON.store(1 + u8::from(on), Relaxed);
3686 on
3687 }
3688 n => n == 2,
3689 }
3690}
3691
3692fn wave_stats_dump() {
3693 let ms = |n: u64| n as f64 / 1e6;
3694 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
3695 for i in 0..WS_SLOTS {
3696 let jobs = WS_JOBS[i].load(Relaxed);
3697 if jobs == 0 {
3698 continue;
3699 }
3700 s += &format!(
3701 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
3702 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
3703 ms(WS_BUSY[i].load(Relaxed)),
3704 ms(WS_WAIT[i].load(Relaxed)),
3705 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
3706 );
3707 }
3708 s += &format!(
3709 " | pipe={}/{}",
3710 PIPE_FRAMES.load(Relaxed),
3711 PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
3712 );
3713 s += &format!(
3714 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
3715 ms(WS_PARSE.load(Relaxed)),
3716 ms(WS_BARRIER.load(Relaxed)),
3717 WS_BARRIERS.load(Relaxed),
3718 ms(WS_DRAIN.load(Relaxed)),
3719 WS_BLOCK_ABOVE.load(Relaxed),
3720 WS_BLOCK_LEFT.load(Relaxed),
3721 );
3722 eprintln!("{s}");
3723}
3724
3725#[allow(unsafe_code)]
3726fn wave_worker(st: &WaveState, idx: usize) {
3727 let fctx = FrameCtx::new();
3728 fctx.bit_depth.set(st.bit_depth);
3729 fctx.enable_edge_filter.set(st.enable_edge_filter);
3730 let (sx, sy) = st.subsampling;
3731 fctx.subsampling_x.set(sx);
3732 fctx.subsampling_y.set(sy);
3733 let stats = wave_stats();
3734 let slot = idx.min(WS_SLOTS - 1);
3735 loop {
3736 let t0 = std::time::Instant::now();
3737 let mut q = st.q.lock().unwrap();
3738 let (r, c, job) = loop {
3739 if let Some(job) = q.take_runnable(st.last_col, stats) {
3740 break job;
3741 }
3742 if q.closed && q.queued == 0 {
3743 return;
3744 }
3745 q = st.cv.wait(q).unwrap();
3746 };
3747 q.active += 1;
3748 drop(q);
3749 if stats {
3750 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3751 WS_JOBS[slot].fetch_add(1, Relaxed);
3752 WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
3753 }
3754 let t1 = std::time::Instant::now();
3755 let ReconPlanes(y, u, v) = st.planes;
3756 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
3757 // every superblock that could have written or be reading them is
3758 // complete by the wavefront rule above.
3759 let mut cur: [Vec<u16>; 3] = Default::default();
3760 let ReconJob {
3761 mut ops,
3762 mut coeffs,
3763 mut preds,
3764 } = job;
3765 unsafe {
3766 for op in ops.drain(..) {
3767 exec_op(
3768 op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx,
3769 );
3770 }
3771 }
3772 if stats {
3773 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
3774 }
3775 coeffs.clear();
3776 preds.clear();
3777 let mut q = st.q.lock().unwrap();
3778 // lane-sballoc: hand the three buffers back for the next submit.
3779 if q.free.len() < q.free_cap {
3780 q.free.push((ops, coeffs, preds));
3781 }
3782 q.done[r] = c as isize;
3783 q.active -= 1;
3784 st.cv.notify_all();
3785 }
3786}
3787
3788/// Installs the wavefront for one tile and joins its workers on every exit
3789/// from the tile decoder, including the `?` ones -- the jobs hold raw
3790/// pointers into the tile's planes, so no worker may outlive them.
3791/// (lane-pool1: the workers come from this thread's persistent pool, so a
3792/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
3793/// with fresh scratch.)
3794pub(crate) struct WaveGuard<'a>(
3795 &'a crate::decode::FrameCtx,
3796 Option<crate::par::Batch<'static>>,
3797);
3798
3799#[allow(unsafe_code)]
3800impl<'a> WaveGuard<'a> {
3801 fn install(
3802 fctx: &'a crate::decode::FrameCtx,
3803 y: &mut PlaneBuf<'static>,
3804 u: &mut PlaneBuf<'static>,
3805 v: &mut PlaneBuf<'static>,
3806 rows: usize,
3807 cols: usize,
3808 ) -> Option<Self> {
3809 let threads = crate::par::recon_threads();
3810 if threads == 1 || rows == 0 || cols == 0 {
3811 return None;
3812 }
3813 let st = std::sync::Arc::new(WaveState {
3814 q: std::sync::Mutex::new(WaveQueue {
3815 rows: (0..rows)
3816 .map(|_| std::collections::VecDeque::new())
3817 .collect(),
3818 queued: 0,
3819 done: vec![-1; rows],
3820 last_sub: vec![-1; rows],
3821 last_push: vec![-1; rows],
3822 active: 0,
3823 closed: false,
3824 free: Vec::new(),
3825 free_cap: threads + 2,
3826 }),
3827 cv: std::sync::Condvar::new(),
3828 // SAFETY: the planes are locals of the tile decoder and outlive
3829 // this guard, which joins every worker in `drop`.
3830 planes: ReconPlanes(
3831 std::ptr::from_mut(y),
3832 std::ptr::from_mut(u),
3833 std::ptr::from_mut(v),
3834 ),
3835 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
3836 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
3837 subsampling: (
3838 fctx.subsampling_x.with(std::cell::Cell::get),
3839 fctx.subsampling_y.with(std::cell::Cell::get),
3840 ),
3841 last_col: cols - 1,
3842 });
3843 let batch = crate::par::Batch::new("ec-av1-recon");
3844 for idx in 0..threads {
3845 let st = std::sync::Arc::clone(&st);
3846 batch.submit(move || wave_worker(&st, idx));
3847 }
3848 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
3849 fctx.wave_mark
3850 .with(|c| c.set(Some(std::time::Instant::now())));
3851 Some(Self(fctx, Some(batch)))
3852 }
3853}
3854
3855impl Drop for WaveGuard<'_> {
3856 fn drop(&mut self) {
3857 let st = self.0.wave.with(|w| w.borrow_mut().take());
3858 if let Some(st) = st {
3859 st.q.lock().unwrap().closed = true;
3860 st.cv.notify_all();
3861 }
3862 let t0 = std::time::Instant::now();
3863 // Dropping the batch waits every worker out, as the joins did.
3864 drop(self.1.take());
3865 if wave_stats() {
3866 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3867 WS_TILES.fetch_add(1, Relaxed);
3868 wave_stats_dump();
3869 }
3870 }
3871}
3872
3873/// An empty buffer for the next superblock: the recycled one when it is at
3874/// least as big as the superblock just parsed, else a fresh sized one
3875/// (lane-sballoc; `v` is always empty).
3876fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> {
3877 if v.capacity() < cap {
3878 v.reserve_exact(cap - v.len());
3879 }
3880 v
3881}
3882
3883/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
3884/// when there is no wavefront (one reconstruction thread), in which case the
3885/// caller replays them itself.
3886fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
3887 let st = fctx.wave.with(|w| w.borrow().clone());
3888 let Some(st) = st else { return false };
3889 // lane-blockmem: the op list is replaced sized for the next superblock,
3890 // exactly as the two arenas below are -- taking it left a zero-capacity
3891 // `Vec` that regrew (and memmoved every recorded op) from nothing on
3892 // every superblock.
3893 // lane-sballoc: the replacement comes from the finished jobs' free list
3894 // when there is one (warm capacity, already faulted in); only the first
3895 // superblocks of a tile allocate.
3896 let mut q = st.q.lock().unwrap();
3897 let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default();
3898 let ops = fctx.recon_ops.with(|c| {
3899 let mut c = c.borrow_mut();
3900 let cap = c.len();
3901 std::mem::replace(&mut *c, reuse(sops, cap))
3902 });
3903 // The job owns its coefficients: the arena is replaced by an empty one
3904 // sized for the next superblock, so parse never regrows from nothing and
3905 // the worker frees this buffer once, instead of once per unit.
3906 let coeffs = fctx.coeff_arena.with(|c| {
3907 let mut c = c.borrow_mut();
3908 let cap = c.len();
3909 std::mem::replace(&mut *c, reuse(scoeffs, cap))
3910 });
3911 let preds = fctx.pred_arena.with(|c| {
3912 let mut c = c.borrow_mut();
3913 let cap = c.len();
3914 std::mem::replace(&mut *c, reuse(spreds, cap))
3915 });
3916 {
3917 if (c as isize) > q.last_sub[r] {
3918 q.last_sub[r] = c as isize;
3919 }
3920 if !ops.is_empty() {
3921 q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
3922 q.queued += 1;
3923 q.last_push[r] = c as isize;
3924 }
3925 drop(q);
3926 st.cv.notify_all();
3927 }
3928 if wave_stats() {
3929 let now = std::time::Instant::now();
3930 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
3931 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
3932 }
3933 }
3934 true
3935}
3936
3937/// Waits until every submitted job is reconstructed, so the parser may read
3938/// the planes itself (the intrabc source fetch and the interintra intra
3939/// predictor -- see [`flush_recon`]).
3940fn wave_barrier(fctx: &crate::decode::FrameCtx) {
3941 let st = fctx.wave.with(|w| w.borrow().clone());
3942 let Some(st) = st else { return };
3943 let stats = wave_stats();
3944 let t0 = std::time::Instant::now();
3945 let mut q = st.q.lock().unwrap();
3946 while q.queued > 0 || q.active > 0 {
3947 q = st.cv.wait(q).unwrap();
3948 }
3949 drop(q);
3950 if stats {
3951 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3952 WS_BARRIERS.fetch_add(1, Relaxed);
3953 }
3954}
3955
3956/// Performs an intra write at its push site when the tile registered its
3957/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
3958/// caller must record it for the wavefront workers instead.
3959#[allow(unsafe_code)]
3960#[allow(clippy::too_many_arguments)]
3961fn inline_intra(
3962 plane: usize,
3963 x: usize,
3964 oy: usize,
3965 bw: usize,
3966 bh: usize,
3967 rect: bool,
3968 mode: usize,
3969 angle_delta: i32,
3970 reach: Reach,
3971 residual: &[i32],
3972 cfl: Option<(i32, CflSrc)>,
3973 filter_intra: Option<usize>,
3974 smooth_neighbor: bool,
3975 fctx: &crate::decode::FrameCtx,
3976) -> bool {
3977 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3978 return false;
3979 };
3980 let pred = take_palette_pred(fctx);
3981 // SAFETY: see [`ReconPlanes`].
3982 unsafe {
3983 exec_intra(
3984 &mut *y,
3985 &mut *u,
3986 &mut *v,
3987 plane,
3988 x,
3989 oy,
3990 bw,
3991 bh,
3992 rect,
3993 mode,
3994 angle_delta,
3995 reach,
3996 residual,
3997 cfl,
3998 filter_intra,
3999 smooth_neighbor,
4000 pred,
4001 fctx,
4002 );
4003 }
4004 true
4005}
4006
4007/// [`inline_intra`] for a motion-compensated write.
4008#[allow(unsafe_code)]
4009#[allow(clippy::too_many_arguments)]
4010fn inline_mc(
4011 plane: usize,
4012 x: usize,
4013 oy: usize,
4014 stride: usize,
4015 w: usize,
4016 h: usize,
4017 prediction: &[u16],
4018 residual: &[i32],
4019 fctx: &crate::decode::FrameCtx,
4020) -> bool {
4021 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
4022 return false;
4023 };
4024 // SAFETY: see [`ReconPlanes`].
4025 unsafe {
4026 exec_mc(
4027 &mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx,
4028 );
4029 }
4030 true
4031}
4032
4033/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
4034#[allow(clippy::too_many_arguments)]
4035fn push_intra(
4036 plane: usize,
4037 x: usize,
4038 y: usize,
4039 side: usize,
4040 mode: usize,
4041 angle_delta: i32,
4042 reach: Reach,
4043 residual: &[i32],
4044 cfl: Option<(i32, CflSrc)>,
4045 filter_intra: Option<usize>,
4046 smooth_neighbor: bool,
4047 fctx: &crate::decode::FrameCtx,
4048) {
4049 if inline_intra(
4050 plane,
4051 x,
4052 y,
4053 side,
4054 side,
4055 false,
4056 mode,
4057 angle_delta,
4058 reach,
4059 residual,
4060 cfl,
4061 filter_intra,
4062 smooth_neighbor,
4063 fctx,
4064 ) {
4065 return;
4066 }
4067 let pred = take_palette_pred(fctx);
4068 push_op(
4069 fctx,
4070 ReconOp::Intra {
4071 plane,
4072 x,
4073 y,
4074 bw: side,
4075 bh: side,
4076 rect: false,
4077 mode,
4078 angle_delta,
4079 reach,
4080 residual: Residual::done(residual, fctx),
4081 cfl,
4082 filter_intra,
4083 smooth_neighbor,
4084 pred,
4085 },
4086 );
4087}
4088
4089/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
4090#[allow(clippy::too_many_arguments)]
4091fn push_intra_rect(
4092 plane: usize,
4093 x: usize,
4094 y: usize,
4095 bw: usize,
4096 bh: usize,
4097 mode: usize,
4098 angle_delta: i32,
4099 reach: Reach,
4100 residual: &[i32],
4101 cfl: Option<(i32, CflSrc)>,
4102 filter_intra: Option<usize>,
4103 smooth_neighbor: bool,
4104 fctx: &crate::decode::FrameCtx,
4105) {
4106 if inline_intra(
4107 plane,
4108 x,
4109 y,
4110 bw,
4111 bh,
4112 true,
4113 mode,
4114 angle_delta,
4115 reach,
4116 residual,
4117 cfl,
4118 filter_intra,
4119 smooth_neighbor,
4120 fctx,
4121 ) {
4122 return;
4123 }
4124 let pred = take_palette_pred(fctx);
4125 push_op(
4126 fctx,
4127 ReconOp::Intra {
4128 plane,
4129 x,
4130 y,
4131 bw,
4132 bh,
4133 rect: true,
4134 mode,
4135 angle_delta,
4136 reach,
4137 residual: Residual::done(residual, fctx),
4138 cfl,
4139 filter_intra,
4140 smooth_neighbor,
4141 pred,
4142 },
4143 );
4144}
4145
4146/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
4147fn push_mc(
4148 plane: usize,
4149 x: usize,
4150 y: usize,
4151 side: usize,
4152 prediction: Pred<'_>,
4153 residual: &[i32],
4154 fctx: &crate::decode::FrameCtx,
4155) {
4156 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
4157}
4158
4159/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
4160#[allow(clippy::too_many_arguments)]
4161#[track_caller]
4162fn push_mc_rect(
4163 plane: usize,
4164 x: usize,
4165 y: usize,
4166 stride: usize,
4167 w: usize,
4168 h: usize,
4169 prediction: Pred<'_>,
4170 residual: &[i32],
4171 fctx: &crate::decode::FrameCtx,
4172) {
4173 // lane-av1ibcfork: the PUSH site of an MC/inter write. The executed rung
4174 // (`EC_MCWR`, in `reconstruct_mc_rect`) can only name the dispatch, so
4175 // this is what names the block decoder that asked for the write -- the
4176 // only thing that distinguishes two writes of the same shape. It is what
4177 // localized a 4:4:4 intra-BC SKIP block committing its chroma plane block
4178 // at `(px/2, py/2)` instead of the ss origin, clobbering a neighbouring
4179 // block's reconstruction (lanes/av1ibcfork.report.md).
4180 if crate::envflags::env_flag!("EC_MCPUSH") {
4181 eprintln!(
4182 "EC_MCPUSH plane={plane} x={x} y={y} stride={stride} w={w} h={h} \
4183 res_len={} at {}",
4184 residual.len(),
4185 std::panic::Location::caller()
4186 );
4187 }
4188 let (src, stride) = match prediction.inline(stride) {
4189 Some(v) => v,
4190 None => {
4191 let Pred::Cur {
4192 plane: sp,
4193 stride: ss,
4194 off,
4195 } = prediction
4196 else {
4197 unreachable!()
4198 };
4199 push_op(
4200 fctx,
4201 ReconOp::Mc {
4202 plane,
4203 x,
4204 y,
4205 stride: ss,
4206 w,
4207 h,
4208 prediction: PredSrc::Cur {
4209 plane: sp,
4210 off,
4211 src: ss,
4212 },
4213 residual: Residual::done(residual, fctx),
4214 },
4215 );
4216 return;
4217 }
4218 };
4219 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
4220 return;
4221 }
4222 push_op(
4223 fctx,
4224 ReconOp::Mc {
4225 plane,
4226 x,
4227 y,
4228 stride,
4229 w,
4230 h,
4231 // The whole window `reconstruct_mc_rect` reads at `stride`, not
4232 // `w * h`: the record keeps exactly what `src.to_vec()` carried.
4233 prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
4234 residual: Residual::done(residual, fctx),
4235 },
4236 );
4237}
4238
4239/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
4240/// thread the transform runs here, exactly as before; on the wavefront it
4241/// travels with the op and runs on the worker (lane-wave3).
4242#[allow(clippy::too_many_arguments)]
4243fn push_intra_tx(
4244 plane: usize,
4245 x: usize,
4246 y: usize,
4247 bw: usize,
4248 bh: usize,
4249 rect: bool,
4250 mode: usize,
4251 angle_delta: i32,
4252 reach: Reach,
4253 tx: TxParams,
4254 grid: &[i32],
4255 cfl: Option<(i32, CflSrc)>,
4256 filter_intra: Option<usize>,
4257 smooth_neighbor: bool,
4258 fctx: &crate::decode::FrameCtx,
4259) {
4260 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
4261 inline_intra(
4262 plane,
4263 x,
4264 y,
4265 bw,
4266 bh,
4267 rect,
4268 mode,
4269 angle_delta,
4270 reach,
4271 &tx.run(grid),
4272 cfl,
4273 filter_intra,
4274 smooth_neighbor,
4275 fctx,
4276 );
4277 return;
4278 }
4279 let pred = take_palette_pred(fctx);
4280 push_op(
4281 fctx,
4282 ReconOp::Intra {
4283 plane,
4284 x,
4285 y,
4286 bw,
4287 bh,
4288 rect,
4289 mode,
4290 angle_delta,
4291 reach,
4292 residual: Residual::coeffs(tx, grid, fctx),
4293 cfl,
4294 filter_intra,
4295 smooth_neighbor,
4296 pred,
4297 },
4298 );
4299}
4300
4301/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
4302#[allow(clippy::too_many_arguments)]
4303fn push_mc_rect_tx(
4304 plane: usize,
4305 x: usize,
4306 y: usize,
4307 stride: usize,
4308 w: usize,
4309 h: usize,
4310 prediction: Pred<'_>,
4311 tx: TxParams,
4312 grid: &[i32],
4313 fctx: &crate::decode::FrameCtx,
4314) {
4315 // lane-wave4: a deferred prediction is not there to be windowed -- the
4316 // op carries its offset into the block's prediction instead, and the
4317 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
4318 // both buffers at one stride).
4319 let (prediction, stride) = match prediction.inline(stride) {
4320 Some(v) => v,
4321 None => {
4322 let Pred::Cur {
4323 plane: sp,
4324 stride: ss,
4325 off,
4326 } = prediction
4327 else {
4328 unreachable!()
4329 };
4330 let mut tx = tx;
4331 tx.stride = 0;
4332 push_op(
4333 fctx,
4334 ReconOp::Mc {
4335 plane,
4336 x,
4337 y,
4338 stride: w,
4339 w,
4340 h,
4341 prediction: PredSrc::Cur {
4342 plane: sp,
4343 off,
4344 src: ss,
4345 },
4346 residual: Residual::coeffs(tx, grid, fctx),
4347 },
4348 );
4349 return;
4350 }
4351 };
4352 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
4353 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
4354 // stride, so a prediction handed over at the block's stride (a var-tx
4355 // unit's window, lane-wave4) has to be densified for a dense residual
4356 // -- which is exactly what the recorded path below does.
4357 let residual = tx.run(grid);
4358 let res_stride = if tx.stride == 0 { w } else { tx.stride };
4359 let window;
4360 let prediction = if stride == res_stride {
4361 prediction
4362 } else {
4363 debug_assert_eq!(res_stride, w);
4364 let mut win = Vec::with_capacity(w * h);
4365 for row in 0..h {
4366 win.extend_from_slice(&prediction[row * stride..][..w]);
4367 }
4368 window = win;
4369 &window[..]
4370 };
4371 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
4372 return;
4373 }
4374 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
4375 // two buffers at `stride`, so the record carries that window densely
4376 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
4377 // copied 64*64 samples on the PARSING thread before. The residual is then
4378 // produced dense too (`TxParams::stride = 0`), which is the same numbers
4379 // in the same places at stride `w`.
4380 let off = fctx.pred_arena.with(|a| {
4381 let mut a = a.borrow_mut();
4382 let off = a.len();
4383 for row in 0..h {
4384 a.extend_from_slice(&prediction[row * stride..][..w]);
4385 }
4386 off as u32
4387 });
4388 let mut tx = tx;
4389 tx.stride = 0;
4390 push_op(
4391 fctx,
4392 ReconOp::Mc {
4393 plane,
4394 x,
4395 y,
4396 stride: w,
4397 w,
4398 h,
4399 prediction: PredSrc::Owned(off, (w * h) as u32),
4400 residual: Residual::coeffs(tx, grid, fctx),
4401 },
4402 );
4403}
4404
4405/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
4406/// and empties the queue (lane-wave1 step (i)).
4407///
4408/// Called at the top of each superblock visit and at the end of each tile, so
4409/// a whole superblock's parsing runs with no plane access at all; the two
4410/// parse-time pixel READS that survive -- the intrabc source fetch and the
4411/// interintra intra predictor -- flush ahead of themselves instead, which
4412/// keeps them byte-exact and names exactly what step (ii) still has to move.
4413fn flush_recon(
4414 fctx: &crate::decode::FrameCtx,
4415 y: &mut PlaneBuf<'static>,
4416 u: &mut PlaneBuf<'static>,
4417 v: &mut PlaneBuf<'static>,
4418) {
4419 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
4420 // writes in place, not just this superblock's queue.
4421 wave_barrier(fctx);
4422 let mut ops = fctx
4423 .recon_spare
4424 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4425 fctx.recon_ops
4426 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
4427 let mut coeffs = fctx
4428 .coeff_spare
4429 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4430 fctx.coeff_arena
4431 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
4432 let mut preds = fctx
4433 .pred_spare
4434 .with(|c| std::mem::take(&mut *c.borrow_mut()));
4435 fctx.pred_arena
4436 .with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
4437 let mut cur: [Vec<u16>; 3] = Default::default();
4438 for op in ops.drain(..) {
4439 exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
4440 }
4441 coeffs.clear();
4442 preds.clear();
4443 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
4444 fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
4445 fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
4446}
4447
4448/// Performs one recorded write: the body [`flush_recon`] replays, and the
4449/// body [`push_op`] runs immediately when reconstruction is inline.
4450fn exec_op(
4451 op: ReconOp,
4452 y: &mut PlaneBuf<'static>,
4453 u: &mut PlaneBuf<'static>,
4454 v: &mut PlaneBuf<'static>,
4455 cur: &mut [Vec<u16>; 3],
4456 coeffs: &[i32],
4457 preds: &[u16],
4458 fctx: &crate::decode::FrameCtx,
4459) {
4460 // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel
4461 // write, leaving the entropy parse and the per-mi neighbour bookkeeping
4462 // alone. It makes the encoder's own streams garbage, so it is a
4463 // MEASUREMENT rung only -- what it measures is how much of the encoder's
4464 // first decode of its own tiles (`par::S_FIRST`) is reconstruction and
4465 // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile
4466 // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that
4467 // stage and the parse plus the neighbour grids are the other 94%. That
4468 // is why handing the decoder the encoder's own reconstruction cannot
4469 // shrink the stage: only publishing the per-mi neighbour state the
4470 // filters read (and so never parsing at all) can.
4471 if crate::envflags::env_flag!("EC_AV1_NORECON") {
4472 return;
4473 }
4474 let mut scratch = Vec::new();
4475 match op {
4476 ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur),
4477 ReconOp::Intra {
4478 plane,
4479 x,
4480 y: oy,
4481 bw,
4482 bh,
4483 rect,
4484 mode,
4485 angle_delta,
4486 reach,
4487 residual,
4488 cfl,
4489 filter_intra,
4490 smooth_neighbor,
4491 pred,
4492 } => exec_intra(
4493 y,
4494 u,
4495 v,
4496 plane,
4497 x,
4498 oy,
4499 bw,
4500 bh,
4501 rect,
4502 mode,
4503 angle_delta,
4504 reach,
4505 residual.resolve(coeffs, &mut scratch),
4506 cfl,
4507 filter_intra,
4508 smooth_neighbor,
4509 pred,
4510 fctx,
4511 ),
4512 ReconOp::Mc {
4513 plane,
4514 x,
4515 y: oy,
4516 stride,
4517 w,
4518 h,
4519 prediction,
4520 residual,
4521 } => {
4522 let residual = residual.resolve(coeffs, &mut scratch);
4523 match prediction {
4524 PredSrc::Owned(off, len) => {
4525 let p = &preds[off as usize..][..len as usize];
4526 exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
4527 }
4528 PredSrc::Cur {
4529 plane: sp,
4530 off,
4531 src,
4532 } => {
4533 let block = std::mem::take(&mut cur[sp]);
4534 if src == stride {
4535 exec_mc(
4536 y,
4537 u,
4538 v,
4539 plane,
4540 x,
4541 oy,
4542 stride,
4543 w,
4544 h,
4545 &block[off..],
4546 residual,
4547 fctx,
4548 );
4549 } else {
4550 // A transform unit's residual is dense, so its window
4551 // of the block prediction is taken out dense too --
4552 // the copy the parsing thread used to make, made here.
4553 let mut window = Vec::with_capacity(w * h);
4554 for row in 0..h {
4555 window.extend_from_slice(&block[off + row * src..][..w]);
4556 }
4557 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
4558 }
4559 cur[sp] = block;
4560 }
4561 }
4562 }
4563 }
4564}
4565
4566/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
4567/// path ([`push_op`]'s registered planes) reaches it without ever building
4568/// the record -- which is what keeps one reconstruction thread at the cost of
4569/// the pre-lane-wave1 decoder.
4570#[allow(clippy::too_many_arguments)]
4571fn exec_intra(
4572 y: &mut PlaneBuf<'static>,
4573 u: &mut PlaneBuf<'static>,
4574 v: &mut PlaneBuf<'static>,
4575 plane: usize,
4576 x: usize,
4577 oy: usize,
4578 bw: usize,
4579 bh: usize,
4580 rect: bool,
4581 mode: usize,
4582 angle_delta: i32,
4583 reach: Reach,
4584 residual: &[i32],
4585 cfl: Option<(i32, CflSrc)>,
4586 filter_intra: Option<usize>,
4587 smooth_neighbor: bool,
4588 pred: Option<Vec<u16>>,
4589 fctx: &crate::decode::FrameCtx,
4590) {
4591 // The CfL AC signal is read HERE, off the luma that has already been
4592 // written for this block -- at parse time it would have been the previous
4593 // frame's samples.
4594 let ac = cfl.map(|(alpha, src)| {
4595 let sig = cfl_ac_ss(&*y, src.px, src.py, src.bw, src.bh, ss_x(fctx), ss_y(fctx));
4596 (alpha, sig)
4597 });
4598 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
4599 let target: &mut PlaneBuf<'static> = match plane {
4600 0 => &mut *y,
4601 1 => &mut *u,
4602 _ => &mut *v,
4603 };
4604 // lane-av1cmpaudit: label the in-flight reconstruction's plane for the
4605 // `EC_PRED` rung (aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`).
4606 // Saved and restored so the rung reports THIS call's plane even under
4607 // nesting, and so both of exec_intra's return paths need no cleanup.
4608 let prev_plane = RECON_PLANE.with(|c| c.replace(plane));
4609 let _plane_guard = PlaneGuard(prev_plane);
4610 if rect {
4611 target.reconstruct_rect(
4612 x,
4613 oy,
4614 bw,
4615 bh,
4616 mode,
4617 angle_delta,
4618 reach,
4619 residual,
4620 cfl,
4621 filter_intra,
4622 smooth_neighbor,
4623 pred,
4624 fctx,
4625 );
4626 } else {
4627 target.reconstruct(
4628 x,
4629 oy,
4630 bw,
4631 mode,
4632 angle_delta,
4633 reach,
4634 residual,
4635 cfl,
4636 filter_intra,
4637 smooth_neighbor,
4638 pred,
4639 fctx,
4640 );
4641 }
4642}
4643
4644/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
4645#[allow(clippy::too_many_arguments)]
4646fn exec_mc(
4647 y: &mut PlaneBuf<'static>,
4648 u: &mut PlaneBuf<'static>,
4649 v: &mut PlaneBuf<'static>,
4650 plane: usize,
4651 x: usize,
4652 oy: usize,
4653 stride: usize,
4654 w: usize,
4655 h: usize,
4656 prediction: &[u16],
4657 residual: &[i32],
4658 fctx: &crate::decode::FrameCtx,
4659) {
4660 let target: &mut PlaneBuf<'static> = match plane {
4661 0 => &mut *y,
4662 1 => &mut *u,
4663 _ => &mut *v,
4664 };
4665 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
4666}
4667
4668thread_local! {
4669 /// The current frame's `mi` grid, kept only while a frame header set
4670 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
4671 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
4672 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
4673 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
4674 /// does not allow intrabc (so nothing is paid for it).
4675 ///
4676 /// corner-cut: only [`decode_block`] (the square path) records into it,
4677 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
4678 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
4679 /// be wrong there; upgrade = record from the rect/leaf paths too.
4680 /// The block vector [`read_intra_mode`] just decoded, handed to
4681 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
4682 /// which the alternative -- a tenth tuple member through every caller --
4683 /// already avoids). Always `.take()`n by the block that reads it.
4684 /// How many blocks read `use_intrabc == 1` and took the DV path -- the
4685 /// gate's hit counter. Bumped on the READ, before the rect-strip refusal
4686 /// returns too, so it counts reads, not reconstructions (a refused block
4687 /// is never reconstructed).
4688 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4689}
4690// The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
4691// an intrabc block's chroma reads can inherit it (see
4692// [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
4693// through that one arming site.
4694// libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
4695// branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
4696// satisfies (`blockd.h:373`) -- and takes the *colocated luma
4697// transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
4698// `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
4699// intrabc block's two chroma [`read_plane`] calls; the type decides the
4700// `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
4701// -- getting it wrong desyncs the chroma coefficients, it is not a
4702// reconstruction-only detail.
4703
4704/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
4705/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
4706/// needs no separate plumbing to reach the rect-strip mode reader.
4707fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
4708 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
4709}
4710
4711thread_local! {
4712 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
4713 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
4714 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
4715 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4716}
4717
4718/// Current value of [`RECT_INTRABC_READS`].
4719pub(crate) fn rect_intrabc_reads() -> usize {
4720 RECT_INTRABC_READS.with(|c| c.get())
4721}
4722
4723/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
4724#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4725pub(crate) fn reset_rect_intrabc_reads() {
4726 RECT_INTRABC_READS.with(|c| c.set(0));
4727}
4728
4729thread_local! {
4730 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
4731 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
4732 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4733}
4734
4735thread_local! {
4736 /// Chroma reads of an intrabc TX4-split leaf that consulted an ARMED
4737 /// [`INTRABC_CHROMA_TX`] slot -- proof that the arm's frame-copy +
4738 /// inherited-type route actually ran (lane-av1intrapred r2's non-vacuity
4739 /// counter: zero means the gate's fixture no longer reaches the route).
4740 static INTRABC_TX4_CHROMA_COPY_HITS: std::cell::Cell<usize> =
4741 const { std::cell::Cell::new(0) };
4742}
4743
4744/// Current value of [`INTRABC_TX4_CHROMA_COPY_HITS`].
4745#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4746pub(crate) fn intrabc_tx4_chroma_copy_hits() -> usize {
4747 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.get())
4748}
4749
4750/// Zeroes [`INTRABC_TX4_CHROMA_COPY_HITS`] (gate tests call this before a decode).
4751#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4752pub(crate) fn reset_intrabc_tx4_chroma_copy_hits() {
4753 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.set(0));
4754}
4755
4756/// Current value of [`LEAF8_INTRABC_HITS`].
4757pub(crate) fn leaf8_intrabc_hits() -> usize {
4758 LEAF8_INTRABC_HITS.with(|c| c.get())
4759}
4760
4761/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
4762#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4763pub(crate) fn reset_leaf8_intrabc_hits() {
4764 LEAF8_INTRABC_HITS.with(|c| c.set(0));
4765}
4766
4767/// Current value of [`INTRABC_HITS`].
4768#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4769pub(crate) fn intrabc_hits() -> usize {
4770 INTRABC_HITS.with(|c| c.get())
4771}
4772
4773thread_local! {
4774 /// An intrabc block that IS a sub-8x8 group's CHROMA REFERENCE and is
4775 /// SKIPPED: the route that arms [`INTRABC_CHROMA_TX`] and then reads no
4776 /// chroma coefficient at all, so the slot used to stay armed into the NEXT
4777 /// block's chroma read. Both group shapes (4x4 split, 4x8/8x4 rect) count
4778 /// here. A non-zero value is what makes the disarm below load-bearing.
4779 static SKIPPED_INTRABC_CHROMA_ARM_HITS: std::cell::Cell<usize> =
4780 const { std::cell::Cell::new(0) };
4781}
4782
4783/// Current value of [`SKIPPED_INTRABC_CHROMA_ARM_HITS`].
4784#[allow(dead_code)] // read only from the `#[cfg(test)]` gates and the probe
4785pub(crate) fn skipped_intrabc_chroma_arm_hits() -> usize {
4786 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.get())
4787}
4788
4789/// Zeroes [`SKIPPED_INTRABC_CHROMA_ARM_HITS`] (gate tests call this before a
4790/// decode).
4791#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4792pub(crate) fn reset_skipped_intrabc_chroma_arm_hits() {
4793 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.set(0));
4794}
4795
4796thread_local! {
4797 /// lane-av1-ibcskip2: a sub-8x8 4:4:4 leaf that is BOTH intrabc AND
4798 /// `skip` -- the arm whose chroma is the bare frame copy at the DV
4799 /// (libaom `av1_build_inter_predictors_sb` runs regardless of `skip`).
4800 /// Before the fix this route predicted intra-DC and every one of this
4801 /// fixture's 150 such cells differed from the oracle on both chroma
4802 /// planes.
4803 static SKIPPED_INTRABC_DV_COPY_HITS: std::cell::Cell<usize> =
4804 const { std::cell::Cell::new(0) };
4805}
4806
4807/// Current value of [`SKIPPED_INTRABC_DV_COPY_HITS`].
4808#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4809pub(crate) fn skipped_intrabc_dv_copy_hits() -> usize {
4810 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.get())
4811}
4812
4813/// Zeroes [`SKIPPED_INTRABC_DV_COPY_HITS`] (gate tests call this before a
4814/// decode).
4815#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4816pub(crate) fn reset_skipped_intrabc_dv_copy_hits() {
4817 SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.set(0));
4818}
4819
4820/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
4821#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4822pub(crate) fn reset_intrabc_hits() {
4823 INTRABC_HITS.with(|c| c.set(0));
4824}
4825
4826thread_local! {
4827 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
4828 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
4829 /// that replaced the refusal "an intrabc block under TxMode::Select".
4830 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4831 /// lane-av1-ibcvtx: intrabc var-tx trees that resolved to MIXED leaf
4832 /// sizes (not one square size across every leaf) -- the engagement
4833 /// counter proving a witness actually exercises the per-leaf reconstruct.
4834 static INTRABC_VARTX_MIXED_LEAVES_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4835 /// lane-av1txr: as above for a `BLOCK_4X8`/`BLOCK_8X4` intrabc leaf --
4836 /// libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`, so these leaves
4837 /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no
4838 /// symbol here desynced `warped.obu` at the very next block.
4839 static RECT_INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4840 /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction
4841 /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip
4842 /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never
4843 /// this one).
4844 static INTRABC_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4845 /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT).
4846 static INTRABC_RECT_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4847 /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction
4848 /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read),
4849 /// split by the strip's orientation -- `bw > bh` is a HORZ strip,
4850 /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED
4851 /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS`
4852 /// counts neither orientation nor the skip flag, so an arm that flipped
4853 /// to an all-skip stream (no residual reader at all) would stay green.
4854 static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> =
4855 const { std::cell::Cell::new([0, 0]) };
4856 /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`]
4857 /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split
4858 /// by orientation. The r5 panic (residual stride `bw * bh` underrunning
4859 /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was
4860 /// invisible to every gate because they only counted CODED strips.
4861 static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> =
4862 const { std::cell::Cell::new([0, 0]) };
4863 /// lane-ibc444c: rect intra-BC blocks whose chroma plane block was sized
4864 /// `bw >> ss_x` by `bh >> ss_y` -- the 4:4:4 and 4:4:0 cells, where
4865 /// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h) applies no
4866 /// halving of its own. At 4:2:0 this is the same arithmetic as the halving,
4867 /// so a `>= 1` witness can only come from a stream that is not 4:2:0.
4868 /// EXCLUSIVE to this arm: no other caller sizes an intrabc rect block's
4869 /// chroma plane block.
4870 static IBC_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell<usize> =
4871 const { std::cell::Cell::new(0) };
4872 /// lane-whtshape: LOSSLESS rect intrabc blocks whose chroma plane block
4873 /// [`decode_intrabc_rect`] walked as a `(cw/4) * (ch/4)` PLANE-MAJOR
4874 /// raster of TX_4X4 units -- the shape libaom's lossless geometry codes
4875 /// (`read_tx_size` returns `TX_4X4` for EVERY plane of a lossless block,
4876 /// `get_vartx_max_txsize` likewise, and `read_tx_mode` forced the frame's
4877 /// `ONLY_4X4`) -- instead of the single rect unit, which is what put a
4878 /// non-4x4 unit on the lossless Walsh-Hadamard path. EXCLUSIVE to this arm:
4879 /// no other caller walks a rect intrabc block's chroma, so `>= 1` cannot
4880 /// be satisfied by any older route.
4881 static INTRABC_RECT_LOSSLESS_CHROMA4_HITS: std::cell::Cell<usize> =
4882 const { std::cell::Cell::new(0) };
4883 /// lane-av1chromarect: 128-root intra-BC HORZ/VERT strips
4884 /// ([`decode_intrabc_owned_rect`]) whose chroma plane block was sized
4885 /// `bw >> ss_x` by `bh >> ss_y` -- the 4:4:4 and 4:4:0 cells, where
4886 /// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h:1372) applies
4887 /// no halving of its own. At 4:2:0 the two forms are the same arithmetic,
4888 /// so a `>= 1` witness can only come from a stream that is not 4:2:0.
4889 /// EXCLUSIVE to this arm: no other caller sizes a 128-root intra-BC
4890 /// strip's chroma plane block.
4891 static IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell<usize> =
4892 const { std::cell::Cell::new(0) };
4893}
4894
4895/// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed,
4896/// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`].
4897#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4898pub fn intrabc_rect_coded_hits() -> [usize; 2] {
4899 INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get)
4900}
4901
4902/// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks
4903/// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`].
4904#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4905pub fn intrabc_rect_skipped_hits() -> [usize; 2] {
4906 INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get)
4907}
4908
4909/// Current value of [`INTRABC_RECT_HITS`].
4910#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4911pub fn intrabc_rect_hits() -> usize {
4912 INTRABC_RECT_HITS.with(|c| c.get())
4913}
4914
4915/// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`].
4916#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4917pub(crate) fn reset_intrabc_rect_hits() {
4918 INTRABC_RECT_HITS.with(|c| c.set(0));
4919 INTRABC_RECT_VARTX_HITS.with(|c| c.set(0));
4920 INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0]));
4921 INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0]));
4922}
4923
4924/// lane-ibc444c: [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`].
4925#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4926pub fn ibc_rect_chroma_footprint_444_hits() -> usize {
4927 IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get())
4928}
4929
4930/// lane-ibc444c: zeroes [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`].
4931#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4932pub(crate) fn reset_ibc_rect_chroma_footprint_444_hits() {
4933 IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0));
4934}
4935
4936/// lane-av1chromarect: [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`].
4937#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4938pub fn ibc_owned_rect_chroma_footprint_444_hits() -> usize {
4939 IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get())
4940}
4941
4942/// lane-av1chromarect: zeroes [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`].
4943#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4944pub(crate) fn reset_ibc_owned_rect_chroma_footprint_444_hits() {
4945 IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0));
4946}
4947
4948/// lane-whtshape: [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
4949#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4950pub fn intrabc_rect_lossless_chroma4_hits() -> usize {
4951 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.get())
4952}
4953
4954/// lane-whtshape: zeroes [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`].
4955#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4956pub(crate) fn reset_intrabc_rect_lossless_chroma4_hits() {
4957 INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.set(0));
4958}
4959
4960/// Current value of [`INTRABC_RECT_VARTX_HITS`].
4961#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4962pub fn intrabc_rect_vartx_hits() -> usize {
4963 INTRABC_RECT_VARTX_HITS.with(|c| c.get())
4964}
4965
4966thread_local! {
4967 /// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip
4968 /// (BLOCK_128X64 / BLOCK_64X128) whose reconstruction
4969 /// [`decode_intrabc_128rect`] ran -- the shape the named refusal used to
4970 /// guard (`decode_block_128rect`). A refused block bumps
4971 /// [`INTRABC_HITS`] but never this one.
4972 static INTRABC_128RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4973 /// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc
4974 /// strip's mu-chunk walk read, one per `read_inter_plane` chroma call.
4975 /// At 4:2:0 a 64x64 mu chunk's chroma plane block is 32x32, so one
4976 /// TX_32X32 per plane per chunk; at 4:2:2 it is 32x64 and holds TWO
4977 /// STACKED units per plane. The square-cut `chunk_chroma = cside * 64 /
4978 /// side` model walked the 4:2:0 count on every axis, so this counter is
4979 /// the reach/arm witness for the per-axis walk.
4980 static INTRABC_128RECT_CHROMA_CHUNK_HITS: std::cell::Cell<usize> =
4981 const { std::cell::Cell::new(0) };
4982 /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as
4983 /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the
4984 /// per-axis walk used. A 4:2:2 run and a 4:2:0 run of the same block
4985 /// differ here (32|64 vs 32|32), which is what the de-square-cut fixes.
4986 static INTRABC_128RECT_CHUNK_SHAPE: std::cell::Cell<usize> =
4987 const { std::cell::Cell::new(0) };
4988}
4989
4990/// Current value of [`INTRABC_128RECT_HITS`].
4991#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4992pub fn intrabc_128rect_hits() -> usize {
4993 INTRABC_128RECT_HITS.with(|c| c.get())
4994}
4995
4996/// Zeroes [`INTRABC_128RECT_HITS`].
4997#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4998pub(crate) fn reset_intrabc_128rect_hits() {
4999 INTRABC_128RECT_HITS.with(|c| c.set(0));
5000}
5001
5002/// Current value of [`INTRABC_128RECT_CHROMA_CHUNK_HITS`].
5003#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5004pub fn intrabc_128rect_chroma_chunk_hits() -> usize {
5005 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.get())
5006}
5007
5008/// Current value of [`INTRABC_128RECT_CHUNK_SHAPE`].
5009#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5010pub fn intrabc_128rect_chunk_shape() -> usize {
5011 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.get())
5012}
5013
5014/// Zeroes [`INTRABC_128RECT_CHROMA_CHUNK_HITS`] and
5015/// [`INTRABC_128RECT_CHUNK_SHAPE`].
5016#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5017pub(crate) fn reset_intrabc_128rect_chroma_chunk_hits() {
5018 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(0));
5019 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.set(0));
5020}
5021
5022/// Current value of [`INTRABC_VARTX_HITS`].
5023pub fn intrabc_vartx_hits() -> usize {
5024 INTRABC_VARTX_HITS.with(|c| c.get())
5025}
5026
5027/// Current value of [`INTRABC_VARTX_MIXED_LEAVES_HITS`].
5028pub fn intrabc_vartx_mixed_leaves_hits() -> usize {
5029 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.get())
5030}
5031
5032/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
5033#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5034pub(crate) fn reset_intrabc_vartx_hits() {
5035 INTRABC_VARTX_HITS.with(|c| c.set(0));
5036}
5037
5038/// Zeroes [`INTRABC_VARTX_MIXED_LEAVES_HITS`] (gate tests call this before a
5039/// decode).
5040#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5041pub(crate) fn reset_intrabc_vartx_mixed_leaves_hits() {
5042 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.set(0));
5043}
5044
5045/// Current value of [`RECT_INTRABC_VARTX_HITS`].
5046#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5047pub fn rect_intrabc_vartx_hits() -> usize {
5048 RECT_INTRABC_VARTX_HITS.with(|c| c.get())
5049}
5050
5051/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
5052/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
5053/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
5054/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
5055fn record_intrabc_mi(
5056 mi_r: usize,
5057 mi_c: usize,
5058 n4: usize,
5059 dv: Option<(i32, i32)>,
5060 n: &mut Neighbours,
5061 fctx: &crate::decode::FrameCtx,
5062) {
5063 record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx);
5064}
5065
5066/// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs`
5067/// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4`
5068/// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr).
5069///
5070/// Also stamps libaom's `is_inter_block` verdict for this block into the
5071/// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override
5072/// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] >
5073/// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and
5074/// `get_tx_size_context` reads its BLOCK size rather than its transform band.
5075/// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which
5076/// every block runs; this runs after it (class leaked-band otherwise).
5077fn record_intrabc_mi_rect(
5078 mi_r: usize,
5079 mi_c: usize,
5080 n4_w: usize,
5081 n4_h: usize,
5082 dv: Option<(i32, i32)>,
5083 n: &mut Neighbours,
5084 fctx: &crate::decode::FrameCtx,
5085) {
5086 if dv.is_some() {
5087 for i in 0..n4_w {
5088 if let Some(cell) = n.above_inter.get_mut(mi_c + i) {
5089 *cell = true;
5090 }
5091 }
5092 for i in 0..n4_h {
5093 if let Some(cell) = n.left_inter.get_mut(mi_r + i) {
5094 *cell = true;
5095 }
5096 }
5097 // lane-av1txctxband: the per-CELL `is_inter_block` an INTRABC block
5098 // publishes (`blockd.h:372-374` counts it), at the granularity
5099 // `get_tx_size_context` reads it. The band above is one slot per
5100 // column and so survives every later block in that column.
5101 n.mark_inter_grid_rect((mi_r, mi_c), n4_w, n4_h, true);
5102 }
5103 fctx.intrabc_mi_grid.with(|g| {
5104 let mut g = g.borrow_mut();
5105 let Some((grid, _, _)) = g.as_mut() else {
5106 return;
5107 };
5108 let info = crate::mvstack::MiInfo {
5109 is_inter: dv.is_some(),
5110 ref_frame: 0,
5111 ref_frame1: NO_REF1,
5112 mv: mv16(dv.unwrap_or((0, 0))),
5113 mv1: (0, 0),
5114 is_new_mv: dv.is_some(),
5115 is_global_mv0: false,
5116 is_global_mv1: false,
5117 size: n4_w as u8,
5118 size_h: n4_h as u8,
5119 };
5120 for r in mi_r..mi_r + n4_h {
5121 for c in mi_c..mi_c + n4_w {
5122 grid.set(r, c, info);
5123 }
5124 }
5125 });
5126}
5127
5128// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
5129// proves a real `skip_mode_present` stream actually reached a block that
5130// picked it, not just that the frame header bit was set.
5131thread_local! {
5132 static SKIP_MODE_HITS: std::cell::Cell<usize> =
5133 const { std::cell::Cell::new(0) };
5134}
5135
5136/// Current value of [`SKIP_MODE_HITS`].
5137#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5138pub(crate) fn skip_mode_hits() -> usize {
5139 SKIP_MODE_HITS.with(|c| c.get())
5140}
5141
5142// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
5143// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
5144// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
5145// reached [`obmc_blend`], not just the header bit.
5146thread_local! {
5147 static OBMC_HITS: std::cell::Cell<usize> =
5148 const { std::cell::Cell::new(0) };
5149}
5150
5151// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
5152// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
5153// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
5154// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
5155// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
5156// decoder used to read with the wrong alphabet, so a gate that asserts this
5157// counter advanced proves the fixed path fired (class
5158// `gate-blind-to-feature`).
5159thread_local! {
5160 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5161}
5162
5163/// Current value of [`FIMV_ALPHABET_HITS`].
5164pub fn fimv_alphabet_hits() -> usize {
5165 FIMV_ALPHABET_HITS.with(|c| c.get())
5166}
5167
5168// lane-fimv r1: how many frame headers this decoder has decoded with
5169// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
5170// prove the encoder really produced the header state under test rather than
5171// assume it.
5172thread_local! {
5173 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5174}
5175
5176/// Current value of [`FIMV_FRAME_HITS`].
5177pub fn fimv_frame_hits() -> usize {
5178 FIMV_FRAME_HITS.with(|c| c.get())
5179}
5180
5181/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
5182/// `force_integer_mv` bit is set.
5183pub fn note_force_integer_mv_frame() {
5184 hit!(FIMV_FRAME_HITS);
5185}
5186
5187/// Current value of [`OBMC_HITS`].
5188#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5189pub(crate) fn obmc_hits() -> usize {
5190 OBMC_HITS.with(|c| c.get())
5191}
5192
5193// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
5194// off the neighbour band -- the positive half of the proof for "an OBMC
5195// neighbour whose switchable interp filter was never recorded". A
5196// fixed-filter frame returns before this point (its neighbours legitimately
5197// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
5198// `interp_filter` symbols were published by `record_inter_rect_mi`.
5199thread_local! {
5200 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5201}
5202
5203/// Current value of [`OBMC_FILTER_BAND_READS`].
5204#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5205pub(crate) fn obmc_filter_band_reads() -> usize {
5206 OBMC_FILTER_BAND_READS.with(|c| c.get())
5207}
5208
5209// lane-scaledref r1: per-case firing counts for the scaled-reference gate
5210// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
5211// reference would pass just as well and prove nothing, so the gate
5212// hard-asserts each combination this round lifts actually occurred:
5213// a compound block with a scaled tap, a warp block whose warp libaom
5214// suppresses because the reference is scaled, an OBMC block, an interintra
5215// block, and an 8x8 leaf.
5216thread_local! {
5217 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5218 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5219 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5220 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5221 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5222 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5223 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5224}
5225
5226/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
5227/// scaled and one unscaled tap.
5228#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5229pub(crate) fn mixed_scale_compound_hits() -> usize {
5230 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
5231}
5232
5233/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
5234/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
5235/// instead because their reference is scaled (libaom `motion_mode_allowed`,
5236/// `blockd.h:1484`).
5237#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5238pub(crate) fn scaled_warp_suppressed_hits() -> usize {
5239 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
5240}
5241
5242/// Current value of [`SCALED_COMPOUND_HITS`].
5243#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5244pub(crate) fn scaled_compound_hits() -> usize {
5245 SCALED_COMPOUND_HITS.with(|c| c.get())
5246}
5247
5248/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
5249pub fn scaled_warp_fallback_hits() -> usize {
5250 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
5251}
5252
5253/// Current value of [`SCALED_OBMC_HITS`].
5254#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5255pub(crate) fn scaled_obmc_hits() -> usize {
5256 SCALED_OBMC_HITS.with(|c| c.get())
5257}
5258
5259/// Current value of [`SCALED_INTERINTRA_HITS`].
5260#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5261pub(crate) fn scaled_interintra_hits() -> usize {
5262 SCALED_INTERINTRA_HITS.with(|c| c.get())
5263}
5264
5265/// Current value of [`SCALED_BLOCK8_HITS`].
5266#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5267pub(crate) fn scaled_block8_hits() -> usize {
5268 SCALED_BLOCK8_HITS.with(|c| c.get())
5269}
5270
5271// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
5272// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
5273// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
5274// 8x8-leaf OBMC block apart from a 16x16+ one.
5275thread_local! {
5276 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5277}
5278
5279// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
5280// pair whose two directions differ (`enable_dual_filter` only -- with dual
5281// filter off both directions take the single symbol, so this can never fire).
5282// A gate asserting it proves the stream really carries dual-filter blocks.
5283thread_local! {
5284 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5285}
5286
5287// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
5288// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
5289// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
5290// no-filter sentinel that made a neighbouring OBMC block panic).
5291thread_local! {
5292 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5293}
5294
5295/// Current value of [`DUAL_FILTER_DIFF_HITS`].
5296#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5297pub(crate) fn dual_filter_diff_hits() -> usize {
5298 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
5299}
5300
5301/// Current value of [`COMPOUND8_FILTER_HITS`].
5302#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5303pub(crate) fn compound8_filter_hits() -> usize {
5304 COMPOUND8_FILTER_HITS.with(|c| c.get())
5305}
5306
5307// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
5308// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
5309// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
5310// -- the gate's proof that a fixture really exercises the alphabet this
5311// round changed, even though the block itself still refuses (warp
5312// estimation/filter not ported).
5313thread_local! {
5314 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
5315 const { std::cell::Cell::new(0) };
5316}
5317
5318/// Current value of [`WARP_SELECTED_HITS`].
5319#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5320pub(crate) fn warp_selected_hits() -> usize {
5321 WARP_SELECTED_HITS.with(|c| c.get())
5322}
5323
5324// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
5325// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
5326// into the compound intermediate) rather than translationally -- the
5327// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
5328// really reached [`crate::warp::warp_affine_compound`].
5329// lane-av1422warp: the 4:2:2 coverage witness has to show compound and warped
5330// motion firing ABOVE the vertical midpoint, and every pre-existing warp
5331// counter is frame-global. These two are the same arms restricted to blocks
5332// whose top mode-info row is in the frame's upper half, which is the half
5333// this lane's evidence covers.
5334thread_local! {
5335 static TOP_HALF_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5336 static TOP_HALF_WARP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5337}
5338
5339/// How many `GLOBAL_GLOBALMV` (compound) inter blocks decoded in the frame's
5340/// upper half -- the block's top mode-info row is under `mi_rows / 2`.
5341///
5342/// NO COMMITTED TEST READS THIS, and none can while the 4:2:2 header refusal
5343/// stands: the pinned 4:2:2 coverage gate asserts the byte pin and the
5344/// refusal by name, so nothing in the suite ever decodes a 4:2:2 stream.
5345/// The figure quoted for that fixture comes from a patch-run-restore build
5346/// with the `EC_AV1_ALLOW_422_PROBE` bypass applied and then reverted, which
5347/// is the same discipline every 4:2:2 lane in this family uses.
5348#[allow(dead_code)]
5349pub(crate) fn top_half_compound_hits() -> usize {
5350 TOP_HALF_COMPOUND_HITS.with(std::cell::Cell::get)
5351}
5352
5353/// How many inter blocks in the frame's upper half satisfy libaom's
5354/// `is_global_mv_block` on at least one reference slot -- mode
5355/// `GLOBAL_GLOBALMV` AND block >= 8x8 AND that slot's own global-motion
5356/// model > `TRANSLATION`. This is the block set whose prediction goes
5357/// through `crate::warp`, and it is exactly `is_global_mv0 || is_global_mv1`
5358/// as computed at the increment site; it is NOT merely "some slot has a
5359/// non-TRANSLATION model", which also counts blocks that are not global-mv
5360/// blocks.
5361///
5362/// Like [`top_half_compound_hits`], no committed test reads it: with the
5363/// 4:2:2 header refusal in force nothing in the suite decodes the stream
5364/// these numbers describe.
5365#[allow(dead_code)]
5366pub(crate) fn top_half_warp_hits() -> usize {
5367 TOP_HALF_WARP_HITS.with(std::cell::Cell::get)
5368}
5369
5370thread_local! {
5371 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
5372 const { std::cell::Cell::new(0) };
5373}
5374
5375/// Current value of [`COMPOUND_WARP_HITS`].
5376#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5377pub(crate) fn compound_warp_hits() -> usize {
5378 COMPOUND_WARP_HITS.with(|c| c.get())
5379}
5380
5381// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
5382// arm ([`decode_inter_block8`]) -- that arm predicted both taps
5383// translationally until r3, so a gate needs to tell a warped 8x8 compound
5384// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
5385thread_local! {
5386 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
5387 const { std::cell::Cell::new(0) };
5388}
5389
5390/// Current value of [`COMPOUND_WARP_HITS_8`].
5391#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5392pub(crate) fn compound_warp_hits_8() -> usize {
5393 COMPOUND_WARP_HITS_8.with(|c| c.get())
5394}
5395
5396// lane-gmaffine r1: how many blocks built their prediction from a
5397// SIX-parameter (`AFFINE`) global-motion model through
5398// `crate::warp::global_warp_params` -- the gate's proof that a stream really
5399// carried an AFFINE `global_motion_params` AND that a block was predicted
5400// with it, not merely that the header parsed one.
5401thread_local! {
5402 static AFFINE_GM_HITS: std::cell::Cell<usize> =
5403 const { std::cell::Cell::new(0) };
5404}
5405
5406/// Current value of [`AFFINE_GM_HITS`].
5407#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5408pub(crate) fn affine_gm_hits() -> usize {
5409 AFFINE_GM_HITS.with(|c| c.get())
5410}
5411
5412// lane-av1distwtd: how many blocks took the DISTANCE-WEIGHTED compound
5413// combine rather than the simple average -- `compound_idx == 0` under
5414// `enable_jnt_comp`, whose weights come from
5415// [`crate::compound::dist_wtd_comp_weight_assign`] instead of the constant
5416// `(8, 8)` split. Counting the `idx == 0` arm (not merely the
5417// `compound_idx` symbol read) is what makes this a witness of the TOOL: a
5418// stream that carries `enable_jnt_comp = true` in its sequence header but
5419// codes every compound block with `compound_idx == 1` leaves this at 0 and
5420// decoded identically without the whole distance-weight path.
5421thread_local! {
5422 static DIST_WTD_COMP_HITS: std::cell::Cell<usize> =
5423 const { std::cell::Cell::new(0) };
5424}
5425
5426/// Current value of [`DIST_WTD_COMP_HITS`].
5427#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5428pub(crate) fn dist_wtd_comp_hits() -> usize {
5429 DIST_WTD_COMP_HITS.with(|c| c.get())
5430}
5431
5432/// Resets [`DIST_WTD_COMP_HITS`] to 0.
5433#[allow(dead_code)] // test-only
5434pub(crate) fn reset_dist_wtd_comp_hits() {
5435 DIST_WTD_COMP_HITS.with(|c| c.set(0));
5436}
5437
5438// lane-av1gwarp12: how many 16x16+ blocks built their SINGLE-reference
5439// prediction through `crate::warp::global_warp_params` with a FOUR-parameter
5440// (`ROTZOOM`) model. Vanilla aomenc pins its global-motion search to ROTZOOM
5441// (`global_motion_facade.c:24`), so this is the only >TRANSLATION single-ref
5442// global-warp arm a real aomenc stream can reach (AFFINE needs the widened
5443// side build and its own counter, [`AFFINE_GM_HITS`]).
5444thread_local! {
5445 static ROTZOOM_GM_WARP_HITS: std::cell::Cell<usize> =
5446 const { std::cell::Cell::new(0) };
5447}
5448
5449/// Current value of [`ROTZOOM_GM_WARP_HITS`].
5450#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5451pub(crate) fn rotzoom_gm_warp_hits() -> usize {
5452 ROTZOOM_GM_WARP_HITS.with(|c| c.get())
5453}
5454
5455// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
5456// differently at the block's WIDTH than at libaom's
5457// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
5458// pick the wrong motion_mode alphabet.
5459thread_local! {
5460 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5461}
5462
5463/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
5464pub fn tr_reach_longer_side_hits() -> usize {
5465 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
5466}
5467
5468// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
5469// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
5470// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
5471// reads its interp-filter symbol. Counts the blocks where that guard flips
5472// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
5473// and a 4-px side, which we used to suppress the interp read on (a pre-mode
5474// entropy desync one symbol wide).
5475thread_local! {
5476 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5477}
5478
5479/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
5480pub fn gm_nontrans_small_side_hits() -> usize {
5481 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
5482}
5483
5484// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
5485// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
5486// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
5487// only once `find_projection` returned a usable model, unlike
5488// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
5489// proof that the leaf path itself fired, not the 16x16+ one.
5490thread_local! {
5491 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5492 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5493}
5494
5495/// Current value of [`GLOBALMV_HITS_8`].
5496#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5497pub(crate) fn globalmv_hits_8() -> usize {
5498 GLOBALMV_HITS_8.with(|c| c.get())
5499}
5500
5501/// Current value of [`WARP_HITS_8`].
5502#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5503pub(crate) fn warp_hits_8() -> usize {
5504 WARP_HITS_8.with(|c| c.get())
5505}
5506
5507// How many blocks decoded `interintra == 1` with the non-wedge blended
5508// prediction applied (lane-interintra r1) -- the gate's proof that a
5509// stream actually exercised interintra.
5510thread_local! {
5511 static INTERINTRA_HITS: std::cell::Cell<usize> =
5512 const { std::cell::Cell::new(0) };
5513}
5514
5515/// Current value of [`INTERINTRA_HITS`].
5516#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5517pub(crate) fn interintra_hits() -> usize {
5518 INTERINTRA_HITS.with(|c| c.get())
5519}
5520
5521// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
5522// -- the shape `interintra_blend` used to build a square `side x side` intra
5523// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
5524// pre-existing interintra gate passed with that bug, so the rect arm needs
5525// its own counter to stop being vacuous.
5526thread_local! {
5527 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5528}
5529
5530/// Current value of [`INTERINTRA_RECT_HITS`].
5531pub fn interintra_rect_hits() -> usize {
5532 INTERINTRA_RECT_HITS.with(|c| c.get())
5533}
5534
5535// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
5536// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
5537// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
5538// gate fixture actually exercises this alphabet, even though the block
5539// still refuses (the mask blend itself is unported).
5540thread_local! {
5541 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5542 const { std::cell::Cell::new(0) };
5543}
5544
5545/// Current value of [`MASKED_COMPOUND_HITS`].
5546#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5547pub(crate) fn masked_compound_hits() -> usize {
5548 MASKED_COMPOUND_HITS.with(|c| c.get())
5549}
5550
5551// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
5552// masked-compound block whose true footprint is rectangular, i.e. the case
5553// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
5554// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
5555// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
5556thread_local! {
5557 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
5558 const { std::cell::Cell::new(0) };
5559}
5560
5561/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
5562#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5563pub(crate) fn rect_masked_compound_hits() -> usize {
5564 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
5565}
5566
5567// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
5568// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
5569// actually exercised the wedge blend, not just the DIFFWTD half of
5570// `MASKED_COMPOUND_HITS`.
5571thread_local! {
5572 static WEDGE_HITS: std::cell::Cell<usize> =
5573 const { std::cell::Cell::new(0) };
5574}
5575
5576/// Current value of [`WEDGE_HITS`].
5577#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5578pub(crate) fn wedge_hits() -> usize {
5579 WEDGE_HITS.with(|c| c.get())
5580}
5581
5582// How many blocks decoded a real wedge-INTERINTRA block
5583// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
5584// a gate fixture exercised the wedge blend (fixed sign 0), not just the
5585// smooth arm counted by `INTERINTRA_HITS`.
5586thread_local! {
5587 static WII_HITS: std::cell::Cell<usize> =
5588 const { std::cell::Cell::new(0) };
5589}
5590
5591/// Current value of [`WII_HITS`].
5592#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5593pub(crate) fn wii_hits() -> usize {
5594 WII_HITS.with(|c| c.get())
5595}
5596
5597// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
5598// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
5599// wide <= 32 && high <= 32). The witness that a gate stream really carries a
5600// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
5601// frame carrying one.
5602thread_local! {
5603 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5604}
5605
5606/// Current value of [`NOCFL_UV_MODE_HITS`].
5607#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5608pub(crate) fn nocfl_uv_mode_hits() -> usize {
5609 NOCFL_UV_MODE_HITS.with(|c| c.get())
5610}
5611
5612/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
5613/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
5614pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
5615 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
5616
5617fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
5618 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
5619}
5620
5621// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
5622// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
5623// the rect wedge masks lifted this round actually fired, not just the square
5624// ones already counted by `WEDGE_HITS`/`WII_HITS`.
5625thread_local! {
5626 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5627 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
5628}
5629
5630/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5631pub(crate) fn rect_wedge_hits() -> [usize; 6] {
5632 RECT_WEDGE_HITS.with(|c| c.get())
5633}
5634
5635/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
5636pub(crate) fn rect_wii_hits() -> [usize; 6] {
5637 RECT_WII_HITS.with(|c| c.get())
5638}
5639
5640// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
5641// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
5642// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
5643// aomdec, neighbour list included).
5644thread_local! {
5645 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5646}
5647
5648/// Current value of [`OBMC_RECT_LEAF_HITS`].
5649pub(crate) fn obmc_rect_leaf_hits() -> usize {
5650 OBMC_RECT_LEAF_HITS.with(|c| c.get())
5651}
5652
5653// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
5654// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
5655// to be read from the pair's FIRST mi, which is a different block and, when
5656// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
5657// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
5658thread_local! {
5659 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5660}
5661
5662/// Current value of [`OBMC_PAIR_FILTER_HITS`].
5663pub(crate) fn obmc_pair_filter_hits() -> usize {
5664 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
5665}
5666
5667// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
5668// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
5669// own side, so a block overhanging the bottom/right still predicts the full
5670// neighbour strip (the destination write is what clips). We used to shrink the
5671// prediction to the visible part, which at 4 chroma rows/cols also swaps the
5672// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
5673thread_local! {
5674 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5675}
5676
5677/// Current value of [`OBMC_EDGE_SPAN_HITS`].
5678#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5679pub(crate) fn obmc_edge_span_hits() -> usize {
5680 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
5681}
5682
5683/// Current value of [`OBMC_HITS_8`].
5684#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5685pub(crate) fn obmc_hits_8() -> usize {
5686 OBMC_HITS_8.with(|c| c.get())
5687}
5688
5689// lane-rectgate r1: how many 32x32 quadrants actually decoded a
5690// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
5691// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
5692// `VERT_B` all still fall into the generic "a partition type this encoder
5693// never writes" refusal below) -- the gate's proof that a free-partition
5694// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
5695// coincidentally never selecting one.
5696thread_local! {
5697 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
5698 const { std::cell::Cell::new(0) };
5699}
5700
5701/// Current value of [`EXTENDED_PARTITION_HITS`].
5702#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5703pub(crate) fn extended_partition_hits() -> usize {
5704 EXTENDED_PARTITION_HITS.with(|c| c.get())
5705}
5706
5707// lane-partitions r1: how many 32x32 quadrants decoded a real
5708// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
5709// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
5710// gate's proof this round's arms actually fired.
5711thread_local! {
5712 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
5713 const { std::cell::Cell::new(0) };
5714}
5715
5716/// Current value of [`RECT_PARTITION_HITS`].
5717#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5718pub(crate) fn rect_partition_hits() -> usize {
5719 RECT_PARTITION_HITS.with(|c| c.get())
5720}
5721
5722// lane-inter8 r1: how many superblocks an inter tile coded as a single
5723// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
5724// static content, previously a named refusal).
5725thread_local! {
5726 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
5727 /// path decoded as one whole block (its gate's own witness).
5728 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5729 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
5730 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5731 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5732}
5733
5734/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
5735pub(crate) fn inter_sb128_horz_hits() -> usize {
5736 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
5737}
5738
5739/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
5740pub(crate) fn inter_sb128_vert_hits() -> usize {
5741 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
5742}
5743
5744/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
5745pub fn inter_sb128_none_hits() -> usize {
5746 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
5747}
5748
5749thread_local! {
5750 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
5751 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
5752 /// units) -- the gate's witness that the lifted refusal's case fired.
5753 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5754}
5755
5756/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
5757pub fn intra_128_in_inter_hits() -> usize {
5758 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
5759}
5760
5761thread_local! {
5762 /// lane-av1ibc128arm: how many 64x64 mu-chunk CHROMA units the
5763 /// intra-in-inter 128x128 root read (`decode_inter_block`'s
5764 /// `side > 64` mu-chunk arm, the INTRA half of the inter pair). Every
5765 /// unit is one `read_plane` on U and one on V, so the counter is the
5766 /// gate's proof the arm ran at all -- no committed 4:4:4 fixture
5767 /// reached it before this lane.
5768 pub(crate) static INTRA_128_IN_INTER_MU_CHROMA_HITS: std::cell::Cell<usize> =
5769 const { std::cell::Cell::new(0) };
5770}
5771
5772/// Current value of [`INTRA_128_IN_INTER_MU_CHROMA_HITS`], for a gate's
5773/// before/after delta.
5774pub fn intra_128_in_inter_mu_chroma_hits() -> usize {
5775 INTRA_128_IN_INTER_MU_CHROMA_HITS.with(std::cell::Cell::get)
5776}
5777
5778thread_local! {
5779 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
5780 const { std::cell::Cell::new(0) };
5781}
5782
5783/// Current value of [`INTER_SB_NONE_HITS`].
5784#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5785pub(crate) fn inter_sb_none_hits() -> usize {
5786 INTER_SB_NONE_HITS.with(|c| c.get())
5787}
5788
5789// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
5790// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
5791// path has always run that loop, so only this counter proves the newly-lifted
5792// alphabet value fired.
5793thread_local! {
5794 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
5795 const { std::cell::Cell::new(0) };
5796}
5797
5798/// Current value of [`INTER_SUB16_SPLIT_HITS`].
5799#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5800pub(crate) fn inter_sub16_split_hits() -> usize {
5801 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
5802}
5803
5804// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
5805// while at least one reference picture was SCALED (superres) -- the counter
5806// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
5807thread_local! {
5808 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
5809 const { std::cell::Cell::new(0) };
5810}
5811
5812/// Current value of [`SCALED_LEAF8_HITS`].
5813pub fn scaled_leaf8_hits() -> usize {
5814 SCALED_LEAF8_HITS.with(|c| c.get())
5815}
5816
5817// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
5818// rect pair) were predicted from a SCALED reference -- the counter behind the
5819// lifted "sub-8x8 inter block under a scaled reference" refusal.
5820thread_local! {
5821 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
5822 const { std::cell::Cell::new(0) };
5823}
5824
5825/// Current value of [`SCALED_SUB8_HITS`].
5826pub fn scaled_sub8_hits() -> usize {
5827 SCALED_SUB8_HITS.with(|c| c.get())
5828}
5829
5830// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
5831// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
5832// rect coefficient reader itself fired, not just the strip-level partition
5833// symbol [`RECT_PARTITION_HITS`] already counts.
5834thread_local! {
5835 static RECT_COEFF_HITS: std::cell::Cell<usize> =
5836 const { std::cell::Cell::new(0) };
5837}
5838
5839/// Current value of [`RECT_COEFF_HITS`].
5840#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5841pub(crate) fn rect_coeff_hits() -> usize {
5842 RECT_COEFF_HITS.with(|c| c.get())
5843}
5844
5845// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
5846// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
5847// charter's real-aomenc gate hard-asserts.
5848thread_local! {
5849 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
5850 const { std::cell::Cell::new(0) };
5851}
5852
5853/// Current value of [`RECT_LEAF_COEFF_HITS`].
5854#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5855pub(crate) fn rect_leaf_coeff_hits() -> usize {
5856 RECT_LEAF_COEFF_HITS.with(|c| c.get())
5857}
5858
5859// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
5860// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
5861// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
5862// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
5863// needs rectangular intra prediction" before this round.
5864thread_local! {
5865 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
5866 const { std::cell::Cell::new([0; 3]) };
5867}
5868
5869/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
5870/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
5871#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5872pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
5873 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
5874}
5875
5876// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
5877// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
5878// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
5879// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
5880// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
5881// a single counter cannot tell an axis swap from a working arm
5882// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
5883thread_local! {
5884 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
5885 const { std::cell::Cell::new([0; 2]) };
5886}
5887
5888/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
5889/// (0 = 64x32, 1 = 32x64).
5890pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
5891 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
5892}
5893
5894// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
5895// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
5896// is never incremented) -- the gate's proof that the lifted path ran per depth.
5897thread_local! {
5898 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
5899 const { std::cell::Cell::new([0; 3]) };
5900}
5901
5902// lane-t900 r21: rect intra strips inside an inter frame that read the
5903// screen-content palette syntax (`allow_screen_content_tools` set and the
5904// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
5905// refusal used to guard, so this counter is what keeps its witness gate
5906// non-vacuous.
5907thread_local! {
5908 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5909}
5910
5911/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
5912#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5913pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
5914 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
5915}
5916
5917/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
5918#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5919pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
5920 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
5921}
5922
5923/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
5924#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5925pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
5926 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
5927}
5928
5929// lane-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid
5930// approximation would have resolved off a DIFFERENT CDF row than the real
5931// `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY
5932// frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block"
5933// tally is green on the old code too (class gate-blind-to-feature).
5934thread_local! {
5935 static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell<usize> =
5936 const { std::cell::Cell::new(0) };
5937}
5938
5939/// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`].
5940#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
5941pub(crate) fn txctx_deblock_divergence_hits() -> usize {
5942 TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get)
5943}
5944// lane-av1txctxband: how many `get_tx_size_context` reads the per-CELL
5945// `is_inter_block` cover and the per-COLUMN `above_inter`/`left_inter` bands
5946// DISAGREE about -- i.e. exactly the reads whose CDF row the old code chose
5947// wrongly. Green on the old code too (a plain "some block was inter" tally
5948// would be), so this is the non-vacuity arm of the witness gate: it is 0 on
5949// every stream where the bands happened to be right and non-zero on the
5950// 4:4:4 lossy `--sb-size=128` cq-62 stream whose entropy forked at read 32813
5951// on the 8x4 intra leaf at mi(57,52).
5952thread_local! {
5953 static TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS: std::cell::Cell<usize> =
5954 const { std::cell::Cell::new(0) };
5955}
5956
5957/// Current value of [`TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS`].
5958#[allow(dead_code)] // read only from the `#[cfg(test)]` gate
5959pub(crate) fn txctx_inter_cell_band_divergence_hits() -> usize {
5960 TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS.with(std::cell::Cell::get)
5961}
5962
5963/// Zeroes [`TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS`].
5964#[allow(dead_code)] // read only from the `#[cfg(test)]` gate
5965pub(crate) fn reset_txctx_inter_cell_band_divergence_hits() {
5966 TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS.with(|c| c.set(0));
5967}
5968
5969// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
5970// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
5971// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
5972// rect strip on the inter block path" before this round.
5973thread_local! {
5974 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
5975 const { std::cell::Cell::new([0; 4]) };
5976}
5977
5978/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
5979/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
5980pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
5981 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
5982}
5983
5984// lane-av1444rect: how many 1:4 inter strips at `ss_x == 0` read their chroma
5985// coefficient context over the STRIP'S OWN extent instead of the 4:2:0 pair's
5986// (see [`decode_inter_block`]'s `around_c`). `is_chroma_reference`
5987// (av1_common_int.h:1454) is unconditionally true at ss (0,0), so no pair
5988// exists there; the counter keeps a 4:4:4 1:4-strip gate from passing
5989// vacuously (a 4:2:0 stream of the same content leaves it at 0). It proves
5990// REACH only, never that the fix bites -- that is the gate's byte compare and
5991// its mutation, not this count (skill://ec-av1-pipeline-gate-counters).
5992thread_local! {
5993 static RECT4_INTER_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5994}
5995
5996/// Current value of [`RECT4_INTER_OWN_CHROMA444_HITS`].
5997#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5998pub(crate) fn rect4_inter_own_chroma444_hits() -> usize {
5999 RECT4_INTER_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
6000}
6001
6002/// Resets [`RECT4_INTER_OWN_CHROMA444_HITS`] before a decode.
6003#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6004pub(crate) fn reset_rect4_inter_own_chroma444_hits() {
6005 RECT4_INTER_OWN_CHROMA444_HITS.with(|c| c.set(0));
6006}
6007
6008// lane-av1444rect r2: how many intra-BC 1:4 strips at `ss (0,0)` took the
6009// own-chroma arm of [`decode_rect4_16_intrabc`]'s `own444`. A 4:2:0 / 4:2:2
6010// stream of the same recipe leaves it at 0, which is what makes it the
6011// 4:4:4-only route.
6012//
6013// WHAT THIS COUNTER IS NOT: it is NOT evidence that the fix bites, and it
6014// never was. A route counter fires identically before and after a change that
6015// changes nothing downstream, so a non-zero count proves REACH and nothing
6016// more. On this lane it is also armed deliberately OUTSIDE the `own444`
6017// expression, so that the mutation (`own444 = false`) still increments it and
6018// the red comes from the pixel/entropy arm instead. The evidence that the ss
6019// gate bites is the measured fork move -- first entropy fork read 11750 ->
6020// 12465, luma first wrong sample 164416 -> 205264, 455240 -> 390380 total --
6021// not this count. See skill://ec-av1-pipeline-gate-counters: a counter needs
6022// a DIFFERS-style assertion to carry a claim.
6023thread_local! {
6024 static INTRABC_RECT4_OWN_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6025}
6026
6027/// Current value of [`INTRABC_RECT4_OWN_CHROMA444_HITS`].
6028#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6029pub(crate) fn intrabc_rect4_own_chroma444_hits() -> usize {
6030 INTRABC_RECT4_OWN_CHROMA444_HITS.with(std::cell::Cell::get)
6031}
6032
6033/// Resets [`INTRABC_RECT4_OWN_CHROMA444_HITS`] before a decode.
6034#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6035pub(crate) fn reset_intrabc_rect4_own_chroma444_hits() {
6036 INTRABC_RECT4_OWN_CHROMA444_HITS.with(|c| c.set(0));
6037}
6038
6039// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
6040// through one of the key-frame rect readers ([`decode_block_rect4`],
6041// [`decode_block_rect64`]). `Some((size_group, skip))` tells
6042// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
6043// already read by [`decode_inter_block`] and (b) the luma mode comes off
6044// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
6045// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
6046
6047// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
6048// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
6049// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
6050// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
6051thread_local! {
6052 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
6053 const { std::cell::Cell::new(0) };
6054}
6055
6056/// Current value of [`MODE_MI_OVERRIDE_HITS`].
6057#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6058pub(crate) fn mode_mi_override_hits() -> usize {
6059 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
6060}
6061
6062// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
6063// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
6064// mode from the previous tile, where libaom's `up_available`/`left_available`
6065// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
6066// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
6067// per superblock row in `start_row`, so the luma fallback cannot leak the way
6068// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
6069// the invariant that makes the coarse fallback safe.
6070thread_local! {
6071 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
6072 const { std::cell::Cell::new(0) };
6073}
6074
6075/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
6076#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6077pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
6078 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
6079}
6080
6081// lane-cfl r1: how many times a chroma intra-edge filter-type read
6082// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
6083// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
6084// r1 defect would have filtered a chroma edge with the wrong strength.
6085thread_local! {
6086 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
6087 const { std::cell::Cell::new(0) };
6088}
6089
6090/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
6091#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6092pub(crate) fn uv_mode_mi_override_hits() -> usize {
6093 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
6094}
6095
6096// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
6097// `uv_mode` from the mi GRID where the one-slot-per-column map would have
6098// answered differently -- the sub-8x8 pair case where the pair's own first
6099// half had already overwritten the column slot the chroma-ref half reads.
6100thread_local! {
6101 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
6102 const { std::cell::Cell::new(0) };
6103}
6104
6105/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
6106pub fn uv_mode_grid_override_hits() -> usize {
6107 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
6108}
6109
6110// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
6111// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
6112// from an earlier block in that pixel row/column while the mi-exact map --
6113// which an inter block only started writing this round -- correctly says the
6114// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
6115// an INTER mode, and its `uv_mode` "is not set for inter blocks").
6116thread_local! {
6117 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
6118 const { std::cell::Cell::new(0) };
6119}
6120
6121/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
6122#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6123pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
6124 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
6125}
6126
6127// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
6128// suppressed at a TILE edge that is not a frame edge -- the above/left
6129// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
6130// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
6131// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
6132// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
6133// above would decide this tile's chroma edge filter strength.
6134thread_local! {
6135 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
6136 const { std::cell::Cell::new(0) };
6137}
6138
6139/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
6140#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6141pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
6142 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
6143}
6144
6145// lane-av1leftref: how many chroma intra-edge filter-type reads land on a
6146// left neighbour whose `uv_mode` at libaom's real read cell
6147// (`base_mi[ss_y * mi_stride - 1]` = row `+ss_y`, col `-1`) DIFFERS from the
6148// cell this decoder used to read (its own mi row). Two buckets: the raw mode
6149// value moved, and `is_smooth_mode` -- the boolean the read actually feeds --
6150// flipped. The second is the one that can move pixels.
6151thread_local! {
6152 static UV_LEFT_SS_Y_MODE_DIFF_HITS: std::cell::Cell<usize> =
6153 const { std::cell::Cell::new(0) };
6154 static UV_LEFT_SS_Y_SMOOTH_DIFF_HITS: std::cell::Cell<usize> =
6155 const { std::cell::Cell::new(0) };
6156}
6157thread_local! {
6158 static UV_LEFT_SS_Y_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6159}
6160
6161/// Current value of [`UV_LEFT_SS_Y_READS`].
6162pub fn uv_left_ss_y_reads() -> usize {
6163 UV_LEFT_SS_Y_READS.with(|c| c.get())
6164}
6165
6166/// Current value of [`UV_LEFT_SS_Y_MODE_DIFF_HITS`].
6167pub fn uv_left_ss_y_mode_diff_hits() -> usize {
6168 UV_LEFT_SS_Y_MODE_DIFF_HITS.with(|c| c.get())
6169}
6170
6171/// Current value of [`UV_LEFT_SS_Y_SMOOTH_DIFF_HITS`].
6172pub fn uv_left_ss_y_smooth_diff_hits() -> usize {
6173 UV_LEFT_SS_Y_SMOOTH_DIFF_HITS.with(|c| c.get())
6174}
6175
6176// lane-av1leftwit: decode-path chroma edge-filter-type reads at `ss_y > 0`
6177// whose left-neighbour COLUMN holds a run of length 1 -- the cell this
6178// decoder reads (its own mi row) and the cell libaom reads (one row down)
6179// were written by two DIFFERENT blocks, i.e. the left neighbour is at most
6180// 1 mi tall. That is the only geometry in which the `+ss_y` term can change
6181// the answer at all; `UV_LEFT_SS_Y_READS` alone proves nothing about it.
6182thread_local! {
6183 static UV_LEFT_1MI_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6184}
6185
6186/// Current value of [`UV_LEFT_1MI_SPLIT_HITS`].
6187pub fn uv_left_1mi_split_hits() -> usize {
6188 UV_LEFT_1MI_SPLIT_HITS.with(|c| c.get())
6189}
6190
6191// lane-av1leftwit: the per-tile epoch `uv_owner` cells are stamped with.
6192// Bumped in `Neighbours::start_tile`; never read by decode logic.
6193thread_local! {
6194 static UV_OWNER_EPOCH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
6195}
6196
6197// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
6198// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
6199// shapes the r1 chroma defect showed up on.
6200thread_local! {
6201 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6202 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6203}
6204// lane-av1cfl: which `cfl_ac_ss` arm ran, one bump per CfL block. The 4:4:4
6205// arm is libaom `cfl_luma_subsampling_444_lbd_c` (1x1 luma per chroma sample)
6206// and the 4:2:2 arm is `cfl_luma_subsampling_422_lbd_c`; only the last two
6207// reach `cfl_ac_q3_at`'s 2x2 average, so these four are the reachability
6208// evidence for that function's format-blind extent.
6209thread_local! {
6210 static CFL_AC_444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6211 static CFL_AC_422_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6212 static CFL_AC_420_SQ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6213 static CFL_AC_420_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6214 static CFL_AC_Q3_AT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6215}
6216
6217/// `[4:4:4, 4:2:2, 4:2:0 square, 4:2:0 rect]` [`cfl_ac_ss`] arm hits.
6218pub fn cfl_ac_arm_hits() -> [usize; 4] {
6219 [
6220 CFL_AC_444_HITS.with(|c| c.get()),
6221 CFL_AC_422_HITS.with(|c| c.get()),
6222 CFL_AC_420_SQ_HITS.with(|c| c.get()),
6223 CFL_AC_420_RECT_HITS.with(|c| c.get()),
6224 ]
6225}
6226
6227/// Entries into [`cfl_ac_q3_at`] itself -- the one arm whose extent is
6228/// `bw / 2, bh / 2` and whose footprint is a 2x2 luma average. The gate
6229/// proves it is reached ONLY at 4:2:0.
6230pub fn cfl_ac_q3_at_hits() -> usize {
6231 CFL_AC_Q3_AT_HITS.with(|c| c.get())
6232}
6233
6234/// Current value of [`CFL_BLOCK_HITS`].
6235#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6236pub(crate) fn cfl_block_hits() -> usize {
6237 CFL_BLOCK_HITS.with(|c| c.get())
6238}
6239
6240/// Current value of [`UV_ANGLE_DELTA_HITS`].
6241#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6242pub(crate) fn uv_angle_delta_hits() -> usize {
6243 UV_ANGLE_DELTA_HITS.with(|c| c.get())
6244}
6245
6246// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
6247// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
6248// gate's proof this round's arms actually reached a real block, not just
6249// that `partition_w64` read one of those two symbol values.
6250thread_local! {
6251 static SB_RECT_HITS: std::cell::Cell<usize> =
6252 const { std::cell::Cell::new(0) };
6253}
6254
6255// Current value of [`SB_RECT_HITS`].
6256// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
6257// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
6258// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
6259// non-SPLIT edge arm actually decoded (before this round the bit was read and
6260// thrown away, so that arm was unreachable).
6261thread_local! {
6262 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6263}
6264
6265/// Current value of [`EDGE_PART_HITS`].
6266#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6267pub(crate) fn edge_part_hits() -> [usize; 4] {
6268 EDGE_PART_HITS.with(|c| c.get())
6269}
6270
6271/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
6272#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6273pub(crate) fn reset_edge_part_hits() {
6274 EDGE_PART_HITS.with(|c| c.set([0; 4]));
6275}
6276
6277fn bump_edge_part(slot: usize) {
6278 hit_do! {
6279 EDGE_PART_HITS.with(|c| {
6280 let mut h = c.get();
6281 h[slot] += 1;
6282 c.set(h);
6283 });
6284 }
6285}
6286
6287#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6288pub(crate) fn sb_rect_hits() -> usize {
6289 SB_RECT_HITS.with(|c| c.get())
6290}
6291
6292// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
6293// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
6294// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
6295// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
6296// paths (intra and inter) feed the same counter.
6297//
6298// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
6299// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
6300// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
6301// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
6302// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
6303// every SB of the last row), so the 32-level slots stay 0 on that content and
6304// only these prove the arm fired.
6305thread_local! {
6306 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
6307 const { std::cell::Cell::new([0; 8]) };
6308}
6309
6310/// Current value of [`EDGE32_HITS`].
6311#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6312pub(crate) fn edge32_hits() -> [usize; 8] {
6313 EDGE32_HITS.with(|c| c.get())
6314}
6315
6316/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
6317/// reads are `if`-conditions, so the counter has to ride the expression.
6318fn bump_edge32_bit(base: usize, bit: usize) -> usize {
6319 bump_edge32(base + bit.min(1));
6320 bit
6321}
6322
6323fn bump_edge32(slot: usize) {
6324 hit_do! {
6325 EDGE32_HITS.with(|c| {
6326 let mut h = c.get();
6327 h[slot] += 1;
6328 c.set(h)
6329 });
6330 }
6331}
6332
6333// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
6334// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
6335// strip) fired. Real aomenc picks these at 64 even with
6336// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
6337// the counter the gate hard-asserts.
6338thread_local! {
6339 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
6340 const { std::cell::Cell::new([0; 4]) };
6341}
6342
6343/// Current value of [`SB_AB_HITS`], summed over the four arms.
6344#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6345pub(crate) fn sb_ab_hits() -> usize {
6346 SB_AB_HITS.with(|c| c.get().iter().sum())
6347}
6348
6349/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
6350/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
6351/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
6352/// proof of all four.
6353#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6354pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
6355 SB_AB_HITS.with(std::cell::Cell::get)
6356}
6357
6358// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
6359// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
6360// strips). Two counters, not one, because a gate that only proved "some 1:4
6361// strip fired" would pass on a stream that never coded the other axis, and
6362// every scan/context table this round added comes in a transposed pair.
6363thread_local! {
6364 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6365 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6366}
6367
6368/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
6369#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6370pub(crate) fn sb_rect4_horz_hits() -> usize {
6371 SB_RECT4_HORZ_HITS.with(|c| c.get())
6372}
6373
6374/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
6375#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6376pub(crate) fn sb_rect4_vert_hits() -> usize {
6377 SB_RECT4_VERT_HITS.with(|c| c.get())
6378}
6379
6380// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
6381// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
6382// strips), the arms the ReelB mid-film extract stops at.
6383thread_local! {
6384 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6385 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6386 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
6387 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
6388 /// `PARTITION_VERT_4`.
6389 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6390 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6391 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
6392 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
6393 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6394 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6395 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6396 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6397}
6398
6399// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
6400// a gate that only counted strips would pass on an all-skip stream, which
6401// exercises none of the new scan/context tables.
6402thread_local! {
6403 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6404}
6405
6406// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
6407// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
6408// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
6409// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
6410// counts the same for a 16x8/8x16 strip below 16x16.
6411thread_local! {
6412 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6413 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6414 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6415}
6416
6417/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
6418#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6419pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
6420 (
6421 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
6422 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
6423 )
6424}
6425
6426/// Current value of `SUB16_SPLIT_HITS`.
6427#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6428pub(crate) fn sub16_split_hits() -> usize {
6429 SUB16_SPLIT_HITS.with(|c| c.get())
6430}
6431
6432// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
6433// luma transform is SPLIT and which therefore leave through that fn's early
6434// return -- the arm that published no `TXFM_CONTEXT` band until this round.
6435thread_local! {
6436 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6437}
6438
6439/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
6440#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6441pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
6442 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
6443}
6444
6445/// Current value of `RECT4_COEFF_HITS`.
6446pub(crate) fn rect4_coeff_hits() -> usize {
6447 RECT4_COEFF_HITS.with(|c| c.get())
6448}
6449
6450// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
6451// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
6452// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
6453// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
6454// asserts the arms it proves separately so a run whose RD only picked one
6455// cannot pass as proof of the others.
6456thread_local! {
6457 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6458}
6459
6460/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
6461/// inter frame).
6462pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
6463 SB_AB_INTER_HITS.with(std::cell::Cell::get)
6464}
6465
6466// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
6467// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
6468// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
6469// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
6470// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
6471// arm separately so a run whose RD only picked one cannot pass as proof of
6472// four.
6473thread_local! {
6474 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
6475}
6476
6477/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
6478/// inter frame).
6479pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
6480 AB16_INTER_HITS.with(std::cell::Cell::get)
6481}
6482
6483// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
6484// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
6485// counts the odd strips that close a 4:2:0 chroma pair
6486// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
6487// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
6488// the PREVIOUS strip's own mv/ref/filters -- libaom
6489// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
6490// through `is_sub8x8_inter` (same file, :54).
6491thread_local! {
6492 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6493 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6494 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6495 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6496}
6497
6498// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
6499// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
6500// pair's single 8x4 (4x8) chroma unit for BOTH strips.
6501thread_local! {
6502 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
6503 const { std::cell::Cell::new([0; 3]) };
6504}
6505
6506/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
6507/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
6508pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
6509 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
6510 (v[0], v[1], v[2])
6511}
6512
6513/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
6514/// strips, chroma pairs closed, chroma pairs built from two different
6515/// strips' motion vectors)`.
6516pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
6517 (
6518 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
6519 INTER16_VERT4_HITS.with(std::cell::Cell::get),
6520 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
6521 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
6522 )
6523}
6524
6525/// One 16x4 / 4x16 inter strip's chroma situation, handed to
6526/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
6527/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
6528/// that all mean "an ordinary block, chroma of its own".
6529#[derive(Clone, Copy)]
6530pub(crate) struct InterStripChroma {
6531 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
6532 /// read and reconstruct NO chroma at all.
6533 has_chroma: bool,
6534 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
6535 horz: bool,
6536 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
6537 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
6538 /// i.e. the origin of the 8x4 (4x8) chroma transform.
6539 pair_mi: (usize, usize),
6540 /// The previous (even) strip's single-reference MC parameters, `None`
6541 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
6542 /// and the whole chroma block is predicted from THIS strip's mv.
6543 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
6544}
6545
6546/// The single-reference MC parameters of the inter block that decoded
6547/// last -- read by the next 1:4 strip to build its pair's chroma.
6548
6549fn bump_ab16_inter(arm: usize) {
6550 hit_do! {
6551 AB16_INTER_HITS.with(|c| {
6552 let mut v = c.get();
6553 v[arm] += 1;
6554 c.set(v);
6555 });
6556 }
6557}
6558
6559// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
6560// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
6561// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
6562thread_local! {
6563 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6564 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6565 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6566 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6567 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6568 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
6569 /// base mi differs from what the strip's own (odd) mi would have said --
6570 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
6571 /// key frame miss by 1. Zero here means a gate never exercised the fix.
6572 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6573 /// lane-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s.
6574 static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6575 /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip.
6576 static RECT4_16_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6577 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
6578 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
6579 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6580 /// lane-av1-loss64: chroma transform units the frame-edge clip skipped
6581 /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in
6582 /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless
6583 /// block overhanging the frame does NOT code.
6584 static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6585 /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma
6586 /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`,
6587 /// decodeframe.c:1262) instead of leaking the previous occupant's.
6588 static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6589 /// lane-av1-llband: 4x4 chroma transform units a lossless HORZ/VERT strip
6590 /// walked at subsampling 0/0 (one unit per mi cell -- the geometry the
6591 /// hardcoded 4:2:0 span mis-stepped).
6592 static RECT_SPLIT_LOSSLESS_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6593 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma
6594 /// coefficients a lossless frame walked as per-4x4 inter units (the walk
6595 /// that replaced the single rect unit).
6596 static INTRABC_RECT8_LOSSLESS_LUMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6597 /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a
6598 /// lossless 4:4:4 frame walked as per-4x4 [`TxbSet::Chroma4`] units.
6599 static INTRABC_RECT8_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6600 /// lane-av1loss444kf: 4:4:4 lossless sub-8x8 RECT (8x4 / 4x8) leaf chroma
6601 /// units whose libaom-faithful block-relative reach
6602 /// ([`Reach::of_tu`] over the leaf's own bsize) differs from the
6603 /// standalone-BLOCK_4X4 lookup that used to answer for them. Zero means
6604 /// no stream reached a rect leaf where the two disagree -- a gate
6605 /// asserting the reach fix must see this nonzero, or the fixture never
6606 /// exercised the fixed path.
6607 static SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6608}
6609
6610/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
6611/// that reconstructed as flat DC before lane-kf1200 r2).
6612pub fn skip_cfl_hits() -> usize {
6613 SKIP_CFL_HITS.with(|c| c.get())
6614}
6615
6616/// How many chroma transform units the frame-edge clip skipped in
6617/// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a
6618/// stream whose lossless blocks never overhang the frame -- a gate asserting
6619/// the clip fired must see this nonzero.
6620pub fn chroma_edge_tu_clip_hits() -> usize {
6621 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get())
6622}
6623
6624/// How many skipped lossless intrabc rect strips had their luma entropy
6625/// bands zeroed per unit (lane-av1-loss64).
6626pub fn skip_lossless_band_reset_hits() -> usize {
6627 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get())
6628}
6629
6630/// How many 4x4 chroma transform units a lossless HORZ/VERT strip walked at
6631/// subsampling 0/0 (lane-av1-llband). Zero means a stream never decoded the
6632/// 4:4:4 lossless unit walk this counter proves -- a gate asserting the fix
6633/// must see this nonzero.
6634pub fn rect_split_lossless_chroma444_hits() -> usize {
6635 RECT_SPLIT_LOSSLESS_CHROMA444_HITS.with(|c| c.get())
6636}
6637
6638/// How many unskipped intrabc 8x4/4x8 leaves a lossless frame walked luma as
6639/// per-4x4 inter units (lane-av1-ibc444rect).
6640pub fn intrabc_rect8_lossless_luma_hits() -> usize {
6641 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.get())
6642}
6643
6644/// How many unskipped intrabc 8x4/4x8 leaves a lossless 4:4:4 frame walked
6645/// chroma as per-4x4 [`TxbSet::Chroma4`] units (lane-av1-ibc444rect).
6646pub fn intrabc_rect8_lossless_chroma_hits() -> usize {
6647 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6648}
6649
6650/// How many 4:4:4 lossless sub-8x8 RECT leaf chroma units took the
6651/// block-relative reach libaom's `has_bottom_left` gives, where the
6652/// standalone-BLOCK_4X4 lookup that used to answer disagreed
6653/// (lane-av1loss444kf). Zero on a stream with no such leaf.
6654pub fn sub8_chroma444_lossless_tu_reach_hits() -> usize {
6655 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.get())
6656}
6657
6658/// Gate-side reset for [`SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS`].
6659pub fn reset_sub8_chroma444_tu_reach_hits() {
6660 SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.set(0));
6661}
6662
6663/// Gate-side reset for the two lane-av1-ibc444rect counters above.
6664pub fn reset_ibc444rect_hits() {
6665 INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.set(0));
6666 INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6667}
6668
6669/// Gate-side reset for the two lane-av1-loss64 counters above.
6670pub fn reset_loss64_hits() {
6671 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0));
6672 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0));
6673}
6674
6675/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
6676/// from the pair's base mi than the strip's own mi would have given.
6677pub fn rect4_16_uv_pair_filt_hits() -> usize {
6678 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
6679}
6680
6681/// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane.
6682pub fn rect4_16_lossless_chroma_hits() -> usize {
6683 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get())
6684}
6685
6686/// How many 16x4/4x16 strips reconstructed as intra block copy.
6687pub fn rect4_16_intrabc_hits() -> usize {
6688 RECT4_16_INTRABC_HITS.with(|c| c.get())
6689}
6690
6691/// Zero the lane-av1-rect14 pair counters so a gate measures one stream.
6692pub fn reset_rect4_16_pair_hits() {
6693 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
6694 RECT4_16_INTRABC_HITS.with(|c| c.set(0));
6695}
6696
6697// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
6698// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
6699// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
6700// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
6701// intra-edge filter type must come from the chroma-reference position).
6702thread_local! {
6703 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6704 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
6705}
6706
6707/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
6708pub fn reelc_chroma_counters() -> (usize, usize) {
6709 (
6710 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
6711 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
6712 )
6713}
6714
6715/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
6716/// strips, chroma-reference strips, strips with a coded residual, strips
6717/// whose luma transform is split)`.
6718pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
6719 (
6720 RECT4_16_HORZ_HITS.with(|c| c.get()),
6721 RECT4_16_VERT_HITS.with(|c| c.get()),
6722 RECT4_16_CHROMA_HITS.with(|c| c.get()),
6723 RECT4_16_COEFF_HITS.with(|c| c.get()),
6724 RECT4_16_SPLIT_HITS.with(|c| c.get()),
6725 )
6726}
6727
6728/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
6729pub(crate) fn rect4_32_horz_hits() -> usize {
6730 RECT4_32_HORZ_HITS.with(|c| c.get())
6731}
6732
6733/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
6734pub(crate) fn rect4_32_vert_hits() -> usize {
6735 RECT4_32_VERT_HITS.with(|c| c.get())
6736}
6737
6738/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
6739pub(crate) fn rect4_32_horz_inter_hits() -> usize {
6740 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
6741}
6742
6743/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
6744pub(crate) fn rect4_32_vert_inter_hits() -> usize {
6745 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
6746}
6747
6748/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
6749pub(crate) fn inter_sb_horz_hits() -> usize {
6750 INTER_SB_HORZ_HITS.with(|c| c.get())
6751}
6752
6753/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
6754pub(crate) fn inter_sb_vert_hits() -> usize {
6755 INTER_SB_VERT_HITS.with(|c| c.get())
6756}
6757
6758/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
6759pub(crate) fn inter_sb_horz4_hits() -> usize {
6760 INTER_SB_HORZ4_HITS.with(|c| c.get())
6761}
6762
6763/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
6764pub(crate) fn inter_sb_vert4_hits() -> usize {
6765 INTER_SB_VERT4_HITS.with(|c| c.get())
6766}
6767
6768// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
6769// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
6770// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
6771// just inert-compiled. Zero forever on a passing gate means that gate's
6772// stream never carries `delta_q_present=1` through a rect64 block.
6773thread_local! {
6774 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
6775 const { std::cell::Cell::new(0) };
6776}
6777
6778/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
6779#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6780pub(crate) fn rect64_qidx_drift_hits() -> usize {
6781 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
6782}
6783
6784// lane-partab r1: how many 32x32 quadrants decoded an AB partition
6785// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
6786// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
6787// free-partition gate's proof this round's arms actually fired.
6788thread_local! {
6789 static PARTAB_HITS: std::cell::Cell<usize> =
6790 const { std::cell::Cell::new(0) };
6791}
6792
6793/// Current value of [`PARTAB_HITS`].
6794#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6795pub(crate) fn partab_hits() -> usize {
6796 PARTAB_HITS.with(|c| c.get())
6797}
6798
6799// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
6800// one counter per arm rather than one shared total -- the gate hard-asserts
6801// each of these individually nonzero so a recipe that only ever fires
6802// HORZ_A can't silently stand in for the whole set.
6803thread_local! {
6804 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
6805 const { std::cell::Cell::new(0) };
6806 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
6807 const { std::cell::Cell::new(0) };
6808 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
6809 const { std::cell::Cell::new(0) };
6810 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
6811 const { std::cell::Cell::new(0) };
6812}
6813
6814/// Current value of [`INTRA_HORZ_A_HITS`].
6815#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6816pub(crate) fn intra_horz_a_hits() -> usize {
6817 INTRA_HORZ_A_HITS.with(|c| c.get())
6818}
6819/// Current value of [`INTRA_HORZ_B_HITS`].
6820#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6821pub(crate) fn intra_horz_b_hits() -> usize {
6822 INTRA_HORZ_B_HITS.with(|c| c.get())
6823}
6824/// Current value of [`INTRA_VERT_A_HITS`].
6825#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6826pub(crate) fn intra_vert_a_hits() -> usize {
6827 INTRA_VERT_A_HITS.with(|c| c.get())
6828}
6829/// Current value of [`INTRA_VERT_B_HITS`].
6830#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6831pub(crate) fn intra_vert_b_hits() -> usize {
6832 INTRA_VERT_B_HITS.with(|c| c.get())
6833}
6834
6835// How many [`read_inter_compound_mode`] reads actually happened
6836// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
6837// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
6838// mvstack build), not just that `comp_mode` fired. Still refused right
6839// after (no MV assignment or MC wired), so this only counts attempted
6840// reads.
6841thread_local! {
6842 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
6843 const { std::cell::Cell::new(0) };
6844}
6845
6846/// Current value of [`COMPOUND_MODE_HITS`].
6847#[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds
6848pub(crate) fn compound_mode_hits() -> usize {
6849 COMPOUND_MODE_HITS.with(|c| c.get())
6850}
6851
6852/// How many query blocks folded in at least one temporal MV candidate
6853/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
6854/// temporal-MV gate's own firing counter (lane-av1tmvp).
6855///
6856/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
6857/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
6858/// this file (`decode_inter_block`) still passes `tpl: None` -- this
6859/// counter compiles and the projection math it counts is unit-tested
6860/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
6861/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
6862/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
6863/// against any real stream today. See the module doc on
6864/// `crate::motion_field` and this crate's ledger for the remaining wiring.
6865#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6866pub(crate) fn tmv_hits() -> usize {
6867 crate::mvstack::tmv_hits()
6868}
6869
6870/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
6871/// produced on this thread, the 10-bit inter gate's firing proof.
6872#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6873pub(crate) fn inter_pred_hits() -> usize {
6874 crate::mc::inter_pred_hits()
6875}
6876
6877/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
6878/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
6879/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
6880/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
6881/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
6882/// needs to turn a query block's own resolved `ref_frame` into
6883/// `TplArgs::cur_offset_0` (spec 7.9.3).
6884pub(crate) struct TplFrameArgs<'a> {
6885 pub field: &'a crate::motion_field::TplField,
6886 pub order_hint_bits: u32,
6887 pub order_hint: u32,
6888 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
6889 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
6890 /// frame's own `ref_frame_idx` names for each single reference.
6891 pub ref_order_hints: [u32; 7],
6892}
6893
6894/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
6895/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
6896/// decoded `grid`: every 4x4 unit an inter block covers reads the same
6897/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
6898/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
6899/// exact — every block this crate ever codes is at least 8x8, so no 8x8
6900/// cell straddles two different blocks' values.
6901#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
6902pub(crate) fn build_motion_field(
6903 grid: &MiGrid,
6904 mi_cols: usize,
6905 mi_rows: usize,
6906 order_hint: u32,
6907 order_hint_bits: u32,
6908 ref_order_hints: [u32; 7],
6909 fctx: &FrameCtx,
6910) -> crate::motion_field::MotionField {
6911 let mut field =
6912 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
6913 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
6914 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
6915 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
6916 // referencing one stores only its OTHER side's mv. With
6917 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
6918 // nothing is skipped.
6919 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
6920 // only on the reference frame, so it is 7 table lookups per frame instead
6921 // of two per inter unit.
6922 let other_side: [bool; 8] = std::array::from_fn(|rf| {
6923 let i = rf.wrapping_sub(LAST_FRAME as usize);
6924 order_hint_bits != 0
6925 && i < 7
6926 && (crate::motion_field::get_relative_dist(
6927 order_hint_bits,
6928 ref_order_hints[i],
6929 order_hint,
6930 ) > 0
6931 || ref_order_hints[i] == order_hint)
6932 });
6933 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
6934 // capped at 12 bits per component; a longer one is not stored at all.
6935 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
6936 let (cols, rows, cells) = field.cells_mut();
6937 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
6938 // never touch each other (an 8x8 cell lives in one cell row, and mi row
6939 // `row` writes cell row `row / 2`).
6940 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
6941 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
6942 let out = &mut out[(row / 2 - r0) * cols..][..cols];
6943 for col in 0..mi_cols {
6944 let Some(info) = grid.get_frame(row, col) else {
6945 continue;
6946 };
6947 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
6948 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
6949 // so an intra block -- or an inter block whose every slot is on the
6950 // other side / over the limit -- wipes what an earlier block wrote
6951 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
6952 // share a cell).
6953 if !info.is_inter {
6954 out[col / 2] = None;
6955 continue;
6956 }
6957 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
6958 // qualifying one wins -- a compound block stores its second
6959 // reference's mv, never its first (unless the second is on the
6960 // other side or over the limit). Storing slot 0 unconditionally
6961 // put the wrong (mv, ref_frame_offset) pair in every compound
6962 // block's cell, which a later frame's temporal candidate then
6963 // projected with the wrong reference distance.
6964 let mut saved: Option<crate::motion_field::SavedMv> = None;
6965 for (rf, mv) in [
6966 (info.ref_frame, Some(mv32(info.mv))),
6967 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
6968 ] {
6969 let (Some(mv), true) = (mv, rf > 0) else {
6970 continue;
6971 };
6972 if other_side[rf as usize] {
6973 continue;
6974 }
6975 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
6976 continue;
6977 }
6978 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
6979 }
6980 out[col / 2] = saved;
6981 }
6982 }
6983 };
6984 // lane-mf: the whole-frame pass split over the filter pool in cell-row
6985 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
6986 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
6987 let bands = crate::par::bands(rows, crate::par::filter_threads());
6988 if bands.len() <= 1 {
6989 fill(0, rows, cells);
6990 } else {
6991 let shared = crate::par::Shared::new(cells);
6992 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
6993 // SAFETY: cell rows `r0..r1` are this band's alone.
6994 let cells = unsafe { shared.get() };
6995 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
6996 });
6997 }
6998 if crate::envflags::env_flag!("EC_TRACE_TPL") {
6999 eprintln!("EC_TPL_SAVED oh={order_hint}");
7000 for (r, row) in field.occupancy().iter().enumerate() {
7001 eprintln!("EC_TPL_SAVED r{r} {row}");
7002 }
7003 }
7004 field
7005}
7006
7007/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
7008/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
7009#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7010pub(crate) fn ref_hits(ref_frame: i8) -> usize {
7011 let c = match ref_frame {
7012 LAST2_FRAME => &LAST2_HITS,
7013 LAST3_FRAME => &LAST3_HITS,
7014 GOLDEN_FRAME => &GOLDEN_HITS,
7015 BWDREF_FRAME => &BWDREF_HITS,
7016 ALTREF2_FRAME => &ALTREF2_HITS,
7017 ALTREF_FRAME => &ALTREF_HITS,
7018 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
7019 };
7020 c.with(|v| v.get())
7021}
7022
7023/// The sequence header's `enable_intra_edge_filter`, set once per
7024/// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
7025/// own read of it, kept off the call stack (see that function's own doc
7026/// comment for why) rather than threaded through every `read_plane`/
7027/// `decode_block`/`decode_leaf8` call between here and there.
7028
7029/// Set [`ENABLE_EDGE_FILTER`] for this thread.
7030///
7031/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
7032/// never did -- so an inter frame's intra blocks read whatever value the last
7033/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
7034/// harmless (its own key frame sets it first), but a caller that decodes an
7035/// inter frame directly, or a test harness running several streams on one
7036/// thread, inherits a foreign sequence's bit: decode stops being a pure
7037/// function of the bitstream. `decode_stream` now calls this once per stream
7038/// from the sequence header, which covers every frame including inter ones.
7039pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
7040 fctx.enable_edge_filter.with(|f| f.set(value));
7041}
7042
7043/// Current value of [`ANGLE_DELTA_HITS`].
7044#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7045pub(crate) fn angle_delta_hits() -> usize {
7046 ANGLE_DELTA_HITS.with(|c| c.get())
7047}
7048
7049/// Current value of [`TX_CLASS1_HITS`].
7050#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7051pub(crate) fn tx_class1_hits() -> usize {
7052 TX_CLASS1_HITS.with(|c| c.get())
7053}
7054
7055// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
7056// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
7057// bottom) this thread's decode actually reconstructed -- the same
7058// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
7059// genuinely exercised the sub-8x8 leaf path rather than every attempt
7060// coincidentally landing on `PARTITION_NONE`.
7061thread_local! {
7062 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7063 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
7064 /// sub-blocks (lane-intersub8).
7065 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7066 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
7067 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
7068 /// `[1] = VERT` (two BLOCK_4X8).
7069 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
7070 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
7071 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
7072 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
7073 /// MIXED groups whose chroma reference is INTER while its sibling is
7074 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
7075 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
7076 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
7077 /// so only this cell separates the split arm from the HORZ/VERT one).
7078 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
7079}
7080
7081/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
7082/// mixed groups, split 4x4 leaves)`.
7083pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
7084 SUB8_INTRA_RECT_HITS.with(|c| {
7085 let h = c.get();
7086 (h[0], h[1], h[2], h[3], h[4])
7087 })
7088}
7089
7090/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
7091pub fn sub8_inter_rect_hits() -> (usize, usize) {
7092 SUB8_INTER_RECT_HITS.with(|c| {
7093 let h = c.get();
7094 (h[0], h[1])
7095 })
7096}
7097
7098// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
7099// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
7100// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
7101// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
7102// (b) was 0 for every stream before this round -- the leaf path never touched
7103// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
7104// filtered where libaom skips it. A gate asserts both are non-zero.
7105thread_local! {
7106 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7107 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7108 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
7109 // crosses the cropped frame edge -- the only units for which "clamp at
7110 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
7111 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
7112 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
7113 // whose width or height is not a multiple of 8 is the only shape that
7114 // produces one; the straddling-band gate arms assert it grew.
7115 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7116 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
7117 // (see `Neighbours::skip_written`).
7118 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7119 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
7120 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
7121 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
7122 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
7123 // 8-tall strip pair where only one half is skip must still be FILTERED.
7124 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7125 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7126}
7127
7128/// Current value of `RECT_SKIP_BAND_HITS`.
7129pub fn rect_skip_band_hits() -> usize {
7130 RECT_SKIP_BAND_HITS.with(|c| c.get())
7131}
7132
7133/// Current value of `CDEF_MIXED_SKIP_UNITS`.
7134pub fn cdef_mixed_skip_units() -> usize {
7135 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
7136}
7137
7138/// Current value of `CDEF_SKIPPED_UNITS`.
7139#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7140pub(crate) fn cdef_skipped_units() -> usize {
7141 CDEF_SKIPPED_UNITS.with(|c| c.get())
7142}
7143
7144/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
7145/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
7146pub fn cdef_unwritten_skip_units() -> usize {
7147 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
7148}
7149
7150/// Current value of `INTER8_SKIP_BAND_HITS`.
7151#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7152pub(crate) fn inter8_skip_band_hits() -> usize {
7153 INTER8_SKIP_BAND_HITS.with(|c| c.get())
7154}
7155
7156/// Current value of `CDEF_STRADDLE_UNITS`.
7157#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7158pub(crate) fn cdef_straddle_units() -> usize {
7159 CDEF_STRADDLE_UNITS.with(|c| c.get())
7160}
7161
7162/// Current value of [`SUB8_SPLIT_HITS`].
7163#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7164pub(crate) fn sub8_split_hits() -> usize {
7165 SUB8_SPLIT_HITS.with(|c| c.get())
7166}
7167
7168/// Current value of [`SUB8_INTER_SPLIT_HITS`].
7169pub fn sub8_inter_split_hits() -> usize {
7170 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
7171}
7172
7173// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
7174// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
7175// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
7176// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
7177// first sub-block's type is never the one). Reading it off sub-block 0
7178// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
7179// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
7180// see this rule through this counter.
7181thread_local! {
7182 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7183}
7184
7185/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
7186pub fn sub8_chroma_tx_from_ref_hits() -> usize {
7187 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
7188}
7189
7190fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
7191 if coeffs && first_sub != chroma_ref {
7192 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
7193 }
7194}
7195
7196// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
7197// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
7198// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
7199// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
7200// asserts on these two rather than a plain leaf count.
7201thread_local! {
7202 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7203 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7204 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
7205 /// two 4x4 transform units, predicted one after the other. A separate
7206 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
7207 /// the gate can prove THIS path fired.
7208 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7209 /// 16x8/8x16 intra strips whose prediction actually read past the block's
7210 /// own width (above-right) or height (below-left) -- the samples
7211 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
7212 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
7213 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7214 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
7215 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
7216 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7217}
7218
7219/// Current value of [`RECT8_SPLIT_TX_HITS`].
7220#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7221pub(crate) fn rect8_split_tx_hits() -> usize {
7222 RECT8_SPLIT_TX_HITS.with(|c| c.get())
7223}
7224
7225/// Current value of [`RECT_STRIP_PRED_HITS`].
7226#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7227pub(crate) fn rect_strip_pred_hits() -> usize {
7228 RECT_STRIP_PRED_HITS.with(|c| c.get())
7229}
7230
7231/// Current value of [`RECT_STRIP_REACH_HITS`].
7232#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7233pub(crate) fn rect_strip_reach_hits() -> usize {
7234 RECT_STRIP_REACH_HITS.with(|c| c.get())
7235}
7236
7237/// Current value of [`TX4X8_CODED_HITS`].
7238#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7239pub(crate) fn tx4x8_coded_hits() -> usize {
7240 TX4X8_CODED_HITS.with(|c| c.get())
7241}
7242
7243/// Current value of [`TX8X4_CODED_HITS`].
7244#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7245pub(crate) fn tx8x4_coded_hits() -> usize {
7246 TX8X4_CODED_HITS.with(|c| c.get())
7247}
7248
7249// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
7250// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
7251// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
7252// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
7253// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
7254// (`eob_pt_{16,64,128,256}_chroma_class1`).
7255thread_local! {
7256 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
7257 const { std::cell::Cell::new(0) };
7258}
7259
7260/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
7261#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7262pub(crate) fn chroma_eob_class1_hits() -> usize {
7263 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
7264}
7265
7266/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
7267/// `tx_type` put this block's `eob_pt` on the class-1 row.
7268fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
7269 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
7270 hit!(CHROMA_EOB_CLASS1_HITS);
7271 }
7272}
7273
7274// Which plane the in-flight INTRA reconstruction is writing (0=Y, 1=U, 2=V).
7275// lane-av1cmpaudit: aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`, and
7276// without the same field on our side an `EC_PREDOUT8` vs `OUR_PRED` diff of a
7277// per-plane prediction cannot be read off ours -- a luma/chroma disagreement
7278// looked identical to a same-plane disagreement. Set by `exec_intra` (the
7279// single place a `PlaneBuf::reconstruct{,_rect}` is reached from) and read only
7280// by the `EC_PRED` rung, so it cannot change a decode.
7281thread_local! {
7282 static RECON_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7283}
7284
7285/// The plane index the `EC_PRED` rung prints as `plane=`.
7286fn recon_plane() -> usize {
7287 RECON_PLANE.with(std::cell::Cell::get)
7288}
7289
7290/// Restores [`RECON_PLANE`] on drop, so `exec_intra` needs no cleanup path on
7291/// either of its two early returns.
7292struct PlaneGuard(usize);
7293impl Drop for PlaneGuard {
7294 fn drop(&mut self) {
7295 RECON_PLANE.with(|c| c.set(self.0));
7296 }
7297}
7298
7299const SUB_MI: u32 = 4;
7300const MI: usize = 4;
7301const SB: usize = 64;
7302/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
7303/// (tile start, superblock-row start).
7304///
7305/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
7306/// `av1_get_partition_plane_context` reads its own zero-initialised
7307/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
7308/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
7309/// (64), which reads identically at every level up to 64x64 but sets the bit
7310/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
7311/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
7312/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
7313const NO_NEIGHBOUR_SIDE: usize = 128;
7314const BLOCK: usize = 32;
7315const SUB: usize = 16;
7316const TX32: usize = 32;
7317const TX16: usize = 16;
7318const TX8: usize = 8;
7319const TX4: usize = 4;
7320const DC_PRED: usize = 0;
7321/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
7322/// carries an angle delta — [`crate::tile`]'s own private copy of the same
7323/// constant.
7324const V_PRED: usize = 1;
7325const H_PRED: usize = 2;
7326/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
7327/// `Fimode_To_Intradir`, libaom `blockd.h`).
7328const D157_PRED: usize = 6;
7329/// The last directional mode, `D67_PRED`.
7330const D67_PRED: usize = 8;
7331/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
7332/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
7333/// codes anything else, so this decoder never reads anything else either.
7334const ANGLE_DELTA_ZERO: usize = 3;
7335const NUM_BASE_LEVELS: i32 = 2;
7336const COEFF_BASE_RANGE: i32 = 12;
7337const BR_STEP: i32 = 3;
7338const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
7339
7340/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
7341/// whose probability mass a superblock or block half outside the frame
7342/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
7343/// duplicated here (that module is another lane's territory this round) and
7344/// kept in step with it by the byte-exact round-trip tests below rather than
7345/// by sharing code.
7346const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
7347const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
7348
7349fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
7350 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7351 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
7352 }
7353}
7354
7355fn element_prob(cdf: &[u16], element: usize) -> u16 {
7356 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
7357}
7358
7359/// The two-symbol CDF a partial superblock/block's forced-split flag is read
7360/// with: the mass of `elements` becomes the probability of the one partition
7361/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
7362/// (the encoder's non-adapting counterpart to this read).
7363fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
7364 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
7365 [32768 - split, 32768, 0]
7366}
7367
7368fn unsupported(what: impl Into<String>) -> Error {
7369 Error::unsupported("AV1 tile", what.into())
7370}
7371
7372/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
7373/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
7374/// same rule.
7375pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
7376 match base_q_idx {
7377 0..=20 => 0,
7378 21..=60 => 1,
7379 61..=120 => 2,
7380 _ => 3,
7381 }
7382}
7383
7384/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
7385/// [`crate::tile`]'s writer generates its scan tables with.
7386fn default_scan(side: usize) -> &'static [u16] {
7387 // One table per transform side (4/8/16/32), built once: this used to be a
7388 // fresh heap allocation plus the whole anti-diagonal walk on every
7389 // transform block read.
7390 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
7391 [
7392 default_scan_gen(4),
7393 default_scan_gen(8),
7394 default_scan_gen(16),
7395 default_scan_gen(32),
7396 ]
7397 });
7398 assert!(
7399 matches!(side, 4 | 8 | 16 | 32),
7400 "no default scan for a {side}-point transform"
7401 );
7402 &SCANS[side.trailing_zeros() as usize - 2]
7403}
7404
7405fn default_scan_gen(side: usize) -> Vec<u16> {
7406 let mut scan = Vec::with_capacity(side * side);
7407 for d in 0..(2 * side - 1) {
7408 let lo = d.saturating_sub(side - 1);
7409 let hi = d.min(side - 1);
7410 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
7411 if d % 2 == 0 {
7412 scan.extend(diagonal.rev());
7413 } else {
7414 scan.extend(diagonal);
7415 }
7416 }
7417 scan
7418}
7419
7420/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
7421/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
7422/// in, instead of the default zigzag. libaom's own tables are keyed by a
7423/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
7424/// physically column-major level buffer, but they decompose to the exact
7425/// same (row, col) walk as a flat row-major traversal of *our* row-major
7426/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
7427/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
7428/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
7429/// transposed (column 0 down every row, then column 1, ...).
7430pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
7431 class_scan_table_wh(side, side, class)
7432}
7433
7434/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
7435/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
7436/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
7437/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
7438/// transcribed with -- `mrow` is the plain row-major raster in our indexing
7439/// and `mcol` its transpose, at rect sizes exactly as at square ones.
7440fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
7441 match class {
7442 TxClass::Vert => (0..(w * h) as u16).collect(),
7443 TxClass::Horiz => (0..w)
7444 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
7445 .collect(),
7446 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
7447 }
7448}
7449
7450fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
7451 match scan_idx {
7452 0 => 0,
7453 i if i <= area / 8 => 1,
7454 i if i <= area / 4 => 2,
7455 _ => 3,
7456 }
7457}
7458
7459/// One cell of [`read_coeffs`]'s level buffer.
7460///
7461/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
7462/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
7463/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
7464/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
7465/// zero cells instead of needing the `row >= side || col >= side` edge test
7466/// this used to run five times per coefficient. Nothing writes a padding
7467/// cell, so the values are the same zeros the test returned.
7468#[inline]
7469fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7470 grid[row * stride + col] as i32
7471}
7472
7473/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
7474/// `txb_common.h`): everything but the two lone-axis-identity types this
7475/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
7476#[derive(Clone, Copy, PartialEq, Eq)]
7477pub(crate) enum TxClass {
7478 TwoD,
7479 Horiz,
7480 Vert,
7481}
7482
7483impl TxClass {
7484 pub(crate) fn of(tx_type: TxType) -> Self {
7485 match tx_type {
7486 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
7487 // key on axis alone -- FLIPADST is still ADST for this purpose.
7488 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
7489 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
7490 _ => Self::TwoD,
7491 }
7492 }
7493}
7494
7495/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
7496/// table (indexed by the position along the transform's *coded* axis --
7497/// `col` for horiz, `row` for vert) that places their contexts past the 2D
7498/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
7499/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
7500pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
7501 match i {
7502 0 => 26,
7503 1 => 31,
7504 _ => 36,
7505 }
7506}
7507
7508fn base_ctx(
7509 grid: &[u8],
7510 stride: usize,
7511 row: usize,
7512 col: usize,
7513 class: TxClass,
7514 rect_shape: Option<(usize, usize)>,
7515) -> usize {
7516 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
7517 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
7518 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
7519 // position through the full 1D neighbour sum and offset table. Skipping
7520 // that for every class desynced the last (DC) coefficient of a
7521 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
7522 // 0, which then read one extra `BR` symbol at the max and forced a
7523 // spurious third Golomb call).
7524 if class == TxClass::TwoD && row == 0 && col == 0 {
7525 return 0;
7526 }
7527 let offsets: [(usize, usize); 5] = match class {
7528 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7529 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7530 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7531 };
7532 let mag: i32 = offsets
7533 .iter()
7534 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
7535 .sum();
7536 let ctx = ((mag + 1) >> 1).min(4) as usize;
7537 match class {
7538 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
7539 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
7540 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
7541 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
7542 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
7543 // strip, which own a genuinely different table from the square one
7544 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
7545 // square table vs the real ctx 13 the rect table gives).
7546 TxClass::TwoD => {
7547 // lane-rectsplit r4: apply libaom's GENERATING RULE
7548 // (`txb_common.h:199-209`) directly instead of indexing the
7549 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
7550 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
7551 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
7552 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
7553 // so 32 consecutive entries are one COLUMN: the [`cdf`]
7554 // transcriptions are `[col][row]` and this read had them as
7555 // `[row][col]` -- the transpose, i.e. the other shape's rule with
7556 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
7557 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
7558 // pins the rule against the tables over their whole 5x5 domain.
7559 if let Some((w, h)) = rect_shape {
7560 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
7561 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
7562 }
7563 if w < h && row < 2 {
7564 return ctx + 11;
7565 }
7566 if w > h && col < 2 {
7567 return ctx + 16;
7568 }
7569 }
7570 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7571 }
7572 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7573 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7574 }
7575}
7576
7577/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
7578/// offsets into the padded level frame (lane-coefread): the tap pattern is a
7579/// function of the tx class alone, which is fixed for a whole transform unit,
7580/// so resolving it once per unit takes the class match and the `(dr, dc)`
7581/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
7582/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
7583/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
7584/// original `(dr, dc)` form.
7585fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
7586 match class {
7587 TxClass::TwoD => (
7588 [stride, 1, stride + 1, 2 * stride, 2],
7589 [stride, 1, stride + 1],
7590 ),
7591 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
7592 TxClass::Vert => (
7593 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
7594 [stride, 1, 2 * stride],
7595 ),
7596 }
7597}
7598
7599/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
7600/// neighbours) + 1) >> 1`, clamped to 4.
7601#[inline(always)]
7602fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
7603 let mut mag = 0u32;
7604 for &t in taps {
7605 mag += u32::from(grid[idx + t]).min(3);
7606 }
7607 (((mag + 1) >> 1) as usize).min(4)
7608}
7609
7610/// [`br_ctx`]'s neighbour sum, off flat taps.
7611#[inline(always)]
7612fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
7613 let mut mag = 0u32;
7614 for &t in taps {
7615 mag += u32::from(grid[idx + t]);
7616 }
7617 (((mag + 1) >> 1) as usize).min(6)
7618}
7619
7620/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
7621/// origin-offset tail the two coefficient readers state inline; kept as the
7622/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
7623/// flat one against.
7624#[cfg(test)]
7625fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7626 let extra = match class {
7627 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
7628 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
7629 TxClass::Vert => neighbour(grid, stride, row + 2, col),
7630 };
7631 let mag = neighbour(grid, stride, row + 1, col) + neighbour(grid, stride, row, col + 1) + extra;
7632 let mag = (((mag + 1) >> 1).min(6)) as usize;
7633 if row == 0 && col == 0 {
7634 return mag;
7635 }
7636 let near_origin = match class {
7637 TxClass::TwoD => row < 2 && col < 2,
7638 TxClass::Horiz => col == 0,
7639 TxClass::Vert => row == 0,
7640 };
7641 if near_origin { mag + 7 } else { mag + 14 }
7642}
7643
7644/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
7645/// transposed from libaom's column-major buffer into this decoder's row-major
7646/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
7647/// against the real table). Not the square zigzag formula generalized to
7648/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
7649const SCAN_32X16: [u16; 512] = [
7650 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7651 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39, 8,
7652 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72, 41,
7653 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229, 198,
7654 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, 13,
7655 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418, 387,
7656 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326, 295,
7657 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234, 203,
7658 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142, 111, 80,
7659 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19, 485, 454,
7660 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424, 393, 362,
7661 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332, 301, 270,
7662 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178,
7663 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148, 117, 86, 55,
7664 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, 491, 460, 429,
7665 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430, 399, 368, 337,
7666 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338, 307, 276, 245,
7667 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246, 215, 184, 153,
7668 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154, 123, 92, 61, 30,
7669 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 497, 466, 435,
7670 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405, 374, 343, 312,
7671 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251, 220, 189, 158,
7672 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439, 408, 377, 346,
7673 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503, 472, 441, 410,
7674 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443, 412, 381, 350,
7675 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415, 509, 478, 447,
7676 510, 479, 511,
7677];
7678
7679/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
7680/// [`SCAN_32X16`]'s doc comment).
7681const SCAN_16X32: [u16; 512] = [
7682 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,
7683 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
7684 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
7685 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
7686 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
7687 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
7688 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
7689 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
7690 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
7691 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
7692 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
7693 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
7694 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
7695 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
7696 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
7697 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
7698 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
7699 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
7700 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
7701 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
7702 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
7703 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
7704 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
7705 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
7706 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
7707 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
7708];
7709
7710/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
7711/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
7712/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
7713/// the same source).
7714const SCAN_4X8: [u16; 32] = [
7715 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,
7716 23, 26, 29, 27, 30, 31,
7717];
7718
7719/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
7720const SCAN_8X4: [u16; 32] = [
7721 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,
7722 29, 22, 15, 30, 23, 31,
7723];
7724
7725/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
7726/// [`SCAN_32X16`]'s doc comment).
7727const SCAN_16X8: [u16; 128] = [
7728 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,
7729 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
7730 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
7731 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
7732 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
7733 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
7734];
7735
7736/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
7737/// [`SCAN_32X16`]'s doc comment).
7738const SCAN_8X16: [u16; 128] = [
7739 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,
7740 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7741 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7742 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7743 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
7744 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
7745];
7746
7747/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
7748/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
7749/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
7750/// scans column-major (`p = col * height + row`), so a naive copy of
7751/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
7752/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
7753/// are byte-identical to this decoder's [`SCAN_8X16`].
7754const SCAN_32X8: [u16; 256] = [
7755 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
7756 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226,
7757 195, 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104,
7758 73, 42, 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200,
7759 169, 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78,
7760 47, 16, 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205,
7761 174, 143, 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83,
7762 52, 21, 239, 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210,
7763 179, 148, 117, 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88,
7764 57, 26, 244, 213, 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215,
7765 184, 153, 122, 91, 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93,
7766 62, 31, 249, 218, 187, 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127,
7767 252, 221, 190, 159, 253, 222, 191, 254, 223, 255,
7768];
7769/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
7770/// 16x64 `PARTITION_VERT_4` strip).
7771const SCAN_8X32: [u16; 256] = [
7772 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,
7773 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
7774 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
7775 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
7776 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
7777 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
7778 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
7779 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
7780 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
7781 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
7782 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
7783 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
7784 239, 246, 253, 247, 254, 255,
7785];
7786/// `Default_Scan_16x4`, this decoder's own row-major transcription of
7787/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
7788/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
7789/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
7790/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
7791/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
7792/// were emitted -- a naive copy installs the transpose (class
7793/// reference-layout-not-spec).
7794const SCAN_16X4: [u16; 64] = [
7795 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,
7796 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
7797 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
7798];
7799/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
7800/// 8x32 `PARTITION_VERT_4` strip).
7801const SCAN_4X16: [u16; 64] = [
7802 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,
7803 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
7804 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
7805];
7806
7807/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
7808/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
7809/// padding already holds.
7810#[inline]
7811fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
7812 grid[row * stride + col] as i32
7813}
7814
7815/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
7816/// the rect generalization is libaom's own comment in
7817/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
7818/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
7819/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
7820/// [`decode_block_rect`] codes (see that function's own doc comment).
7821fn base_ctx_rect(
7822 grid: &[u8],
7823 stride: usize,
7824 w: usize,
7825 h: usize,
7826 row: usize,
7827 col: usize,
7828 class: TxClass,
7829) -> usize {
7830 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
7831 // the 2D class short-circuits the DC position.
7832 if class == TxClass::TwoD && row == 0 && col == 0 {
7833 return 0;
7834 }
7835 let offsets: [(usize, usize); 5] = match class {
7836 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
7837 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
7838 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
7839 };
7840 let mag: i32 = offsets
7841 .iter()
7842 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
7843 .sum();
7844 let ctx = ((mag + 1) >> 1).min(4) as usize;
7845 match class {
7846 TxClass::TwoD => {
7847 if w < h && row < 2 {
7848 return ctx + 11;
7849 }
7850 if w > h && col < 2 {
7851 return ctx + 16;
7852 }
7853 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7854 }
7855 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
7856 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
7857 // position along one axis only).
7858 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
7859 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
7860 }
7861}
7862
7863/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
7864/// neighbour-offset math itself is shape-independent, only the boundary
7865/// clamp needs the real bound in each axis.
7866/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
7867/// its body was character-for-character [`br_ctx`]'s, which
7868/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
7869#[cfg(test)]
7870fn br_ctx_rect(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
7871 let extra = match class {
7872 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
7873 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
7874 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
7875 };
7876 let mag = neighbour_rect(grid, stride, row + 1, col)
7877 + neighbour_rect(grid, stride, row, col + 1)
7878 + extra;
7879 let mag = (((mag + 1) >> 1).min(6)) as usize;
7880 if row == 0 && col == 0 {
7881 return mag;
7882 }
7883 let near_origin = match class {
7884 TxClass::TwoD => row < 2 && col < 2,
7885 TxClass::Horiz => col == 0,
7886 TxClass::Vert => row == 0,
7887 };
7888 if near_origin { mag + 7 } else { mag + 14 }
7889}
7890
7891fn dc_vote(dc: Option<bool>) -> i32 {
7892 match dc {
7893 None => 0,
7894 Some(true) => -1,
7895 Some(false) => 1,
7896 }
7897}
7898
7899fn dc_sign_ctx(vote: i32) -> usize {
7900 match vote.signum() {
7901 0 => 0,
7902 -1 => 1,
7903 _ => 2,
7904 }
7905}
7906
7907/// The `tx_type` a CDF symbol names, given the width of the row it was read
7908/// from.
7909///
7910/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
7911/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
7912/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
7913/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
7914/// members are a prefix of the five.
7915///
7916/// One function rather than a `match` at each reader, so
7917/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
7918/// tests the mapping the readers actually use.
7919pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
7920 match cdf_len {
7921 17 => TxType::from_symbol_all16(t),
7922 13 => TxType::from_symbol_set2_12(t),
7923 8 => TxType::from_symbol_set1(t),
7924 _ => TxType::from_symbol(t),
7925 }
7926}
7927
7928/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
7929/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
7930/// (class `table-and-reader-move-together` -- the writer picks its symbol
7931/// through the reader's own map, so the two cannot drift).
7932pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
7933 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
7934}
7935
7936/// The remainder of a level the base and base-range syntax could not reach
7937/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
7938/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
7939pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
7940 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
7941 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
7942 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
7943 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
7944 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
7945 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
7946 // stream_can_carry` enumerates that whole value domain.
7947 //
7948 // So this refusal never names a reader gap: it is always the SYMPTOM of an
7949 // earlier desync (class `refusal-hides-a-defect`), and every historical
7950 // instance was closed by fixing that desync -- lane-dgolomb's
7951 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
7952 // Raising the cap only trades a clean refusal for silent corruption:
7953 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
7954 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
7955 // from a refusal into a frame-0 LUMA MISMATCH.
7956 let mut length = 1u32;
7957 while dec.literal(1) == 0 {
7958 length += 1;
7959 if length > 20 {
7960 return Err(unsupported("a Golomb tail longer than this decoder reads"));
7961 }
7962 }
7963 let mut x = 1u32;
7964 for _ in 1..length {
7965 x = (x << 1) | dec.literal(1);
7966 }
7967 Ok(x - 1)
7968}
7969
7970/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
7971/// [`crate::tile`]'s `write_eob`.
7972fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
7973 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
7974 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
7975
7976 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
7977 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
7978 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
7979 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
7980 // `eob_multi_ctx`). Missing that split desynced the very first
7981 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
7982 // against a real aomdec trace).
7983 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
7984 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
7985 (_, Some(class1)) => class1,
7986 };
7987 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
7988 let (range, value) = dec.debug_state();
7989 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
7990 }
7991 let group = dec.symbol(eob_pt) + 1;
7992 if trace {
7993 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
7994 }
7995 let bits = OFFSET_BITS[group];
7996 let mut offset = 0u32;
7997 if bits > 0 {
7998 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
7999 if trace {
8000 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
8001 }
8002 offset = top << (bits - 1);
8003 if bits > 1 {
8004 offset |= dec.literal(bits - 1);
8005 }
8006 }
8007 GROUP_START[group] + offset as usize
8008}
8009
8010/// One transform block's levels, the inverse of [`crate::tile`]'s
8011/// `write_coeffs`, returned as a `side * side` grid in raster order, along
8012/// with the transform type that grid was coded under (`DCT_DCT` when the
8013/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
8014/// 64-point transforms, which never code anything else).
8015///
8016/// # Errors
8017/// Returns an error if the `tx_type` symbol decodes to a value outside its
8018/// CDF's own set (a corrupt or unsupported bitstream) — every value the
8019/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
8020/// produce dispatches to a real inverse transform.
8021/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
8022/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
8023/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
8024/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
8025/// the plane's own predicted mode instead. Every entry this table can
8026/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
8027/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
8028/// table ever names), so unlike the CDF-coded luma path there is no
8029/// ext-tx-set membership check to fall back from here.
8030pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
8031 use crate::intra::{
8032 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
8033 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
8034 };
8035 match mode {
8036 DC_PRED | D45_PRED => TxType::DctDct,
8037 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
8038 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
8039 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
8040 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
8041 }
8042}
8043
8044/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
8045/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
8046/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
8047fn is_smooth_mode(mode: usize) -> bool {
8048 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
8049}
8050
8051/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
8052/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
8053/// nine of them inside the base/sign loops pinned nine sets of values in the
8054/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
8055/// traffic). Out of line, the loop keeps its values in registers and the
8056/// trace output is character-for-character what it was.
8057#[cold]
8058#[inline(never)]
8059fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
8060 eprintln!(
8061 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
8062 );
8063}
8064
8065#[cold]
8066#[inline(never)]
8067fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
8068 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
8069}
8070
8071#[cold]
8072#[inline(never)]
8073fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
8074 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
8075}
8076
8077#[cold]
8078#[inline(never)]
8079fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
8080 let (rng, _) = dec.debug_state();
8081 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
8082}
8083
8084#[cold]
8085#[inline(never)]
8086fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
8087 let (rng, _) = dec.debug_state();
8088 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
8089}
8090
8091#[cold]
8092#[inline(never)]
8093fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
8094 let (rng, _) = dec.debug_state();
8095 eprintln!(
8096 "EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}",
8097 negative as i32
8098 );
8099}
8100
8101#[cold]
8102#[inline(never)]
8103fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
8104 let (rng, _) = dec.debug_state();
8105 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
8106}
8107
8108#[cold]
8109#[inline(never)]
8110fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
8111 let (rng, _) = dec.debug_state();
8112 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
8113}
8114
8115// lane-ibc444c: see `read_coeffs_rect`'s `#[track_caller]`.
8116#[track_caller]
8117fn read_coeffs(
8118 dec: &mut SymbolDecoder,
8119 coding: &mut TxbTables,
8120 scan: &[u16],
8121 skip_ctx: usize,
8122 sign_ctx: usize,
8123 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
8124 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
8125 // nothing at all; `DctDct` for every luma call and every chroma call at
8126 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
8127 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
8128 default_tx_type: TxType,
8129 // `Some((w, h))` with `w != h` when this read is a superblock-level
8130 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
8131 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
8132 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
8133 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
8134 // caller's block genuinely is `side` x `side`.
8135 rect_shape: Option<(usize, usize)>,
8136) -> Result<(Grid, TxType)> {
8137 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
8138 let side = coding.side;
8139 // lane-av1readcensus: this unit's own entry state, so the census line
8140 // carries the pre-read rng and pairs against the oracle's `EC_COEFF`
8141 // (which prints `r->ec.rng` before the same `txb_skip` read).
8142 let census_entry_rng = dec.debug_state().0;
8143 let (census_w, census_h) = rect_shape.unwrap_or((side, side));
8144 // lane-av1ibcfork: the per-unit BIT INTERVAL, the twin of the oracle's
8145 // `EC_ECDUMP_IN` / `_OUT` / `_END`. The census plane, not a fresh label:
8146 // it is the same source `census_unit` reads, so the interval line and the
8147 // census line can never disagree about which plane a unit is on.
8148 let iv_plane = CENSUS_PLANE.with(|c| c.get()).min(2);
8149 let iv_bit = unit_iv_in(iv_plane, census_w, census_h, skip_ctx, dec);
8150 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
8151 let (range, value) = dec.debug_state();
8152 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
8153 }
8154 if crate::envflags::env_flag!("EC_ECDUMP_IN") {
8155 let (range, value) = dec.debug_state();
8156 let bit = dec.debug_bitpos();
8157 eprintln!(
8158 "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})"
8159 );
8160 }
8161 let dbg_txbskip = if coeff_trace_on() {
8162 coding.txb_skip[skip_ctx]
8163 } else {
8164 [0; 3]
8165 };
8166 let sq_bit = if coeff_trace_on() {
8167 dec.debug_bitpos()
8168 } else {
8169 0
8170 };
8171 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
8172 unit_iv_skip(
8173 dec, iv_bit, iv_plane, census_w, census_h, skip_ctx, all_zero,
8174 );
8175 // lane-ibc444c: this reader logs an `all_zero` step even for a read that
8176 // consumes ZERO bits, so `post_bit == bit` means "no symbol was read" --
8177 // filter on it before pairing anything against the oracle.
8178 if crate::envflags::env_flag!("EC_IBCTX") {
8179 eprintln!(
8180 "EC_IBCTX2 side={} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={sq_bit} at {}",
8181 coding.side,
8182 std::panic::Location::caller(),
8183 );
8184 }
8185 if coeff_trace_on() {
8186 let (rng, _) = dec.debug_state();
8187 eprintln!(
8188 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng} bit={sq_bit} post_bit={}",
8189 coding.side,
8190 all_zero as i32,
8191 dec.debug_bitpos()
8192 );
8193 }
8194 if crate::envflags::env_flag!("EC_AV1_TELL") {
8195 eprintln!(
8196 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
8197 all_zero as u8,
8198 dec.debug_bitpos(),
8199 dec.debug_state().0
8200 );
8201 }
8202 if trace {
8203 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
8204 }
8205 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
8206 let (range, value) = dec.debug_state();
8207 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
8208 }
8209 if all_zero {
8210 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
8211 // shared zero grid instead of allocating and zeroing its own.
8212 census_unit(
8213 census_w,
8214 census_h,
8215 TxType::DctDct,
8216 0,
8217 true,
8218 census_entry_rng,
8219 dec,
8220 );
8221 unit_iv_end(dec, iv_plane, census_w, census_h, skip_ctx);
8222 return Ok((Grid::Zero(side * side), TxType::DctDct));
8223 }
8224 let mut grid = vec![0i32; side * side];
8225 let mut tx_type = default_tx_type;
8226 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
8227 // The CDF row's own width names its set (lane-cdffwd2: extended
8228 // past the original two-way intra split once wider `reduced_tx_set
8229 // == 0` inter sets joined the table): 17 slots (16 symbols) is
8230 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
8231 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
8232 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
8233 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
8234 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
8235 let len = tx_type_cdf.len();
8236 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
8237 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
8238 }
8239 let t = dec.symbol(tx_type_cdf);
8240 crate::census::tx_type(len, t);
8241 if coeff_trace_on() {
8242 let (rng, _) = dec.debug_state();
8243 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
8244 }
8245 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
8246 let (range, value) = dec.debug_state();
8247 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
8248 }
8249 if trace {
8250 eprintln!("TRACE tx_type value={t} len={len}");
8251 }
8252 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
8253 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
8254 })?;
8255 }
8256
8257 let class = TxClass::of(tx_type);
8258 if class != TxClass::TwoD {
8259 hit!(TX_CLASS1_HITS);
8260 hit!(RECT_CLASS1_HITS);
8261 }
8262 let eob = read_eob(dec, coding, class);
8263 if trace {
8264 eprintln!("TRACE eob value={eob}");
8265 }
8266 let ec_trace_coeff = coeff_trace_on();
8267 if ec_trace_coeff {
8268 let (rng, _) = dec.debug_state();
8269 let cls = match class {
8270 TxClass::TwoD => "2d",
8271 TxClass::Horiz => "horiz",
8272 TxClass::Vert => "vert",
8273 };
8274 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
8275 }
8276 let class_scan;
8277 let scan: &[u16] = if class == TxClass::TwoD {
8278 scan
8279 } else {
8280 class_scan = class_scan_table(side, class);
8281 &class_scan
8282 };
8283 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
8284 // coefficient `pos / side`, `pos % side` was a hardware divide where a
8285 // shift and a mask say the same thing, and the level buffer fits a fixed
8286 // 32x32 frame of stack instead of a heap allocation per transform block.
8287 debug_assert!(side.is_power_of_two() && side <= 32);
8288 let sh = side.trailing_zeros();
8289 let col_mask = side - 1;
8290 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
8291 // `stride = side + 4` columns and four spare rows, so the widest read
8292 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
8293 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
8294 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
8295 let stride = side + 4;
8296 let mut levels_buf = [0u8; 36 * 36];
8297 let levels = &mut levels_buf[..stride * stride];
8298 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
8299 // `pos >> sh` / `& mask` decomposition and load the level back out of the
8300 // padded frame just to skip the zeros. The base pass already knows both,
8301 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
8302 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
8303 // pass walks that list in reverse (the base pass runs in reverse scan
8304 // order, so reversing it is forward scan order: the same coefficients, in
8305 // the same order, with the same `c` the trace prints).
8306 let mut nz_buf = [0u16; 1024];
8307 let mut nz_n = 0usize;
8308 let (base_taps, br_taps) = flat_taps(stride, class);
8309 for scan_idx in (0..eob).rev() {
8310 let pos = scan[scan_idx] as usize;
8311 let (row, col) = (pos >> sh, pos & col_mask);
8312 let idx = row * stride + col;
8313 let level = if scan_idx == eob - 1 {
8314 let ctx = eob_coeff_ctx(scan_idx, side * side);
8315 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
8316 if trace {
8317 trace_base_eob(scan_idx, pos, row, col, ctx, v);
8318 }
8319 v
8320 } else {
8321 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
8322 if row == 0 && col == 0 {
8323 0
8324 } else {
8325 base_mag(levels, idx, &base_taps)
8326 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8327 }
8328 } else {
8329 base_ctx(levels, stride, row, col, class, rect_shape)
8330 };
8331 let v = dec.symbol(&mut coding.base[ctx]) as i32;
8332 if ec_trace_coeff {
8333 // `pos` in libaom's column-major `coeff_idx` convention, so
8334 // the ladder lines up with instrumented `aomdec`.
8335 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
8336 }
8337 if trace {
8338 trace_base(scan_idx, pos, row, col, ctx, v);
8339 }
8340 v
8341 };
8342 let level = if level > NUM_BASE_LEVELS {
8343 let ctx = {
8344 let mag = br_mag(levels, idx, &br_taps);
8345 if row == 0 && col == 0 {
8346 mag
8347 } else {
8348 let near_origin = match class {
8349 TxClass::TwoD => row < 2 && col < 2,
8350 TxClass::Horiz => col == 0,
8351 TxClass::Vert => row == 0,
8352 };
8353 if near_origin { mag + 7 } else { mag + 14 }
8354 }
8355 };
8356 let mut level = level;
8357 let mut sent = 0;
8358 loop {
8359 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8360 if ec_trace_coeff {
8361 // lane-leaf8tx r3: the `br` rung was missing from THIS
8362 // path's trace, so the cross-decoder range ladder was
8363 // blind to every base-range symbol and mis-reported the
8364 // first divergence (class [[gate-blind-to-feature]]).
8365 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
8366 }
8367 if trace {
8368 trace_br(scan_idx, pos, row, col, ctx, k);
8369 }
8370 level += k;
8371 sent += BR_STEP;
8372 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8373 break;
8374 }
8375 }
8376 level
8377 } else {
8378 level
8379 };
8380 if ec_trace_coeff && scan_idx == eob - 1 {
8381 coeff_step_base_eob_level(dec, level);
8382 }
8383 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
8384 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
8385 // added in the sign pass below, straight into `grid`), so the context
8386 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
8387 // byte gather (lane-coefbuf).
8388 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8389 levels[idx] = level as u8;
8390 if level != 0 {
8391 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8392 nz_n += 1;
8393 }
8394 }
8395 if ec_trace_coeff {
8396 let (rng, _) = dec.debug_state();
8397 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8398 }
8399
8400 for &packed in nz_buf[..nz_n].iter().rev() {
8401 let c = (packed >> 4) as usize;
8402 let pos = scan[c] as usize;
8403 let level = (packed & 15) as i32;
8404 let negative = if pos == 0 {
8405 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
8406 if trace {
8407 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
8408 }
8409 v
8410 } else {
8411 dec.literal(1) == 1
8412 };
8413 if ec_trace_coeff {
8414 coeff_step_sign(dec, c, negative);
8415 }
8416 let level = if level > MAX_BR_LEVEL {
8417 let g = read_golomb(dec)?;
8418 if trace {
8419 eprintln!("TRACE golomb pos={pos} value={g}");
8420 }
8421 level + g as i32
8422 } else {
8423 level
8424 };
8425 if ec_trace_coeff {
8426 coeff_step_post_golomb(dec, c, level);
8427 }
8428 grid[pos] = if negative { -level } else { level };
8429 }
8430 census_unit(
8431 census_w,
8432 census_h,
8433 tx_type,
8434 eob,
8435 false,
8436 census_entry_rng,
8437 dec,
8438 );
8439 unit_iv_end(dec, iv_plane, census_w, census_h, skip_ctx);
8440 Ok((Grid::Own(grid), tx_type))
8441}
8442
8443/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
8444/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
8445/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
8446/// can ever produce, since every `tx_type` this decoder's rect sets can read
8447/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
8448/// rather than guess-decode if a non-2D class ever shows up here, since
8449/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
8450/// form for those.
8451
8452// lane-ibc444c: `#[track_caller]` so the EC_IBCTX rung below names the CALLER
8453// of this reader -- the only thing that identifies a unit's route. No plane is
8454// printed here: the plane is the ORACLE's side of the pairing, and a label
8455// here is one more thing that can disagree with it.
8456#[track_caller]
8457fn read_coeffs_rect(
8458 dec: &mut SymbolDecoder,
8459 coding: &mut TxbTables,
8460 scan: &[u16],
8461 w: usize,
8462 h: usize,
8463 skip_ctx: usize,
8464 sign_ctx: usize,
8465 default_tx_type: TxType,
8466 // lane-av1chrtx: the plane this unit belongs to (0 luma, 1 U, 2 V) --
8467 // printed by the two `EC_COEFF_STEP` traces below, which hardcoded
8468 // `plane=0` and so mis-attributed a CHROMA read as a luma one in two
8469 // independent lane reports.
8470 plane: usize,
8471) -> Result<(Grid, TxType)> {
8472 let rect_trace = coeff_trace_on();
8473 let entry_rng = dec.debug_state().0;
8474 // lane-av1readcensus: this reader is handed the real plane (lane-av1chrtx
8475 // threaded it in for the `EC_COEFF_STEP` traces), so it stamps the census
8476 // plane itself rather than inheriting whichever reader did last. The
8477 // luma-only readers (`decode_rect_split`, `decode_block_rect64`,
8478 // `read_inter_plane_rect`'s corner) are all plane 0 -- the stamp's initial
8479 // value -- and the other plane-owning readers stamp on entry.
8480 set_census_plane(plane);
8481 let ibctx_on = crate::envflags::env_flag!("EC_IBCTX");
8482 let entry_bit = if ibctx_on { dec.debug_bitpos() } else { 0 };
8483 let iv_bit = unit_iv_in(plane, w, h, skip_ctx, dec);
8484 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
8485 unit_iv_skip(dec, iv_bit, plane, w, h, skip_ctx, all_zero);
8486 if rect_trace {
8487 eprintln!(
8488 "EC_COEFF_STEP tag=all_zero plane={plane} ctx={skip_ctx} entry={entry_rng} all_zero={} rng={} bit={entry_bit} post_bit={}",
8489 all_zero as i32,
8490 dec.debug_state().0,
8491 dec.debug_bitpos()
8492 );
8493 }
8494 if ibctx_on {
8495 // lane-ibc444c. `bit`/`post_bit` are the STREAM POSITION, not the coder
8496 // range: the only collision-free key for pairing this unit against the
8497 // oracle's `EC_ECDUMP_IN`. And `post_bit != bit` is how a caller tells
8498 // a real symbol read from a 0-bit one -- the SQUARE reader logs a step
8499 // either way, which is exactly the artifact that made an earlier
8500 // round of this lane claim a false exactness.
8501 eprintln!(
8502 "EC_IBCTX w={w} h={h} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={entry_bit} post_bit={} at {}",
8503 dec.debug_bitpos(),
8504 std::panic::Location::caller(),
8505 );
8506 }
8507 if all_zero {
8508 census_unit(w, h, TxType::DctDct, 0, true, entry_rng, dec);
8509 unit_iv_end(dec, plane, w, h, skip_ctx);
8510 return Ok((Grid::Zero(w * h), TxType::DctDct));
8511 }
8512 let mut grid = vec![0i32; w * h];
8513 hit!(RECT_COEFF_TU_HITS);
8514 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
8515 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
8516 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
8517 // context offsets -- both of which now have rect forms
8518 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
8519 // The rect sets that carry no symbol at all still pass `None` here.
8520 let mut tx_type = default_tx_type;
8521 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
8522 let len = tx_type_cdf.len();
8523 let t = dec.symbol(tx_type_cdf);
8524 crate::census::tx_type(len, t);
8525 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
8526 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
8527 })?;
8528 if rect_trace {
8529 eprintln!(
8530 "EC_COEFF_STEP tag=tx_type plane={plane} rng={}",
8531 dec.debug_state().0
8532 );
8533 }
8534 }
8535 let class = TxClass::of(tx_type);
8536 if class != TxClass::TwoD {
8537 hit!(TX_CLASS1_HITS);
8538 }
8539 let eob = read_eob(dec, coding, class);
8540 if rect_trace {
8541 eprintln!(
8542 "EC_COEFF_STEP tag=eob eob={eob} rng={}",
8543 dec.debug_state().0
8544 );
8545 }
8546 let class_scan;
8547 let scan: &[u16] = if class == TxClass::TwoD {
8548 scan
8549 } else {
8550 class_scan = class_scan_table_wh(w, h, class);
8551 &class_scan
8552 };
8553 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
8554 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
8555 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
8556 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
8557 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
8558 // mask rather than a hardware divide.
8559 let stride = w + 4;
8560 let n = stride * (h + 4);
8561 if !(w.is_power_of_two() && n <= 36 * 36) {
8562 panic!("rect coeff scratch w={w} h={h} n={n}");
8563 }
8564 let (mut b96, mut b256, mut b768);
8565 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
8566 let levels: &mut [u8] = if n <= 96 {
8567 b96 = [0u8; 96];
8568 &mut b96[..n]
8569 } else if n <= 256 {
8570 b256 = [0u8; 256];
8571 &mut b256[..n]
8572 } else {
8573 b768 = [0u8; 768];
8574 &mut b768[..n]
8575 };
8576 let wsh = w.trailing_zeros();
8577 let wmask = w - 1;
8578 // lane-coefread: the non-zero list [`read_coeffs`] documents.
8579 let mut nz_buf = [0u16; 1024];
8580 let mut nz_n = 0usize;
8581 let (base_taps, br_taps) = flat_taps(stride, class);
8582 let (wlt, wgt) = (w < h, w > h);
8583 for scan_idx in (0..eob).rev() {
8584 let pos = scan[scan_idx] as usize;
8585 let (row, col) = (pos >> wsh, pos & wmask);
8586 let idx = row * stride + col;
8587 // libaom's column-major `coeff_idx`, for ladder comparison.
8588 let _apos = col * h + row;
8589 let level = if scan_idx == eob - 1 {
8590 let ctx = eob_coeff_ctx(scan_idx, w * h);
8591 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
8592 if rect_trace {
8593 eprintln!(
8594 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
8595 dec.debug_state().0
8596 );
8597 }
8598 v
8599 } else {
8600 let ctx = if class == TxClass::TwoD {
8601 if row == 0 && col == 0 {
8602 0
8603 } else {
8604 let m = base_mag(levels, idx, &base_taps);
8605 if wlt && row < 2 {
8606 m + 11
8607 } else if wgt && col < 2 {
8608 m + 16
8609 } else {
8610 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
8611 }
8612 }
8613 } else {
8614 base_ctx_rect(levels, stride, w, h, row, col, class)
8615 };
8616 let v = dec.symbol(&mut coding.base[ctx]) as i32;
8617 if rect_trace {
8618 eprintln!(
8619 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
8620 dec.debug_state().0
8621 );
8622 }
8623 v
8624 };
8625 let level = if level > NUM_BASE_LEVELS {
8626 let ctx = {
8627 let mag = br_mag(levels, idx, &br_taps);
8628 if row == 0 && col == 0 {
8629 mag
8630 } else {
8631 let near_origin = match class {
8632 TxClass::TwoD => row < 2 && col < 2,
8633 TxClass::Horiz => col == 0,
8634 TxClass::Vert => row == 0,
8635 };
8636 if near_origin { mag + 7 } else { mag + 14 }
8637 }
8638 };
8639 let mut level = level;
8640 let mut sent = 0;
8641 loop {
8642 let k = dec.symbol(&mut coding.br[ctx]) as i32;
8643 if rect_trace {
8644 eprintln!(
8645 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
8646 dec.debug_state().0
8647 );
8648 }
8649 level += k;
8650 sent += BR_STEP;
8651 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
8652 break;
8653 }
8654 }
8655 level
8656 } else {
8657 level
8658 };
8659 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
8660 levels[idx] = level as u8;
8661 if level != 0 {
8662 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
8663 nz_n += 1;
8664 }
8665 if rect_trace {
8666 let (rng, _) = dec.debug_state();
8667 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
8668 }
8669 }
8670 if rect_trace {
8671 let (rng, _) = dec.debug_state();
8672 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
8673 }
8674 for &packed in nz_buf[..nz_n].iter().rev() {
8675 let pos = scan[(packed >> 4) as usize] as usize;
8676 let level = (packed & 15) as i32;
8677 let negative = if pos == 0 {
8678 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
8679 } else {
8680 dec.literal(1) == 1
8681 };
8682 if rect_trace {
8683 let (rng, _) = dec.debug_state();
8684 eprintln!(
8685 "EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}",
8686 u8::from(negative)
8687 );
8688 }
8689 let level = if level > MAX_BR_LEVEL {
8690 let g = read_golomb(dec)?;
8691 level + g as i32
8692 } else {
8693 level
8694 };
8695 grid[pos] = if negative { -level } else { level };
8696 }
8697 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
8698 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
8699 // grids differ is a reader defect, one whose grids agree is a transform
8700 // defect.
8701 if crate::envflags::env_flag!("EC_DQCOEFF") {
8702 let nz: Vec<String> = grid
8703 .iter()
8704 .enumerate()
8705 .filter(|&(_, &v)| v != 0)
8706 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
8707 .collect();
8708 eprintln!(
8709 "OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}",
8710 nz.join(",")
8711 );
8712 }
8713 census_unit(w, h, tx_type, eob, false, entry_rng, dec);
8714 unit_iv_end(dec, plane, w, h, skip_ctx);
8715 Ok((Grid::Own(grid), tx_type))
8716}
8717
8718/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
8719/// [`read_plane`] family already has.
8720///
8721/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
8722/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
8723/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
8724/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
8725/// enforces that for every strip that reads its chroma through it, but the rect
8726/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
8727/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
8728/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
8729/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
8730/// chroma read desyncs at the FIRST rect leaf of the frame and every later
8731/// symbol -- and therefore every later pixel -- is decoded from the wrong
8732/// place, without ever tripping a refusal (the desynced values stay inside
8733/// every coded alphabet).
8734fn read_chroma_coeffs_rect(
8735 dec: &mut SymbolDecoder,
8736 coding: &mut TxbTables,
8737 scan: &[u16],
8738 w: usize,
8739 h: usize,
8740 skip_ctx: usize,
8741 sign_ctx: usize,
8742 default_tx_type: TxType,
8743 fctx: &crate::decode::FrameCtx,
8744 // lane-av1chrtx: the plane index, threaded to `read_coeffs_rect`'s
8745 // `EC_COEFF_STEP` traces (they used to print a hardcoded `plane=0`, so a
8746 // V-plane read was indistinguishable from a luma one in the log).
8747 plane: usize,
8748) -> Result<(Grid, TxType)> {
8749 if mono(fctx) {
8750 return Ok((Grid::Zero(w * h), TxType::DctDct));
8751 }
8752 read_coeffs_rect(
8753 dec,
8754 coding,
8755 scan,
8756 w,
8757 h,
8758 skip_ctx,
8759 sign_ctx,
8760 default_tx_type,
8761 plane,
8762 )
8763}
8764
8765/// What one coded block leaves behind for the blocks that read it as a
8766/// neighbour: whether it coded anything at all, and the sign of its DC —
8767/// [`crate::tile`]'s own private `Neighbour`.
8768#[derive(Clone, Copy, Default)]
8769struct Neighbour {
8770 /// The transform unit's cumulative coefficient level (spec `cul_level`,
8771 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
8772 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
8773 /// boolean (`level != 0`) is enough for every context this decoder read
8774 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
8775 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
8776 /// needs the actual magnitude tier of its above/left neighbours, not
8777 /// just whether they coded anything.
8778 level: u8,
8779 dc: Option<bool>,
8780}
8781
8782/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
8783/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
8784/// grid is dropped, never a panic. One `memset` per grid row instead of a
8785/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
8786/// is contiguous, so this writes exactly the cells the cell loop did,
8787/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
8788/// next row.
8789#[inline]
8790fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
8791 let end = (start + n).min(dst.len());
8792 if start < end {
8793 dst[start..end].fill(v);
8794 }
8795}
8796
8797fn neighbour_state(grid: &[i32]) -> Neighbour {
8798 // lane-coefgrid: the shared zero grid sums to zero by construction; this
8799 // sum has no early exit, so the 60% of units that code nothing used to
8800 // walk their whole grid here.
8801 if is_zero_grid(grid) {
8802 return Neighbour::default();
8803 }
8804 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
8805 Neighbour {
8806 level: cul.min(7) as u8,
8807 dc: (grid[0] != 0).then_some(grid[0] < 0),
8808 }
8809}
8810
8811/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
8812/// transform unit smaller than the block it sits in): `top`/`left` are the
8813/// above/left neighbours' magnitude tiers, each already clamped to 4.
8814pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
8815 [1, 2, 2, 2, 3],
8816 [2, 4, 4, 4, 5],
8817 [2, 4, 4, 4, 5],
8818 [2, 4, 4, 4, 5],
8819 [3, 5, 5, 5, 6],
8820];
8821
8822/// The `skip` flag, its written-instrument bit, and the covering coded
8823/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
8824/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
8825/// nothing else, so a block's row is one fill instead of four, and the
8826/// deblocker's `pu_edge` reads origin and dims off one cache line.
8827#[derive(Clone, Copy)]
8828struct BlkCell {
8829 skip: bool,
8830 written: bool,
8831 org: [u16; 2],
8832 dim: [u8; 2],
8833}
8834
8835/// The neighbour state a block's contexts are read from — a duplicate of
8836/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
8837/// territory this round), kept at the same two granularities the real writer
8838/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
8839/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
8840/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
8841/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
8842/// chroma transform straddling the true, odd-sized frame edge see its
8843/// neighbour's state clamped at its own subsampled edge rather than luma's.
8844#[derive(Clone)]
8845struct Neighbours {
8846 above: Vec<[Neighbour; 3]>,
8847 left: Vec<[Neighbour; 3]>,
8848 above_mode: Vec<usize>,
8849 left_mode: Vec<usize>,
8850 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
8851 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
8852 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
8853 /// luma one -- the same block can (and often does) code a different
8854 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
8855 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
8856 /// within-block neighbour finer than this grid) is luma-only -- a known,
8857 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
8858 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
8859 above_uv_mode: Vec<usize>,
8860 left_uv_mode: Vec<usize>,
8861 above_side: Vec<usize>,
8862 left_side: Vec<usize>,
8863 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
8864 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
8865 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
8866 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
8867 /// array cannot tell the second leaf's partition symbol that the first
8868 /// one was coded at 8x8.
8869 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
8870 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
8871 above_side_mi: Vec<u8>,
8872 left_side_mi: Vec<u8>,
8873 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
8874 /// / row, with the mi position it was written at
8875 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
8876 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
8877 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
8878 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
8879 /// leaf whose neighbour is another split group needs that group's leaf 3
8880 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
8881 /// and read only by [`decode_leaf_split4`]; the position guard makes it
8882 /// fall back to the coarse slot whenever the real neighbour was a block
8883 /// of 8x8 or larger (whose one mode is correct for every row it spans).
8884 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
8885 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
8886 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
8887 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
8888 /// frame is 65536 px = 16384 mi).
8889 sub8_mode_col: Vec<(u16, u8)>,
8890 sub8_mode_row: Vec<(u16, u8)>,
8891 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
8892 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
8893 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
8894 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
8895 /// the leaf above writes the same row slot the block to the left owns.
8896 uv_mode_col: Vec<(u16, u8)>,
8897 uv_mode_row: Vec<(u16, u8)>,
8898 /// Every mi cell's own `uv_mode`, the mi grid libaom's
8899 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
8900 /// blockd.h). lane-t900 r12: the one-slot-per-column
8901 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
8902 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
8903 /// overwrote the row the pair's chroma-ref half then wanted to read --
8904 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
8905 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
8906 uv_mode_grid: Vec<u8>,
8907 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
8908 /// every other band here).
8909 uv_grid_cols: usize,
8910 /// lane-av1leftwit: which BLOCK wrote each cell of [`Self::uv_mode_grid`],
8911 /// as `(epoch << 24) | (mi_r << 12) | mi_c` of the writing block's own
8912 /// top-left mi. The `uv_mode` value alone cannot answer "are the two cells
8913 /// the `+ss_y` read compares written by the same block?", which is the
8914 /// whole question the `+ss_y` term turns on: the term is only observable
8915 /// when the left neighbour is 1 mi tall, i.e. when the cell this decoder
8916 /// used to read and the cell libaom reads hold DIFFERENT blocks. `epoch`
8917 /// is [`UV_OWNER_EPOCH`], bumped once per tile, so a cell no block wrote
8918 /// in this tile can never be mistaken for a written one.
8919 uv_owner: Vec<u32>,
8920 /// Whether the block above/left of this column/row was coded `skip` --
8921 /// an inter frame's own `skip` context (spec `SkipContext`), which the
8922 /// key-frame writer never tracks (its skip context is always zero); a
8923 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
8924 /// `left_skip`.
8925 above_skip: Vec<bool>,
8926 left_skip: Vec<bool>,
8927 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
8928 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
8929 /// pixels last written over each unit by `set_txfm_ctxs`/
8930 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
8931 /// symbol reads its context from (lane-txselect, spec 5.11.17).
8932 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
8933 /// array is exactly libaom's per-superblock-row reset, since each mi row
8934 /// is only ever visited inside one superblock row.
8935 above_txfm: Vec<u8>,
8936 left_txfm: Vec<u8>,
8937 /// Whether the block above/left of this column/row coded `skip_mode`
8938 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
8939 /// lane-av1comp round 14.
8940 above_skip_mode: Vec<bool>,
8941 left_skip_mode: Vec<bool>,
8942 /// Whether the block above/left was coded inter -- the `is_inter`
8943 /// context (spec `av1_get_intra_inter_context`), a duplicate of
8944 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
8945 above_inter: Vec<bool>,
8946 left_inter: Vec<bool>,
8947 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
8948 /// alphabet) the block above/left of this column/row coded, or `-1` for
8949 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
8950 /// functions (`mvstack::ref_ctx` family) need the real reference, not
8951 /// just "was it inter" (lane-av1refs: every inter block used to be
8952 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
8953 /// enough).
8954 above_ref: Vec<i8>,
8955 left_ref: Vec<i8>,
8956 /// The block above/left's *second* reference frame when it was coded
8957 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
8958 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
8959 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
8960 /// `i8`, once a compound `read_ref_frames` lands.
8961 /// lane-publish2 audit: the "always `None` today" note this doc used to
8962 /// carry is long stale -- compound blocks do occur, and
8963 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
8964 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
8965 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
8966 /// [`crate::mvstack::NeighbourRef`] construction (class
8967 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
8968 above_ref1: Vec<Option<i8>>,
8969 left_ref1: Vec<Option<i8>>,
8970 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
8971 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
8972 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
8973 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
8974 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
8975 above_comp_group_idx: Vec<u8>,
8976 left_comp_group_idx: Vec<u8>,
8977 above_compound_idx: Vec<u8>,
8978 left_compound_idx: Vec<u8>,
8979 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
8980 /// `3` = "no info": an intra neighbour or the frame's own border) of the
8981 /// block above/left of this column/row -- spec
8982 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
8983 above_filter: Vec<[u8; 2]>,
8984 left_filter: Vec<[u8; 2]>,
8985 mi_cols: usize,
8986 mi_rows: usize,
8987 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
8988 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
8989 /// 7.15) never filters an 8x8 luma block whose covering coded block read
8990 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
8991 /// grain [`Self::record_mi`] already writes at), read back at 8x8
8992 /// granularity by [`apply_cdef`] since `skip` is constant across every
8993 /// mi cell one coded block covers.
8994 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
8995 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
8996 /// the `skip` bit at this mi cell during this frame. A fresh
8997 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
8998 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
8999 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
9000 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
9001 /// unobservable from the pixels alone. Counted by
9002 /// [`cdef_unwritten_skip_units`].
9003 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
9004 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
9005 /// which re-enables the loop filter at a prediction boundary between two
9006 /// skipped inter blocks (lane-mergefix r4). Written by
9007 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
9008 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
9009 /// that cell -- the other half of `pu_edge`: libaom tests the edge
9010 /// coordinate against the block's size in the FILTERED plane's own
9011 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
9012 blk_grid: Vec<BlkCell>,
9013 skip_grid_cols_mi: usize,
9014 /// Per-4x4-mi `is_inter_block` of the coded block COVERING that cell --
9015 /// lane-av1txctxband. libaom's `get_tx_size_context`
9016 /// (`av1/common/pred_common.h:361-370`) gates its "an inter neighbour
9017 /// contributes its own BLOCK size" override on `xd->above_mbmi` /
9018 /// `xd->left_mbmi`, which `set_mi_offsets` takes as `xd->mi[-mi_stride]`
9019 /// / `xd->mi[-1]`: the block whose bottom (left) edge abuts THIS block's
9020 /// top (right) edge at THIS cell. `setup_mbs` (`decodeframe.c:355-361`)
9021 /// writes that pointer into EVERY mi cell a block covers, so libaom's
9022 /// granularity is the covering block PER CELL -- not one slot per column.
9023 /// [`Self::above_inter`]/[`Self::left_inter`] are per-COLUMN bands holding
9024 /// the LAST block written in that column, which is the covering block only
9025 /// for the block immediately below it: on a 4:4:4 lossy `--sb-size=128`
9026 /// cq-62 stream the 8x4 intra leaf at mi(57,52) read `above_inter` as
9027 /// `true` (stale, from an intrabc block earlier in column 52) with
9028 /// `above_side_mi` 4, took the override, and read `tx_size_cat0[1]` where
9029 /// libaom reads row 2 -- the `EC_SYMR` fork at read 32813.
9030 /// Written by exactly the three places that already write the bands:
9031 /// [`Self::record_inter_rect_mi`], `record_intrabc_mi_rect` and
9032 /// `fill_lf_grid_rect`'s intra-only clear.
9033 inter_grid: Vec<bool>,
9034 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
9035 /// never splits a coded block's transform below its own size (round 2:
9036 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
9037 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
9038 /// edge-length lookup (`apply_deblock`).
9039 tx_grid: Vec<u8>,
9040 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
9041 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
9042 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
9043 tx_h_grid: Vec<u8>,
9044 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
9045 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
9046 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
9047 /// does NOT follow luma's `tx_depth` split, so deriving it as
9048 /// `tx_grid / 2` invented chroma transform edges the deblocker then
9049 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
9050 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
9051 /// every caller routes through.
9052 uv_tx_grid: Vec<u8>,
9053 uv_tx_h_grid: Vec<u8>,
9054 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
9055 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
9056 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
9057 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
9058 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
9059 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
9060 /// reference onto `LAST_FRAME`'s own delta).
9061 ref_grid: Vec<i8>,
9062 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
9063 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
9064 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
9065 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
9066 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
9067 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
9068 /// to know which mode produced the value.
9069 delta_lf_grid: Vec<[i8; 4]>,
9070 /// The block above/left's own palette-Y size (0 = not a palette block)
9071 /// and its base colours -- `av1_get_palette_mode_ctx`/
9072 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
9073 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
9074 above_palette_size: Vec<u8>,
9075 left_palette_size: Vec<u8>,
9076 above_palette_colors: Vec<[u16; 8]>,
9077 left_palette_colors: Vec<[u16; 8]>,
9078 /// As the four fields above, for the neighbour's own chroma (U-channel
9079 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
9080 /// palette size/colours (lane-palette2 r1).
9081 above_palette_uv_size: Vec<u8>,
9082 left_palette_uv_size: Vec<u8>,
9083 above_palette_uv_colors: Vec<[u16; 8]>,
9084 left_palette_uv_colors: Vec<[u16; 8]>,
9085 /// This tile's own top-left corner, in 4x4 mode-info units (spec
9086 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
9087 /// neighbour" check compares against this instead of literal `0`, since a
9088 /// block at the tile's own top/left edge has no usable neighbour even
9089 /// though a decoded block sits there in the picture (spec `decode_tile`'s
9090 /// per-tile `clear_above_context`/`left_available`/`up_available`).
9091 /// `0` for a single-tile frame, matching every existing caller exactly.
9092 tile_row0_mi: usize,
9093 tile_col0_mi: usize,
9094}
9095
9096#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9097impl Neighbours {
9098 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
9099 /// true (unpadded) size in 4x4 mode-info units.
9100 fn new(
9101 cols: usize,
9102 rows: usize,
9103 mi_cols: usize,
9104 mi_rows: usize,
9105 fctx: &crate::decode::FrameCtx,
9106 ) -> Self {
9107 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
9108 // neighbour state over the whole 64-row extent, past the frame's last
9109 // mi row (mi_rows 198, block rows 192..208). libaom's own context
9110 // buffers are superblock-aligned for exactly that reason
9111 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
9112 // side arrays to a superblock multiple and leave those cells unread --
9113 // every availability check uses the true `mi_rows`/`mi_cols` below.
9114 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
9115 let (cols, rows) = (cols.next_multiple_of(sb_sub), rows.next_multiple_of(sb_sub));
9116 Self {
9117 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
9118 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
9119 above_mode: vec![DC_PRED; cols],
9120 left_mode: vec![DC_PRED; rows],
9121 above_uv_mode: vec![DC_PRED; cols],
9122 left_uv_mode: vec![DC_PRED; rows],
9123 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
9124 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
9125 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
9126 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
9127 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
9128 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
9129 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
9130 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
9131 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
9132 uv_grid_cols: cols * (SUB / MI),
9133 uv_owner: vec![0; cols * (SUB / MI) * rows * (SUB / MI)],
9134 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
9135 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
9136 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
9137 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
9138 // 16x16 block beside it, which a SUB-grid slot cannot name
9139 // (class context-read-from-one-cell).
9140 above_skip: vec![false; cols * (SUB / MI)],
9141 left_skip: vec![false; rows * (SUB / MI)],
9142 above_skip_mode: vec![false; cols * (SUB / MI)],
9143 left_skip_mode: vec![false; rows * (SUB / MI)],
9144 above_inter: vec![false; cols * (SUB / MI)],
9145 left_inter: vec![false; rows * (SUB / MI)],
9146 above_ref: vec![-1; cols * (SUB / MI)],
9147 left_ref: vec![-1; rows * (SUB / MI)],
9148 above_ref1: vec![None; cols * (SUB / MI)],
9149 left_ref1: vec![None; rows * (SUB / MI)],
9150 above_comp_group_idx: vec![0; cols * (SUB / MI)],
9151 left_comp_group_idx: vec![0; rows * (SUB / MI)],
9152 above_compound_idx: vec![0; cols * (SUB / MI)],
9153 left_compound_idx: vec![0; rows * (SUB / MI)],
9154 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
9155 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
9156 mi_cols,
9157 mi_rows,
9158 blk_grid: vec![
9159 BlkCell {
9160 skip: false,
9161 written: false,
9162 org: [0; 2],
9163 dim: [1; 2]
9164 };
9165 cols * (SUB / MI) * rows * (SUB / MI)
9166 ],
9167 skip_grid_cols_mi: cols * (SUB / MI),
9168 inter_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
9169 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
9170 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
9171 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
9172 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
9173 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
9174 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
9175 above_palette_size: vec![0; cols * (SUB / MI)],
9176 left_palette_size: vec![0; rows * (SUB / MI)],
9177 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
9178 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
9179 above_palette_uv_size: vec![0; cols * (SUB / MI)],
9180 left_palette_uv_size: vec![0; rows * (SUB / MI)],
9181 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
9182 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
9183 tile_row0_mi: 0,
9184 tile_col0_mi: 0,
9185 }
9186 }
9187
9188 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
9189 /// tile's own column span (`col1_mi` exclusive), plus recording
9190 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
9191 /// availability check below. Left context resets every superblock row
9192 /// regardless of tile ([`Self::start_row`], already called once per SB
9193 /// row by every caller) so it needs no tile-specific reset here.
9194 fn start_tile(
9195 &mut self,
9196 row0_mi: usize,
9197 col0_mi: usize,
9198 col1_mi: usize,
9199 fctx: &crate::decode::FrameCtx,
9200 ) {
9201 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
9202 // are tile-relative, same as every other neighbour lookup here.
9203 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
9204 // lane-av1leftwit: a fresh epoch stamps every `uv_owner` cell this
9205 // tile writes, so the `+ss_y` read's "different block?" probe never
9206 // compares against a cell a previous tile left behind.
9207 UV_OWNER_EPOCH.with(|c| c.set(c.get().wrapping_add(1) | (1 << 24)));
9208 self.tile_row0_mi = row0_mi;
9209 self.tile_col0_mi = col0_mi;
9210 let end = col1_mi.min(self.above.len());
9211 for i in col0_mi.min(end)..end {
9212 self.above[i] = Default::default();
9213 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
9214 }
9215 let (sc0, sc1) = (
9216 col0_mi / (SUB / MI),
9217 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
9218 );
9219 for i in sc0.min(sc1)..sc1 {
9220 self.above_mode[i] = DC_PRED;
9221 self.above_side[i] = NO_NEIGHBOUR_SIDE;
9222 }
9223 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
9224 // the tile's own mi column span directly.
9225 let mend = col1_mi.min(self.above_skip.len());
9226 for i in col0_mi.min(mend)..mend {
9227 self.above_skip[i] = false;
9228 self.above_skip_mode[i] = false;
9229 self.above_inter[i] = false;
9230 self.above_ref[i] = -1;
9231 self.above_ref1[i] = None;
9232 self.above_comp_group_idx[i] = 0;
9233 self.above_compound_idx[i] = 0;
9234 self.above_filter[i] = [3u8; 2];
9235 }
9236 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
9237 // stale `(row, mode)` from the tile to the LEFT names an mi row this
9238 // tile's first block would read as its own above neighbour.
9239 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
9240 for i in col0_mi.min(mcol_end)..mcol_end {
9241 self.sub8_mode_col[i] = (u16::MAX, 0);
9242 self.uv_mode_col[i] = (u16::MAX, 0);
9243 }
9244 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
9245 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
9246 // not zero) -- without it a second tile column reads the first one's
9247 // resolved transform sizes as its own above context.
9248 let tend = col1_mi.min(self.above_txfm.len());
9249 for i in col0_mi.min(tend)..tend {
9250 self.above_txfm[i] = TXFM_CTX_INIT;
9251 }
9252 }
9253
9254 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
9255 /// for a non-palette block, clearing any stale neighbour state) into every
9256 /// [`SUB`]-grid cell it covers on both the above and left edges --
9257 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
9258 /// call sites are all square blocks).
9259 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
9260 self.record_palette_y_rect(
9261 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
9262 side,
9263 side,
9264 size,
9265 colors,
9266 );
9267 }
9268
9269 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
9270 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
9271 /// [`Self::record`]): a true rect strip's above/left neighbour spans
9272 /// differ.
9273 fn record_palette_y_rect(
9274 &mut self,
9275 mi: (usize, usize),
9276 w: usize,
9277 h: usize,
9278 size: usize,
9279 colors: [u16; 8],
9280 ) {
9281 let (r, c) = mi;
9282 if crate::envflags::env_flag!("EC_PALPUB") {
9283 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
9284 }
9285 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
9286 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
9287 // cell immediately left of the block, not its 16px [`SUB`] cell. The
9288 // old SUB grid let a 16x8 strip pair share one slot, so the second
9289 // strip of mi(0,8) read the FIRST strip's palette size and the colour
9290 // cache came out one entry short (class [[context-read-from-one-cell]]).
9291 for cell in 0..(w / MI).max(1) {
9292 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
9293 *e = size as u8;
9294 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
9295 // neighbour's colours only where its palette size > 0, so a
9296 // non-palette block need not stamp 16 bytes of zeroes here.
9297 if size > 0 {
9298 self.above_palette_colors[c + cell] = colors;
9299 }
9300 }
9301 }
9302 for cell in 0..(h / MI).max(1) {
9303 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
9304 *e = size as u8;
9305 if size > 0 {
9306 self.left_palette_colors[r + cell] = colors;
9307 }
9308 }
9309 }
9310 }
9311
9312 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
9313 /// neighbours that are themselves a palette-Y block, plus
9314 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
9315 /// cache (pred_common.c:73).
9316 ///
9317 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
9318 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
9319 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
9320 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
9321 /// the ctx too made every superblock in the frame's second SB row read
9322 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
9323 /// palette block decoded as "no palette" and the tile desynced from
9324 /// there (class [[cdf-row-held-constant]]).
9325 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
9326 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
9327 }
9328
9329 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
9330 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
9331 /// drops the above neighbour on a 64-px superblock boundary
9332 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
9333 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
9334 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
9335 /// every strip in an SB's top cell row, which libaom does not do.
9336 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
9337 let (r, c) = mi;
9338 let above_ok = r % 16 != 0;
9339 // `xd->above_mbmi` exists for every row but the tile's own first.
9340 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
9341 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
9342 (
9343 usize::from(self.above_palette_size[c]),
9344 self.above_palette_colors[c],
9345 )
9346 } else {
9347 (0, [0u16; 8])
9348 };
9349 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
9350 // is NULL whenever the block sits at its TILE's own left column
9351 // (`left_available`), not the frame's -- without this guard a second
9352 // tile column reads the previous tile's palette colours into its cache
9353 // and its `palette_y_mode` ctx.
9354 let left_ok = c > self.tile_col0_mi;
9355 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
9356 (
9357 usize::from(self.left_palette_size[r]),
9358 self.left_palette_colors[r],
9359 )
9360 } else {
9361 (0, [0u16; 8])
9362 };
9363 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
9364 let mut cache = Vec::with_capacity(16);
9365 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
9366 if cache.last() != Some(&v) {
9367 cache.push(v);
9368 }
9369 };
9370 let (mut ai, mut li) = (0usize, 0usize);
9371 while ai < above_n && li < left_n {
9372 let (va, vl) = (above_colors[ai], left_colors[li]);
9373 if vl < va {
9374 push_dedup(&mut cache, vl);
9375 li += 1;
9376 } else {
9377 push_dedup(&mut cache, va);
9378 ai += 1;
9379 if vl == va {
9380 li += 1;
9381 }
9382 }
9383 }
9384 while ai < above_n {
9385 push_dedup(&mut cache, above_colors[ai]);
9386 ai += 1;
9387 }
9388 while li < left_n {
9389 push_dedup(&mut cache, left_colors[li]);
9390 li += 1;
9391 }
9392 (ctx, cache)
9393 }
9394
9395 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
9396 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
9397 /// same way (lane-palette2 r1).
9398 fn record_palette_uv(
9399 &mut self,
9400 at: (usize, usize),
9401 side: usize,
9402 size: usize,
9403 colors: [u16; 8],
9404 ) {
9405 self.record_palette_uv_rect(
9406 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
9407 side,
9408 side,
9409 size,
9410 colors,
9411 );
9412 }
9413
9414 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
9415 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
9416 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
9417 /// luma resolution regardless of which plane the recorded state is for).
9418 fn record_palette_uv_rect(
9419 &mut self,
9420 mi: (usize, usize),
9421 w: usize,
9422 h: usize,
9423 size: usize,
9424 colors: [u16; 8],
9425 ) {
9426 let (r, c) = mi;
9427 // mi granularity, see [`Self::record_palette_y_rect`].
9428 for cell in 0..(w / MI).max(1) {
9429 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
9430 *e = size as u8;
9431 if size > 0 {
9432 self.above_palette_uv_colors[c + cell] = colors;
9433 }
9434 }
9435 }
9436 for cell in 0..(h / MI).max(1) {
9437 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
9438 *e = size as u8;
9439 if size > 0 {
9440 self.left_palette_uv_colors[r + cell] = colors;
9441 }
9442 }
9443 }
9444 }
9445
9446 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
9447 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
9448 /// no neighbour lookup at all (it is this block's own just-decided Y
9449 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
9450 /// so only the cache is wanted here.
9451 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
9452 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
9453 }
9454
9455 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
9456 /// [`Self::palette_ctx_and_cache_mi`].
9457 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
9458 let (r, c) = mi;
9459 let above_ok = r % 16 != 0;
9460 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
9461 (
9462 usize::from(self.above_palette_uv_size[c]),
9463 self.above_palette_uv_colors[c],
9464 )
9465 } else {
9466 (0, [0u16; 8])
9467 };
9468 // Same tile-relative left availability as the luma cache above.
9469 let left_ok = c > self.tile_col0_mi;
9470 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
9471 (
9472 usize::from(self.left_palette_uv_size[r]),
9473 self.left_palette_uv_colors[r],
9474 )
9475 } else {
9476 (0, [0u16; 8])
9477 };
9478 let mut cache = Vec::with_capacity(16);
9479 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
9480 if cache.last() != Some(&v) {
9481 cache.push(v);
9482 }
9483 };
9484 let (mut ai, mut li) = (0usize, 0usize);
9485 while ai < above_n && li < left_n {
9486 let (va, vl) = (above_colors[ai], left_colors[li]);
9487 if vl < va {
9488 push_dedup(&mut cache, vl);
9489 li += 1;
9490 } else {
9491 push_dedup(&mut cache, va);
9492 ai += 1;
9493 if vl == va {
9494 li += 1;
9495 }
9496 }
9497 }
9498 while ai < above_n {
9499 push_dedup(&mut cache, above_colors[ai]);
9500 ai += 1;
9501 }
9502 while li < left_n {
9503 push_dedup(&mut cache, left_colors[li]);
9504 li += 1;
9505 }
9506 cache
9507 }
9508
9509 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
9510 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
9511 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
9512 /// units as [`Self::fill_skip_grid`].
9513 fn fill_lf_grid(
9514 &mut self,
9515 at_mi: (usize, usize),
9516 side_mi: usize,
9517 tx_px: u8,
9518 ref_frame: i8,
9519 fctx: &crate::decode::FrameCtx,
9520 ) {
9521 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
9522 }
9523
9524 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
9525 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
9526 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
9527 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
9528 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
9529 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
9530 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
9531 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
9532 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
9533 /// block's published transform extent to its own size is exactly that
9534 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
9535 /// that needs it is the 128 root, whose chroma extent is the one
9536 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
9537 /// never suppressed (libaom's `is_inter_block` term), so this is called
9538 /// only from the skipped-inter branch.
9539 ///
9540 /// The extent is the block's own CHROMA footprint, `w_mi * MI >> ss_x` per
9541 /// axis -- `av1_setup_dst_planes`'s `get_plane_block_size(bsize, ss_x,
9542 /// ss_y)` (`common_data.c:38`, which at ss (0,0) is BLOCK_128X128
9543 /// itself, so 128 and not 64). This used to be a hardcoded `w_mi * MI / 2`,
9544 /// correct at 4:2:0 by the `>> 1 == / 2` identity and half the truth at
9545 /// 4:4:4; lane-av1txsizeaudit r2 replaced it with the per-axis shift, the
9546 /// form its sibling `fill_lf_grid_rect` already used. The `fctx` is
9547 /// threaded in for it: `Neighbours` carries no subsampling of its own, so
9548 /// no format guard was possible inside this method until now.
9549 ///
9550 /// **MEASURED INERT, and do not go looking for a pixel regression.** The
9551 /// widening defeats the deblocker's alignment gate (`x0 & (tx - 1)`), but
9552 /// every edge it lets through then meets the SAME libaom rule applied at
9553 /// the correct place, `edge_params_body`'s spec-7.14.2 / libaom
9554 /// `set_lpf_parameters` term `!pu_edge && cur_ref != 0 && pv_ref != 0 &&
9555 /// skip_at && skip_at`. Inside one skipped block both cells are that same
9556 /// block, so all four terms hold and the edge dies there too. The masking
9557 /// is TOTAL, not incidental: this method is only ever called for a block
9558 /// that is itself skipped, so no input exists on which one side of an
9559 /// internal edge is not skipped. Measured over 26 frames / 2 555 904
9560 /// samples across five 4:4:4 `--sb-size=128` streams that fire this arm
9561 /// 30 times: `64` and `128` both decode pixel-exact against aomdec, and
9562 /// differ from each other in not one sample. The gate for this value is
9563 /// therefore a source scan, not a pixel gate --
9564 /// `refusal_inventory::the_skipped_128_root_chroma_suppression_publishes_the_blocks_own_per_axis_chroma_extent`.
9565 fn suppress_internal_lf_edges(
9566 &mut self,
9567 at_mi: (usize, usize),
9568 w_mi: usize,
9569 h_mi: usize,
9570 fctx: &FrameCtx,
9571 ) {
9572 let (mi_r, mi_c) = at_mi;
9573 let (uv_w, uv_h) = (
9574 ((w_mi * MI) >> ss_x(fctx)).max(4) as u8,
9575 ((h_mi * MI) >> ss_y(fctx)).max(4) as u8,
9576 );
9577 for rr in 0..h_mi {
9578 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9579 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
9580 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
9581 }
9582 }
9583
9584 fn fill_lf_grid_rect(
9585 &mut self,
9586 at_mi: (usize, usize),
9587 w_mi: usize,
9588 h_mi: usize,
9589 tx_px: u8,
9590 tx_h_px: u8,
9591 ref_frame: i8,
9592 fctx: &crate::decode::FrameCtx,
9593 ) {
9594 let (mi_r, mi_c) = at_mi;
9595 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
9596 // half its luma one (min 4 px, the smallest transform), capped at
9597 // TX_32X32 -- independent of this block's luma `tx_depth`.
9598 let uv_tx_w = (((w_mi * MI) >> ss_x(fctx)).max(4).min(32)) as u8;
9599 let uv_tx_h = (((h_mi * MI) >> ss_y(fctx)).max(4).min(32)) as u8;
9600 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9601 eprintln!(
9602 "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}"
9603 );
9604 }
9605 crate::census::tx(tx_px, tx_h_px);
9606 let cur = fctx.current_delta_lf.with(|c| c.get());
9607 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
9608 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
9609 } else {
9610 [cur[0].clamp(-63, 63) as i8; 4]
9611 };
9612 for rr in 0..h_mi {
9613 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9614 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9615 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9616 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
9617 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
9618 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
9619 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
9620 }
9621 if fctx.intra_only.with(std::cell::Cell::get) {
9622 // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size,
9623 // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi),
9624 // xd)` for EVERY block, an intra-only frame's included, and
9625 // `get_tx_size_context` / `txfm_partition_context` read those two
9626 // `TXFM_CONTEXT` bands. This grid carries the same transform size
9627 // over the same footprint, so the publish is this write: the
9628 // `skip && is_inter` term is 0 for every intra-only block that is
9629 // not an intrabc one, and the bodies that can code an intrabc
9630 // block publish their own (the term is then the BLOCK size, a value
9631 // this grid cannot express -- see `decode_block`/`decode_leaf8`).
9632 // Inter frames publish at their own sites and are excluded here
9633 // because their skipped-block term needs the block size too.
9634 txfm_partition_update_rect(
9635 self,
9636 at_mi,
9637 (tx_px as usize, tx_h_px as usize),
9638 (w_mi * MI, h_mi * MI),
9639 );
9640 // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`),
9641 // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size
9642 // instead of its transform band. Every block stamps its own cells
9643 // here; the intrabc bodies re-stamp theirs `true` afterwards
9644 // (`record_intrabc_inter_bands`).
9645 for i in 0..w_mi {
9646 if let Some(cell) = self.above_inter.get_mut(mi_c + i) {
9647 *cell = false;
9648 }
9649 }
9650 for i in 0..h_mi {
9651 if let Some(cell) = self.left_inter.get_mut(mi_r + i) {
9652 *cell = false;
9653 }
9654 }
9655 // lane-av1txctxband: the same clear at libaom's own per-CELL
9656 // granularity. The band above clears one slot per column, so a
9657 // block that covered column 52 and a later block in the SAME
9658 // column but a different row leave the band describing whichever
9659 // wrote last; the grid clears exactly the cells this block owns.
9660 self.mark_inter_grid_rect(at_mi, w_mi, h_mi, false);
9661 }
9662 // lane-av1-intrabc r4: publish this coded block's own mi footprint
9663 // into the intrabc MV grid's block-COVERAGE map -- every coded block,
9664 // not just the intrabc ones. A later intrabc block's DV predictor is
9665 // built by libaom's own row/col scans over `xd->mi[]`, which holds an
9666 // `MB_MODE_INFO` for EVERY block and steps by
9667 // `mi_size_wide/height[candidate->bsize]`; without this footprint a
9668 // non-intrabc neighbour reads as uncovered and the scan advances it
9669 // by one cell instead of by its real width.
9670 fctx.intrabc_mi_grid.with(|g| {
9671 if let Some((grid, _, _)) = g.borrow_mut().as_mut() {
9672 grid.cover_rect(mi_r, mi_c, w_mi, h_mi);
9673 }
9674 });
9675 }
9676
9677 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
9678 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
9679 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
9680 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
9681 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
9682 /// dims from the LEAF span and so invented chroma transform edges the
9683 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
9684 /// are already correct from the block's own fill over the same span.
9685 fn fill_lf_grid_leaf_luma(
9686 &mut self,
9687 at_mi: (usize, usize),
9688 w_mi: usize,
9689 h_mi: usize,
9690 tx_px: u8,
9691 tx_h_px: u8,
9692 ) {
9693 let (mi_r, mi_c) = at_mi;
9694 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
9695 eprintln!(
9696 "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}"
9697 );
9698 }
9699 for rr in 0..h_mi {
9700 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9701 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
9702 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
9703 }
9704 }
9705
9706 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
9707 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
9708 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
9709 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
9710 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
9711 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
9712 }
9713
9714 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
9715 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
9716 let (mi_r, mi_c) = at_mi;
9717 if skip && w_mi != h_mi {
9718 hit!(RECT_SKIP_BAND_HITS);
9719 }
9720 // lane-census: an INTRA frame's blocks never reach the inter
9721 // publisher, and this one is what every coded block writes.
9722 crate::census::block_intra_frame(w_mi, h_mi, skip);
9723 for rr in 0..h_mi {
9724 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
9725 fill_span(
9726 &mut self.blk_grid,
9727 start,
9728 w_mi,
9729 BlkCell {
9730 skip,
9731 written: true,
9732 org: [mi_r as u16, mi_c as u16],
9733 dim: [w_mi as u8, h_mi as u8],
9734 },
9735 );
9736 }
9737 }
9738 /// Publishes one coded block's `is_inter_block` over EVERY 4x4 mi cell it
9739 /// covers -- lane-av1txctxband. libaom's `setup_mbs`
9740 /// (`decodeframe.c:355-361`) writes the block's own `MB_MODE_INFO`
9741 /// pointer into all of them, so `xd->mi[-xd->mi_stride]` /
9742 /// `xd->mi[-1]` name the block COVERING the cell, not "the last block
9743 /// written in this column" ([`Self::above_inter`] /
9744 /// [`Self::left_inter`], which is a per-column band and therefore stale
9745 /// for any block below the last writer in its column).
9746 /// Separate from [`Self::fill_skip_grid_rect`] because the two publishers
9747 /// run in BOTH orders at different call sites; both write disjoint fields,
9748 /// so the order does not matter. The value read is libaom's
9749 /// `is_inter_block` (`blockd.h:372-374`): an INTRABC block counts.
9750 fn mark_inter_grid_rect(
9751 &mut self,
9752 at_mi: (usize, usize),
9753 w_mi: usize,
9754 h_mi: usize,
9755 is_inter: bool,
9756 ) {
9757 for rr in 0..h_mi {
9758 let start = (at_mi.0 + rr) * self.skip_grid_cols_mi + at_mi.1;
9759 fill_span(&mut self.inter_grid, start, w_mi, is_inter);
9760 }
9761 }
9762
9763 /// `is_inter_block` of the coded block covering the mi cell
9764 /// `(mi_r, mi_c)`, or `false` for a cell no block has written yet (a tile
9765 /// border or a not-yet-decoded cell) -- lane-av1txctxband. The caller's
9766 /// `up_available` / `left_available` guard already excludes the borders.
9767 fn inter_at(&self, mi_r: usize, mi_c: usize) -> bool {
9768 self.inter_grid
9769 .get(mi_r * self.skip_grid_cols_mi + mi_c)
9770 .copied()
9771 .unwrap_or(false)
9772 }
9773
9774 /// The covering block's own `(block_size_wide, block_size_high)` in
9775 /// pixels at the mi cell `(mi_r, mi_c)`, from [`Self::blk_grid`]'s `dim`
9776 /// (the published mi extent) scaled by [`MI`] -- lane-av1txctxband. This
9777 /// is libaom's `block_size_wide[above_mbmi->bsize]` /
9778 /// `block_size_high[left_mbmi->bsize]`, read at the abutting CELL rather
9779 /// than from the per-column [`Self::above_side_mi`] /
9780 /// [`Self::left_side_mi`] band.
9781 fn blk_side_at(&self, mi_r: usize, mi_c: usize) -> (usize, usize) {
9782 self.blk_grid
9783 .get(mi_r * self.skip_grid_cols_mi + mi_c)
9784 .filter(|c| c.written)
9785 .map_or((0, 0), |c| (c.dim[0] as usize * MI, c.dim[1] as usize * MI))
9786 }
9787
9788 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
9789 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
9790 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
9791 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
9792 /// straddle the region with a mix of skip/non-skip blocks).
9793 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
9794 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
9795 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
9796 /// filtered edge's two sides are each exactly one coded block wide.
9797 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
9798 self.blk_grid
9799 .get(mi_r * self.skip_grid_cols_mi + mi_c)
9800 .is_some_and(|c| c.skip)
9801 }
9802
9803 /// The `skip_txfm` context of a block whose top-left mi cell is
9804 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
9805 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
9806 /// with an absent neighbour contributing 0. The mi grid is per tile, so
9807 /// row/column 0 is a tile edge and has no neighbour on that axis.
9808 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
9809 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
9810 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
9811 }
9812
9813 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
9814 (0..2).all(|rr| {
9815 (0..2).all(|cc| {
9816 self.blk_grid
9817 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
9818 .is_some_and(|c| c.skip)
9819 })
9820 })
9821 }
9822
9823 fn start_row(&mut self) {
9824 self.left.iter_mut().for_each(|l| *l = Default::default());
9825 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
9826 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
9827 self.left_side
9828 .iter_mut()
9829 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
9830 self.left_side_mi
9831 .iter_mut()
9832 .for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
9833 self.left_skip.iter_mut().for_each(|s| *s = false);
9834 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
9835 self.left_inter.iter_mut().for_each(|i| *i = false);
9836 self.left_ref.iter_mut().for_each(|r| *r = -1);
9837 self.left_ref1.iter_mut().for_each(|r| *r = None);
9838 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
9839 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
9840 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
9841 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
9842 // context (a tile/SB-row boundary has no left neighbour).
9843 self.sub8_mode_row
9844 .iter_mut()
9845 .for_each(|s| *s = (u16::MAX, 0));
9846 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
9847 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
9848 // are per-mi maps like every other one here, so they reset with the
9849 // row too -- the left guard above is what actually stops a cross-tile
9850 // read, this keeps a stale colour out of the arrays at all.
9851 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
9852 self.left_palette_colors
9853 .iter_mut()
9854 .for_each(|c| *c = [0u16; 8]);
9855 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
9856 self.left_palette_uv_colors
9857 .iter_mut()
9858 .for_each(|c| *c = [0u16; 8]);
9859 // lane-mergefix r2: `av1_zero_left_context` memsets
9860 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
9861 // every superblock row of every tile -- the var-tx left context does
9862 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
9863 // previous tile column's last block otherwise).
9864 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
9865 }
9866
9867 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
9868 /// block that reads it as a neighbour -- [`crate::tile`]'s
9869 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
9870 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
9871 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
9872 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
9873 /// the real value, not just `is_inter`).
9874 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9875 fn record_inter(
9876 &mut self,
9877 at: (usize, usize),
9878 side: usize,
9879 skip: bool,
9880 is_inter: bool,
9881 ref_frame: i8,
9882 filter: [u8; 2],
9883 skip_mode: bool,
9884 ) {
9885 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
9886 }
9887
9888 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
9889 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
9890 /// r1: a true rectangular strip's above-context span (its own width) and
9891 /// left-context span (its own height) differ, unlike every caller before
9892 /// this round (class neighbour-votes-all-its-fields).
9893 #[allow(clippy::too_many_arguments)]
9894 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9895 fn record_inter_rect(
9896 &mut self,
9897 at: (usize, usize),
9898 w_sub: usize,
9899 h_sub: usize,
9900 skip: bool,
9901 is_inter: bool,
9902 ref_frame: i8,
9903 filter: [u8; 2],
9904 skip_mode: bool,
9905 ) {
9906 let (r, c) = at;
9907 self.record_inter_rect_mi(
9908 (r * (SUB / MI), c * (SUB / MI)),
9909 w_sub / MI,
9910 h_sub / MI,
9911 skip,
9912 is_inter,
9913 ref_frame,
9914 filter,
9915 skip_mode,
9916 );
9917 }
9918
9919 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
9920 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
9921 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
9922 /// routes through the wrapper above.
9923 #[allow(clippy::too_many_arguments)]
9924 fn record_inter_rect_mi(
9925 &mut self,
9926 at_mi: (usize, usize),
9927 w_mi: usize,
9928 h_mi: usize,
9929 skip: bool,
9930 is_inter: bool,
9931 ref_frame: i8,
9932 filter: [u8; 2],
9933 skip_mode: bool,
9934 ) {
9935 let (r, c) = at_mi;
9936 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
9937 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
9938 // writes for a whole block class): an INTER block left the luma mode
9939 // map untouched, so a later intra block's `get_intra_edge_filter_type`
9940 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
9941 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
9942 // block in that pixel row -- the directional edge filter then ran at
9943 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
9944 // which for an inter block is an INTER mode (>= NEARESTMV) and is
9945 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
9946 // already stamped it).
9947 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
9948 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
9949 // uv map must read DC_PRED over an inter block's cells too.
9950 if is_inter {
9951 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9952 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
9953 }
9954 // lane-av1txctxband: the per-CELL `is_inter_block` the per-column
9955 // `above_inter` band stands in for, at libaom's own granularity.
9956 self.mark_inter_grid_rect(at_mi, w_mi, h_mi, is_inter);
9957 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
9958 self.above_skip[c..c + w_mi].fill(skip);
9959 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
9960 self.above_inter[c..c + w_mi].fill(is_inter);
9961 self.above_ref[c..c + w_mi].fill(ref_frame);
9962 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
9963 // this with the block's real second reference for a compound block,
9964 // called right after this one (lane-publish2 audit).
9965 self.above_ref1[c..c + w_mi].fill(None);
9966 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
9967 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
9968 // as `3`/`1` even though this block has no second reference.
9969 // `record_compound_ctx` overwrites this with the real bit for an
9970 // actual compound block's cells, called right after this one.
9971 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
9972 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
9973 self.above_filter[c..c + w_mi].fill(filter);
9974 self.left_skip[r..r + h_mi].fill(skip);
9975 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
9976 self.left_inter[r..r + h_mi].fill(is_inter);
9977 self.left_ref[r..r + h_mi].fill(ref_frame);
9978 self.left_ref1[r..r + h_mi].fill(None);
9979 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
9980 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
9981 self.left_filter[r..r + h_mi].fill(filter);
9982 }
9983
9984 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
9985 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
9986 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
9987 /// `get_comp_index_context`) -- called right after `record_inter` for
9988 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
9989 /// stamps `above_ref1`/`left_ref1` with the block's real second
9990 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
9991 /// this is the one caller that actually knows it) -- so the next block's
9992 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
9993 /// neighbour instead of `record_inter`'s single-ref default.
9994 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
9995 fn record_compound_ctx(
9996 &mut self,
9997 at: (usize, usize),
9998 side: usize,
9999 ref1: i8,
10000 comp_group_idx: u8,
10001 compound_idx: u8,
10002 ) {
10003 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
10004 }
10005
10006 /// [`Self::record_compound_ctx`] with independent above/left extents,
10007 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
10008 #[allow(clippy::too_many_arguments)]
10009 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
10010 fn record_compound_ctx_rect(
10011 &mut self,
10012 at: (usize, usize),
10013 w_sub: usize,
10014 h_sub: usize,
10015 ref1: i8,
10016 comp_group_idx: u8,
10017 compound_idx: u8,
10018 ) {
10019 let (r, c) = at;
10020 self.record_compound_ctx_rect_mi(
10021 (r * (SUB / MI), c * (SUB / MI)),
10022 w_sub / MI,
10023 h_sub / MI,
10024 ref1,
10025 comp_group_idx,
10026 compound_idx,
10027 );
10028 }
10029
10030 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
10031 /// [`Self::record_inter_rect_mi`]).
10032 fn record_compound_ctx_rect_mi(
10033 &mut self,
10034 at_mi: (usize, usize),
10035 w_mi: usize,
10036 h_mi: usize,
10037 ref1: i8,
10038 comp_group_idx: u8,
10039 compound_idx: u8,
10040 ) {
10041 let (r, c) = at_mi;
10042 crate::census::compound();
10043 for cell in 0..w_mi {
10044 self.above_ref1[c + cell] = Some(ref1);
10045 self.above_comp_group_idx[c + cell] = comp_group_idx;
10046 self.above_compound_idx[c + cell] = compound_idx;
10047 }
10048 for cell in 0..h_mi {
10049 self.left_ref1[r + cell] = Some(ref1);
10050 self.left_comp_group_idx[r + cell] = comp_group_idx;
10051 self.left_compound_idx[r + cell] = compound_idx;
10052 }
10053 }
10054
10055 /// The context of a block's partition symbol: delegates to the mi-precise
10056 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
10057 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
10058 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
10059 /// only touches the finer mi arrays -- leaves them stale for the *next*
10060 /// sibling's own partition symbol.
10061 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
10062 let (r, c) = at;
10063 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
10064 }
10065
10066 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
10067 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
10068 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
10069 /// than the enclosing 16x16 slot's stale, shared state.
10070 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
10071 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
10072 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
10073 }
10074
10075 /// The gathered coded/DC-sign state of the blocks above and to the left
10076 /// of a block `side` samples across, per plane.
10077 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
10078 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
10079 }
10080
10081 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
10082 /// units, for the same reason [`Self::record_mi`] does.
10083 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
10084 let side_mi = side / MI;
10085 // One pass over the cells accumulating all three planes, not one pass
10086 // per plane: the three planes of a cell live in the same
10087 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
10088 // cache lines three times (lane-publish). Clamp each edge to the true
10089 // frame extent: a block at the right/bottom edge may be padded beyond
10090 // `mi_cols`/`mi_rows`, and libaom's unavailable context is zero there.
10091 let above_mi = side_mi.min(self.mi_cols.saturating_sub(mi_c));
10092 let left_mi = side_mi.min(self.mi_rows.saturating_sub(mi_r));
10093 let mut out = [(false, false, 0i32); 3];
10094 for cell in 0..above_mi {
10095 let above = &self.above[mi_c + cell];
10096 for (plane, o) in out.iter_mut().enumerate() {
10097 o.0 |= above[plane].level != 0;
10098 o.2 += dc_vote(above[plane].dc);
10099 }
10100 }
10101 for cell in 0..left_mi {
10102 let left = &self.left[mi_r + cell];
10103 for (plane, o) in out.iter_mut().enumerate() {
10104 o.1 |= left[plane].level != 0;
10105 o.2 += dc_vote(left[plane].dc);
10106 }
10107 }
10108 out
10109 }
10110
10111 /// [`Self::around_mi_rect`] for the CHROMA planes of a 4:2:2 frame
10112 /// (lane-av1-422f): libaom `get_txb_ctx_general` reads its above votes
10113 /// over `txb_w_unit` CHROMA 4-px cells, and at ss_x 1 one chroma cell
10114 /// spans TWO luma mi columns. Both cells of a column carry the covering
10115 /// unit's whole-unit dc sign (the same value libaom stores), so the
10116 /// per-luma-mi sum counts each chroma column twice -- and
10117 /// `dc_sign_ctx`'s signum flips whenever the above and left votes have
10118 /// opposite signs with equal magnitude (measured at mi(4,4) plane 1 of
10119 /// the t422 fixture: ours read `dc_sign_cdf[1]`, the oracle row 0).
10120 /// Sampling every second above cell counts each chroma column once,
10121 /// which IS libaom's sum. The left extent is unsubsquared at ss_y 0, so
10122 /// its per-mi cells already line up one-to-one. The level booleans are
10123 /// ORs over duplicated cells, so the sampling cannot change them.
10124 fn around_mi_422_chroma(
10125 &self,
10126 (mi_r, mi_c): (usize, usize),
10127 w: usize,
10128 h: usize,
10129 ) -> [(bool, bool, i32); 3] {
10130 let (w_mi, h_mi) = (w / MI, h / MI);
10131 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
10132 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
10133 let mut out = [(false, false, 0i32); 3];
10134 for cell in (0..above_mi).step_by(2) {
10135 let above = &self.above[mi_c + cell];
10136 for (plane, o) in out.iter_mut().enumerate() {
10137 o.0 |= above[plane].level != 0;
10138 o.2 += dc_vote(above[plane].dc);
10139 }
10140 }
10141 for cell in 0..left_mi {
10142 let left = &self.left[mi_r + cell];
10143 for (plane, o) in out.iter_mut().enumerate() {
10144 o.1 |= left[plane].level != 0;
10145 o.2 += dc_vote(left[plane].dc);
10146 }
10147 }
10148 if crate::envflags::env_flag!("EC_DCDUMP") {
10149 // lane-av1422mi24: same dump [`Self::around_mi_rect`] prints, so
10150 // a rerouted 4:2:2 chroma gather stays visible under EC_DCDUMP=1.
10151 // The above rows are the SAMPLED (every-second) cells.
10152 for (plane, o) in out.iter().enumerate() {
10153 let vote = o.2;
10154 let ab: Vec<String> = (0..above_mi)
10155 .step_by(2)
10156 .map(|k| {
10157 format!(
10158 "{:?}/{}",
10159 self.above[mi_c + k][plane].dc,
10160 self.above[mi_c + k][plane].level
10161 )
10162 })
10163 .collect();
10164 let lf: Vec<String> = (0..left_mi)
10165 .map(|k| {
10166 format!(
10167 "{:?}/{}",
10168 self.left[mi_r + k][plane].dc,
10169 self.left[mi_r + k][plane].level
10170 )
10171 })
10172 .collect();
10173 eprintln!(
10174 "EC_DCDUMP422 mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
10175 ab.join(","),
10176 lf.join(",")
10177 );
10178 }
10179 }
10180 out
10181 }
10182
10183 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
10184 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
10185 /// extent pattern for a true rectangular strip's own coefficient context.
10186 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
10187 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
10188 }
10189
10190 /// [`Self::around_rect`] taking the block's position directly in 4x4
10191 /// mode-info units, mirroring [`Self::around_mi`].
10192 fn around_mi_rect(
10193 &self,
10194 (mi_r, mi_c): (usize, usize),
10195 w: usize,
10196 h: usize,
10197 ) -> [(bool, bool, i32); 3] {
10198 let (w_mi, h_mi) = (w / MI, h / MI);
10199 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
10200 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
10201 // [`Self::around_mi`]'s single pass, with the two extents split.
10202 let mut out = [(false, false, 0i32); 3];
10203 for cell in 0..above_mi {
10204 let above = &self.above[mi_c + cell];
10205 for (plane, o) in out.iter_mut().enumerate() {
10206 o.0 |= above[plane].level != 0;
10207 o.2 += dc_vote(above[plane].dc);
10208 }
10209 }
10210 for cell in 0..left_mi {
10211 let left = &self.left[mi_r + cell];
10212 for (plane, o) in out.iter_mut().enumerate() {
10213 o.1 |= left[plane].level != 0;
10214 o.2 += dc_vote(left[plane].dc);
10215 }
10216 }
10217 if crate::envflags::env_flag!("EC_DCDUMP") {
10218 for (plane, o) in out.iter().enumerate() {
10219 let vote = o.2;
10220 let ab: Vec<String> = (0..above_mi)
10221 .map(|k| {
10222 format!(
10223 "{:?}/{}",
10224 self.above[mi_c + k][plane].dc,
10225 self.above[mi_c + k][plane].level
10226 )
10227 })
10228 .collect();
10229 let lf: Vec<String> = (0..left_mi)
10230 .map(|k| {
10231 format!(
10232 "{:?}/{}",
10233 self.left[mi_r + k][plane].dc,
10234 self.left[mi_r + k][plane].level
10235 )
10236 })
10237 .collect();
10238 eprintln!(
10239 "EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
10240 ab.join(","),
10241 lf.join(",")
10242 );
10243 }
10244 }
10245 out
10246 }
10247
10248 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
10249 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
10250 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
10251 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
10252 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
10253 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
10254 /// is always 0, spec's `plane_bsize == tx_size` branch).
10255 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
10256 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
10257 }
10258
10259 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
10260 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
10261 /// context over `tx_size_wide` and the left one over `tx_size_high`.
10262 fn luma_skip_ctx_rect(&self, (mi_r, mi_c): (usize, usize), w_mi: usize, h_mi: usize) -> usize {
10263 let side_mi = w_mi;
10264 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
10265 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
10266 let mut top = 0u8;
10267 let mut left = 0u8;
10268 for cell in 0..above_mi {
10269 top |= self.above[mi_c + cell][0].level;
10270 }
10271 for cell in 0..left_mi {
10272 left |= self.left[mi_r + cell][0].level;
10273 }
10274 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
10275 if crate::envflags::env_flag!("EC_ECDUMP") {
10276 let ab: Vec<String> = (0..above_mi)
10277 .map(|k| self.above[mi_c + k][0].level.to_string())
10278 .collect();
10279 let lf: Vec<String> = (0..left_mi)
10280 .map(|k| self.left[mi_r + k][0].level.to_string())
10281 .collect();
10282 // lane-av1mix: the last few msac register states, so the
10283 // byte-position of the `all_zero` read can be matched against
10284 // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a
10285 // second run.
10286 let recent = crate::msac::symtrace::ecdump_recent(4)
10287 .iter()
10288 .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})"))
10289 .collect::<Vec<_>>()
10290 .join(" ");
10291 eprintln!(
10292 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]",
10293 ab.join(","),
10294 lf.join(","),
10295 recent
10296 );
10297 }
10298 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10299 eprintln!(
10300 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
10301 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
10302 );
10303 }
10304 ctx
10305 }
10306
10307 /// Writes one coded block into every cell it covers, on both grids: the
10308 /// mode/side arrays up to `side`'s own width, and the coefficient-context
10309 /// arrays up to the true frame edge — the units past it are left at their
10310 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
10311 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
10312 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
10313 /// not from this block's own side).
10314 fn record(
10315 &mut self,
10316 at: (usize, usize),
10317 side: usize,
10318 mode: usize,
10319 uv_mode: usize,
10320 grids: &[&[i32]; 3],
10321 ) {
10322 self.record_rect(at, side, side, mode, uv_mode, grids);
10323 }
10324
10325 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
10326 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
10327 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
10328 /// spec's per-edge partition-context rule, so a true rectangular block
10329 /// naturally wants two different values here rather than one.
10330 /// Writes this block's luma `mode` into the mi-granular
10331 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
10332 /// position a *later* neighbour would read it from: the block's LAST mi
10333 /// row for every column it spans (what the block below reads via
10334 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
10335 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
10336 /// read these back, and only when the recorded position is exactly their
10337 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
10338 fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) {
10339 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
10340 let mode = mode as u8;
10341 for cell in 0..mi_w {
10342 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
10343 *slot = (last_r, mode);
10344 }
10345 }
10346 for cell in 0..mi_h {
10347 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
10348 *slot = (last_c, mode);
10349 }
10350 }
10351 }
10352
10353 /// The mi-exact above/left neighbour luma mode for a block whose top-left
10354 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
10355 /// mi position (then the coarse [`SUB`]-grid slot is right by
10356 /// construction). See [`Self::record_mode_mi`].
10357 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
10358 match self.sub8_mode_col.get(mi_c) {
10359 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => {
10360 Some(usize::from(m))
10361 }
10362 _ => None,
10363 }
10364 }
10365
10366 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
10367 match self.sub8_mode_row.get(mi_r) {
10368 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => {
10369 Some(usize::from(m))
10370 }
10371 _ => None,
10372 }
10373 }
10374
10375 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
10376 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
10377 fn record_uv_mode_mi(
10378 &mut self,
10379 mi_r: usize,
10380 mi_c: usize,
10381 mi_w: usize,
10382 mi_h: usize,
10383 uv_mode: usize,
10384 ) {
10385 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
10386 fill_span(
10387 &mut self.uv_mode_col,
10388 mi_c,
10389 mi_w,
10390 (last_r as u16, uv_mode as u8),
10391 );
10392 fill_span(
10393 &mut self.uv_mode_row,
10394 mi_r,
10395 mi_h,
10396 (last_c as u16, uv_mode as u8),
10397 );
10398 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
10399 // covers, so the chroma neighbour read below is a plain grid read.
10400 let stride = self.uv_grid_cols;
10401 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
10402 for row in mi_r..=last_r {
10403 fill_span(
10404 &mut self.uv_mode_grid,
10405 row * stride + mi_c,
10406 n,
10407 uv_mode as u8,
10408 );
10409 }
10410 // lane-av1leftwit: stamp the writing block's own mi over its extent,
10411 // the same cells and the same clipping as `uv_mode_grid` above.
10412 let owner = UV_OWNER_EPOCH.with(|c| c.get()) | ((mi_r as u32) << 12) | mi_c as u32;
10413 for row in mi_r..=last_r {
10414 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);
10415 }
10416 if crate::envflags::env_flag!("EC_LEFTSSY") {
10417 eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}");
10418 }
10419 }
10420
10421 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
10422 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
10423 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
10424 /// block has recorded the exact neighbouring mi.
10425 fn smooth_uv_neighbour(
10426 &self,
10427 mi_r: usize,
10428 mi_c: usize,
10429 r: usize,
10430 c: usize,
10431 fctx: &crate::decode::FrameCtx,
10432 ) -> bool {
10433 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
10434 // REFERENCE block, not off the mi that carries the chroma syntax.
10435 // `set_mi_row_col` (`blockd.h`) takes
10436 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
10437 // only then `chroma_above_mbmi = base_mi[-stride]` /
10438 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
10439 // the ODD mi, so without the snap we looked one mi row/column too far
10440 // down/right -- the mi-exact slot never matched and the coarse
10441 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
10442 // 8x4 at (688, 100) = mi (51, 344): libaom's
10443 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
10444 // `UV_SMOOTH_PRED`), ours was 0, which flips
10445 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
10446 // false for type 1, TRUE for type 0) and upsampled an edge libaom
10447 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
10448 // predicting from it (class `context-read-from-one-cell`).
10449 // lane-av1-444: the snap is the SEQUENCE's subsampling, hardcoded
10450 // `& !1` before -- at subsampling 0/0 libaom's `mi_row & 0` snaps
10451 // nothing, and the hardcoded snap read a 4x4 leaf's smooth
10452 // neighbour two mi away (frame 0 of `av1-profile1-444.ivf`, leaf
10453 // mi(5,15): left neighbour SMOOTH_V at mi(5,14), read at mi(4,13)).
10454 let snap_y = (1usize << ss_y(fctx)) - 1;
10455 let snap_x = (1usize << ss_x(fctx)) - 1;
10456 // The snap IS libaom's `base_mi` de-offsetting (`set_mi_row_col`,
10457 // `av1_common_int.h:1395-1412`): `base_mi` is the block's own mi moved
10458 // by `-(mi_row & ss_y) * stride - (mi_col & ss_x)`. The helper applies
10459 // the two chroma-reference offsets on top of it -- see its own comment
10460 // for which axis each one moves.
10461 self.smooth_uv_neighbour_unsnapped(
10462 mi_r & !snap_y,
10463 mi_c & !snap_x,
10464 r,
10465 c,
10466 ss_x(fctx),
10467 ss_y(fctx),
10468 true,
10469 )
10470 }
10471
10472 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
10473 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
10474 /// counter wants this: it measures how often the snap CHANGES the answer,
10475 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
10476 /// decode path uses the snapping form.
10477 /// `decode_path` is `true` only for the snapping form every decode call
10478 /// site uses; the 16x4/4x16 pair witness's mirror passes `false`, so the
10479 /// `+ss_y` counters measure a read that actually filters a chroma edge and
10480 /// not the counter-only one.
10481 ///
10482 /// lane-av1leftwit: the mirror's justification used to be "no committed
10483 /// fixture reaches the shape on the decode path", and that was false --
10484 /// `UV_LEFT_1MI_SPLIT_HITS` fires on five of them. The flag stays (a
10485 /// counter-only mirror at an ODD mi row is still not a decode-path read,
10486 /// and its result feeds only `RECT4_16_UV_PAIR_FILT_HITS`), but it is no
10487 /// longer evidence about the `+ss_y` term, and nothing may cite it as such.
10488 /// The decode path's own reach is `uv_left_1mi_split_hits()`.
10489 fn smooth_uv_neighbour_unsnapped(
10490 &self,
10491 mi_r: usize,
10492 mi_c: usize,
10493 r: usize,
10494 c: usize,
10495 ss_x: usize,
10496 ss_y: usize,
10497 decode_path: bool,
10498 ) -> bool {
10499 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
10500 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
10501 // array that `start_tile` does not clear, so a block on a tile's first
10502 // mi row used to read the uv_mode of the block above it in the tile
10503 // ABOVE and filter its chroma edge at that neighbour's strength
10504 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
10505 // at chroma (120, 32), the top-right tile's first block).
10506 let have_above = mi_r > self.tile_row0_mi;
10507 let have_left = mi_c > self.tile_col0_mi;
10508 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
10509 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
10510 {
10511 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
10512 }
10513 // The mi grid is libaom's own read; the two maps below stay as the
10514 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
10515 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
10516 (col < self.uv_grid_cols)
10517 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
10518 .flatten()
10519 .filter(|&m| m != u8::MAX)
10520 .map(usize::from)
10521 };
10522 // libaom's two chroma-reference mi, from `set_mi_row_col`
10523 // (`av1_common_int.h:1400-1401`), with `mi_r`/`mi_c` already
10524 // de-offset by the caller's `(mi_row & ss_y)` / `(mi_col & ss_x)`
10525 // snap -- i.e. already libaom's `base_mi`:
10526 //
10527 // chroma_above_mi = base_mi[-mi_stride + ss_x] row -1, col +ss_x
10528 // chroma_left_mi = base_mi[ss_y*mi_stride - 1] row +ss_y, col -1
10529 //
10530 // SHIPPED: the above COLUMN. It is `+ss_x` wherever `ss_x == 1` --
10531 // 4:2:0, 4:2:2 AND 4:4:0 all carry that column shift, and only 4:4:4
10532 // (`ss_x == 0`) leaves the read where it was. Measured: folding it in
10533 // leaves the 4:2:0 control byte-identical to `aomdec --rawvideo`; the
10534 // boolean it feeds is simply not exercised differently by that stream
10535 // at its blocks. One chroma column spans two luma mi columns, so the
10536 // chroma edge reaches into the right-hand luma block, and that is where
10537 // its reference lives.
10538 //
10539 // SHIPPED (lane-av1leftref): the left read's `+ss_y` ROW term -- the
10540 // last open item lane-av1422warp carried. libaom puts the left
10541 // reference one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`) and on
10542 // its own row at 4:2:2 (`ss_y == 0`); this read its own row at every
10543 // subsampling. An earlier attempt applied the `ss_y` term to the WRONG
10544 // read (the above) and regressed the byte-exact 4:2:0 control, which
10545 // is what exposed the crossing. lane-av1leftwit CORRECTED the claim
10546 // this comment used to make: "six committed 4:2:0 fixtures reach it,
10547 // and on `reelb_ss600_key_frame.obu` the boolean flips" was never
10548 // measured. Measured over all 48 committed fixtures that decode
10549 // (`lanes/av1leftwit.report.md`), `reelb_ss600_key_frame.obu` reads
10550 // `mode_diff=0 smooth_diff=0 split1mi=0`, and exactly FIVE fixtures
10551 // put a 1-mi-tall left neighbour in front of a decode-path read at
10552 // all -- `gm_small_side_witness` (5), `reelc_sb128_inter_witness` (7),
10553 // `av112bit-{inter,compound,compound-masked}` (1 each) -- and in every
10554 // one of those reads the two blocks agree on `uv_mode`. So the SHAPE is
10555 // reachable (see `UV_LEFT_1MI_SPLIT_HITS`) and the term's VALUE
10556 // changing is what is still unwitnessed.
10557 let above_mi = (mi_r.saturating_sub(1), mi_c + ss_x);
10558 // lane-av1leftref: libaom's LEFT read carries the `+ss_y` ROW term --
10559 // `base_mi[ss_y * mi_stride - 1]` (`av1_common_int.h:1400-1401`) is
10560 // one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`), and on its own
10561 // row at 4:2:2 (`ss_y == 0`) and 4:4:4. The read below used its own
10562 // row at every subsampling. The term is only observable when the two
10563 // cells hold DIFFERENT blocks, i.e. the left neighbour is 1 mi tall or
10564 // shorter -- then `(row, col-1)` and `(row+1, col-1)` are two blocks
10565 // and only libaom's is the chroma reference. Three counters measure
10566 // that, and the third is the one the other two need: a read can only
10567 // differ if the two cells are written by DIFFERENT blocks, which
10568 // `UV_LEFT_1MI_SPLIT_HITS` counts off the per-cell owner stamp
10569 // (`uv_owner`, below). A DIFF bucket that reads 0 while SPLIT reads 0
10570 // was never in contention; a DIFF bucket that reads 0 while SPLIT
10571 // reads > 0 is the term being unobservable on real material, not
10572 // unreachable. `..._MODE_DIFF_HITS` / `..._SMOOTH_DIFF_HITS` then say
10573 // whether the mode value, and the boolean this feeds
10574 // (`is_smooth_mode` -> `av1_get_intra_edge_filter_type` -> the chroma
10575 // edge filter), actually moved.
10576 let left_mi = (mi_r + ss_y, mi_c.saturating_sub(1));
10577 let read_left = |row: usize| -> usize {
10578 match self.uv_mode_row.get(row) {
10579 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, row, left_mi.1) => m,
10580 Some(&(col, m)) if have_left && usize::from(col) == left_mi.1 => usize::from(m),
10581 _ if have_left => self.left_uv_mode[r],
10582 _ => DC_PRED,
10583 }
10584 };
10585 let above = match self.uv_mode_col.get(above_mi.1) {
10586 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, above_mi.0, above_mi.1) => m,
10587 Some(&(row, m)) if have_above && usize::from(row) == above_mi.0 => usize::from(m),
10588 _ if have_above => self.above_uv_mode[c],
10589 _ => DC_PRED,
10590 };
10591 let left = read_left(left_mi.0);
10592 // lane-av1leftref: the gate's reach + load-bearing counters. `READS` is
10593 // how many chroma edge-filter-type reads took this path at all, so a
10594 // gate can tell "the arm never ran" from "the arm ran and the `+ss_y`
10595 // term did not change the answer". The two DIFF buckets compare
10596 // libaom's read cell against the pre-lane own-row cell; both read 0 on
10597 // every committed fixture and every one of the ~1000 encodes swept in
10598 // `lanes/av1leftref.report.md`, which is what makes the read change a
10599 // proven no-op on today's material rather than an unmeasured guess.
10600 if decode_path && have_left && ss_y > 0 {
10601 hit!(UV_LEFT_SS_Y_READS);
10602 // The pre-lane read, kept as the counter's own-row arm: it is what
10603 // this decoder answered before the `+ss_y` term landed, and
10604 // comparing against it is what proves the term is load-bearing.
10605 let own_row = read_left(mi_r);
10606 if own_row != left {
10607 hit!(UV_LEFT_SS_Y_MODE_DIFF_HITS);
10608 }
10609 if is_smooth_mode(own_row) != is_smooth_mode(left) {
10610 hit!(UV_LEFT_SS_Y_SMOOTH_DIFF_HITS);
10611 }
10612 // lane-av1leftwit: the geometry the `+ss_y` term needs. The two
10613 // cells are one left mi column apart, so they are two different
10614 // blocks exactly when the left neighbour is 1 mi tall or shorter.
10615 let col = left_mi.1;
10616 let epoch = UV_OWNER_EPOCH.with(|c| c.get()) & 0xff00_0000;
10617 let own = (col < self.uv_grid_cols)
10618 .then(|| self.uv_owner.get(mi_r * self.uv_grid_cols + col).copied())
10619 .flatten()
10620 .filter(|o| o & 0xff00_0000 == epoch)
10621 .unwrap_or(0);
10622 let down = self
10623 .uv_owner
10624 .get((mi_r + ss_y) * self.uv_grid_cols + col)
10625 .copied()
10626 .filter(|o| o & 0xff00_0000 == epoch)
10627 .unwrap_or(0);
10628 if own != 0 && down != 0 && own != down {
10629 hit!(UV_LEFT_1MI_SPLIT_HITS);
10630 if crate::envflags::env_flag!("EC_LEFTSSY") {
10631 eprintln!(
10632 "EC_LEFTSSY epoch={} mi=({mi_r},{mi_c}) left_col={col} \
10633 owners=({},{})->({},{}) modes={own_row}/{left}",
10634 epoch >> 24,
10635 own >> 12 & 0xfff,
10636 own & 0xfff,
10637 down >> 12 & 0xfff,
10638 down & 0xfff,
10639 );
10640 }
10641 }
10642 }
10643 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
10644 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
10645 }) || have_left && cell(&self.uv_mode_grid, left_mi.0, left_mi.1).is_some_and(|m| {
10646 !matches!(self.uv_mode_row.get(left_mi.0), Some(&(col, cm)) if usize::from(col) == left_mi.1 && usize::from(cm) == m)
10647 }) {
10648 hit!(UV_MODE_GRID_OVERRIDE_HITS);
10649 }
10650 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
10651 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
10652 // have been filtered at the wrong strength by the coarse map alone.
10653 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
10654 hit!(UV_MODE_MI_OVERRIDE_HITS);
10655 }
10656 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
10657 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
10658 {
10659 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10660 }
10661 is_smooth_mode(above) || is_smooth_mode(left)
10662 }
10663
10664 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
10665 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
10666 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
10667 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
10668 /// holding an OLDER, larger block's mode -- it only ever recorded into the
10669 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
10670 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
10671 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
10672 /// a different CDF for the same mode value).
10673 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
10674 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
10675 /// only when `up_available` and `left_mbmi` only when `left_available`;
10676 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
10677 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
10678 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
10679 /// strip's mode as its "left neighbour" (measured on the band fixture at
10680 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
10681 fn modes_above_left_mi(
10682 &self,
10683 mi_r: usize,
10684 mi_c: usize,
10685 fallback: (usize, usize),
10686 ) -> (usize, usize) {
10687 let above = if mi_r > self.tile_row0_mi {
10688 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
10689 } else {
10690 DC_PRED
10691 };
10692 let left = if mi_c > self.tile_col0_mi {
10693 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
10694 } else {
10695 DC_PRED
10696 };
10697 (above, left)
10698 }
10699
10700 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
10701 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
10702 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
10703 /// per superblock row and never per tile, so the first block column of
10704 /// tile 2..N read the previous tile's mode as its left neighbour, and the
10705 /// above band survives across a tile ROW boundary the same way lane-mtfix's
10706 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
10707 /// `up_available`/`left_available` and uses DC_PRED otherwise
10708 /// ([`Self::modes_above_left_mi`]).
10709 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
10710 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10711 let (above, left) =
10712 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
10713 if above != self.above_mode[c] || left != self.left_mode[r] {
10714 hit!(MODE_MI_OVERRIDE_HITS);
10715 }
10716 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
10717 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
10718 {
10719 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
10720 }
10721 // A neighbour the coarse band offered where the tile edge makes it
10722 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
10723 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
10724 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
10725 {
10726 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
10727 }
10728 (above, left)
10729 }
10730
10731 fn record_rect(
10732 &mut self,
10733 at: (usize, usize),
10734 w: usize,
10735 h: usize,
10736 mode: usize,
10737 uv_mode: usize,
10738 grids: &[&[i32]; 3],
10739 ) {
10740 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
10741 }
10742
10743 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
10744 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
10745 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
10746 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
10747 /// the [`SUB`]-unit path does).
10748 fn record_rect_mi(
10749 &mut self,
10750 at_mi: (usize, usize),
10751 w: usize,
10752 h: usize,
10753 mode: usize,
10754 uv_mode: usize,
10755 grids: &[&[i32]; 3],
10756 ) {
10757 self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode);
10758 self.record_mi_rect(at_mi, w, h, grids);
10759 }
10760
10761 /// [`Self::record_rect_mi`]'s mode and transform-size half, without the
10762 /// coefficient-context stamp.
10763 fn record_rect_mi_modes(
10764 &mut self,
10765 at_mi: (usize, usize),
10766 w: usize,
10767 h: usize,
10768 mode: usize,
10769 uv_mode: usize,
10770 ) {
10771 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
10772 // lane-inter4 r2: a strip whose own footprint runs past the frame's
10773 // last 16-px column/row stamps only the cells that exist (libaom's
10774 // arrays are padded past the frame and those cells are never read).
10775 for cell in 0..w / SUB {
10776 if c + cell >= self.above_mode.len() {
10777 break;
10778 }
10779 self.above_mode[c + cell] = mode;
10780 self.above_uv_mode[c + cell] = uv_mode;
10781 self.above_side[c + cell] = w;
10782 }
10783 for cell in 0..h / SUB {
10784 if r + cell >= self.left_mode.len() {
10785 break;
10786 }
10787 self.left_mode[r + cell] = mode;
10788 self.left_uv_mode[r + cell] = uv_mode;
10789 self.left_side[r + cell] = h;
10790 }
10791 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
10792 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
10793 }
10794
10795 /// lane-av1chromarect: [`Self::record_rect_mi`] for a block whose uv
10796 /// plane block is SEVERAL transform units, each of which stamped its own
10797 /// span through [`Self::record_mi_chroma`]. Writing one whole-block state
10798 /// over them is the `override-slot-on-one-arm` class: libaom keeps the
10799 /// per-unit above/left contexts distinct, and the next block's first
10800 /// unit reads them. The luma plane has one unit here, so it is stamped
10801 /// exactly as the whole-block record stamps it.
10802 fn record_rect_mi_luma_only(
10803 &mut self,
10804 at_mi: (usize, usize),
10805 w: usize,
10806 h: usize,
10807 mode: usize,
10808 uv_mode: usize,
10809 luma_grid: &[i32],
10810 ) {
10811 self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode);
10812 fill_span(&mut self.left_side_mi, at_mi.0, h / MI, h as u8);
10813 fill_span(&mut self.above_side_mi, at_mi.1, w / MI, w as u8);
10814 self.record_mi_luma_rect(at_mi, w, h, luma_grid);
10815 }
10816
10817 /// The coefficient-context half of [`Self::record`], taking the block's
10818 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
10819 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
10820 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
10821 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
10822 self.record_mi_rect(at_mi, side, side, grids);
10823 }
10824
10825 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
10826 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
10827 fn record_mi_rect(&mut self, at_mi: (usize, usize), w: usize, h: usize, grids: &[&[i32]; 3]) {
10828 let (mi_r, mi_c) = at_mi;
10829 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
10830 let (w_mi, h_mi) = (w / MI, h / MI);
10831 if crate::envflags::env_flag!("EC_ECPUB") {
10832 eprintln!(
10833 "EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}",
10834 states[0].level
10835 );
10836 }
10837 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
10838 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
10839 // A chroma 4x4 unit straddling the true luma edge is still whole in
10840 // chroma's own halved grid, so libaom rounds the luma bound up to the
10841 // plane's own 4x4 unit before clamping a subsampled plane
10842 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
10843 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10844 let bound_h = [
10845 self.mi_rows,
10846 round_up_even(self.mi_rows),
10847 round_up_even(self.mi_rows),
10848 ];
10849 let bound_w = [
10850 self.mi_cols,
10851 round_up_even(self.mi_cols),
10852 round_up_even(self.mi_cols),
10853 ];
10854 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
10855 // past the padded side arrays (mi_rows 198, block rows 192..208);
10856 // libaom's own arrays are superblock-sized, so those cells simply
10857 // have no reader -- [`fill_span`] drops them, as the `break` did.
10858 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
10859 // predicate is three contiguous runs: all planes, chroma only, none
10860 // (lane-mi).
10861 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
10862 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
10863 let uv_only = [Neighbour::default(), states[1], states[2]];
10864 fill_span(&mut self.left, mi_r, luma_h, states);
10865 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
10866 fill_span(
10867 &mut self.left,
10868 mi_r + chroma_h,
10869 h_mi - chroma_h,
10870 [Neighbour::default(); 3],
10871 );
10872 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
10873 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
10874 let uv_only_w = [Neighbour::default(), states[1], states[2]];
10875 fill_span(&mut self.above, mi_c, luma_w, states);
10876 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
10877 fill_span(
10878 &mut self.above,
10879 mi_c + chroma_w,
10880 w_mi - chroma_w,
10881 [Neighbour::default(); 3],
10882 );
10883 }
10884
10885 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
10886 /// inside a coded block whose luma transform is smaller than its own
10887 /// side (`TxMode::Select`): the real per-transform-unit coefficient
10888 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
10889 /// coarse per-block `tx_grid`/`fill_lf_grid` state
10890 /// [`Self::record_split_luma`] still writes once for the whole block.
10891 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
10892 /// the caller's own [`Self::record_split_luma`] call sets those once,
10893 /// at the block's own true side, not this TU's.
10894 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
10895 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
10896 }
10897
10898 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
10899 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
10900 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
10901 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
10902 /// coefficient-context arrays are indexed by luma mi, the convention
10903 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
10904 /// clamp included.
10905 fn record_mi_chroma(
10906 &mut self,
10907 (mi_r, mi_c): (usize, usize),
10908 w_px: usize,
10909 h_px: usize,
10910 plane: usize,
10911 grid: &[i32],
10912 ) {
10913 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10914 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
10915 let state = neighbour_state(grid);
10916 if crate::envflags::env_flag!("EC_CHROMA_PUB") {
10917 eprintln!(
10918 "EC_CHROMA_PUB plane={plane} mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={} dc={}",
10919 state.level,
10920 state.dc.map_or(-1, |s| i32::from(s))
10921 );
10922 }
10923 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
10924 self.left[mi_r + cell][plane] = state;
10925 }
10926 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
10927 self.above[mi_c + cell][plane] = state;
10928 }
10929 }
10930
10931 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
10932 /// r1): the above context spans the unit's width, the left context its
10933 /// height, which for a square unit is the same loop it always was.
10934 fn record_mi_luma_rect(
10935 &mut self,
10936 (mi_r, mi_c): (usize, usize),
10937 w_px: usize,
10938 h_px: usize,
10939 grid: &[i32],
10940 ) {
10941 let state = neighbour_state(grid);
10942 if crate::envflags::env_flag!("EC_ECPUB") {
10943 eprintln!(
10944 "EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}",
10945 state.level
10946 );
10947 }
10948 for cell in 0..h_px / MI {
10949 if mi_r + cell < self.mi_rows {
10950 self.left[mi_r + cell][0] = state;
10951 }
10952 }
10953 for cell in 0..w_px / MI {
10954 if mi_c + cell < self.mi_cols {
10955 self.above[mi_c + cell][0] = state;
10956 }
10957 }
10958 }
10959
10960 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
10961 /// block whose luma was decoded as several transform units through
10962 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
10963 /// whole-block luma write -- everything [`Self::record`] does except
10964 /// plane 0, which is already correct per-TU by the time this runs.
10965 fn record_split_luma(
10966 &mut self,
10967 at: (usize, usize),
10968 side: usize,
10969 mode: usize,
10970 uv_mode: usize,
10971 chroma_grids: [&[i32]; 2],
10972 ) {
10973 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
10974 }
10975
10976 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
10977 /// extents in pixels (lane-rectsplit r1), the same relationship
10978 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
10979 /// luma transform split into several square units needs exactly this
10980 /// bookkeeping, at its own true rectangular extents.
10981 fn record_split_luma_rect(
10982 &mut self,
10983 at: (usize, usize),
10984 w: usize,
10985 h: usize,
10986 mode: usize,
10987 uv_mode: usize,
10988 chroma_grids: [&[i32]; 2],
10989 ) {
10990 let (r, c) = at;
10991 self.record_split_luma_rect_mi(
10992 (r * (SUB / MI), c * (SUB / MI)),
10993 w,
10994 h,
10995 mode,
10996 uv_mode,
10997 chroma_grids,
10998 );
10999 }
11000
11001 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
11002 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
11003 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
11004 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
11005 /// convention [`decode_block_rect4`] already established for 1:4 strips.
11006 fn record_split_luma_rect_mi(
11007 &mut self,
11008 at_mi: (usize, usize),
11009 w: usize,
11010 h: usize,
11011 mode: usize,
11012 uv_mode: usize,
11013 chroma_grids: [&[i32]; 2],
11014 ) {
11015 self.record_split_luma_rect_mi_modes(at_mi, w, h, mode, uv_mode);
11016 let (mi_r, _) = at_mi;
11017 let (w_mi, h_mi) = (w / MI, h / MI);
11018 let round_up_even = |n: usize| n.div_ceil(2) * 2;
11019 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
11020 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
11021 let plane = plane_idx + 1;
11022 let state = neighbour_state(grid);
11023 for cell in 0..h_mi {
11024 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
11025 self.left[mi_r + cell][plane] = state;
11026 }
11027 }
11028 for cell in 0..w_mi {
11029 if cell < w_mi.min(bound_w.saturating_sub(at_mi.1)) {
11030 self.above[at_mi.1 + cell][plane] = state;
11031 }
11032 }
11033 }
11034 }
11035
11036 /// [`Self::record_split_luma_rect_mi`]'s mode and transform-size half,
11037 /// without the per-plane coefficient stamp -- see
11038 /// [`Self::record_rect_mi_luma_only`] for why a multi-unit chroma block
11039 /// must not take the whole-block stamp.
11040 fn record_split_luma_rect_mi_modes(
11041 &mut self,
11042 at_mi: (usize, usize),
11043 w: usize,
11044 h: usize,
11045 mode: usize,
11046 uv_mode: usize,
11047 ) {
11048 let (mi_r, mi_c) = at_mi;
11049 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
11050 for cell in 0..w.div_ceil(SUB) {
11051 if c + cell >= self.above_mode.len() {
11052 break;
11053 }
11054 self.above_mode[c + cell] = mode;
11055 self.above_uv_mode[c + cell] = uv_mode;
11056 self.above_side[c + cell] = w;
11057 }
11058 for cell in 0..h.div_ceil(SUB) {
11059 if r + cell >= self.left_mode.len() {
11060 break;
11061 }
11062 self.left_mode[r + cell] = mode;
11063 self.left_uv_mode[r + cell] = uv_mode;
11064 self.left_side[r + cell] = h;
11065 }
11066
11067 let (w_mi, h_mi) = (w / MI, h / MI);
11068 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
11069 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
11070 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
11071 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
11072 }
11073}
11074
11075/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
11076/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
11077/// exactly — including its skip context, which the real key-frame writer
11078/// always writes at a fixed context of zero (it never tracks a neighbour-based
11079/// one for intra blocks; that is the inter-frame writer's rule instead).
11080/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
11081/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
11082/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
11083/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
11084/// plain DC chroma.
11085/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
11086/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
11087/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
11088/// instead (the defect commit 1a89ed9 fixed at the square sites).
11089pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
11090 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
11091 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
11092}
11093
11094/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
11095/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
11096/// bound (spec `filter_intra_mode_info` never reads a symbol there).
11097pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
11098 match side {
11099 4 => Some(0),
11100 8 => Some(1),
11101 16 => Some(2),
11102 32 => Some(3),
11103 _ => None,
11104 }
11105}
11106
11107/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
11108/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
11109/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
11110/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
11111fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
11112 match (bw, bh) {
11113 (32, 16) => Some(4),
11114 (16, 32) => Some(5),
11115 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
11116 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
11117 // here dropped that symbol on every DC_PRED strip of that size and
11118 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
11119 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
11120 (16, 8) => Some(6),
11121 (8, 16) => Some(7),
11122 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
11123 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
11124 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
11125 (4, 8) => Some(8),
11126 (8, 4) => Some(9),
11127 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
11128 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
11129 // `use_filter_intra` symbol on those strips although aomenc writes
11130 // one for every DC_PRED block of that shape with
11131 // `--enable-filter-intra=1` (its default), silently desyncing the
11132 // tile (class symbol-consumption-gap).
11133 (32, 8) => Some(10),
11134 (8, 32) => Some(11),
11135 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
11136 // strips), rows 17/16 of `default_filter_intra_cdfs`.
11137 (16, 4) => Some(12),
11138 (4, 16) => Some(13),
11139 _ if bw == bh => filter_intra_size_class(bw),
11140 _ => None,
11141 }
11142}
11143
11144/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
11145/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
11146/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
11147/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
11148/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
11149pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
11150 palette_bsize_ctx_wh(side, side)
11151}
11152
11153/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
11154/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
11155/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
11156/// for ANY bsize, not just the square ones a hand-picked table happened to
11157/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
11158/// row breaks the moment its indexing field moves off the diagonal, and a
11159/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
11160/// block dimension is a power of two, so `bw*bh` always is too and
11161/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
11162/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
11163fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
11164 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
11165 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
11166 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
11167 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
11168 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
11169 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
11170 if bw > 64 || bh > 64 || bw * bh < 64 {
11171 return None;
11172 }
11173 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
11174}
11175
11176/// A just-decoded palette-Y block's own size, base colours (only the first
11177/// `size` entries are real), and per-pixel colour-index map (`side*side`,
11178/// row-major, each entry `< size`).
11179struct PaletteY {
11180 size: usize,
11181 colors: [u16; 8],
11182 map: Vec<u8>,
11183}
11184
11185/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
11186/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
11187/// shared between U and V, both co-located after 4:2:0 subsampling) plus
11188/// each plane's own base colours.
11189struct PaletteUv {
11190 size: usize,
11191 u_colors: [u16; 8],
11192 v_colors: [u16; 8],
11193 map: Vec<u8>,
11194}
11195
11196/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
11197/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
11198/// `get_unsigned_bits`, which is the same formula): smallest `n` with
11199/// `2^n >= x`, `0` for `x <= 1`.
11200pub(crate) fn ceil_log2(x: u32) -> u32 {
11201 if x < 2 {
11202 0
11203 } else {
11204 32 - (x - 1).leading_zeros()
11205 }
11206}
11207
11208/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
11209/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
11210fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
11211 let l = ceil_log2(n as u32);
11212 let m = (1usize << l) - n;
11213 let v = dec.literal(l - 1) as usize;
11214 if v < m {
11215 v
11216 } else {
11217 (v << 1) - m + dec.literal(1) as usize
11218 }
11219}
11220
11221/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
11222/// colours (already-known, from the above/left neighbours) with the
11223/// ascending `transmitted` ones (delta-coded off the wire) back into one
11224/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
11225/// value picks the cached copy first, matching the C `<=`.
11226fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
11227 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
11228 let (mut ci, mut ti) = (0, 0);
11229 while ci < cached.len() && ti < transmitted.len() {
11230 if cached[ci] <= transmitted[ti] {
11231 out.push(cached[ci]);
11232 ci += 1;
11233 } else {
11234 out.push(transmitted[ti]);
11235 ti += 1;
11236 }
11237 }
11238 out.extend_from_slice(&cached[ci..]);
11239 out.extend_from_slice(&transmitted[ti..]);
11240 out
11241}
11242
11243/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
11244/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
11245/// each delta's width, the `range` bound and the clamp) is sized by
11246/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
11247/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
11248/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
11249/// the msac range, so a cross-decoder range ladder stays bit-identical
11250/// through the whole miscount -- only the decoded VALUE differs (class
11251/// `compare-range-not-tell`'s blind spot). (this
11252/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
11253/// (one flag bit each, in cache order), then delta-codes the remainder
11254/// (first value raw, each following delta `>= 1` off a shrinking bit width),
11255/// and merges the two ascending lists back together.
11256fn read_palette_colors_y(
11257 dec: &mut SymbolDecoder,
11258 n: usize,
11259 cache: &[u16],
11260 fctx: &crate::decode::FrameCtx,
11261) -> [u16; 8] {
11262 let mut cached = Vec::with_capacity(n);
11263 for &c in cache {
11264 if cached.len() >= n {
11265 break;
11266 }
11267 if dec.literal(1) == 1 {
11268 cached.push(c);
11269 }
11270 }
11271 let bd = u32::from(bit_depth(fctx));
11272 let max_val = (1i32 << bd) - 1;
11273 let mut colors = [0u16; 8];
11274 let n_cached = cached.len();
11275 if n_cached < n {
11276 let mut transmitted = Vec::with_capacity(n - n_cached);
11277 let first = dec.literal(bd) as u16;
11278 transmitted.push(first);
11279 if n_cached + 1 < n {
11280 let min_bits = bd - 3;
11281 let mut bits = min_bits + dec.literal(2);
11282 let mut range = (1i32 << bd) - i32::from(first) - 1;
11283 for _ in (n_cached + 1)..n {
11284 let delta = dec.literal(bits) as i32 + 1;
11285 let prev = *transmitted.last().unwrap();
11286 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
11287 range -= i32::from(val) - i32::from(prev);
11288 bits = bits.min(ceil_log2(range.max(0) as u32));
11289 transmitted.push(val);
11290 }
11291 }
11292 let merged = merge_colors(&transmitted, &cached);
11293 colors[..n].copy_from_slice(&merged);
11294 } else {
11295 colors[..n].copy_from_slice(&cached[..n]);
11296 }
11297 colors
11298}
11299
11300/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
11301/// `bit_depth` (see [`read_palette_colors_y`]): U reads
11302/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
11303/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
11304/// unbiased by `+1` -- both differences from Y's own reader, matching the C
11305/// side by side). V never uses a cache: a leading bit picks either `n` raw
11306/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
11307/// rather than clamp.
11308fn read_palette_colors_uv(
11309 dec: &mut SymbolDecoder,
11310 n: usize,
11311 cache: &[u16],
11312 fctx: &crate::decode::FrameCtx,
11313) -> ([u16; 8], [u16; 8]) {
11314 let mut cached = Vec::with_capacity(n);
11315 for &c in cache {
11316 if cached.len() >= n {
11317 break;
11318 }
11319 if dec.literal(1) == 1 {
11320 cached.push(c);
11321 }
11322 }
11323 let bd = u32::from(bit_depth(fctx));
11324 let max_val = 1i32 << bd;
11325 let mut u_colors = [0u16; 8];
11326 let n_cached = cached.len();
11327 if n_cached < n {
11328 let mut transmitted = Vec::with_capacity(n - n_cached);
11329 let first = dec.literal(bd) as u16;
11330 transmitted.push(first);
11331 if n_cached + 1 < n {
11332 let min_bits = bd - 3;
11333 let mut bits = min_bits + dec.literal(2);
11334 let mut range = max_val - i32::from(first);
11335 for _ in (n_cached + 1)..n {
11336 let delta = dec.literal(bits) as i32;
11337 let prev = *transmitted.last().unwrap();
11338 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
11339 range -= i32::from(val) - i32::from(prev);
11340 bits = bits.min(ceil_log2(range.max(0) as u32));
11341 transmitted.push(val);
11342 }
11343 }
11344 let merged = merge_colors(&transmitted, &cached);
11345 u_colors[..n].copy_from_slice(&merged);
11346 } else {
11347 u_colors[..n].copy_from_slice(&cached[..n]);
11348 }
11349 let mut v_colors = [0u16; 8];
11350 if dec.literal(1) == 1 {
11351 let min_bits_v = bd - 4;
11352 let bits = min_bits_v + dec.literal(2);
11353 v_colors[0] = dec.literal(bd) as u16;
11354 for i in 1..n {
11355 let mut delta = dec.literal(bits) as i32;
11356 if delta != 0 && dec.literal(1) == 1 {
11357 delta = -delta;
11358 }
11359 let mut val = i32::from(v_colors[i - 1]) + delta;
11360 if val < 0 {
11361 val += max_val;
11362 }
11363 if val >= max_val {
11364 val -= max_val;
11365 }
11366 v_colors[i] = val as u16;
11367 }
11368 } else {
11369 for i in 0..n {
11370 v_colors[i] = dec.literal(bd) as u16;
11371 }
11372 }
11373 (u_colors, v_colors)
11374}
11375
11376/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
11377/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
11378/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
11379const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
11380
11381/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
11382/// map's own per-pixel context and colour-order permutation, from the
11383/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
11384/// selection sort). `map`'s stride is `side` (this decoder never crops a
11385/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
11386/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
11387/// actual colour index to store.
11388pub(crate) fn palette_color_index_context(
11389 map: &[u8],
11390 side: usize,
11391 row: usize,
11392 col: usize,
11393 n: usize,
11394) -> (usize, [u8; 8]) {
11395 let left = if col >= 1 {
11396 Some(map[row * side + col - 1])
11397 } else {
11398 None
11399 };
11400 let up_left = if col >= 1 && row >= 1 {
11401 Some(map[(row - 1) * side + col - 1])
11402 } else {
11403 None
11404 };
11405 let up = if row >= 1 {
11406 Some(map[(row - 1) * side + col])
11407 } else {
11408 None
11409 };
11410 let mut scores = [0i32; 8];
11411 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
11412 if let Some(v) = neighbour {
11413 scores[v as usize] += weight;
11414 }
11415 }
11416 let mut color_order = [0u8; 8];
11417 for i in 0..8 {
11418 color_order[i] = i as u8;
11419 }
11420 for i in 0..3 {
11421 let mut max = scores[i];
11422 let mut max_idx = i;
11423 for j in (i + 1)..n {
11424 if scores[j] > max {
11425 max = scores[j];
11426 max_idx = j;
11427 }
11428 }
11429 if max_idx != i {
11430 let max_score = scores[max_idx];
11431 let max_color = color_order[max_idx];
11432 for k in (i + 1..=max_idx).rev() {
11433 scores[k] = scores[k - 1];
11434 color_order[k] = color_order[k - 1];
11435 }
11436 scores[i] = max_score;
11437 color_order[i] = max_color;
11438 }
11439 }
11440 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
11441 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
11442 (ctx as usize, color_order)
11443}
11444
11445/// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512):
11446/// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block
11447/// cut by the frame's bottom or right mi edge codes its colour-index map only
11448/// over this part and replicates it outward -- reading the full `bw x bh` grid
11449/// consumed symbols libaom never wrote and desynced the rest of the tile
11450/// (lane-svtinter; class map-read-past-frame-edge).
11451fn palette_onscreen(
11452 mi_r: usize,
11453 mi_c: usize,
11454 bw: usize,
11455 bh: usize,
11456 fctx: &crate::decode::FrameCtx,
11457) -> (usize, usize) {
11458 // lane-palw: the ENCODER's own in-process reconstruct runs on a
11459 // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
11460 // frame encoders publish the header's mi dims onto it themselves
11461 // (`encode.rs`, beside their `true_width`/`true_height`) so that this
11462 // clamp and `tile::write_color_index_map`'s now agree there too.
11463 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
11464 palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
11465}
11466
11467/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
11468/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
11469/// compute the same on-screen extent or the decoder reads a different number
11470/// of symbols than the encoder wrote.
11471pub(crate) fn palette_onscreen_dims(
11472 mi_r: usize,
11473 mi_c: usize,
11474 bw: usize,
11475 bh: usize,
11476 (mi_rows, mi_cols): (usize, usize),
11477) -> (usize, usize) {
11478 (
11479 bw.min(mi_cols.saturating_sub(mi_c) * MI),
11480 bh.min(mi_rows.saturating_sub(mi_r) * MI),
11481 )
11482}
11483
11484/// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus
11485/// the SAME sub-8 bump the caller's own `(bw >> ss).max(4)` applies to the
11486/// block dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move
11487/// together or a cut 8-wide block reads its chroma map at the wrong width.
11488/// lane-av1-444: the shifts are the sequence's own subsampling (a 4:4:4
11489/// intra-in-inter palette read its chroma map at the 4:2:0 extent and
11490/// panicked feeding the 4:2:0-sized prediction to a full-size reconstruct).
11491pub(crate) fn palette_onscreen_uv(
11492 luma: (usize, usize),
11493 on: (usize, usize),
11494 chroma: (usize, usize),
11495 ss: (usize, usize),
11496) -> (usize, usize) {
11497 (
11498 (on.0 >> ss.0) + (chroma.0 - (luma.0 >> ss.0)),
11499 (on.1 >> ss.1) + (chroma.1 - (luma.1 >> ss.1)),
11500 )
11501}
11502
11503/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
11504/// map's wavefront decode over a `side x side` grid, read over the on-screen
11505/// `on_side x on_side` corner (see [`palette_onscreen`]).
11506fn decode_color_index_map(
11507 dec: &mut SymbolDecoder,
11508 cdfs: &mut Cdfs,
11509 n: usize,
11510 side: usize,
11511 on: (usize, usize),
11512 uv: bool,
11513) -> Vec<u8> {
11514 decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv)
11515}
11516
11517/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
11518/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
11519/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
11520/// independently rather than one shared `side` -- the square call above is
11521/// just `bw == bh`.
11522fn decode_color_index_map_wh(
11523 dec: &mut SymbolDecoder,
11524 cdfs: &mut Cdfs,
11525 n: usize,
11526 bw: usize,
11527 bh: usize,
11528 // `(onscreenWidth, onscreenHeight)` in this plane's own units.
11529 on: (usize, usize),
11530 uv: bool,
11531) -> Vec<u8> {
11532 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
11533 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
11534 if on_bw < bw || on_bh < bh {
11535 hit!(PALETTE_ONSCREEN_CUT_HITS);
11536 }
11537 let mut map = vec![0u8; bw * bh];
11538 if trace {
11539 let (rng, _) = dec.debug_state();
11540 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
11541 }
11542 map[0] = read_uniform(dec, n) as u8;
11543 if trace {
11544 let (rng, _) = dec.debug_state();
11545 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
11546 }
11547 for i in 1..(on_bw + on_bh - 1) {
11548 let j_hi = i.min(on_bw - 1);
11549 let j_lo = i.saturating_sub(on_bh - 1);
11550 for j in (j_lo..=j_hi).rev() {
11551 let row = i - j;
11552 let col = j;
11553 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
11554 if trace {
11555 let (rng, _) = dec.debug_state();
11556 let row_cdf = if uv {
11557 &cdfs.palette_uv_color_index[n - 2][ctx]
11558 } else {
11559 &cdfs.palette_y_color_index[n - 2][ctx]
11560 };
11561 eprintln!(
11562 "EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}",
11563 row_cdf[0], row_cdf[n]
11564 );
11565 }
11566 let symbol = if uv {
11567 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
11568 } else {
11569 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
11570 };
11571 map[row * bw + col] = color_order[symbol];
11572 if trace {
11573 let (rng, _) = dec.debug_state();
11574 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
11575 }
11576 }
11577 }
11578 palette_replicate(&mut map, bw, bh, on);
11579 map
11580}
11581
11582/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
11583/// last on-screen column then the last on-screen row are replicated over the
11584/// off-screen remainder, so the prediction still covers the whole block. The
11585/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
11586/// so the pixels it prices and reconstructs are the ones the on-screen
11587/// symbols it writes really decode to.
11588pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
11589 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
11590 for row in 0..on_bh {
11591 let last = map[row * bw + on_bw - 1];
11592 map[row * bw + on_bw..row * bw + bw].fill(last);
11593 }
11594 for row in on_bh..bh {
11595 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
11596 }
11597}
11598
11599/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
11600/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
11601/// size class comes from [`filter_intra_size_class_rect`] instead of the
11602/// square-only [`filter_intra_size_class`], and the palette read (when
11603/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
11604/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
11605/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
11606/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
11607#[allow(clippy::too_many_arguments)]
11608fn read_intra_mode_rect(
11609 dec: &mut SymbolDecoder,
11610 cdfs: &mut Cdfs,
11611 above_mode: usize,
11612 left_mode: usize,
11613 cfl: bool,
11614 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
11615 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
11616 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
11617 // chroma is coded once, on the closing strip). Every other caller is a
11618 // block big enough to own its chroma and passes `true`.
11619 has_chroma: bool,
11620 bw: usize,
11621 bh: usize,
11622 enable_filter_intra: bool,
11623 skip_ctx: usize,
11624 allow_screen_content_tools: bool,
11625 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
11626 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
11627 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
11628 palette: Option<(usize, &[u16])>,
11629 palette_uv_cache: &[u16],
11630 mi_r: usize,
11631 mi_c: usize,
11632 fctx: &crate::decode::FrameCtx,
11633) -> Result<(
11634 bool,
11635 usize,
11636 i32,
11637 usize,
11638 i32,
11639 Option<(i32, i32)>,
11640 Option<usize>,
11641 Option<PaletteY>,
11642 Option<PaletteUv>,
11643 // lane-av1-intrabc: the block vector, `Some` exactly when this block's
11644 // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns
11645 // straight out of `read_intra_frame_mode_info` then, so every later field
11646 // of the tuple is at its default (mode/uv_mode DC, no angle, no palette,
11647 // no filter intra). A caller that can reconstruct intrabc at its shape
11648 // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by
11649 // name with the same string it always did.
11650 Option<(i32, i32)>,
11651)> {
11652 // lane-av1mono: libaom guards every chroma symbol read with
11653 // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
11654 // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
11655 // `palette_uv` even on a chroma-reference strip. Fold the plane count
11656 // into the same `has_chroma` this reader already gates on.
11657 let has_chroma = has_chroma && !mono(fctx);
11658 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
11659 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
11660 if ec_istep {
11661 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
11662 // (decodemv.c:818), printed at the same point: before the first
11663 // mode-info symbol of the block, so a cross-decoder range ladder can
11664 // be keyed on the BLOCK, not just on the symbol sequence.
11665 eprintln!(
11666 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}",
11667 enable_filter_intra as i32,
11668 filter_intra_size_class_rect(bw, bh),
11669 dec.debug_state().0
11670 );
11671 }
11672 macro_rules! istep {
11673 ($name:literal, $val:expr) => {
11674 if ec_istep {
11675 let (rng, _) = dec.debug_state();
11676 eprintln!(
11677 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
11678 $name, $val
11679 );
11680 }
11681 };
11682 }
11683 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
11684 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
11685 // the one point every rect caller routes through, so no call site can
11686 // offer the 14-symbol CFL alphabet on a 64-axis block (class
11687 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
11688 let cfl = if cfl && bw.max(bh) > 32 {
11689 hit!(NOCFL_UV_MODE_HITS);
11690 false
11691 } else {
11692 cfl
11693 };
11694 // lane-intra14 r1: on the INTER block path everything up to and including
11695 // `is_inter` was already read by [`decode_inter_block`], so this reader
11696 // starts at the mode syntax with the `skip` that caller read.
11697 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
11698 let skip = if let Some((_, skip)) = inter {
11699 skip
11700 } else {
11701 // Same `intra_segment_id` placement as the square reader above.
11702 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
11703 if seg_id_pre_skip(fctx) {
11704 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
11705 }
11706 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
11707 istep!("skip", skip as i32);
11708 if !seg_id_pre_skip(fctx) {
11709 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
11710 }
11711 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
11712 istep!("cdef", 0);
11713 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
11714 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
11715 // `false`.
11716 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11717 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
11718 istep!("dq", 0);
11719 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
11720 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
11721 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
11722 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
11723 // rect strips read it exactly like square leaves ([`read_intra_mode`],
11724 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
11725 // decoder at the FIRST symbol of the first rect block of every
11726 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
11727 // block at this shape is out of scope, so the flag is consumed and
11728 // refused by name when it fires.
11729 if allow_intrabc_frame(fctx) {
11730 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
11731 hit!(RECT_INTRABC_READS);
11732 istep!("intrabc", use_intrabc as i32);
11733 if use_intrabc {
11734 hit!(INTRABC_HITS);
11735 // libaom `read_intrabc_info`: the DV read, then an immediate
11736 // return out of the mode-info read -- no `y_mode`, no `uv_mode`,
11737 // no angle deltas, no palette, no filter intra. The caller owns
11738 // the reconstruction at its own shape.
11739 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx);
11740 return Ok((
11741 skip,
11742 DC_PRED,
11743 0,
11744 DC_PRED,
11745 0,
11746 None,
11747 None,
11748 None,
11749 None,
11750 Some(dv),
11751 ));
11752 }
11753 }
11754 skip
11755 };
11756 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
11757 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
11758 // off `kf_y_mode_cdf[above][left]`).
11759 let mode = if let Some((size_group, _)) = inter {
11760 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
11761 dec.symbol(&mut cdfs.y_mode[size_group])
11762 } else {
11763 let above_ctx = INTRA_MODE_CTX[above_mode];
11764 let left_ctx = INTRA_MODE_CTX[left_mode];
11765 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
11766 };
11767 istep!("mode", mode as i32);
11768 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
11769 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
11770 } else {
11771 0
11772 };
11773 istep!("angle_y", angle_delta_y);
11774 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
11775 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
11776 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
11777 // here, from the block's own size, is the single point every caller routes
11778 // through -- a caller passing `true` for a >32 strip used to pick the
11779 // 14-symbol CFL CDF, same value but a different range (class
11780 // wrong-alphabet-same-value).
11781 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
11782 let uv_mode = if !has_chroma {
11783 DC_PRED
11784 } else if cfl {
11785 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
11786 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
11787 } else {
11788 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
11789 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
11790 };
11791 istep!("uv_mode", uv_mode as i32);
11792 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
11793 Some(read_cfl_alphas(dec, cdfs))
11794 } else {
11795 None
11796 };
11797 if has_chroma && (9..=12).contains(&uv_mode) {
11798 hit!(SMOOTH_UV_HITS);
11799 }
11800 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
11801 hit!(DIRECTIONAL_UV_HITS);
11802 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
11803 } else {
11804 0
11805 };
11806 istep!("angle_uv", angle_delta_uv);
11807 if angle_delta_uv != 0 {
11808 hit!(UV_ANGLE_DELTA_HITS);
11809 }
11810 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
11811 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
11812 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
11813 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
11814 // colours only here, the colour-index maps deferred past `filter_intra`
11815 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
11816 // runs from the caller, after the whole mode-info read).
11817 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
11818 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
11819 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
11820 // r6: this is the exact site the removed blanket refusal used to
11821 // guard -- reached for EVERY rect strip in a screen-content frame,
11822 // independent of whether the block ends up using a palette.
11823 hit!(RECT_SCREEN_CONTENT_HITS);
11824 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
11825 let use_palette_y =
11826 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
11827 if use_palette_y {
11828 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
11829 let colors = read_palette_colors_y(dec, n, cache, fctx);
11830 palette_y_pending = Some((n, colors));
11831 }
11832 let palette_uv_mode_ctx = usize::from(use_palette_y);
11833 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
11834 if has_chroma
11835 && uv_mode == DC_PRED
11836 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
11837 {
11838 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
11839 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
11840 palette_uv_pending = Some((n, u_colors, v_colors));
11841 }
11842 }
11843 let mut filter_intra = None;
11844 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11845 let (rng, _) = dec.debug_state();
11846 eprintln!(
11847 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
11848 class={:?} rng={rng}",
11849 enable_filter_intra as i32,
11850 filter_intra_size_class_rect(bw, bh)
11851 );
11852 }
11853 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
11854 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
11855 if mode == DC_PRED
11856 && enable_filter_intra
11857 && palette_y_pending.is_none()
11858 && let Some(class) = filter_intra_size_class_rect(bw, bh)
11859 {
11860 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
11861 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11862 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
11863 }
11864 istep!("use_filter_intra", use_filter_intra as i32);
11865 if use_filter_intra {
11866 hit!(FILTER_INTRA_HITS);
11867 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
11868 istep!("filter_intra_mode", fi_mode as i32);
11869 filter_intra = Some(fi_mode);
11870 }
11871 }
11872 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
11873 // same order as [`read_intra_mode`]'s own square path.
11874 let palette_y = palette_y_pending.map(|(n, colors)| {
11875 let map = decode_color_index_map_wh(
11876 dec,
11877 cdfs,
11878 n,
11879 bw,
11880 bh,
11881 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
11882 false,
11883 );
11884 hit!(PALETTE_HITS);
11885 hit!(PALETTE_RECT_HITS);
11886 PaletteY {
11887 size: n,
11888 colors,
11889 map,
11890 }
11891 });
11892 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
11893 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
11894 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
11895 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
11896 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
11897 // chroma palette and desynced the tile from there.
11898 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
11899 let on = palette_onscreen_uv(
11900 (bw, bh),
11901 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
11902 (cw, ch),
11903 (ss_x(fctx), ss_y(fctx)),
11904 );
11905 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
11906 hit!(PALETTE_UV_HITS);
11907 PaletteUv {
11908 size: n,
11909 u_colors,
11910 v_colors,
11911 map,
11912 }
11913 });
11914 Ok((
11915 skip,
11916 mode,
11917 angle_delta_y,
11918 uv_mode,
11919 angle_delta_uv,
11920 alpha,
11921 filter_intra,
11922 palette_y,
11923 palette_uv,
11924 None,
11925 ))
11926}
11927
11928/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
11929/// at the strip's REAL mi position. `av1_get_palette_cache` reads
11930/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
11931/// block, so each strip owns its own rows and columns and no aliasing rule
11932/// is needed (lane-kf900 r6).
11933#[allow(clippy::too_many_arguments)]
11934fn record_strip_palette(
11935 n: &mut Neighbours,
11936 mi: (usize, usize),
11937 bw: usize,
11938 bh: usize,
11939 y_size: usize,
11940 y_colors: [u16; 8],
11941 uv_size: usize,
11942 uv_colors: [u16; 8],
11943) {
11944 let (r, c) = mi;
11945 // lane-t900 r23 rung: every publication of a block's palette state into
11946 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
11947 // path left a stale `left_palette_size` behind when
11948 // `av1_get_palette_mode_ctx` disagrees with libaom's.
11949 if crate::envflags::env_flag!("EC_PALPUB") {
11950 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
11951 }
11952 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
11953 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
11954 // existed because the 16px [`SUB`] cell held one slot for all the strips
11955 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
11956 // real neighbour leaf 1 reads.
11957 {
11958 for cell in 0..(bw / MI).max(1) {
11959 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
11960 *e = y_size as u8;
11961 n.above_palette_uv_size[c + cell] = uv_size as u8;
11962 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
11963 // colours of a size-0 neighbour are never read.
11964 if y_size > 0 {
11965 n.above_palette_colors[c + cell] = y_colors;
11966 }
11967 if uv_size > 0 {
11968 n.above_palette_uv_colors[c + cell] = uv_colors;
11969 }
11970 }
11971 }
11972 }
11973 {
11974 for cell in 0..(bh / MI).max(1) {
11975 if n.left_palette_size.get(r + cell).is_none() {
11976 break;
11977 }
11978 n.left_palette_size[r + cell] = y_size as u8;
11979 n.left_palette_uv_size[r + cell] = uv_size as u8;
11980 if y_size > 0 {
11981 n.left_palette_colors[r + cell] = y_colors;
11982 }
11983 if uv_size > 0 {
11984 n.left_palette_uv_colors[r + cell] = uv_colors;
11985 }
11986 }
11987 }
11988}
11989
11990/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
11991fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
11992 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| {
11993 i32::from(y.data[ly * y.width + lx])
11994 })
11995}
11996
11997/// Everything a rect strip already read out of the stream before its luma
11998/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
11999/// (nine values that would otherwise be nine more parameters).
12000struct RectStripModes {
12001 skip: bool,
12002 mode: usize,
12003 angle_delta_y: i32,
12004 uv_predict_mode: usize,
12005 angle_delta_uv: i32,
12006 alpha: Option<(i32, i32)>,
12007 filter_intra: Option<usize>,
12008 smooth_neighbor: bool,
12009 smooth_neighbor_uv: bool,
12010 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
12011 /// mapped through the colour table), sliced per transform unit below --
12012 /// palette prediction reads no edge pixels, so a unit's slice of the
12013 /// whole-block map IS its prediction. Without this a palette strip whose
12014 /// transform splits predicted DC and came out flat grey while the entropy
12015 /// stream stayed in sync (the coefficients are read either way).
12016 palette_y: Option<Vec<u16>>,
12017 /// As `palette_y`, for the un-split chroma transform (U, V).
12018 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
12019}
12020
12021/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
12022/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
12023/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
12024/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
12025/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
12026/// TX_32X16`) and only the second reaches a square -- the reason
12027/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
12028/// already square) mis-tiled 1:4 strips.
12029fn depth_to_tx_wh(
12030 bw: usize,
12031 bh: usize,
12032 depth: usize,
12033 fctx: &crate::decode::FrameCtx,
12034) -> (usize, usize) {
12035 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
12036 // `read_tx_size`: the lossless early return comes before
12037 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
12038 if lossless(fctx) {
12039 return (4, 4);
12040 }
12041 let (mut w, mut h) = (bw.min(64), bh.min(64));
12042 for _ in 0..depth {
12043 match w.cmp(&h) {
12044 std::cmp::Ordering::Greater => w /= 2,
12045 std::cmp::Ordering::Less => h /= 2,
12046 std::cmp::Ordering::Equal => {
12047 w /= 2;
12048 h /= 2;
12049 }
12050 }
12051 }
12052 (w, h)
12053}
12054
12055/// lane-av1-422stripanchor: [`decode_rect_split`]'s 4-wide-strip port of the
12056/// split4 floored-pair anchor ([`sub8_leaf_chroma422`]'s rule). A 1-mi-wide
12057/// strip (luma `(4, 16)` / `(4, 8)`) has NO chroma plane block of its own at
12058/// ss (1, 0) -- `av1_ss_size_lookup[BLOCK_4X16][1][0]` and
12059/// `[BLOCK_4X8][1][0]` are both BLOCK_INVALID (`common_data.c`), and a
12060/// 2-px-wide area is not a transform shape. The strip pairs with its
12061/// even-column sibling (`is_chroma_reference`'s `mi_col & 1` column clause,
12062/// the rule [`decode_rect4_16_strip`] implements one partition level up), and
12063/// the ODD-column strip codes the PAIR's `(4, bh)` plane anchored at
12064/// `av1_setup_dst_planes`' mi-exact floor `(mi_col & !1) * MI >> ss_x`, with
12065/// the entropy context on the floored cell. Returns
12066/// `(pair block width, pair block height, write anchor x, entropy mi column)`
12067/// for that pair, or `None` when the strip keeps its own plane block at its
12068/// own origin -- which is every 4:2:0 and 4:4:4 cell (their chroma is never
12069/// 2 px wide) and every 4:2:2 strip of 8 px or more.
12070fn chroma422_pair_plane(
12071 ss_x: bool,
12072 ss_y: bool,
12073 mi_col: usize,
12074 bw: usize,
12075 bh: usize,
12076) -> Option<(usize, usize, usize, usize)> {
12077 if ss_x && !ss_y && (bw >> 1) == 2 {
12078 Some((4, bh, ((mi_col & !1) * MI) >> 1, mi_col & !1))
12079 } else {
12080 None
12081 }
12082}
12083
12084/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
12085/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
12086/// rect path here refused by name until now ("per-unit rect prediction is not
12087/// ported").
12088///
12089/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
12090/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
12091/// strip the very first step already lands on a SQUARE transform
12092/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
12093/// every further step halves a square) -- so each unit is square and reads
12094/// through the ordinary square [`read_plane`]. What is genuinely rectangular
12095/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
12096/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
12097/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
12098/// split by luma's depth.
12099///
12100/// Each unit predicts off whatever the earlier units of this same block
12101/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
12102/// inside `av1_foreach_transformed_block`, raster order), which is exactly
12103/// what predicting the whole strip in one shot got wrong.
12104#[allow(clippy::too_many_arguments)]
12105fn decode_rect_split(
12106 dec: &mut SymbolDecoder,
12107 cdfs: &mut Cdfs,
12108 neighbours: &mut Neighbours,
12109 at_mi: (usize, usize),
12110 bw: usize,
12111 bh: usize,
12112 // The transform unit's own width and height in pixels. Square for every
12113 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
12114 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
12115 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
12116 tx_w: usize,
12117 tx_h: usize,
12118 m: &RectStripModes,
12119 y: &mut PlaneBuf<'static>,
12120 u: &mut PlaneBuf<'static>,
12121 v: &mut PlaneBuf<'static>,
12122 base_q_idx: u8,
12123 reduced_tx_set: bool,
12124 fctx: &crate::decode::FrameCtx,
12125) -> Result<()> {
12126 let (mi_r, mi_c) = at_mi;
12127 let (px, py) = (mi_c * MI, mi_r * MI);
12128 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
12129 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
12130 // lane-av1-422blockhalf: at ss (1,0) the tall/wide 1:2 and 1:4 strips'
12131 // chroma plane block is BLOCK_INVALID (`av1_ss_size_lookup[...][1][0]`,
12132 // blockd.h -- the 4:2:2 column maps BLOCK_8X16/16X32/32X64/64X128 and
12133 // BLOCK_8X32/16X64, plus 4-wide BLOCK_4X16, to BLOCK_INVALID), so
12134 // `av1_get_max_uv_txsize` indexes `max_txsize_rect_lookup` OUT OF BOUNDS
12135 // and the pinned Release oracle byte there is TX_4X8 (the lane-av1-422m
12136 // measurement). The plane is still coded -- `decode_token_recon_block`
12137 // steps it in that (4, 8) unit shape -- so the strip's chroma tiles into
12138 // 4x8 rect units, plane-major.
12139 let chroma_422_oob = ss_x(fctx) == 1
12140 && ss_y(fctx) == 0
12141 && matches!(
12142 (bw, bh),
12143 (8, 16) | (16, 32) | (32, 64) | (64, 128) | (8, 32) | (16, 64)
12144 );
12145 // lane-av1-422stripanchor: the 4-wide strips' PAIR chroma -- the ported
12146 // floored-pair anchor. `chroma422_pair_plane` is `Some` exactly when this
12147 // strip's own chroma block would be 2 px wide at ss (1, 0); the pair's
12148 // plane is then `(4, chroma_h)` written at the FLOORED cell
12149 // (`chroma_x`), and the skip/tiled chroma arms below tile it in (4, 8)
12150 // units (the OOB `max_txsize_rect_lookup[BLOCK_INVALID]` byte, TX_4X8 --
12151 // the same walk the (8, 32) class takes). The lossless raster arm keeps
12152 // the strip's own geometry: no caller of this function can present a
12153 // 4-wide strip yet (the enumeration test pins the five callers at
12154 // `8 <= min`), and the skip/tiled arms are the routes a future caller
12155 // needs.
12156 let chroma422_pair = chroma422_pair_plane(ss_x(fctx) == 1, ss_y(fctx) == 0, mi_c, bw, bh);
12157 let chroma_422_pair_wide = chroma422_pair.is_some();
12158 let (chroma_block_w, chroma_block_h, chroma_x) =
12159 chroma422_pair.map_or((chroma_w, chroma_h, cpx), |(w, h, x, _)| (w, h, x));
12160 // The chroma transform is picked before any symbol is read, so an
12161 // unsupported chroma shape refuses before this strip desyncs the tile.
12162 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
12163 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
12164 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
12165 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
12166 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
12167 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
12168 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
12169 // squares a rect transform down to a CDF set by
12170 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
12171 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
12172 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
12173 // paths already prove for these same shapes.
12174 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
12175 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
12176 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
12177 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
12178 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
12179 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
12180 _ => None,
12181 };
12182 // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted
12183 // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled
12184 // below; everything else still needs a single-unit table.
12185 // lane-av1-422: a 4:2:2 strip's chroma plane keeps the strip's HEIGHT and
12186 // halves only the width, so a rect luma strip codes a SQUARE chroma block
12187 // (16x8 luma -> 8x8 chroma) -- the square rows below. At 4:2:0 and 4:4:4 a
12188 // rect strip's chroma is itself rect, so the square rows are unreachable
12189 // there and cannot change their results.
12190 // lane-av1-422blockhalf: the tiled arms below handle every shape this
12191 // strip can carry (including the 4:2:2 BLOCK_INVALID planes), so the
12192 // diagnostic names only the shapes that would actually refuse -- it used
12193 // to fire for every tiled square too (the parent lane's `chroma=8x8`
12194 // rows) and sent the next lane chasing handled shapes.
12195 let chroma_tiled = chroma_422_pair_wide
12196 || chroma_422_oob
12197 || matches!(
12198 (chroma_w, chroma_h),
12199 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)
12200 );
12201 if !m.skip {
12202 if let Some(i) = match (chroma_w, chroma_h) {
12203 (32, 8) => Some(0),
12204 (8, 32) => Some(1),
12205 (8, 4) => Some(2),
12206 (4, 8) => Some(3),
12207 _ => None,
12208 } {
12209 hit_do! {
12210 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
12211 let mut hits = c.get();
12212 hits[i] += 1;
12213 c.set(hits);
12214 });
12215 }
12216 }
12217 if !m.skip && chroma.is_none() && !chroma_tiled {
12218 // Diagnostic for the next caller that lands here (class
12219 // refusal-names-a-correlate: the message names the tool, not the
12220 // shape); the refusal below keeps its inventory-pinned wording.
12221 eprintln!(
12222 "EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} \
12223 chroma={chroma_w}x{chroma_h}"
12224 );
12225 }
12226 }
12227 // lane-rectsplit r2 (verifier finding): with both callers wired
12228 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
12229 // 64x32/32x64) every shape that reaches here has a table above, so this
12230 // arm is UNREACHABLE today. It stays as the shape guard for the next
12231 // caller -- a new strip size would otherwise hit the `expect` below and
12232 // panic instead of refusing by name -- and so stays in
12233 // `refusal_inventory::REFUSALS`.
12234 if !m.skip && chroma.is_none() && !chroma_tiled {
12235 return Err(unsupported(
12236 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
12237 ));
12238 }
12239 hit!(RECT_SPLIT_TX_HITS);
12240 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
12241 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
12242 }
12243 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
12244 // A square unit reads through the ordinary square [`read_plane`]; a rect
12245 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
12246 // the very tables the unsplit 16x8/32x16 paths use.
12247 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
12248 (w, h) if w == h => None,
12249 (16, 8) | (8, 16) => Some((
12250 if reduced_tx_set {
12251 TxbSet::LumaRect16x8
12252 } else {
12253 TxbSet::LumaRect16x8Set1
12254 },
12255 if tx_w == 16 {
12256 &SCAN_16X8[..]
12257 } else {
12258 &SCAN_8X16[..]
12259 },
12260 )),
12261 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
12262 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
12263 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
12264 // strip, read through the `luma_64corner` arm below instead of a rect
12265 // table -- a 64-length axis codes only its low 32 coefficients
12266 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
12267 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
12268 // depth-0 arm already reads on the key-frame path.
12269 //
12270 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
12271 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
12272 // sub-8x8 intra leaves still refused: with those lifted (r2) the
12273 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
12274 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
12275 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
12276 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
12277 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
12278 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
12279 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
12280 (64, 32) | (32, 64) => None,
12281 _ => {
12282 return Err(unsupported(format!(
12283 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
12284 coefficient tables for that shape here)"
12285 )));
12286 }
12287 };
12288 // The `None` above that is NOT the square arm.
12289 let luma_64corner = tx_w != tx_h;
12290 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
12291 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
12292 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
12293 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
12294 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
12295 // per-unit rect walk stay wired above/below; the round that finds that
12296 // defect deletes this refusal and nothing else.
12297 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
12298 let luma_scan = default_scan(tx_w.min(tx_h));
12299 let zero_tu = vec![0i32; tx_w * tx_h];
12300 // The strip's OWN edge availability, the fallback for a transform unit
12301 // whose top-right/bottom-left pixels fall outside the strip.
12302 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12303 for tu_row in 0..bh / tx_h {
12304 for tu_col in 0..bw / tx_w {
12305 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
12306 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
12307 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
12308 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
12309 // libaom clips `av1_foreach_transformed_block_in_plane` to
12310 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
12311 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
12312 // TOP-LEFT sample falls outside the frame is never coded. We read
12313 // coefficients for those phantom units and desynced the stream at
12314 // the very next symbol.
12315 if tu_px >= y.true_width || tu_py >= y.true_height {
12316 continue;
12317 }
12318 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
12319 // transform unit INSIDE a block, which is a different rule from
12320 // the standalone-block table [`Reach::of`] applies -- and the
12321 // reason a depth-2 superblock strip came out one sample off
12322 // before this: `Reach::of(tx, ..)` answered as if the unit were
12323 // its own block at that superblock position.
12324 // * top-right: if the unit's right neighbour is still inside the
12325 // strip the pixels are already reconstructed (`col_off +
12326 // tx_wide < plane_bw`); otherwise only the strip's own top row
12327 // of units can reach past it, through the block-level answer.
12328 // * bottom-left: a unit that is not in the strip's left column
12329 // has none (`col_off > 0` returns 0); inside the strip
12330 // (`row_off + tx_high < plane_bh`) they are the left
12331 // neighbour's, already reconstructed; the last row falls back
12332 // to the block-level answer.
12333 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
12334 // The unit's own window on the block's palette prediction.
12335 if let Some(buf) = &m.palette_y {
12336 let tu_buf: Vec<u16> = (0..tx_h)
12337 .flat_map(|i| {
12338 let base = (row_off + i) * bw + col_off;
12339 buf[base..base + tx_w].iter().copied()
12340 })
12341 .collect();
12342 set_palette_pred(tu_buf, fctx);
12343 }
12344 if m.skip {
12345 push_intra_rect(
12346 0,
12347 tu_px,
12348 tu_py,
12349 tx_w,
12350 tx_h,
12351 m.mode,
12352 m.angle_delta_y,
12353 tu_reach,
12354 &zero_tu,
12355 None,
12356 m.filter_intra,
12357 m.smooth_neighbor,
12358 fctx,
12359 );
12360 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
12361 } else if luma_64corner && luma_rect.is_none() {
12362 // The un-split 64-level luma transform: `read_coeffs` on the
12363 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
12364 // and the real rect shape passed through for
12365 // `av1_nz_map_ctx_offset` -- byte for byte
12366 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
12367 // 64-level strip gate already proves. `tx_type` is not coded
12368 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
12369 // the square-up size is TX_64X64), and this unit covers its
12370 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
12371 if crate::envflags::env_flag!("EC_RECT64TU") {
12372 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
12373 }
12374 hit_do! {
12375 RECT64_CORNER_TU_HITS.with(|c| {
12376 let mut v = c.get();
12377 v[usize::from(tx_h > tx_w)] += 1;
12378 c.set(v);
12379 });
12380 }
12381 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
12382 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
12383 let (corner, tu_tx_type) = read_coeffs(
12384 dec,
12385 &mut coding,
12386 default_scan(TX32),
12387 0,
12388 dc_sign_ctx(tu_around.2),
12389 TxType::DctDct,
12390 Some((tx_w, tx_h)),
12391 )?;
12392 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
12393 let mut tu_grid = vec![0i32; tx_w * tx_h];
12394 for row in 0..ch {
12395 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
12396 }
12397 let residual = dequant_and_inverse_typed_wh(
12398 &tu_grid,
12399 tx_w,
12400 tx_h,
12401 crate::decode::bit_depth(fctx),
12402 block_q_idx(fctx),
12403 plane_q_delta(0, fctx).0,
12404 plane_q_delta(0, fctx).1,
12405 tu_tx_type,
12406 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
12407 );
12408 push_intra_rect(
12409 0,
12410 tu_px,
12411 tu_py,
12412 tx_w,
12413 tx_h,
12414 m.mode,
12415 m.angle_delta_y,
12416 tu_reach,
12417 &residual,
12418 None,
12419 m.filter_intra,
12420 m.smooth_neighbor,
12421 fctx,
12422 );
12423 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12424 } else if let Some((rect_set, rect_scan)) = luma_rect {
12425 // The rect-unit twin of the square arm below: same contexts,
12426 // same order, through the rect coefficient reader. The
12427 // `tx_type` CDF row of a filter-intra block is
12428 // `fimode_to_intradir[filter_intra_mode]`, never the block's
12429 // own (always DC_PRED) mode -- [`read_plane`] applies that
12430 // for the square arm, so this one must too.
12431 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
12432 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
12433 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
12434 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
12435 // neighbour-magnitude table is for a unit SMALLER than its
12436 // block. [`decode_block_rect`]'s own unsplit read passes a
12437 // literal 0 for the same reason; this arm applied the table
12438 // unconditionally and desynced every depth-0 rect strip that
12439 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
12440 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
12441 0
12442 } else {
12443 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
12444 };
12445 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
12446 let (tu_grid, tu_tx_type) = read_coeffs_rect(
12447 dec,
12448 &mut coding,
12449 rect_scan,
12450 tx_w,
12451 tx_h,
12452 tu_skip_ctx,
12453 dc_sign_ctx(tu_around.2),
12454 TxType::DctDct,
12455 0,
12456 )?;
12457 let residual = dequant_and_inverse_typed_wh(
12458 &tu_grid,
12459 tx_w,
12460 tx_h,
12461 crate::decode::bit_depth(fctx),
12462 block_q_idx(fctx),
12463 plane_q_delta(0, fctx).0,
12464 plane_q_delta(0, fctx).1,
12465 tu_tx_type,
12466 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
12467 );
12468 push_intra_rect(
12469 0,
12470 tu_px,
12471 tu_py,
12472 tx_w,
12473 tx_h,
12474 m.mode,
12475 m.angle_delta_y,
12476 tu_reach,
12477 &residual,
12478 None,
12479 m.filter_intra,
12480 m.smooth_neighbor,
12481 fctx,
12482 );
12483 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12484 } else {
12485 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
12486 // This unit is smaller than the block it sits in, so
12487 // `txb_skip_ctx` is the neighbour-magnitude table, not the
12488 // lone-TU 0 (spec `get_txb_ctx_general`).
12489 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
12490 let tu_grid = read_plane(
12491 dec,
12492 cdfs,
12493 luma_set,
12494 &luma_scan,
12495 0,
12496 tu_around,
12497 m.mode,
12498 m.mode,
12499 m.angle_delta_y,
12500 tu_reach,
12501 y,
12502 tu_px,
12503 tu_py,
12504 tx_w,
12505 tx_w,
12506 base_q_idx,
12507 None,
12508 m.filter_intra,
12509 Some(tu_skip_ctx),
12510 m.smooth_neighbor,
12511 fctx,
12512 )?;
12513 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
12514 }
12515 }
12516 }
12517 // CHROMA: one un-split rect transform for the whole strip.
12518 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
12519 // units -- each stamps its own neighbour context as it is read, and the
12520 // whole-block `record_split_luma_rect_mi` below would overwrite all of
12521 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
12522 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
12523 // collected here and replayed after that record.
12524 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
12525 // The chroma_tiled arm below stamps each unit's coefficient context
12526 // immediately (so the NEXT unit reads it), then the whole-strip
12527 // `record_split_luma_rect_mi` rewrites every chroma cell with ONE
12528 // whole-strip state and the per-unit DC signs and levels are lost
12529 // (class `override-slot-on-one-arm`). The units are collected here and
12530 // replayed after that record, the way the lossless arm's
12531 // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail
12532 // already do.
12533 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
12534 let ac = m.alpha.map(|_| {
12535 // lane-av1-422stripanchor: the pair unit's CfL source is the PAIR's
12536 // luma -- the 8-px-wide region the floored 4-px chroma block covers
12537 // (`av1_setup_dst_planes`' floor), never the odd strip's own 4 px.
12538 if chroma_422_pair_wide {
12539 cfl_src_rect((mi_c & !1) * MI, py, 8, bh)
12540 } else {
12541 cfl_src_rect(px, py, bw, bh)
12542 }
12543 });
12544 let reach = if chroma_422_pair_wide {
12545 // The chroma units predict off the PAIR block's edges: an odd-column
12546 // strip's pair starts 4 luma px to the strip's left, so the strip's
12547 // own answer names the wrong above/right samples (the pair16 arm's
12548 // `pair_reach`, one partition level up).
12549 Reach::of_rect(8, bh, (mi_c & !1) * MI, py, y.width, y.height, fctx)
12550 } else {
12551 block_reach
12552 };
12553 let (u_grid, v_grid) = if mono(fctx) {
12554 // lane-av1mono: a monochrome frame codes no chroma coefficients on
12555 // any block (`plane < av1_num_planes == 1`), so the whole chroma
12556 // section -- the skipped-strip pushes, the lossless raster and the
12557 // un-split `read_coeffs_rect` below -- is bypassed.
12558 let zero = Grid::Zero(chroma_w * chroma_h);
12559 (zero.clone(), zero)
12560 } else if m.skip {
12561 let zero = Grid::Zero(chroma_block_w * chroma_block_h);
12562 if chroma_422_pair_wide || chroma_422_oob {
12563 // lane-av1-422blockhalf: libaom predicts an INTRA strip's chroma
12564 // per transform unit even when the strip is skipped
12565 // (`decode_token_recon_block`'s per-TU plane walk runs before the
12566 // skip guard), so the BLOCK_INVALID plane predicts as (4, 8)
12567 // units -- one whole-plane push here would ask the intra
12568 // predictor for a 1:8 rect it never needs.
12569 // lane-av1-422stripanchor: the 4-wide strip's PAIR plane does the
12570 // same, over the pair's own `(chroma_block_w, chroma_block_h)`
12571 // grid at the floored anchor `chroma_x`.
12572 let (uw, uh) = (4usize, 8usize);
12573 for plane_idx in 1..=2 {
12574 if let Some((ub, vb)) = &m.palette_uv {
12575 let buf = if plane_idx == 1 { ub } else { vb };
12576 set_palette_pred(buf.clone(), fctx);
12577 }
12578 for cu_row in 0..chroma_block_h / uh {
12579 for cu_col in 0..chroma_block_w / uw {
12580 push_intra_rect(
12581 plane_idx,
12582 chroma_x + cu_col * uw,
12583 cpy + cu_row * uh,
12584 uw,
12585 uh,
12586 m.uv_predict_mode,
12587 m.angle_delta_uv,
12588 reach,
12589 &ZERO_RESIDUAL[..uw * uh],
12590 m.alpha
12591 .zip(ac.clone())
12592 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
12593 None,
12594 m.smooth_neighbor_uv,
12595 fctx,
12596 );
12597 }
12598 }
12599 }
12600 } else {
12601 if let Some((ub, _)) = &m.palette_uv {
12602 set_palette_pred(ub.clone(), fctx);
12603 }
12604 push_intra_rect(
12605 1,
12606 cpx,
12607 cpy,
12608 chroma_w,
12609 chroma_h,
12610 m.uv_predict_mode,
12611 m.angle_delta_uv,
12612 reach,
12613 &zero,
12614 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12615 None,
12616 m.smooth_neighbor_uv,
12617 fctx,
12618 );
12619 if let Some((_, vb)) = &m.palette_uv {
12620 set_palette_pred(vb.clone(), fctx);
12621 }
12622 push_intra_rect(
12623 2,
12624 cpx,
12625 cpy,
12626 chroma_w,
12627 chroma_h,
12628 m.uv_predict_mode,
12629 m.angle_delta_uv,
12630 reach,
12631 &zero,
12632 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12633 None,
12634 m.smooth_neighbor_uv,
12635 fctx,
12636 );
12637 }
12638 (zero.clone(), zero)
12639 } else if lossless(fctx) {
12640 // lane-lossless: the strip's chroma plane block is coded as 4x4
12641 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
12642 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
12643 // (`decode_token_recon_block`'s mu-chunk loop, measured against
12644 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
12645 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
12646 // offset (our `+3` row base) whenever the plane block is bigger than
12647 // the transform.
12648 let scan4 = default_scan(4);
12649 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
12650 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
12651 // lane-av1-llband: one 4x4 chroma unit's extent in LUMA pixels -- 4
12652 // chroma px scaled by the plane's own subsampling. The hardcoded 8
12653 // was the 4:2:0 unit's span; at 4:4:4 a unit is 4x4 LUMA px (one mi
12654 // cell), and the 8-px step made every unit past the first column/row
12655 // read its `txb_skip` context at the WRONG mi (two cells over) and
12656 // stamp a 2-cell span with one unit's state -- the polluted above-band
12657 // cell behind a 16x8 leaf's U bc=2 unit of the 444 lossless key frame
12658 // (measured: oracle `EC_DBGCTX` reads 1-cell spans at 1-mi steps;
12659 // ours read `above[28..29]` where the oracle read `above[26]`).
12660 let span_x = 4 << ss_x(fctx);
12661 let span_y = 4 << ss_y(fctx);
12662 let mut last = [Grid::Zero(16), Grid::Zero(16)];
12663 for plane_idx in 1..=2 {
12664 for cu_row in 0..ch_n {
12665 for cu_col in 0..cw_n {
12666 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
12667 let cu_around = neighbours.around_mi_rect(cu_mi, span_x, span_y);
12668 let cu_reach = tu_reach(
12669 bw,
12670 bh,
12671 cu_col * span_x,
12672 cu_row * span_y,
12673 span_x,
12674 block_reach,
12675 px,
12676 py,
12677 y.width,
12678 y.height,
12679 fctx,
12680 );
12681 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
12682 if let Some((ub, vb)) = &m.palette_uv {
12683 let pbuf = if plane_idx == 1 { ub } else { vb };
12684 set_palette_pred(
12685 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
12686 fctx,
12687 );
12688 }
12689 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12690 let grid = read_plane(
12691 dec,
12692 cdfs,
12693 TxbSet::Chroma4,
12694 &scan4,
12695 plane_idx,
12696 cu_around[plane_idx],
12697 m.mode,
12698 m.uv_predict_mode,
12699 m.angle_delta_uv,
12700 cu_reach,
12701 plane,
12702 cu_x,
12703 cu_y,
12704 4,
12705 4,
12706 base_q_idx,
12707 m.alpha
12708 .zip(ac)
12709 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
12710 None,
12711 offset,
12712 m.smooth_neighbor_uv,
12713 fctx,
12714 )?;
12715 if span_x == 4 && span_y == 4 {
12716 hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS);
12717 }
12718 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid);
12719 ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y));
12720 last[plane_idx - 1] = grid;
12721 }
12722 }
12723 }
12724 let [ug, vg] = last;
12725 (ug, vg)
12726 } else if chroma_tiled {
12727 let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) =
12728 if chroma_422_pair_wide || chroma_422_oob {
12729 // lane-av1-422blockhalf / lane-av1-422stripanchor: the
12730 // BLOCK_INVALID-plane chroma's (4, 8) units -- the Release
12731 // oracle's out-of-bounds `max_txsize_rect_lookup` byte (TX_4X8,
12732 // see above). For the 4-wide strip the units tile the PAIR's
12733 // plane, stepping from the floored anchor.
12734 (4, 8, TxbSet::ChromaRect8x4, &SCAN_4X8)
12735 } else {
12736 match (chroma_w, chroma_h) {
12737 (64, 32) | (32, 64) | (32, 32) => (32, 32, TxbSet::Chroma32, default_scan(32)),
12738 (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16),
12739 (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32),
12740 // lane-av1-422: the 4:2:2 square chroma planes (height unhalved),
12741 // through the square reader like every other square chroma unit.
12742 (16, 16) => (16, 16, TxbSet::Chroma16, default_scan(16)),
12743 (8, 8) => (8, 8, TxbSet::Chroma8, default_scan(8)),
12744 _ => unreachable!("chroma_tiled"),
12745 }
12746 };
12747 // lane-av1-422: the witness counter, keyed to ss (1,0) so only a 4:2:2
12748 // frame's square chroma units count it.
12749 if uw == uh && ss_x(fctx) == 1 && ss_y(fctx) == 0 {
12750 hit!(CHROMA422_SQUARE_HITS);
12751 }
12752 if chroma_422_pair_wide {
12753 hit!(CHROMA422_PAIR_WIDE_HITS);
12754 }
12755 let (nw, nh) = (chroma_block_w / uw, chroma_block_h / uh);
12756 // lane-av1-422stripanchor: the pair's plane block is BLOCK_INVALID
12757 // whatever the pair size (`num_pels_log2_lookup[255]` reads 0xff in
12758 // the pinned Release oracle), so its txb_skip rows always carry the
12759 // bigger-plane +3 (the av1422q rule the pair16 arm measures).
12760 let bigger = chroma_422_pair_wide || chroma_w * chroma_h > uw * uh;
12761 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
12762 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra;
12763 // smaller rect units (the 4:2:2 BLOCK_INVALID-plane (4, 8)s) take the
12764 // mode-indexed default, the same rule the unsplit arm below applies.
12765 let default_tx = if uw.max(uh) >= 32 {
12766 TxType::DctDct
12767 } else {
12768 default_intra_tx_type(m.uv_predict_mode as u8)
12769 };
12770 let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)];
12771 for plane_idx in 1..=2 {
12772 for cu_row in 0..nh {
12773 for cu_col in 0..nw {
12774 let luma_span_x = uw << ss_x(fctx);
12775 let luma_span_y = uh << ss_y(fctx);
12776 let cu_mi = (
12777 mi_r + cu_row * (luma_span_y / MI),
12778 if chroma_422_pair_wide {
12779 mi_c & !1
12780 } else {
12781 mi_c
12782 } + cu_col * (luma_span_x / MI),
12783 );
12784 // lane-av1-422blockhalf: the 4:2:2 (4, 8) units read their
12785 // chroma context per chroma cell
12786 // ([`Neighbours::around_mi_422_chroma`], the block-8
12787 // rule) -- the plain rect walk samples one chroma cell
12788 // twice at ss_x 1. Every pre-existing shape keeps its own
12789 // walk.
12790 // lane-av1422mi24: the plain rect walk's double-count
12791 // hits EVERY unit shape at ss (1,0), not just the (4, 8)
12792 // one -- the (8, 8) unit of a 16x8 intra-in-inter strip
12793 // read its above dc votes twice and its U dc_sign one
12794 // ctx row high (t422 frame 1). Route every ss (1,0)
12795 // unit through the every-second-above-cell sampling;
12796 // 4:2:0/4:4:4 keep the plain walk verbatim.
12797 let cu_around = if chroma_422_oob || (ss_x(fctx) == 1 && ss_y(fctx) == 0) {
12798 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
12799 } else {
12800 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
12801 };
12802 let (cu_x, cu_y) = (chroma_x + cu_col * uw, cpy + cu_row * uh);
12803 let cfl = m.alpha.map(|(au, av)| {
12804 let alpha = if plane_idx == 1 { au } else { av };
12805 (
12806 alpha,
12807 if chroma_422_pair_wide {
12808 // The unit's co-located luma is the PAIR's
12809 // 8-px-wide band at the floored mi column.
12810 cfl_src_rect(
12811 (mi_c & !1) * MI + cu_col * luma_span_x,
12812 py + cu_row * luma_span_y,
12813 luma_span_x,
12814 luma_span_y,
12815 )
12816 } else {
12817 cfl_src_rect(
12818 px + cu_col * luma_span_x,
12819 py + cu_row * luma_span_y,
12820 luma_span_x,
12821 luma_span_y,
12822 )
12823 },
12824 )
12825 });
12826 // lane-av1-422kf: the palette colour map is consumed per
12827 // unit here like every other chroma arm (`av1_visit_palette`
12828 // feeds the whole plane block; window it to this unit).
12829 // Without this the square chroma rows decoded a uv-palette
12830 // strip's chroma as plain DC (class same-symbols-silent-
12831 // prediction: the rng stayed in sync, only the prediction
12832 // was dropped).
12833 if let Some((ub, vb)) = &m.palette_uv {
12834 let buf = if plane_idx == 1 { ub } else { vb };
12835 set_palette_pred(
12836 palette_window(buf, chroma_block_w, cu_col * uw, cu_row * uh, uw, uh),
12837 fctx,
12838 );
12839 }
12840 // libaom computes `has_top_right` PER TRANSFORM UNIT (defined
12841 // reconintra.c:196, called from `av1_build_intra_predictors` at
12842 // reconintra.c:1847 with the txb walk's own
12843 // `blk_col`/`blk_row`), never per block: the
12844 // `row_off == 0` arm asks `col_off + top_right_count_unit
12845 // < plane_bw_unit`, so the FIRST unit of a 2-wide chroma
12846 // grid reads its above-right out of the already-reconstructed
12847 // block ABOVE even when the block's own right edge is the
12848 // frame's. Passing this walk's block-level `reach` gave
12849 // every unit the same answer, and `PlaneBuf::edges`
12850 // (decode.rs:20840) truncates the above row at
12851 // `own_across` when `above_right` is false -- so a
12852 // directional unit whose angle is below 90
12853 // (`need_right`, intra.rs:546) predicted with a 32-sample
12854 // above row where libaom used 64.
12855 // MEASURED on `fixtures/r512_rect2x1_1x2_444.obu`
12856 // (4:4:4 8-bit 256x256, one frame): frame 0 plane U 130
12857 // samples and plane V 30 samples wrong, every one of them
12858 // in the right 6 columns of the `cu=(0,0)` unit at
12859 // `mi=(48,48)` `px=(192,192)` -- the unit whose above-right
12860 // the block reach denied. Row0 and col0 of the prediction
12861 // matched the oracle exactly and the prediction SUM did
12862 // not (172662 vs 171512 on U, 125978 vs 126008 on V), so
12863 // the residual read is bit-identical and the divergence is
12864 // prediction-side, not entropy. Gate:
12865 // `a_444_rect_strip_chroma_tiled_2x1_and_1x2_units_take_their_own_above_right_reach`.
12866 let cu_reach = tu_reach_rect(
12867 bw,
12868 bh,
12869 (cu_col * uw) << ss_x(fctx),
12870 (cu_row * uh) << ss_y(fctx),
12871 uw << ss_x(fctx),
12872 uh << ss_y(fctx),
12873 reach,
12874 px,
12875 py,
12876 y.width,
12877 y.height,
12878 fctx,
12879 );
12880 if cu_reach.above_right != reach.above_right
12881 || cu_reach.below_left != reach.below_left
12882 {
12883 hit!(RECT_TILED_CHROMA_UNIT_REACH_HITS);
12884 }
12885 if nw * nh > 1 {
12886 match (nw, nh) {
12887 (2, 1) => hit!(RECT_TILED_CHROMA_2X1_HITS),
12888 (1, 2) => hit!(RECT_TILED_CHROMA_1X2_HITS),
12889 _ => hit!(RECT_TILED_CHROMA_NXN_HITS),
12890 }
12891 }
12892 // 32x32 does not fit read_coeffs_rect's scratch (768). The
12893 // square reader is the path every other 32x32 chroma unit uses.
12894 let levels = if uw == uh {
12895 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
12896 read_plane(
12897 dec,
12898 cdfs,
12899 set,
12900 scan,
12901 plane_idx,
12902 cu_around[plane_idx],
12903 m.mode,
12904 m.uv_predict_mode,
12905 m.angle_delta_uv,
12906 cu_reach,
12907 plane,
12908 cu_x,
12909 cu_y,
12910 uw,
12911 uw,
12912 base_q_idx,
12913 cfl,
12914 None,
12915 bigger.then_some(3),
12916 m.smooth_neighbor_uv,
12917 fctx,
12918 )?
12919 } else {
12920 let skip_ctx = usize::from(cu_around[plane_idx].0)
12921 + usize::from(cu_around[plane_idx].1)
12922 + usize::from(bigger) * 3;
12923 let mut coding = cdfs.txb(set, m.uv_predict_mode);
12924 let (levels, tx_type) = read_coeffs_rect(
12925 dec,
12926 &mut coding,
12927 scan,
12928 uw,
12929 uh,
12930 skip_ctx,
12931 dc_sign_ctx(cu_around[plane_idx].2),
12932 default_tx,
12933 plane_idx,
12934 )?;
12935 let residual = dequant_and_inverse_typed_wh(
12936 &levels,
12937 uw,
12938 uh,
12939 crate::decode::bit_depth(fctx),
12940 block_q_idx(fctx),
12941 plane_q_delta(plane_idx, fctx).0,
12942 plane_q_delta(plane_idx, fctx).1,
12943 tx_type,
12944 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
12945 );
12946 push_intra_rect(
12947 plane_idx,
12948 cu_x,
12949 cu_y,
12950 uw,
12951 uh,
12952 m.uv_predict_mode,
12953 m.angle_delta_uv,
12954 cu_reach,
12955 &residual,
12956 cfl,
12957 None,
12958 m.smooth_neighbor_uv,
12959 fctx,
12960 );
12961 levels
12962 };
12963 neighbours.record_mi_chroma(
12964 cu_mi,
12965 luma_span_x,
12966 luma_span_y,
12967 plane_idx,
12968 &levels,
12969 );
12970 tiled_chroma_units.push((
12971 cu_mi,
12972 plane_idx,
12973 levels.clone(),
12974 luma_span_x,
12975 luma_span_y,
12976 ));
12977 last[plane_idx - 1] = levels;
12978 }
12979 }
12980 }
12981 (last[0].clone(), last[1].clone())
12982 } else {
12983 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
12984 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
12985 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
12986 // so only the 16x8/8x16 pair takes the mode-indexed default.
12987 let default_tx = if chroma_w.max(chroma_h) >= 32 {
12988 TxType::DctDct
12989 } else {
12990 default_intra_tx_type(m.uv_predict_mode as u8)
12991 };
12992 // lane-av1422mi24: at ss (1,0) the chroma above span is `bw >> 1`
12993 // chroma cells spread over `bw` luma mi columns -- the per-mi gather
12994 // counts every chroma column's whole-unit dc sign twice (the t422
12995 // frame-1 mi(26,60) intra-in-inter strip's U dc_sign read one ctx
12996 // row high). Luma keeps the per-mi gather; the two chroma planes
12997 // take [`Neighbours::around_mi_422_chroma`]'s every-second
12998 // above-cell sampling, like every other 4:2:2 chroma gather.
12999 let mut around = neighbours.around_mi_rect(at_mi, bw, bh);
13000 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
13001 let c = neighbours.around_mi_422_chroma(at_mi, bw, bh);
13002 around[1] = c[1];
13003 around[2] = c[2];
13004 }
13005 let mut grids: Vec<Grid> = Vec::with_capacity(2);
13006 for plane_idx in 1..=2 {
13007 let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
13008 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
13009 let (levels, tx_type) = read_coeffs_rect(
13010 dec,
13011 &mut coding,
13012 chroma_scan,
13013 chroma_w,
13014 chroma_h,
13015 skip_ctx,
13016 dc_sign_ctx(around[plane_idx].2),
13017 default_tx,
13018 plane_idx,
13019 )?;
13020 // The same delta_q proof the unsplit rect64 path records
13021 // (lane-rectsplit r4: lifting the split-transform refusal moved
13022 // superblock strips onto this path, so only counting there would
13023 // leave the delta_q gate's counter silent for them).
13024 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
13025 hit!(RECT64_QIDX_DRIFT_HITS);
13026 }
13027 let residual = dequant_and_inverse_typed_wh(
13028 &levels,
13029 chroma_w,
13030 chroma_h,
13031 crate::decode::bit_depth(fctx),
13032 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
13033 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
13034 // reading `current_q_idx` here dropped the segment feature
13035 // that every other dequant site applies (class
13036 // `parsed-then-discarded`).
13037 block_q_idx(fctx),
13038 plane_q_delta(plane_idx, fctx).0,
13039 plane_q_delta(plane_idx, fctx).1,
13040 tx_type,
13041 block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, tx_type),
13042 );
13043 let cfl = m
13044 .alpha
13045 .zip(ac)
13046 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
13047 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
13048 if let Some((ub, vb)) = &m.palette_uv {
13049 let buf = if plane_idx == 1 { ub } else { vb };
13050 set_palette_pred(buf.clone(), fctx);
13051 }
13052 push_intra_rect(
13053 plane_idx,
13054 cpx,
13055 cpy,
13056 chroma_w,
13057 chroma_h,
13058 m.uv_predict_mode,
13059 m.angle_delta_uv,
13060 reach,
13061 &residual,
13062 cfl,
13063 None,
13064 m.smooth_neighbor_uv,
13065 fctx,
13066 );
13067 grids.push(levels);
13068 }
13069 let mut it = grids.into_iter();
13070 (it.next().unwrap(), it.next().unwrap())
13071 };
13072 neighbours.record_split_luma_rect_mi(
13073 at_mi,
13074 bw,
13075 bh,
13076 m.mode,
13077 m.uv_predict_mode,
13078 [&u_grid, &v_grid],
13079 );
13080 for (cu_mi, plane, unit, span_w, span_h) in &ll_chroma_units {
13081 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
13082 }
13083 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
13084 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
13085 }
13086 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
13087 neighbours.fill_lf_grid_rect(
13088 (mi_r, mi_c),
13089 bw / MI,
13090 bh / MI,
13091 tx_w as u8,
13092 tx_h as u8,
13093 0,
13094 fctx,
13095 );
13096 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13097 let (rng, _) = dec.debug_state();
13098 eprintln!(
13099 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
13100 tx={tx_w}x{tx_h} rng={rng}"
13101 );
13102 }
13103 Ok(())
13104}
13105
13106/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
13107/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
13108/// because it predicts squares only. Every pixel here goes through the rect
13109/// machinery the key-frame paths already prove: [`decode_rect_split`], which
13110/// at `depth == 0` is the unsplit strip as a single transform unit and
13111/// beyond it the per-unit walk of [`depth_to_tx_wh`].
13112///
13113/// What is genuinely different from [`decode_block_rect`] is the mode
13114/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
13115/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
13116/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
13117/// intra-in-inter arm's own reads at the rect footprint, including its
13118/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
13119/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
13120/// square and this arm) and a nonzero luma angle delta refused by name.
13121///
13122/// The strip's own neighbour records (luma per transform unit, chroma, skip
13123/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
13124/// inter-side bands and the mi map.
13125#[allow(clippy::too_many_arguments)]
13126/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
13127/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
13128/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
13129/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
13130/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
13131/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
13132/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
13133/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
13134/// table here rather than a shift of `bw.min(bh)`.
13135fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
13136 Some(match (bw.min(bh), bw.max(bh)) {
13137 (8, 16) => (1usize, 1usize),
13138 (16, 32) => (2, 2),
13139 (32, 64) => (3, 3),
13140 (8, 32) => (1, 2),
13141 (16, 64) => (2, 3),
13142 _ => return None,
13143 })
13144}
13145
13146/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
13147/// block path"): the shapes that can reach that arm, enumerated against the
13148/// MEASURED domain of the inter block path
13149/// ([`INTER_BLOCK_SHAPES`], the census the gate
13150/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
13151/// fills from three real streams).
13152///
13153/// [`decode_intra_rect_in_inter`] is called from one site, under
13154/// `write_w != side || write_h != side`, and only after two earlier arms have
13155/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
13156/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
13157/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
13158/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
13159/// and each of those has a row, so the refusal names a shape no measured
13160/// stream can present.
13161#[test]
13162fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
13163 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
13164 // names that string exactly (placeholders included) and pins its guard
13165 // site. The enumeration below establishes the shape domain; on its own it
13166 // never said WHICH string the domain was about, so under a real function
13167 // boundary -- rather than a window that ran into the next test -- the row
13168 // read as unanchored.
13169 const REFUSAL: &str = "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)";
13170 assert!(
13171 include_str!("decode.rs").contains(REFUSAL),
13172 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
13173 );
13174 let mut checked = 0;
13175 for &(side, w, h) in &INTER_BLOCK_SHAPES {
13176 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
13177 continue;
13178 }
13179 assert!(
13180 intra_in_inter_size_row(w, h).is_some(),
13181 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
13182 the \"no size-group/tx-category row\" refusal"
13183 );
13184 checked += 1;
13185 }
13186 assert_eq!(
13187 checked, 10,
13188 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
13189 lookup, not the 10 this claim was measured over"
13190 );
13191}
13192
13193/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
13194/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
13195/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
13196/// matched before the square arm's `log2` shortcut).
13197///
13198/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
13199/// row here"; the enumeration below is what proves no conformant block can
13200/// reach it.
13201pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
13202 Some(match (write_w, write_h) {
13203 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
13204 // below maps 128 to row 4 (BLOCK_16X32).
13205 (64, 128) => 14,
13206 (128, 64) => 15,
13207 (128, 128) => 16,
13208 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
13209 (16, 32) => 4,
13210 (32, 16) => 5,
13211 (32, 64) => 6,
13212 (64, 32) => 7,
13213 (8, 32) => 8,
13214 (32, 8) => 9,
13215 (16, 64) => 10,
13216 (64, 16) => 11,
13217 // lane-inter4 r3: the 16x16-level rect inter leaves.
13218 (8, 16) => 12,
13219 (16, 8) => 13,
13220 _ => return None,
13221 })
13222}
13223
13224/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
13225/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
13226/// `block_size_wide`/`block_size_high`).
13227#[cfg(test)]
13228const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
13229 (4, 4),
13230 (4, 8),
13231 (8, 4),
13232 (8, 8),
13233 (8, 16),
13234 (16, 8),
13235 (16, 16),
13236 (16, 32),
13237 (32, 16),
13238 (32, 32),
13239 (32, 64),
13240 (64, 32),
13241 (64, 64),
13242 (64, 128),
13243 (128, 64),
13244 (128, 128),
13245 (4, 16),
13246 (16, 4),
13247 (8, 32),
13248 (32, 8),
13249 (16, 64),
13250 (64, 16),
13251];
13252
13253/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
13254/// shape with no CDF row here" names a shape no conformant stream can present.
13255///
13256/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
13257/// whose `write_w.min(write_h) >= 8` clause is libaom's
13258/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
13259/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
13260/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
13261/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
13262/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
13263/// clause rejects before the lookup.
13264#[test]
13265fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
13266 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
13267 // names it and pins its guard site.
13268 const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here";
13269 assert!(
13270 crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), REFUSAL),
13271 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
13272 );
13273 let mut rows = std::collections::BTreeSet::new();
13274 let mut excluded = 0;
13275 for (w, h) in BLOCK_SIZES_ALL_WH {
13276 if w.min(h) < 8 {
13277 excluded += 1;
13278 assert!(
13279 w == 4 || h == 4,
13280 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
13281 );
13282 continue;
13283 }
13284 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
13285 panic!(
13286 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
13287 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
13288 )
13289 });
13290 assert!(
13291 row < 17,
13292 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
13293 );
13294 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
13295 }
13296 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
13297 assert_eq!(
13298 rows.len(),
13299 17,
13300 "17 eligible footprints must fill all 17 rows of the motion_mode table"
13301 );
13302}
13303
13304/// lane-av1-422stripanchor, format-cell census for the 4-wide-strip pair port
13305/// ([`chroma422_pair_plane`], [`decode_rect_split`]'s chroma routing): over
13306/// every `BLOCK_SIZES_ALL` footprint at every subsampling cell, the pair arm
13307/// fires exactly when libaom's own `av1_ss_size_lookup[..][1][0]` column
13308/// (`common_data.c`) marks the plane block BLOCK_INVALID AND the plane would
13309/// be 2 px wide -- the 4-wide footprints. The tall/wide BLOCK_INVALID shapes
13310/// stay on the pre-existing `chroma_422_oob` (4, 8) tiling, and 4:2:0 /
13311/// 4:4:4 never enter either arm (the byte-identical claim, checked per cell).
13312#[test]
13313fn chroma422_pair_plane_matches_the_ss_size_lookup_cells() {
13314 // The `av1_ss_size_lookup[..][1][0]` column verbatim (pinned oracle,
13315 // `common_data.c`), keyed by footprint: `true` = BLOCK_INVALID.
13316 let ss10_invalid: &[(&str, bool)] = &[
13317 ("4x4", false),
13318 ("4x8", true),
13319 ("8x4", false),
13320 ("8x8", false),
13321 ("8x16", true),
13322 ("16x8", false),
13323 ("16x16", false),
13324 ("16x32", true),
13325 ("32x16", false),
13326 ("32x32", false),
13327 ("32x64", true),
13328 ("64x32", false),
13329 ("64x64", false),
13330 ("64x128", true),
13331 ("128x64", false),
13332 ("128x128", false),
13333 ("4x16", true),
13334 ("16x4", false),
13335 ("8x32", true),
13336 ("32x8", false),
13337 ("16x64", true),
13338 ("64x16", false),
13339 ];
13340 for (footprint, invalid10) in ss10_invalid {
13341 let (w, h) = footprint.split_once('x').unwrap();
13342 let (bw, bh) = (w.parse::<usize>().unwrap(), h.parse::<usize>().unwrap());
13343 // BLOCK_4X4 is the SQUARE path's leaf, never a strip: its ss cell is
13344 // valid because a (2, 4) plane area rounds UP to the 4x4 read
13345 // (`sub8_leaf_chroma422`'s own rule), and it never reaches
13346 // [`decode_rect_split`] at all.
13347 if (bw, bh) == (4, 4) {
13348 continue;
13349 }
13350 // 4:2:0 and 4:4:4: the port never fires, whatever the footprint.
13351 for (ss_x, ss_y) in [(false, false), (true, true)] {
13352 assert!(
13353 chroma422_pair_plane(ss_x, ss_y, 7, bw, bh).is_none(),
13354 "{bw}x{bh} at ss ({ss_x}, {ss_y}) must keep its own plane block"
13355 );
13356 }
13357 // 4:2:2: the pair arm is exactly the 2-px-wide (4-wide) slice of the
13358 // BLOCK_INVALID column, anchored at the floored mi column.
13359 let pair = chroma422_pair_plane(true, false, 7, bw, bh);
13360 assert_eq!(
13361 pair.is_some(),
13362 *invalid10 && bw == 4,
13363 "{bw}x{bh} at ss (1, 0): pair routing disagrees with ss_size_lookup"
13364 );
13365 if let Some((block_w, block_h, x, ctx_col)) = pair {
13366 assert_eq!((block_w, block_h), (4, bh), "{bw}x{bh} pair plane shape");
13367 assert_eq!(x, ((7 & !1) * MI) >> 1, "{bw}x{bh} floored write anchor");
13368 assert_eq!(ctx_col, 6, "{bw}x{bh} entropy cell is the floored column");
13369 // An even-column strip anchors at its own cell.
13370 let (x_even, col_even) = match chroma422_pair_plane(true, false, 6, bw, bh) {
13371 Some((_, _, x, c)) => (x, c),
13372 None => panic!("{bw}x{bh} lost its pair arm at an even mi_col"),
13373 };
13374 assert_eq!(
13375 (x_even, col_even),
13376 (12, 6),
13377 "even column keeps its own cell"
13378 );
13379 }
13380 }
13381 // The tall/wide BLOCK_INVALID shapes (8 px wide or more) are the
13382 // `chroma_422_oob` tiling's residents, not the pair arm's: both are
13383 // 4:2:2-only, so the two arms partition the BLOCK_INVALID column.
13384 for (bw, bh) in [
13385 (8usize, 16),
13386 (16, 32),
13387 (32, 64),
13388 (64, 128),
13389 (8, 32),
13390 (16, 64),
13391 ] {
13392 assert!(chroma422_pair_plane(true, false, 7, bw, bh).is_none());
13393 }
13394}
13395
13396fn decode_intra_rect_in_inter(
13397 dec: &mut SymbolDecoder,
13398 cdfs: &mut Cdfs,
13399 neighbours: &mut Neighbours,
13400 at: (usize, usize),
13401 bw: usize,
13402 bh: usize,
13403 skip: bool,
13404 allow_screen_content_tools: bool,
13405 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
13406 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
13407 strip16: Option<(bool, bool)>,
13408 y: &mut PlaneBuf<'static>,
13409 u: &mut PlaneBuf<'static>,
13410 v: &mut PlaneBuf<'static>,
13411 base_q_idx: u8,
13412 fctx: &crate::decode::FrameCtx,
13413) -> Result<()> {
13414 // `at` is in MI units (the inter path's own unit since lane-inter4);
13415 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
13416 // below are still keyed by.
13417 let (mi_r, mi_c) = at;
13418 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
13419 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
13420 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
13421 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
13422 // finding -- the category is NOT the same for every strip size).
13423 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
13424 // it is refused by name rather than read from the wrong CDF row.
13425 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
13426 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
13427 // tx-depth category is 1 -- but nothing here has to know either, because
13428 // the strip decodes through the very body the KEY FRAME path proves for
13429 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
13430 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
13431 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
13432 // inter-frame difference is the mode-info read, which
13433 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
13434 // `y_mode[0]` plus the `skip` this caller already read.
13435 if let Some((horz, has_chroma)) = strip16 {
13436 // lane-t900 r22: the screen-content refusal here was STALE (class
13437 // stale-premise): [`decode_rect4_16_strip`] takes
13438 // `allow_screen_content_tools` and reads the whole palette syntax
13439 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
13440 // pair) -- the key frame proves that body. Lifted with the 10-bit
13441 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
13442 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
13443 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
13444 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
13445 let res = decode_rect4_16_strip(
13446 dec,
13447 cdfs,
13448 neighbours,
13449 (mi_r, mi_c),
13450 horz,
13451 has_chroma,
13452 // The inter strips of the same partition publish their own
13453 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
13454 // has nothing to add here.
13455 None,
13456 y,
13457 u,
13458 v,
13459 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13460 allow_screen_content_tools,
13461 base_q_idx,
13462 fctx.tx_select_inter.with(std::cell::Cell::get),
13463 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13464 fctx,
13465 );
13466 fctx.intra_in_inter_mode.with(|c| c.set(None));
13467 let (mode, uv, (tx_w, tx_h)) = res?;
13468 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
13469 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
13470 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
13471 // block of an inter frame, intra ones included, and
13472 // `txfm_partition_update` for the var-tx context. The key-frame body
13473 // writes neither (a key frame has no var-tx tree and its own readers
13474 // use the deblock grid), so the block AFTER this strip read a stale
13475 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
13476 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
13477 // 16x16 row.
13478 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13479 for i in 0..bw / MI {
13480 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
13481 *cell = tx_w as u8;
13482 }
13483 }
13484 for i in 0..bh / MI {
13485 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
13486 *cell = tx_h as u8;
13487 }
13488 }
13489 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
13490 // coarse 16-px cell holds one entry for the whole 16x16 and the last
13491 // block to write it wins).
13492 neighbours.above_mode[c] = mode;
13493 neighbours.left_mode[r] = mode;
13494 if let Some(uvm) = uv {
13495 neighbours.above_uv_mode[c] = uvm;
13496 neighbours.left_uv_mode[r] = uvm;
13497 }
13498 neighbours.above_side[c] = bw;
13499 neighbours.left_side[r] = bh;
13500 if crate::envflags::env_flag!("EC_INTRA16X4") {
13501 eprintln!(
13502 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
13503 mi_c * MI,
13504 mi_r * MI
13505 );
13506 }
13507 hit_do! {
13508 INTRA16X4_IN_INTER_HITS.with(|h| {
13509 let mut v = h.get();
13510 v[usize::from(!horz)] += 1;
13511 v[2] += usize::from(has_chroma);
13512 h.set(v);
13513 });
13514 }
13515 return Ok(());
13516 }
13517 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
13518 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
13519 // puts BLOCK_128X64/64X128/128X128 in group 3 and
13520 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
13521 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
13522 // block decodes through the very body the KEY FRAME path proves for this
13523 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
13524 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
13525 // `Reach` rule and the frame-edge write clip). The only inter-frame
13526 // differences live inside that body: the mode-info read
13527 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
13528 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
13529 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
13530 // palette (>64) do not exist at this size and are refused by name there.
13531 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
13532 // `intra128_in_inter_witness2.obu` (gate
13533 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
13534 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
13535 // all 15 frames, so the hits are counted out of exact frames (class
13536 // `counter-from-refused-stream`). What r16/r17 could not find, and what
13537 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
13538 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
13539 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
13540 // where the frame EDGE forces it: a partial last superblock row has
13541 // `has_rows128 == false`, so the 128x64 top half is implied, and a
13542 // partial last column implies the 64x128 left half. Put content no
13543 // reference holds (a fresh smooth ramp) in exactly those two bands of an
13544 // inter frame and the encoder codes those forced halves INTRA.
13545 if bw.max(bh) == 128 {
13546 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
13547 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
13548 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
13549 // palette_syntax`), so a 128-root half consumes no palette syntax and
13550 // a screen-content frame's half is syntactically identical to the
13551 // non-screen one this arm already decodes byte-exact.
13552 if coeff_trace_on() {
13553 // lane-t900 r16: which decode-order frame this arm fires in --
13554 // interleaved with the `EC_COEFF_FRAME` markers, this is what
13555 // proves the hit is counted out of a frame that compares exact
13556 // (class `counter-from-refused-stream`).
13557 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
13558 }
13559 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
13560 let res = decode_block_128rect(
13561 dec,
13562 cdfs,
13563 neighbours,
13564 (r, c),
13565 bw,
13566 bh,
13567 y,
13568 u,
13569 v,
13570 base_q_idx,
13571 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13572 allow_screen_content_tools,
13573 fctx.tx_select_inter.with(std::cell::Cell::get),
13574 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13575 fctx,
13576 );
13577 fctx.intra_in_inter_mode.with(|c| c.set(None));
13578 return res;
13579 }
13580 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
13581 if crate::envflags::env_flag!("EC_OBMCREC") {
13582 eprintln!(
13583 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
13584 );
13585 }
13586 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
13587 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
13588 // can arrive here are enumerated against the measured block-shape
13589 // census ([`INTER_BLOCK_SHAPES`]) by
13590 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
13591 // -- every one of them has a row, so this arm names a shape no stream
13592 // has been able to present.
13593 return Err(unsupported(format!(
13594 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
13595 )));
13596 };
13597 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
13598 // screen-content frame ("palette syntax is consumed for square blocks
13599 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
13600 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
13601 // it, while the 2:1 reader inlined further down now codes the same syntax
13602 // itself. A real `--tune-content=screen` inter stream reached this refusal
13603 // on 8x16 / 16x8 strips (gate
13604 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
13605 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
13606 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
13607 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
13608 // luma/chroma transform tables, the per-unit split walk and the strip's
13609 // own neighbour records). The ONLY difference on an inter frame is the
13610 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
13611 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
13612 // this caller already read. `tx_cat` above is the same category those
13613 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
13614 // `decode_block_rect64`), asserted here so a future shape cannot drift.
13615 if bw.max(bh) == 4 * bw.min(bh) {
13616 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
13617 fctx.intra_in_inter_mode
13618 .with(|c| c.set(Some((size_group, skip))));
13619 let res = if bw.max(bh) == 64 {
13620 decode_block_rect64(
13621 dec,
13622 cdfs,
13623 neighbours,
13624 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
13625 bw,
13626 bh,
13627 y,
13628 u,
13629 v,
13630 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13631 allow_screen_content_tools,
13632 base_q_idx,
13633 fctx.tx_select_inter.with(std::cell::Cell::get),
13634 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13635 fctx,
13636 )
13637 } else {
13638 decode_block_rect4(
13639 dec,
13640 cdfs,
13641 neighbours,
13642 (mi_r, mi_c),
13643 bw,
13644 bh,
13645 None,
13646 y,
13647 u,
13648 v,
13649 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
13650 allow_screen_content_tools,
13651 base_q_idx,
13652 fctx.tx_select_inter.with(std::cell::Cell::get),
13653 fctx,
13654 )
13655 .map(|_| ())
13656 };
13657 fctx.intra_in_inter_mode.with(|c| c.set(None));
13658 res?;
13659 let shape = match (bw, bh) {
13660 (64, 16) => 0,
13661 (16, 64) => 1,
13662 (32, 8) => 2,
13663 _ => 3,
13664 };
13665 hit_do! {
13666 INTRA_RECT4_IN_INTER_HITS.with(|h| {
13667 let mut v = h.get();
13668 v[shape] += 1;
13669 h.set(v);
13670 });
13671 }
13672 return Ok(());
13673 }
13674 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
13675 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
13676 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
13677 // own, so a cross-decoder bisection could only see the block's first
13678 // coefficient. Same names/format as [`read_tx_size`]'s rung.
13679 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
13680 if step_trace {
13681 eprintln!(
13682 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
13683 dec.debug_state().0
13684 );
13685 }
13686 if mode >= 13 {
13687 return Err(unsupported(
13688 "an intra mode this decoder does not code (round 2)",
13689 ));
13690 }
13691 // lane-angleinter (merged on main for the square intra-in-inter arm):
13692 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
13693 // directional predictor; this arm refused a nonzero one before the merge.
13694 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
13695 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
13696 } else {
13697 0
13698 };
13699 if angle_delta_y != 0 {
13700 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
13701 }
13702 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
13703 // superblock-level strip reads the no-CFL alphabet -- the same split
13704 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
13705 //
13706 // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
13707 // (libaom `decodemv.c:933`).
13708 let has_chroma = !mono(fctx);
13709 let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
13710 let uv_mode = if !has_chroma {
13711 DC_PRED
13712 } else if cfl_allowed {
13713 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
13714 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
13715 } else {
13716 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
13717 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
13718 };
13719 if step_trace {
13720 eprintln!(
13721 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
13722 u8::from(cfl_allowed),
13723 dec.debug_state().0
13724 );
13725 }
13726 if (9..=12).contains(&uv_mode) {
13727 hit!(SMOOTH_UV_HITS);
13728 }
13729 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
13730 Some(read_cfl_alphas(dec, cdfs))
13731 } else {
13732 None
13733 };
13734 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
13735 DC_PRED
13736 } else {
13737 uv_mode
13738 };
13739 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
13740 hit!(DIRECTIONAL_UV_HITS);
13741 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
13742 } else {
13743 0
13744 };
13745 if angle_delta_uv != 0 {
13746 hit!(UV_ANGLE_DELTA_HITS);
13747 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
13748 }
13749 // `read_palette_mode_info` (spec 5.11.13), in the position
13750 // `read_intra_block_mode_info` writes it: after the chroma mode and
13751 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
13752 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
13753 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
13754 // skipping the syntax here desynced the tile at the strip's own symbol.
13755 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
13756 // context and colour cache at its own mi position, and the two
13757 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
13758 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
13759 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
13760 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
13761 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
13762 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
13763 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
13764 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
13765 let use_palette_y =
13766 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
13767 if use_palette_y {
13768 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
13769 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
13770 }
13771 // A 2:1 strip of at least 8x8 is always a chroma reference, so
13772 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
13773 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
13774 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
13775 let use_palette_uv = has_chroma
13776 && uv_mode == DC_PRED
13777 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
13778 if crate::envflags::env_flag!("EC_PALSYN") {
13779 eprintln!(
13780 "EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
13781 use_palette_y as i32,
13782 use_palette_uv as i32,
13783 dec.debug_state().0
13784 );
13785 }
13786 if use_palette_uv {
13787 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
13788 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
13789 palette_uv_pending = Some((n, u_colors, v_colors));
13790 }
13791 }
13792 // lane-fiinter (merged on main for the square intra-in-inter arm):
13793 // `read_filter_intra_mode_info` is the tail of
13794 // `read_intra_block_mode_info`, after the palette syntax (refused whole
13795 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
13796 // 2:1 strips with both sides <= 32 -- their own CDF rows
13797 // ([`filter_intra_size_class_rect`]).
13798 let mut filter_intra = None;
13799 if mode == DC_PRED
13800 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
13801 // `av1_filter_intra_allowed` excludes a palette-Y block.
13802 && palette_y_pending.is_none()
13803 && let Some(class) = filter_intra_size_class_rect(bw, bh)
13804 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
13805 {
13806 hit!(FILTER_INTRA_HITS);
13807 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
13808 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
13809 }
13810 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
13811 let palette_y = palette_y_pending.map(|(n, colors)| {
13812 let map = decode_color_index_map_wh(
13813 dec,
13814 cdfs,
13815 n,
13816 bw,
13817 bh,
13818 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
13819 false,
13820 );
13821 hit!(PALETTE_HITS);
13822 hit!(PALETTE_RECT_HITS);
13823 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
13824 PaletteY {
13825 size: n,
13826 colors,
13827 map,
13828 }
13829 });
13830 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
13831 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
13832 let on = palette_onscreen_uv(
13833 (bw, bh),
13834 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
13835 (cw, ch),
13836 (ss_x(fctx), ss_y(fctx)),
13837 );
13838 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
13839 hit!(PALETTE_UV_HITS);
13840 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
13841 PaletteUv {
13842 size: n,
13843 u_colors,
13844 v_colors,
13845 map,
13846 }
13847 });
13848 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
13849 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
13850 // chroma ones -- [`decode_block_rect`]'s own pair.
13851 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
13852 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
13853 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
13854 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
13855 // one exactly as [`decode_leaf8`] already does (class
13856 // context-read-from-one-cell).
13857 let coarse_pair = neighbours.modes_above_left(r, c);
13858 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
13859 if (nb_above_mode, nb_left_mode) != coarse_pair {
13860 hit!(EDGE_FILTER_MI_FIX_HITS);
13861 }
13862 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
13863 if smooth_neighbor {
13864 hit!(SMOOTH_LUMA_HITS);
13865 }
13866 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
13867 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
13868 // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside
13869 // an inter frame codes no depth symbol either (`xd->lossless` is per
13870 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
13871 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
13872 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
13873 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
13874 let d = match tx_cat {
13875 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
13876 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
13877 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
13878 };
13879 if step_trace {
13880 eprintln!(
13881 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
13882 dec.debug_state().0
13883 );
13884 }
13885 d
13886 } else {
13887 0
13888 };
13889 if depth != 0 || lossless(fctx) {
13890 hit!(TX_DEPTH_HITS);
13891 // lane-intrasplit r1: a split intra strip in an inter frame walks the
13892 // key frame's own per-TU path ([`decode_rect_split`] below); what was
13893 // wrong when this refusal was written was the depth SYMBOL, not the walk.
13894 hit_do! {
13895 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
13896 let mut v = h.get();
13897 v[depth.min(2)] += 1;
13898 h.set(v);
13899 });
13900 }
13901 }
13902 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
13903 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
13904 // the two are indistinguishable when the diagnostic fires on splits alone.
13905 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
13906 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
13907 }
13908 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
13909 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
13910 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
13911 // of an inter frame, intra ones included -- with the skip term 0 it
13912 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
13913 // and `left_txfm_context` to `tx_size_high` over its height. This strip
13914 // wrote neither, so the next block's var-tx `txfm_partition` context read
13915 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
13916 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
13917 // mi(16,0) and desyncing the tile at that symbol.
13918 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13919 let modes = RectStripModes {
13920 skip,
13921 mode,
13922 angle_delta_y,
13923 uv_predict_mode,
13924 angle_delta_uv,
13925 alpha,
13926 filter_intra,
13927 smooth_neighbor,
13928 smooth_neighbor_uv,
13929 palette_y: palette_y
13930 .as_ref()
13931 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
13932 palette_uv: palette_uv.as_ref().map(|p| {
13933 (
13934 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
13935 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
13936 )
13937 }),
13938 };
13939 decode_rect_split(
13940 dec,
13941 cdfs,
13942 neighbours,
13943 (mi_r, mi_c),
13944 bw,
13945 bh,
13946 tx_w,
13947 tx_h,
13948 &modes,
13949 y,
13950 u,
13951 v,
13952 base_q_idx,
13953 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
13954 fctx,
13955 )?;
13956 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
13957 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
13958 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
13959 // left column over its height. This arm wrote neither before lane-intrasplit
13960 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
13961 // context across the strip's footprint.
13962 for i in 0..bw / MI {
13963 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
13964 *cell = tx_w as u8;
13965 }
13966 }
13967 for i in 0..bh / MI {
13968 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
13969 *cell = tx_h as u8;
13970 }
13971 }
13972 // The strip's own palette state into the mi-granular neighbour bands, so
13973 // the next block's colour cache and `palette_y_mode` context are libaom's.
13974 record_strip_palette(
13975 neighbours,
13976 (mi_r, mi_c),
13977 bw,
13978 bh,
13979 palette_y.as_ref().map_or(0, |p| p.size),
13980 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
13981 palette_uv.as_ref().map_or(0, |p| p.size),
13982 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
13983 );
13984 let class = match bw.max(bh) {
13985 64 => 0,
13986 32 => 1,
13987 _ => 2,
13988 };
13989 hit_do! {
13990 INTRA_RECT_IN_INTER_HITS.with(|h| {
13991 let mut v = h.get();
13992 v[class] += 1;
13993 h.set(v);
13994 });
13995 }
13996 Ok(())
13997}
13998
13999/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real
14000/// mi `(mi_r, mi_c)` (lane-av1-intrabc).
14001///
14002/// libaom treats an intrabc block as INTER for everything except the mode-info
14003/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA`
14004/// (`blockd.h:373`), so
14005///
14006/// * `parse_decode_block` reads the transform size through the INTER var-tx
14007/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose
14008/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and
14009/// whose leaves publish their own resolved size back;
14010/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT
14011/// frame's own pre-loop-filter reconstruction, at the coded block vector
14012/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`);
14013/// * `decode_token_recon_block`'s inter branch then reads one residual per
14014/// transform unit, through the INTER coefficient sets
14015/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane
14016/// inheriting the colocated luma unit's coded `tx_type`.
14017///
14018/// Text order is libaom's: transform tree, prediction, luma residual, chroma
14019/// residual, bookkeeping. A skipped block codes no residual at all -- the
14020/// prediction is the reconstruction.
14021#[allow(clippy::too_many_arguments)]
14022fn decode_intrabc_rect(
14023 dec: &mut SymbolDecoder,
14024 cdfs: &mut Cdfs,
14025 neighbours: &mut Neighbours,
14026 (mi_r, mi_c): (usize, usize),
14027 (bw, bh): (usize, usize),
14028 skip: bool,
14029 (dv_row, dv_col): (i32, i32),
14030 y: &mut PlaneBuf<'static>,
14031 u: &mut PlaneBuf<'static>,
14032 v: &mut PlaneBuf<'static>,
14033 base_q_idx: u8,
14034 fctx: &crate::decode::FrameCtx,
14035) -> Result<()> {
14036 hit!(INTRABC_RECT_HITS);
14037 // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
14038 let idx = usize::from(bh > bw);
14039 if skip {
14040 INTRABC_RECT_SKIPPED_HITS.with(|c| {
14041 let mut seen = c.get();
14042 seen[idx] += 1;
14043 c.set(seen);
14044 });
14045 } else {
14046 INTRABC_RECT_CODED_HITS.with(|c| {
14047 let mut seen = c.get();
14048 seen[idx] += 1;
14049 c.set(seen);
14050 });
14051 }
14052 let (px, py) = (mi_c * MI, mi_r * MI);
14053 // lane-whtshape: a LOSSLESS block's chroma plane block is
14054 // `bw >> ss_x` by `bh >> ss_y` at its own origin -- `av1_get_max_uv_txsize`
14055 // is `ss_size_lookup[bsize]` (no halving of its own), so at 4:4:4 that is
14056 // the block's OWN footprint, not the 4:2:0 halving the lossy arm hard-codes.
14057 // Measured on this lane's 4:4:4 lossless witness: with the halving, a
14058 // 16x8 intrabc block's chroma plane block came out 8x4 and the lossless
14059 // walk below coded 2 units per plane where libaom codes 8.
14060 //
14061 // lane-ibc444c: UNSCOPED now. lane-whtshape split this on `lossless` and
14062 // named the LOSSY 4:4:4 footprint as another lane's open cell; this is
14063 // that cell. Measured on `444_intrabc_rect4_witness.obu`: with the
14064 // halving, an 8x16 luma block's 8x16 chroma plane block was read as ONE
14065 // 4x8 rect unit where libaom codes ONE TX_8X16, and the U `txb_skip` of
14066 // the block at mi (92, 104) read all_zero=0 here against the oracle's
14067 // all_zero=1 -- the bit position forks there. Identical arithmetic at
14068 // 4:2:0, where `ss_x = ss_y = 1`, so the pinned 4:2:0 twin of the
14069 // witness is the identity arm of this lane's gate.
14070 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14071 // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the
14072 // halved shape's own `max_txsize_rect_lookup` entry IS that size for every
14073 // shape this helper is called at, so the uv plane block is ONE unit --
14074 // the same call `decode_token_recon_block`'s own chroma loop makes.
14075 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14076 // lane-av1-intrabc r2: the square stride the proven INTER path uses
14077 // (`side`). The residual grids, the prediction windows AND
14078 // `TxParams::stride` are all laid out at it -- the block's own width
14079 // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h`
14080 // exceeds the stride).
14081 let side = bw.max(bh);
14082 let cside = cw.max(ch);
14083 // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right
14084 // or bottom frame edge reads no transform-tree symbol for the units
14085 // outside it.
14086 let mi_cols = 2 * y.true_width.div_ceil(8);
14087 let mi_rows = 2 * y.true_height.div_ceil(8);
14088 let leaves = read_block_tx_size_rect(
14089 dec,
14090 cdfs,
14091 neighbours,
14092 (mi_r, mi_c),
14093 (bw, bh),
14094 (mi_cols, mi_rows),
14095 skip,
14096 fctx,
14097 )?;
14098 if leaves.is_some() {
14099 hit!(INTRABC_RECT_VARTX_HITS);
14100 }
14101 if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
14102 hit!(IBC_RECT_CHROMA_FOOTPRINT_444_HITS);
14103 }
14104 // lane-ibc444c: per-block geometry, for the chroma-tail attribution.
14105 if crate::envflags::env_flag!("EC_IBCBLOCK") {
14106 eprintln!(
14107 "EC_IBCBLOCK mi=({mi_r},{mi_c}) bw={bw} bh={bh} cpx={cpx} cpy={cpy} \
14108 cw={cw} ch={ch} cside={cside} skip={skip}"
14109 );
14110 }
14111 // The whole-block prediction: `predict_inter_block` runs once, before any
14112 // coefficient is read. `flush_recon` first -- the source is this frame's
14113 // own reconstruction, including the writes this superblock has queued.
14114 flush_recon(fctx, y, u, v);
14115 // `mc::predict_with_filter` writes a DENSE window; the residual machinery
14116 // reads it at the square stride, so re-lay it -- the same step the inter
14117 // path takes for its own square prediction buffer.
14118 let mut pred_y_dense = vec![0u16; bw * bh];
14119 mc::predict_with_filter(
14120 &y.data,
14121 y.width,
14122 y.true_width,
14123 y.true_height,
14124 mv_to_q4(px, dv_col, 0),
14125 mv_to_q4(py, dv_row, 0),
14126 bw,
14127 bh,
14128 mc::InterpFilterKind::Bilinear,
14129 &mut pred_y_dense,
14130 fctx,
14131 );
14132 let mut pred_y = vec![0u16; side * side];
14133 for row in 0..bh {
14134 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
14135 }
14136 let mut pred_u_dense = vec![0u16; cw * ch];
14137 mc::predict_with_filter(
14138 &u.data,
14139 u.width,
14140 u.true_width,
14141 u.true_height,
14142 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14143 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14144 cw,
14145 ch,
14146 mc::InterpFilterKind::Bilinear,
14147 &mut pred_u_dense,
14148 fctx,
14149 );
14150 let mut pred_u = vec![0u16; cside * cside];
14151 for row in 0..ch {
14152 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
14153 }
14154 let mut pred_v_dense = vec![0u16; cw * ch];
14155 mc::predict_with_filter(
14156 &v.data,
14157 v.width,
14158 v.true_width,
14159 v.true_height,
14160 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14161 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14162 cw,
14163 ch,
14164 mc::InterpFilterKind::Bilinear,
14165 &mut pred_v_dense,
14166 fctx,
14167 );
14168 let mut pred_v = vec![0u16; cside * cside];
14169 for row in 0..ch {
14170 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
14171 }
14172 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
14173 let luma_tx_type: TxType;
14174 let (luma_grid, u_grid, v_grid);
14175 // lane-whtshape: the LOSSLESS chroma walk's composed plane-major grids,
14176 // kept so their per-4x4 slices can be re-stamped over the whole-block
14177 // record in the tail. `None` on every other arm.
14178 let mut ll_chroma: Option<(Vec<i32>, Vec<i32>)> = None;
14179 if skip {
14180 // No residual syntax at all: the prediction IS the block.
14181 // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes
14182 // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip
14183 // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm.
14184 push_mc_rect(
14185 0,
14186 px,
14187 py,
14188 side,
14189 bw,
14190 bh,
14191 Pred::Inline(&pred_y, side),
14192 &ZERO_RESIDUAL[..side * side],
14193 fctx,
14194 );
14195 push_mc_rect(
14196 1,
14197 cpx,
14198 cpy,
14199 cside,
14200 cw,
14201 ch,
14202 Pred::Inline(&pred_u, cside),
14203 &ZERO_RESIDUAL[..cside * cside],
14204 fctx,
14205 );
14206 push_mc_rect(
14207 2,
14208 cpx,
14209 cpy,
14210 cside,
14211 cw,
14212 ch,
14213 Pred::Inline(&pred_v, cside),
14214 &ZERO_RESIDUAL[..cside * cside],
14215 fctx,
14216 );
14217 if let Some(ls) = leaves.as_ref() {
14218 // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s
14219 // skip arm performs -- libaom `av1_reset_entropy_context`
14220 // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a
14221 // SKIPPED block zeroes its whole entropy-band footprint. This
14222 // helper serves `decode_block_rect4`'s 1:4 strips on this tree,
14223 // so a skipped lossless strip whose `leaves` resolved (every
14224 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
14225 // returns the 4x4 grid before it looks at `skip`) left the
14226 // PREVIOUS occupant's luma bands standing and the NEXT block's
14227 // partition parse diverged from libaom's: the 320x242 lossless
14228 // sb128 gate read a phantom unskipped 8x32 intrabc strip at
14229 // mi(56,66) right after the skipped 8x16 one at mi(48,66).
14230 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
14231 for &(row, col, tw, th) in ls {
14232 neighbours.record_mi_luma_rect(
14233 (mi_r + row, mi_c + col),
14234 tw,
14235 th,
14236 &ZERO_RESIDUAL[..tw * th],
14237 );
14238 }
14239 }
14240 luma_tx_type = TxType::DctDct;
14241 luma_grid = Grid::Zero(side * side);
14242 u_grid = Grid::Zero(cside * cside);
14243 v_grid = Grid::Zero(cside * cside);
14244 } else {
14245 match leaves.as_ref() {
14246 None => {
14247 // One whole-block rectangular transform unit.
14248 // lane-av1422mi24: at ss (1,0) the chroma above span is
14249 // `bw >> 1` chroma cells spread over `bw` luma mi columns --
14250 // the per-mi gather counts every chroma column's whole-unit
14251 // dc sign twice (t422 frame 1, the mi(26,60) intra-in-inter
14252 // strip's U dc_sign read ctx 1 where the oracle's cell sum
14253 // is 0 -> ctx 0). Luma keeps the per-mi gather; the two
14254 // chroma planes take
14255 // [`Neighbours::around_mi_422_chroma`]'s every-second
14256 // above-cell sampling, like every other 4:2:2 chroma gather.
14257 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
14258 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
14259 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
14260 around[1] = c[1];
14261 around[2] = c[2];
14262 }
14263 let (grid, tx_type) = read_inter_plane_rect(
14264 dec,
14265 cdfs,
14266 rect_inter_luma_set(bw, bh, fctx)?,
14267 (bw, bh),
14268 side,
14269 0,
14270 around[0],
14271 0,
14272 y,
14273 px,
14274 py,
14275 Pred::Inline(&pred_y, side),
14276 None,
14277 None,
14278 fctx,
14279 )?;
14280 luma_tx_type = tx_type;
14281 luma_grid = embed_grid_stride(&grid, bw, bh, side);
14282 let (ug, _) = read_inter_plane_rect(
14283 dec,
14284 cdfs,
14285 rect_inter_chroma_set(cw, ch)?,
14286 (cw, ch),
14287 cside,
14288 1,
14289 around[1],
14290 0,
14291 u,
14292 cpx,
14293 cpy,
14294 Pred::Inline(&pred_u, cside),
14295 Some(luma_tx_type),
14296 None,
14297 fctx,
14298 )?;
14299 u_grid = embed_grid_stride(&ug, cw, ch, cside);
14300 let (vg, _) = read_inter_plane_rect(
14301 dec,
14302 cdfs,
14303 rect_inter_chroma_set(cw, ch)?,
14304 (cw, ch),
14305 cside,
14306 2,
14307 around[2],
14308 0,
14309 v,
14310 cpx,
14311 cpy,
14312 Pred::Inline(&pred_v, cside),
14313 Some(luma_tx_type),
14314 None,
14315 fctx,
14316 )?;
14317 v_grid = embed_grid_stride(&vg, cw, ch, cside);
14318 }
14319 Some(leaves) => {
14320 // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies
14321 // the split override to LUMA only, per leaf -- the step the
14322 // proven inter var-tx path applies right after its own residual
14323 // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the
14324 // leaf's own transform edges are never filtered.
14325 for &(row, col, tw, th) in leaves.iter() {
14326 neighbours.fill_lf_grid_leaf_luma(
14327 (mi_r + row, mi_c + col),
14328 tw / MI,
14329 th / MI,
14330 tw as u8,
14331 th as u8,
14332 );
14333 }
14334 // One residual per transform unit, in the order the tree coded
14335 // them; each unit reads its own neighbour-magnitude context off
14336 // the units already decoded before it, and every unit adds onto
14337 // its own window of the block's single prediction.
14338 let mut first_tx_type = TxType::DctDct;
14339 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
14340 let tu_mi = (mi_r + row, mi_c + col);
14341 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14342 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
14343 let (tu_grid, tu_tx_type) = if tw == th {
14344 let scan = default_scan(tw.min(32));
14345 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
14346 read_inter_plane(
14347 dec,
14348 cdfs,
14349 inter_txbset_for(tw, reduced),
14350 scan,
14351 0,
14352 neighbours.around_mi(tu_mi, tw)[0],
14353 0,
14354 y,
14355 tu_px,
14356 tu_py,
14357 tw,
14358 base_q_idx,
14359 tu_pred,
14360 None,
14361 Some(tu_skip_ctx),
14362 fctx,
14363 )?
14364 } else {
14365 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
14366 read_inter_plane_rect(
14367 dec,
14368 cdfs,
14369 rect_inter_luma_set(tw, th, fctx)?,
14370 (tw, th),
14371 side,
14372 0,
14373 neighbours.around_mi_rect(tu_mi, tw, th)[0],
14374 0,
14375 y,
14376 tu_px,
14377 tu_py,
14378 tu_pred,
14379 None,
14380 Some(tu_skip_ctx),
14381 fctx,
14382 )?
14383 };
14384 if idx == 0 {
14385 first_tx_type = tu_tx_type;
14386 }
14387 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
14388 }
14389 // `av1_get_tx_type`'s chroma lookup lands on the colocated
14390 // LUMA unit, which for a split block is the top-left one.
14391 luma_tx_type = first_tx_type;
14392 // lane-av1422mi24: same 4:2:2 chroma gather rule as the
14393 // `None` arm above -- the per-mi rect gather double-counts
14394 // each chroma column's whole-unit dc sign at ss (1,0).
14395 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
14396 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
14397 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
14398 around[1] = c[1];
14399 around[2] = c[2];
14400 }
14401 if lossless(fctx) {
14402 // lane-whtshape: at lossless libaom codes TX_4X4 on EVERY
14403 // plane of a block -- `read_tx_size` returns `TX_4X4` for a
14404 // lossless block before it looks at a tree, `read_tx_mode`
14405 // already forced `ONLY_4X4` for the frame, and
14406 // `get_vartx_max_txsize` returns `TX_4X4` for every plane
14407 // -- so this block's chroma plane block is a
14408 // `(cw/4) * (ch/4)` raster of 4x4 units, PLANE-MAJOR
14409 // (`decode_token_recon_block`: every U unit, then every V
14410 // unit), not the single rect unit the two
14411 // `read_inter_plane_rect` calls below read. That single
14412 // 8x4 unit is what reached the lossless WHT with the wrong
14413 // shape (the `debug_assert_eq!((w, h), (4, 4))` this lane
14414 // replaced). Same helper, same walk, as the inter 8x8 and
14415 // 128 paths.
14416 hit!(INTRABC_RECT_LOSSLESS_CHROMA4_HITS);
14417 let mut uo = vec![0i32; cside * cside];
14418 let mut vo = vec![0i32; cside * cside];
14419 read_inter_chroma_lossless(
14420 dec,
14421 cdfs,
14422 neighbours,
14423 u,
14424 v,
14425 Pred::Inline(&pred_u, cside),
14426 Pred::Inline(&pred_v, cside),
14427 (mi_r, mi_c),
14428 (cpx, cpy),
14429 (0, 0),
14430 (cw, ch),
14431 (cw, ch),
14432 cside,
14433 0,
14434 base_q_idx,
14435 &mut uo,
14436 &mut vo,
14437 fctx,
14438 )?;
14439 // The per-unit walk stamped every unit's own coefficient
14440 // context, but the whole-block `record_split_luma_rect_mi`
14441 // in the tail rewrites every chroma cell with ONE composed
14442 // state, which drops the per-unit DC signs and levels (class
14443 // `override-slot-on-one-arm` -- the same one
14444 // `decode_rect_split`'s `ll_chroma_units` replay exists
14445 // for). The grids are kept here and replayed AFTER that
14446 // record, from the same 4x4 slices, so the same states.
14447 u_grid = embed_grid_stride(&Grid::Own(uo.clone()), cw, ch, cside);
14448 v_grid = embed_grid_stride(&Grid::Own(vo.clone()), cw, ch, cside);
14449 ll_chroma = Some((uo, vo));
14450 luma_grid = Grid::Zero(side * side);
14451 } else {
14452 let (ug, _) = read_inter_plane_rect(
14453 dec,
14454 cdfs,
14455 rect_inter_chroma_set(cw, ch)?,
14456 (cw, ch),
14457 cside,
14458 1,
14459 around[1],
14460 0,
14461 u,
14462 cpx,
14463 cpy,
14464 Pred::Inline(&pred_u, cside),
14465 Some(luma_tx_type),
14466 None,
14467 fctx,
14468 )?;
14469 u_grid = embed_grid_stride(&ug, cw, ch, cside);
14470 let (vg, _) = read_inter_plane_rect(
14471 dec,
14472 cdfs,
14473 rect_inter_chroma_set(cw, ch)?,
14474 (cw, ch),
14475 cside,
14476 2,
14477 around[2],
14478 0,
14479 v,
14480 cpx,
14481 cpy,
14482 Pred::Inline(&pred_v, cside),
14483 Some(luma_tx_type),
14484 None,
14485 fctx,
14486 )?;
14487 v_grid = embed_grid_stride(&vg, cw, ch, cside);
14488 luma_grid = Grid::Zero(side * side);
14489 }
14490 }
14491 }
14492 }
14493 let _ = luma_tx_type;
14494 // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the
14495 // next block reads a neighbour mode, its own block size in both `TXFM`
14496 // bands (already done by `read_block_tx_size_rect`), a zeroed palette
14497 // state (a stale entry would feed the next block's colour cache), and its
14498 // DV into the intrabc mi grid the next block's DV predictor reads.
14499 if leaves.is_some() {
14500 neighbours.record_split_luma_rect_mi(
14501 (mi_r, mi_c),
14502 bw,
14503 bh,
14504 DC_PRED,
14505 DC_PRED,
14506 [&u_grid, &v_grid],
14507 );
14508 } else {
14509 neighbours.record_rect_mi(
14510 (mi_r, mi_c),
14511 bw,
14512 bh,
14513 DC_PRED,
14514 DC_PRED,
14515 &[&luma_grid, &u_grid, &v_grid],
14516 );
14517 }
14518 // lane-whtshape: replay the LOSSLESS walk's per-4x4 chroma states over
14519 // the whole-block record above, so the NEXT block reads the per-unit DC
14520 // signs and levels libaom's plane-major walk left behind instead of one
14521 // composed state for the whole plane block.
14522 if let Some((uo, vo)) = ll_chroma {
14523 for (plane_idx, comp) in [(1usize, &uo), (2, &vo)] {
14524 for ur in 0..ch / 4 {
14525 for uc in 0..cw / 4 {
14526 let mut unit = Vec::with_capacity(16);
14527 for r in 0..4 {
14528 unit.extend_from_slice(&comp[(ur * 4 + r) * cside + uc * 4..][..4]);
14529 }
14530 neighbours.record_mi_chroma(
14531 // lane-av1lm444loss-corr: the MI STEP between chroma
14532 // units is that same footprint expressed in luma mi
14533 // cells, `(4 << ss) / MI` -- which is exactly what
14534 // `decode_inter_block`'s reference `mu_chroma_units`
14535 // construction writes (decode.rs:43688,
14536 // `at.0 + cr * ((cu << ss_y(fctx)) / MI)` with
14537 // `cu = 4` on a lossless frame). The `4 >> ss_y` form
14538 // this replaces is 4:2:0-only arithmetic that happens
14539 // to agree there: at ss (1,1) it is `4 >> 1` = 2 mi
14540 // and the footprint form is `(4 << 1) / 4` = 2 mi, the
14541 // SAME value, so 4:2:0 is unchanged by construction.
14542 // At ss (0,0) it is `4 >> 0` = 4 mi -- four luma mi
14543 // (16 luma px) per 4x4 chroma unit, where a TX_4X4
14544 // chroma unit covers `4 << 0` = 4 luma px = ONE mi.
14545 // The step therefore lands every replayed unit at 4x
14546 // its own mi row/column on a 4:4:4 lossless frame, and
14547 // the whole block's per-unit states are stamped over
14548 // cells that belong to other blocks (or to nothing).
14549 (
14550 mi_r + ur * ((4 << ss_y(fctx)) / MI),
14551 mi_c + uc * ((4 << ss_x(fctx)) / MI),
14552 ),
14553 4 << ss_x(fctx),
14554 4 << ss_y(fctx),
14555 plane_idx,
14556 &Grid::Own(unit),
14557 );
14558 }
14559 }
14560 }
14561 }
14562 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14563 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
14564 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14565 neighbours.fill_lf_grid_rect(
14566 (mi_r, mi_c),
14567 bw / MI,
14568 bh / MI,
14569 bw.min(64) as u8,
14570 bh.min(64) as u8,
14571 0,
14572 fctx,
14573 );
14574 record_intrabc_mi_rect(
14575 mi_r,
14576 mi_c,
14577 bw / MI,
14578 bh / MI,
14579 Some((dv_row, dv_col)),
14580 neighbours,
14581 fctx,
14582 );
14583 Ok(())
14584}
14585
14586/// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root
14587/// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape
14588/// `decode_block_128rect` refused by name before this port. libaom decodes
14589/// such a block through the INTER machinery (an intrabc block
14590/// `is_inter_block`): `predict_inter_block` copies the whole block from this
14591/// frame's own reconstruction at the integer block vector once, then
14592/// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks --
14593/// per chunk every plane, luma units at the block's own resolved transform
14594/// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at
14595/// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per
14596/// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits
14597/// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`,
14598/// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in
14599/// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here.
14600#[allow(clippy::too_many_arguments)]
14601fn decode_intrabc_128rect(
14602 dec: &mut SymbolDecoder,
14603 cdfs: &mut Cdfs,
14604 neighbours: &mut Neighbours,
14605 (mi_r, mi_c): (usize, usize),
14606 (bw, bh): (usize, usize),
14607 skip: bool,
14608 (dv_row, dv_col): (i32, i32),
14609 y: &mut PlaneBuf<'static>,
14610 u: &mut PlaneBuf<'static>,
14611 v: &mut PlaneBuf<'static>,
14612 base_q_idx: u8,
14613 fctx: &crate::decode::FrameCtx,
14614) -> Result<()> {
14615 hit!(INTRABC_128RECT_HITS);
14616 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14617 let (rng, _) = dec.debug_state();
14618 eprintln!(
14619 "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}"
14620 );
14621 }
14622 let (px, py) = (mi_c * MI, mi_r * MI);
14623 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis
14624 // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's
14625 // `mv_to_q4(cpy, dv_row, ss_y(fctx))` calls two lines below already
14626 // scaled the DV on the y axis by ITS OWN subsampling, so the hardcoded
14627 // `/2` origin and extent made the prediction window half as tall as
14628 // the motion vector asked for), 4:2:2 is HALF-WIDTH and FULL-HEIGHT,
14629 // 4:4:4 is luma-sized. At ss (1,1) every value below is the old
14630 // `bw / 2, bh / 2` line-for-line.
14631 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
14632 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
14633 // The square strides the proven INTER path lays its residual grids,
14634 // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2
14635 // note): 128/64 here.
14636 let side = bw.max(bh);
14637 let cside = cw.max(ch);
14638 // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code
14639 // nothing (`decode_reconstruct_tx`'s max_blocks_* early return).
14640 let mi_cols = 2 * y.true_width.div_ceil(8);
14641 let mi_rows = 2 * y.true_height.div_ceil(8);
14642 // An intrabc block is is_inter_block: the tx tree is the INTER one, and
14643 // [`read_block_tx_size_rect`]'s 128-root branch already carries the
14644 // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree
14645 // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid)
14646 // arms (lane-sb128c r7).
14647 let leaves = read_block_tx_size_rect(
14648 dec,
14649 cdfs,
14650 neighbours,
14651 (mi_r, mi_c),
14652 (bw, bh),
14653 (mi_cols, mi_rows),
14654 skip,
14655 fctx,
14656 )?;
14657 // Whole-block prediction, once, before any coefficient is read
14658 // (`predict_inter_block`); the source is this frame's own
14659 // reconstruction, including the writes this superblock has queued.
14660 flush_recon(fctx, y, u, v);
14661 let mut pred_y_dense = vec![0u16; bw * bh];
14662 mc::predict_with_filter(
14663 &y.data,
14664 y.width,
14665 y.true_width,
14666 y.true_height,
14667 mv_to_q4(px, dv_col, 0),
14668 mv_to_q4(py, dv_row, 0),
14669 bw,
14670 bh,
14671 mc::InterpFilterKind::Bilinear,
14672 &mut pred_y_dense,
14673 fctx,
14674 );
14675 let mut pred_y = vec![0u16; side * side];
14676 for row in 0..bh {
14677 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
14678 }
14679 let mut pred_u_dense = vec![0u16; cw * ch];
14680 mc::predict_with_filter(
14681 &u.data,
14682 u.width,
14683 u.true_width,
14684 u.true_height,
14685 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14686 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14687 cw,
14688 ch,
14689 mc::InterpFilterKind::Bilinear,
14690 &mut pred_u_dense,
14691 fctx,
14692 );
14693 let mut pred_u = vec![0u16; cside * cside];
14694 for row in 0..ch {
14695 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
14696 }
14697 let mut pred_v_dense = vec![0u16; cw * ch];
14698 mc::predict_with_filter(
14699 &v.data,
14700 v.width,
14701 v.true_width,
14702 v.true_height,
14703 mv_to_q4(cpx, dv_col, ss_x(fctx)),
14704 mv_to_q4(cpy, dv_row, ss_y(fctx)),
14705 cw,
14706 ch,
14707 mc::InterpFilterKind::Bilinear,
14708 &mut pred_v_dense,
14709 fctx,
14710 );
14711 let mut pred_v = vec![0u16; cside * cside];
14712 for row in 0..ch {
14713 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
14714 }
14715 let (luma_grid, u_grid, v_grid);
14716 // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour
14717 // contexts per transform unit -- the replay after this fn's end-of-block
14718 // record restores them (the record itself re-stamps both planes with ONE
14719 // composed state, class `override-slot-on-one-arm`).
14720 let mut mu_chroma = false;
14721 if skip {
14722 // No residual syntax at all: the prediction IS the block. Strides are
14723 // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes
14724 // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun).
14725 push_mc_rect(
14726 0,
14727 px,
14728 py,
14729 side,
14730 bw,
14731 bh,
14732 Pred::Inline(&pred_y, side),
14733 &ZERO_RESIDUAL[..side * side],
14734 fctx,
14735 );
14736 push_mc_rect(
14737 1,
14738 cpx,
14739 cpy,
14740 cside,
14741 cw,
14742 ch,
14743 Pred::Inline(&pred_u, cside),
14744 &ZERO_RESIDUAL[..cside * cside],
14745 fctx,
14746 );
14747 push_mc_rect(
14748 2,
14749 cpx,
14750 cpy,
14751 cside,
14752 cw,
14753 ch,
14754 Pred::Inline(&pred_v, cside),
14755 &ZERO_RESIDUAL[..cside * cside],
14756 fctx,
14757 );
14758 if let Some(ls) = leaves.as_ref() {
14759 // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4
14760 // grid before it looks at `skip`; the skipped block still zeroes
14761 // its entropy-band footprint over every unit (libaom
14762 // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) --
14763 // the same arm [`decode_intrabc_rect`]'s loss64 merge added.
14764 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
14765 for &(row, col, tw, th) in ls {
14766 neighbours.record_mi_luma_rect(
14767 (mi_r + row, mi_c + col),
14768 tw,
14769 th,
14770 &ZERO_RESIDUAL[..tw * th],
14771 );
14772 }
14773 }
14774 luma_grid = Grid::Zero(side * side);
14775 u_grid = Grid::Zero(cside * cside);
14776 v_grid = Grid::Zero(cside * cside);
14777 } else {
14778 let leaves = leaves
14779 .expect("read_block_tx_size_rect returns None only for skip below 128 at this shape");
14780 // libaom `get_transform_size`'s split override applies to LUMA only,
14781 // per leaf -- each unit's own transform edges get filtered
14782 // ([`decode_intrabc_rect`]'s P2, the proven inter path's step).
14783 for &(row, col, tw, th) in leaves.iter() {
14784 neighbours.fill_lf_grid_leaf_luma(
14785 (mi_r + row, mi_c + col),
14786 tw / MI,
14787 th / MI,
14788 tw as u8,
14789 th as u8,
14790 );
14791 }
14792 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
14793 let mut u_units: Vec<i32> = Vec::new();
14794 let mut v_units: Vec<i32> = Vec::new();
14795 let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new();
14796 // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose
14797 // top-left sample is outside the frame codes nothing.
14798 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
14799 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
14800 // lane-av1h5: chunk-major token order at 128 (see [`mu_chunk_order`]).
14801 let (order, _mu_reordered) = mu_chunk_order(&leaves, side);
14802 for (pos, &idx) in order.iter().enumerate() {
14803 let (row, col, tw, th) = leaves[idx];
14804 debug_assert_eq!(
14805 tw, th,
14806 "a square TX_64X64 tree root only yields square leaves"
14807 );
14808 let tu_mi = (mi_r + row, mi_c + col);
14809 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14810 if tu_px >= y.true_width || tu_py >= y.true_height {
14811 continue;
14812 }
14813 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
14814 let scan = default_scan(tw.min(32));
14815 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
14816 let (tu_grid, tu_tx_type) = read_inter_plane(
14817 dec,
14818 cdfs,
14819 inter_txbset_for(tw, reduced),
14820 &scan,
14821 0,
14822 neighbours.around_mi(tu_mi, tw)[0],
14823 0,
14824 y,
14825 tu_px,
14826 tu_py,
14827 tw,
14828 base_q_idx,
14829 tu_pred,
14830 None,
14831 Some(tu_skip_ctx),
14832 fctx,
14833 )?;
14834 leaf_tx_types.push((row, col, tw, th, tu_tx_type));
14835 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
14836 // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64
14837 // mu chunk before the next one starts: once this chunk's leaves
14838 // are done, its chroma is read immediately (the inter 128 path's
14839 // interleave).
14840 let chunk = (row / 16, col / 16);
14841 let done = pos + 1 == order.len()
14842 || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 1]].1 / 16) != chunk;
14843 if done {
14844 let (cr, cc) = chunk;
14845 // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one
14846 // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster
14847 // within the chunk, plane-major inside the chunk.
14848 let cu_tx = 32usize;
14849 // lane-av1-ibc128chunk: a 64x64 mu chunk's chroma plane
14850 // block is PER-AXIS `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at
14851 // 4:2:0, TWO STACKED TX_32X32 at 4:2:2 (the chunk's chroma
14852 // plane block is 32x64 there), four at 4:4:4. The old
14853 // `chunk_chroma = cside * 64 / side` walked a
14854 // `chroma_side`-SQUARE chunk, i.e. the 4:2:0 count on both
14855 // axes: at 4:2:2 it read HALF the chroma units of a chunk
14856 // (one 32x32 at the chunk's top-left instead of two), left
14857 // the chunk's lower 32 chroma rows with no residual at all,
14858 // and stamped every unit's entropy context over a 16x16-mi
14859 // luma span instead of 16x8. The same defect and the same
14860 // per-axis repair as `decode_inter_block`'s
14861 // `chunk_chroma_w/chunk_chroma_h` (lane-av1-422bigblock,
14862 // witnessed on `422_sb128_3f.obu`).
14863 let chunk_chroma_w = (64usize) >> ss_x(fctx);
14864 let chunk_chroma_h = (64usize) >> ss_y(fctx);
14865 // The unit's own footprint on the LUMA mi grid, per axis:
14866 // `(32 << ss) px` = `(32 << ss) / MI` mi -- 16x16 at 4:2:0,
14867 // 16x8 at 4:2:2, 8x8 at 4:4:4. `around_mi_rect` reads and
14868 // `record_mi_chroma` stamp exactly the unit's own cells.
14869 let unit_luma_w = cu_tx << ss_x(fctx);
14870 let unit_luma_h = cu_tx << ss_y(fctx);
14871 INTRABC_128RECT_CHUNK_SHAPE.with(|c| {
14872 c.set((chunk_chroma_w << 8) | chunk_chroma_h);
14873 });
14874 let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16));
14875 let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16));
14876 let units_x = chunk_w_mi / (unit_luma_w / MI);
14877 let units_y = chunk_h_mi / (unit_luma_h / MI);
14878 if lossless(fctx) {
14879 // TX_4X4 chroma units over this chunk (lane-lossless2's
14880 // walk, shared with the inter 128 path).
14881 read_inter_chroma_lossless(
14882 dec,
14883 cdfs,
14884 neighbours,
14885 u,
14886 v,
14887 Pred::Inline(&pred_u, cside),
14888 Pred::Inline(&pred_v, cside),
14889 (mi_r, mi_c),
14890 (cpx, cpy),
14891 (cc * chunk_chroma_w, cr * chunk_chroma_h),
14892 (chunk_chroma_w, chunk_chroma_h),
14893 (cw, ch),
14894 cside,
14895 0,
14896 base_q_idx,
14897 &mut u_units,
14898 &mut v_units,
14899 fctx,
14900 )?;
14901 // lane-av1-ibcrect: read_inter_chroma_lossless stamped
14902 // every TX_4X4 unit's own context (`record_mi_chroma`
14903 // inside the walk) -- the end-of-block record below must
14904 // not overwrite them with the composed grid (the inter
14905 // 128 path sets the same flag on this arm).
14906 mu_chroma = true;
14907 continue;
14908 }
14909 let cu_scan = default_scan(cu_tx);
14910 for plane_idx in 1..3 {
14911 let (src, buf) = if plane_idx == 1 {
14912 (Pred::Inline(&pred_u, cside), &mut *u)
14913 } else {
14914 (Pred::Inline(&pred_v, cside), &mut *v)
14915 };
14916 for ur in 0..units_y {
14917 for uc in 0..units_x {
14918 let unit_mi = (
14919 mi_r + cr * 16 + ur * (unit_luma_h / MI),
14920 mi_c + cc * 16 + uc * (unit_luma_w / MI),
14921 );
14922 // Per unit, AFTER the earlier units' stamps: this
14923 // unit's coefficient context must see them.
14924 let cu_around =
14925 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h);
14926 if crate::envflags::env_flag!("EC_ECDUMP") {
14927 for p in 1..3 {
14928 let ab: Vec<String> = (0..unit_luma_w / MI)
14929 .map(|k| {
14930 format!(
14931 "{:?}/{}",
14932 neighbours.above[unit_mi.1 + k][p].dc,
14933 neighbours.above[unit_mi.1 + k][p].level
14934 )
14935 })
14936 .collect();
14937 let lf: Vec<String> = (0..unit_luma_h / MI)
14938 .map(|k| {
14939 format!(
14940 "{:?}/{}",
14941 neighbours.left[unit_mi.0 + k][p].dc,
14942 neighbours.left[unit_mi.0 + k][p].level
14943 )
14944 })
14945 .collect();
14946 eprintln!(
14947 "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]",
14948 cu_around[p].0,
14949 cu_around[p].1,
14950 cu_around[p].2,
14951 ab.join(","),
14952 lf.join(",")
14953 );
14954 }
14955 }
14956 let (cu_x, cu_y) = (
14957 cpx + cc * chunk_chroma_w + uc * cu_tx,
14958 cpy + cr * chunk_chroma_h + ur * cu_tx,
14959 );
14960 // `av1_get_tx_type` (blockd.h:1291): an inter
14961 // block's chroma unit never codes a tx_type; it
14962 // inherits the coded type of the luma leaf
14963 // covering its own quadrant (all of this chunk's
14964 // leaves are read by now).
14965 let unit_rel_mi = (unit_mi.0 - mi_r, unit_mi.1 - mi_c);
14966 let covering = covering_leaf_tx_type(&leaf_tx_types, unit_rel_mi);
14967 // The prediction window is the block's own square
14968 // `cside` buffer with the unit's true per-axis
14969 // position inside it.
14970 let cu_pred = src.offset(
14971 (cr * chunk_chroma_h + ur * cu_tx) * cside
14972 + cc * chunk_chroma_w
14973 + uc * cu_tx,
14974 );
14975 let cu_grid = read_inter_plane(
14976 dec,
14977 cdfs,
14978 TxbSet::Chroma32,
14979 &cu_scan,
14980 plane_idx,
14981 cu_around[plane_idx],
14982 0,
14983 buf,
14984 cu_x,
14985 cu_y,
14986 cu_tx,
14987 base_q_idx,
14988 cu_pred,
14989 Some(covering.unwrap_or(TxType::DctDct)),
14990 Some(3),
14991 fctx,
14992 )?
14993 .0;
14994 // Immediately, so the NEXT unit reads this one's
14995 // coefficient context.
14996 neighbours.record_mi_chroma(
14997 unit_mi,
14998 unit_luma_w,
14999 unit_luma_h,
15000 plane_idx,
15001 &cu_grid,
15002 );
15003 if crate::envflags::env_flag!("EC_ECDUMP") {
15004 let st = crate::decode::neighbour_state(&cu_grid);
15005 eprintln!(
15006 "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})",
15007 st.dc, st.level
15008 );
15009 }
15010 hit!(CHROMA_SPLIT_TX_HITS);
15011 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(c.get() + 1));
15012 // lane-av1-ibcrect: per-unit chroma context -- the
15013 // end-of-block record's composed-grid re-stamp
15014 // must not stand (replayed below).
15015 mu_chroma = true;
15016 let dst = mu_units(
15017 if plane_idx == 1 {
15018 &mut u_units
15019 } else {
15020 &mut v_units
15021 },
15022 cside * cside,
15023 );
15024 for rr in 0..cu_tx {
15025 let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * cside
15026 + cc * chunk_chroma_w
15027 + uc * cu_tx;
15028 dst[start..start + cu_tx]
15029 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
15030 }
15031 }
15032 }
15033 }
15034 }
15035 }
15036 // The block-level luma bands were recorded per leaf above; the
15037 // composed chroma grids carry every unit in place.
15038 luma_grid = Grid::Zero(side * side);
15039 u_grid = if u_units.is_empty() {
15040 Grid::Zero(cside * cside)
15041 } else {
15042 Grid::Own(std::mem::take(&mut u_units))
15043 };
15044 v_grid = if v_units.is_empty() {
15045 Grid::Zero(cside * cside)
15046 } else {
15047 Grid::Own(std::mem::take(&mut v_units))
15048 };
15049 }
15050 // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a
15051 // neighbour reads a mode, zeroed palette state, the skip grid, the
15052 // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them),
15053 // and the DV into the intrabc mi grid.
15054 if skip {
15055 neighbours.record_rect_mi(
15056 (mi_r, mi_c),
15057 bw,
15058 bh,
15059 DC_PRED,
15060 DC_PRED,
15061 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
15062 );
15063 } else {
15064 neighbours.record_split_luma_rect_mi(
15065 (mi_r, mi_c),
15066 bw,
15067 bh,
15068 DC_PRED,
15069 DC_PRED,
15070 [&u_grid[..], &v_grid[..]],
15071 );
15072 }
15073 // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER
15074 // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside
15075 // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps
15076 // both planes with ONE `neighbour_state(composed_grid)` over the whole
15077 // span -- level = the SUM of every unit's levels and dc = the top-left
15078 // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128
15079 // inter block: the next block read a stale `dc_sign_ctx` one row low).
15080 // Measured on this shape: the 128x64 block at mi(64,32) of the
15081 // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared
15082 // into chunk-0's cells and the block below read `txb_skip` off the sum.
15083 // Replay every coded unit's own state after the record, in mu-chunk order
15084 // so a later unit still wins over an earlier one on the shared seam cells
15085 // (the composed construction `mu_chroma_units` uses, transcribed here).
15086 if mu_chroma {
15087 let cu = if lossless(fctx) { 4usize } else { 32usize };
15088 // The unit's own footprint on the LUMA mi grid (the chroma context
15089 // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s
15090 // convention), PER AXIS: `cu << ss` px, i.e. 8 px per TX_4x4 unit and
15091 // 64 px per TX_32X32 one at 4:2:0 -- 4 px / 32 px at 4:2:2.
15092 let unit_luma_w = cu << ss_x(fctx);
15093 let unit_luma_h = cu << ss_y(fctx);
15094 // A 64x64 mu chunk's chroma plane block is PER-AXIS
15095 // `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at 4:2:0 (ONE TX_32X32 per
15096 // chunk), 32x64 at 4:2:2 (TWO STACKED), 64x64 at 4:4:4 (FOUR);
15097 // `av1_get_max_uv_txsize` caps the unit at 32 on each axis.
15098 let chunk_chroma_w = (64usize) >> ss_x(fctx);
15099 let chunk_chroma_h = (64usize) >> ss_y(fctx);
15100 if lossless(fctx) {
15101 // lane-av1-ibc128chunk, PRE-EXISTING and NOT this lane's: on a
15102 // LOSSLESS frame `cu` is 4 and the composed plane grid is a raster
15103 // of TX_4x4 units, not a `cu`-per-chunk tiling -- so `rows`/`cols`
15104 // below (which count mu CHUNKS at the 4:2:0 chunk extent) do not
15105 // enumerate it, and this arm re-stamps only the 4x4 at each
15106 // chunk's top-left with a 2x2-mi span. The twin
15107 // (`decode_inter_block`'s `mu_chroma_units`, lane-av1-llinter)
15108 // instead raster-walks the WHOLE plane block at `cu` steps, and
15109 // that is the correct shape here too. It is left as-is on purpose:
15110 // it is a 4:2:0 defect, not a subsampling square-cut, and fixing
15111 // it would change 4:2:0 LOSSLESS output -- which this lane's
15112 // byte-identity requirement forbids doing on an unverified
15113 // reconstruction. Measured unreachability: this arm is entered
15114 // 0 times by the whole `lossless` and `intrabc` gate battery
15115 // (temporary env-gated counter in the arm). Unblock: one
15116 // lossless sb128 4:2:0 stream coding a NON-SKIP 128-root
15117 // intrabc strip (`--lossless=1 --sb-size=128
15118 // --min-partition-size=64 --enable-rect-partitions=1
15119 // --enable-intrabc=1` over near-match screen content).
15120 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
15121 for cr in 0..rows {
15122 for cc in 0..cols {
15123 let unit_mi = (
15124 mi_r + cr * (unit_luma_h / MI),
15125 mi_c + cc * (unit_luma_w / MI),
15126 );
15127 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
15128 let mut unit = Vec::with_capacity(cu * cu);
15129 for rr in 0..cu {
15130 let start = (cr * chunk_chroma_h + rr) * cside + cc * chunk_chroma_w;
15131 unit.extend_from_slice(&grid[start..start + cu]);
15132 }
15133 neighbours.record_mi_chroma(
15134 unit_mi,
15135 unit_luma_w,
15136 unit_luma_h,
15137 plane_idx,
15138 &unit,
15139 );
15140 }
15141 }
15142 }
15143 } else {
15144 // The chunk count on each axis, then EVERY unit inside each
15145 // chunk at its own mi origin, its own `(cu << ss)`-px entropy-cell
15146 // span, and its own quadrant of the composed plane grid -- the
15147 // twin's loop (decode_inter_block's `mu_chroma_units`,
15148 // lane-av1-444 c8). lane-av1-ibc128chunk: the loop used to count
15149 // mu CHUNKS in `rows`/`cols` and then step the mi origin and read
15150 // the grid PER UNIT, which only agrees when a chunk holds exactly
15151 // one unit. At 4:2:0 (`chunk_chroma == cu`) it is
15152 // line-identical to the old walk; at 4:2:2 and 4:4:4 a chunk holds
15153 // 2 or 4, so the old body reached only the first of the stacked
15154 // units and the rest of the chunk kept the composed-grid smearing
15155 // this replay exists to undo. A unit the frame edge clipped codes
15156 // nothing and carries no composed samples beyond the clip, so it
15157 // replays as the zero state exactly like libaom's uncoded unit.
15158 let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);
15159 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
15160 for cr in 0..rows {
15161 for cc in 0..cols {
15162 for kr in 0..ur {
15163 for kc in 0..uc {
15164 let unit_mi = (
15165 mi_r + (cr * 64 + kr * unit_luma_h) / MI,
15166 mi_c + (cc * 64 + kc * unit_luma_w) / MI,
15167 );
15168 let (cy, cx) =
15169 (cr * chunk_chroma_h + kr * cu, cc * chunk_chroma_w + kc * cu);
15170 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
15171 let mut unit = Vec::with_capacity(cu * cu);
15172 for rr in 0..cu {
15173 let start = (cy + rr) * cside + cx;
15174 unit.extend_from_slice(&grid[start..start + cu]);
15175 }
15176 neighbours.record_mi_chroma(
15177 unit_mi,
15178 unit_luma_w,
15179 unit_luma_h,
15180 plane_idx,
15181 &unit,
15182 );
15183 }
15184 }
15185 }
15186 }
15187 }
15188 }
15189 }
15190 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
15191 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
15192 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
15193 neighbours.fill_lf_grid_rect(
15194 (mi_r, mi_c),
15195 bw / MI,
15196 bh / MI,
15197 bw.min(64) as u8,
15198 bh.min(64) as u8,
15199 0,
15200 fctx,
15201 );
15202 record_intrabc_mi_rect(
15203 mi_r,
15204 mi_c,
15205 bw / MI,
15206 bh / MI,
15207 Some((dv_row, dv_col)),
15208 neighbours,
15209 fctx,
15210 );
15211 Ok(())
15212}
15213
15214/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
15215/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
15216/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
15217/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
15218/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
15219/// has no rectangular-transform coefficient reader, and a chroma plane here
15220/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
15221/// with no depth-based square-tiling escape the way luma's own resolved
15222/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
15223/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
15224#[allow(clippy::too_many_arguments)]
15225fn decode_block_rect(
15226 dec: &mut SymbolDecoder,
15227 cdfs: &mut Cdfs,
15228 neighbours: &mut Neighbours,
15229 at: (usize, usize),
15230 bw: usize,
15231 bh: usize,
15232 y: &mut PlaneBuf<'static>,
15233 u: &mut PlaneBuf<'static>,
15234 v: &mut PlaneBuf<'static>,
15235 enable_filter_intra: bool,
15236 allow_screen_content_tools: bool,
15237 base_q_idx: u8,
15238 tx_select: bool,
15239 reduced_tx_set: bool,
15240 fctx: &crate::decode::FrameCtx,
15241) -> Result<()> {
15242 let (r, c) = at;
15243 let (px, py) = (c * SUB, r * SUB);
15244 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
15245 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
15246 let palette_uv_cache = neighbours.palette_uv_cache(at);
15247 let (
15248 skip,
15249 mode,
15250 angle_delta_y,
15251 uv_mode,
15252 angle_delta_uv,
15253 alpha,
15254 filter_intra,
15255 palette_y,
15256 palette_uv,
15257 intrabc,
15258 ) = read_intra_mode_rect(
15259 dec,
15260 cdfs,
15261 nb_above_mode,
15262 nb_left_mode,
15263 true,
15264 true,
15265 bw,
15266 bh,
15267 enable_filter_intra,
15268 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
15269 allow_screen_content_tools,
15270 Some((palette_ctx, &palette_cache)),
15271 &palette_uv_cache,
15272 r * (SUB / MI),
15273 c * (SUB / MI),
15274 fctx,
15275 )?;
15276
15277 if let Some((dv_row, dv_col)) = intrabc {
15278 return decode_intrabc_rect(
15279 dec,
15280 cdfs,
15281 neighbours,
15282 (r * (SUB / MI), c * (SUB / MI)),
15283 (bw, bh),
15284 skip,
15285 (dv_row, dv_col),
15286 y,
15287 u,
15288 v,
15289 base_q_idx,
15290 fctx,
15291 );
15292 }
15293 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
15294 if smooth_neighbor {
15295 hit!(SMOOTH_LUMA_HITS);
15296 }
15297 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
15298 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
15299 // `uv_mode`, not the luma one.
15300 let smooth_neighbor_uv =
15301 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
15302 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
15303 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
15304 // rectangle just as happily), so a `use_filter_intra` strip at this level
15305 // predicts instead of refusing. The below-16x16 leaf arm
15306 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
15307 if filter_intra.is_some() {
15308 hit!(FILTER_INTRA_RECT_HITS);
15309 }
15310 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15311 DC_PRED
15312 } else {
15313 uv_mode
15314 };
15315 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
15316 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
15317 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
15318 // one did not, so with `--enable-tx-size-search=0` -- which several gate
15319 // recipes use -- the decoder consumed a symbol the encoder never wrote and
15320 // desynced the tile from that point on. That is why both strips of the
15321 // pinned HORZ quadrant were wrong from their very first pixel, and why our
15322 // range after the read equalled the oracle's range for the whole block.
15323 // lane-av1mixloss: the lossless-segment early return
15324 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment
15325 // rect block codes no depth symbol here either (class sweep of the sub8
15326 // leaf's fix).
15327 let depth = if tx_select && !lossless(fctx) {
15328 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
15329 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
15330 // intra-only frame publishes them from every block too
15331 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
15332 // 1920x792 128-superblock stream,
15333 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
15334 // `tx_size_cat2` row 1 where libaom reads row 2.
15335 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
15336 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
15337 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15338 eprintln!(
15339 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
15340 dec.debug_state().0
15341 );
15342 }
15343 d
15344 } else {
15345 0
15346 };
15347 // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame
15348 // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
15349 publish_txfm_bands_if_in_inter(
15350 neighbours,
15351 (mi_r, mi_c),
15352 depth_to_tx_wh(bw, bh, depth, fctx),
15353 (bw, bh),
15354 fctx,
15355 );
15356 if depth != 0 || lossless(fctx) {
15357 hit!(TX_DEPTH_HITS);
15358 // lane-rectsplit r1: a split transform is predicted and reconstructed
15359 // per transform unit, each unit taking its edges from the previous
15360 // unit's reconstruction inside this same strip (spec 5.11.36) --
15361 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
15362 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
15363 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
15364 eprintln!(
15365 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
15366 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
15367 angle_y={angle_delta_y}"
15368 );
15369 }
15370 let modes = RectStripModes {
15371 skip,
15372 mode,
15373 angle_delta_y,
15374 uv_predict_mode,
15375 angle_delta_uv,
15376 alpha,
15377 filter_intra,
15378 smooth_neighbor,
15379 smooth_neighbor_uv,
15380 palette_y: palette_y
15381 .as_ref()
15382 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
15383 palette_uv: palette_uv.as_ref().map(|p| {
15384 (
15385 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15386 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15387 )
15388 }),
15389 };
15390 if palette_y.is_some() || palette_uv.is_some() {
15391 hit!(PALETTE_SPLIT_TX_HITS);
15392 }
15393 decode_rect_split(
15394 dec,
15395 cdfs,
15396 neighbours,
15397 (mi_r, mi_c),
15398 bw,
15399 bh,
15400 tx_w,
15401 tx_h,
15402 &modes,
15403 y,
15404 u,
15405 v,
15406 base_q_idx,
15407 reduced_tx_set,
15408 fctx,
15409 )?;
15410 // This early return skips this fn's own tail, so the palette
15411 // neighbour state has to be stamped HERE too: without it a split-tx
15412 // strip left the above/left palette arrays holding a DEAD block's
15413 // colours, and the next block's colour cache
15414 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
15415 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
15416 // and only those pixels were wrong (lane-palette2 r10).
15417 let (py_size, py_colors) = palette_y
15418 .as_ref()
15419 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15420 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
15421 let (puv_size, puv_colors) = palette_uv
15422 .as_ref()
15423 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15424 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
15425 hit!(RECT_PARTITION_HITS);
15426 return Ok(());
15427 }
15428 let (tx_w, tx_h) = (bw, bh);
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 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15433 let (rng, _) = dec.debug_state();
15434 eprintln!(
15435 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
15436 skip={} tx={depth} rng={rng}",
15437 skip as i32
15438 );
15439 }
15440 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
15441 // block's prediction is the reconstructed colour-index map, set fresh
15442 // right before each `reconstruct_rect` call below (lane-palette2 r4).
15443 if let Some(ref pyv) = palette_y {
15444 let buf: Vec<u16> = pyv
15445 .map
15446 .iter()
15447 .map(|&idx| pyv.colors[idx as usize])
15448 .collect();
15449 set_palette_pred(buf, fctx);
15450 }
15451 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
15452 (
15453 puv.map
15454 .iter()
15455 .map(|&idx| puv.u_colors[idx as usize])
15456 .collect(),
15457 puv.map
15458 .iter()
15459 .map(|&idx| puv.v_colors[idx as usize])
15460 .collect(),
15461 )
15462 });
15463 if skip {
15464 push_intra_rect(
15465 0,
15466 px,
15467 py,
15468 bw,
15469 bh,
15470 mode,
15471 angle_delta_y,
15472 reach,
15473 &ZERO_RESIDUAL[..bw * bh],
15474 None,
15475 filter_intra,
15476 smooth_neighbor,
15477 fctx,
15478 );
15479 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15480 if let Some((ub, _)) = &palette_uv_bufs {
15481 set_palette_pred(ub.clone(), fctx);
15482 }
15483 push_intra_rect(
15484 1,
15485 cpx,
15486 cpy,
15487 chroma_w,
15488 chroma_h,
15489 uv_predict_mode,
15490 angle_delta_uv,
15491 reach,
15492 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15493 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15494 None,
15495 smooth_neighbor_uv,
15496 fctx,
15497 );
15498 if let Some((_, vb)) = &palette_uv_bufs {
15499 set_palette_pred(vb.clone(), fctx);
15500 }
15501 push_intra_rect(
15502 2,
15503 cpx,
15504 cpy,
15505 chroma_w,
15506 chroma_h,
15507 uv_predict_mode,
15508 angle_delta_uv,
15509 reach,
15510 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15511 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15512 None,
15513 smooth_neighbor_uv,
15514 fctx,
15515 );
15516 neighbours.record_rect(
15517 at,
15518 bw,
15519 bh,
15520 mode,
15521 uv_predict_mode,
15522 &[
15523 &ZERO_RESIDUAL[..bw * bh],
15524 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15525 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15526 ],
15527 );
15528 } else {
15529 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
15530 // reduces both size pairs to their square-up CDF sets
15531 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
15532 // doc comments); the scan order and 2D context tables are the real
15533 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
15534 let luma_scan: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 };
15535 // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a
15536 // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16
15537 // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis).
15538 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
15539 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
15540 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
15541 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8),
15542 (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16),
15543 // lane-av1-422: a 4:2:2 strip halves only the width. A 32x16
15544 // luma strip's chroma is a 16x16 SQUARE (`TxbSet::Chroma16`, the
15545 // set any 16x16 chroma plane reads); a 16x32 strip's chroma is
15546 // 8x32, whose entropy set is the 16x16 one and whose DCT-only
15547 // default follows the >=32 rule below -- the same pairing the
15548 // (8,32) row of [`decode_rect_split`]'s chroma table proves. At
15549 // 4:2:0 and 4:4:4 a strip's chroma is itself rect, so neither row
15550 // is reachable there.
15551 (16, 16) => (TxbSet::Chroma16, default_scan(16)),
15552 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
15553 _ => {
15554 return Err(unsupported(
15555 "a rectangular chroma transform whose size has no coefficient table",
15556 ));
15557 }
15558 };
15559 let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 {
15560 TxType::DctDct
15561 } else {
15562 default_intra_tx_type(uv_predict_mode as u8)
15563 };
15564 // lane-rectwire r3: real coefficients desync a pixel-exact gate
15565 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
15566 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
15567 // pixel (not a subtle context-table off-by-one), while the sibling
15568 // non-rect quadrants of the same frame match. Range-ladder bisection
15569 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
15570 // but the intra key-frame path has no traced symbol between the
15571 // partition read and the first coefficient block (mode/skip/tx_depth
15572 // reads are all untraced in libaom's decodeframe.c intra path, unlike
15573 // the inter EC_TRACE_MODE this round added), so a same-length range
15574 // comparison wasn't reachable within budget -- see
15575 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
15576 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
15577 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
15578 // libaom and match). lane-rectwire r4: range-ladder against the
15579 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
15580 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
15581 // both confirmed in sync -- rng=58692 on both sides right after
15582 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
15583 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
15584 // immediately after: ours moves rng 58692 -> 43570, which cannot be
15585 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
15586 // its own tx_size read) unless oracle's tx symbol is a near-certainty
15587 // CDF that barely narrows the range -- i.e. this decoder's
15588 // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for
15589 // a 32x16/16x32 strip is the first diverging symbol, not the
15590 // coefficient-context math r3 already cleared. Not confirmed byte-
15591 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
15592 // `read_tx_size`'s own rng, not attempted this round -- budget), so
15593 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
15594 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
15595 // it unconditionally where both square paths gate on `tx_select`. With
15596 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
15597 // decoder consumed one that was never there.
15598 {
15599 // lane-av1422warp r20: this 32x16/16x32 strip reader is the SIBLING of
15600 // `decode_leaf_rect`, and it was the one left ungated: at ss (1,0) the
15601 // strip's chroma is a square (side/2, side) block whose above cells
15602 // spread over `side` LUMA mi columns, so the per-mi rect gather
15603 // double-counts every chroma column's whole-unit dc sign. Measured on
15604 // the pinned 4:2:2 rotzoom stream (a1.obu frame 0): the chroma-U 4x4
15605 // transform of the 32x16 strip at mi(68,16) reads its DC sign from
15606 // `dc_sign_ctx` 1 where libaom reads row 0 -- the first read of
15607 // 45260 whose pre-state, bit position and symbol all match and only
15608 // the CDF row differs, and the first divergence in the EC_SYMR
15609 // sequence (all 45259 reads before it pair exactly). Luma keeps the
15610 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
15611 let mut around = neighbours.around_rect(at, bw, bh);
15612 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
15613 let c2 =
15614 neighbours.around_mi_422_chroma((at.0 * (SUB / MI), at.1 * (SUB / MI)), bw, bh);
15615 around[1] = c2[1];
15616 around[2] = c2[2];
15617 }
15618 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
15619 let (luma_levels, luma_tx_type) = read_coeffs_rect(
15620 dec,
15621 &mut luma_coding,
15622 luma_scan,
15623 bw,
15624 bh,
15625 0,
15626 dc_sign_ctx(around[0].2),
15627 TxType::DctDct,
15628 0,
15629 )?;
15630 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15631 let (rng, _) = dec.debug_state();
15632 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15633 }
15634 let luma_residual = dequant_and_inverse_typed_wh(
15635 &luma_levels,
15636 bw,
15637 bh,
15638 crate::decode::bit_depth(fctx),
15639 block_q_idx(fctx),
15640 plane_q_delta(0, fctx).0,
15641 plane_q_delta(0, fctx).1,
15642 luma_tx_type,
15643 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15644 );
15645 push_intra_rect(
15646 0,
15647 px,
15648 py,
15649 bw,
15650 bh,
15651 mode,
15652 angle_delta_y,
15653 reach,
15654 &luma_residual,
15655 None,
15656 filter_intra,
15657 smooth_neighbor,
15658 fctx,
15659 );
15660 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15661 if let Some((ub, _)) = &palette_uv_bufs {
15662 set_palette_pred(ub.clone(), fctx);
15663 }
15664 let u_default_tx = chroma_default_tx;
15665 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
15666 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
15667 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
15668 dec,
15669 &mut u_coding,
15670 chroma_scan,
15671 chroma_w,
15672 chroma_h,
15673 u_skip_ctx,
15674 dc_sign_ctx(around[1].2),
15675 u_default_tx,
15676 fctx,
15677 1,
15678 )?;
15679 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15680 let (rng, _) = dec.debug_state();
15681 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15682 }
15683 let u_residual = dequant_and_inverse_typed_wh(
15684 &u_levels,
15685 chroma_w,
15686 chroma_h,
15687 crate::decode::bit_depth(fctx),
15688 block_q_idx(fctx),
15689 plane_q_delta(1, fctx).0,
15690 plane_q_delta(1, fctx).1,
15691 u_tx_type,
15692 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
15693 );
15694 push_intra_rect(
15695 1,
15696 cpx,
15697 cpy,
15698 chroma_w,
15699 chroma_h,
15700 uv_predict_mode,
15701 angle_delta_uv,
15702 reach,
15703 &u_residual,
15704 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15705 None,
15706 smooth_neighbor_uv,
15707 fctx,
15708 );
15709 if let Some((_, vb)) = &palette_uv_bufs {
15710 set_palette_pred(vb.clone(), fctx);
15711 }
15712 let v_default_tx = chroma_default_tx;
15713 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
15714 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
15715 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
15716 dec,
15717 &mut v_coding,
15718 chroma_scan,
15719 chroma_w,
15720 chroma_h,
15721 v_skip_ctx,
15722 dc_sign_ctx(around[2].2),
15723 v_default_tx,
15724 fctx,
15725 2,
15726 )?;
15727 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15728 let (rng, _) = dec.debug_state();
15729 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
15730 }
15731 let v_residual = dequant_and_inverse_typed_wh(
15732 &v_levels,
15733 chroma_w,
15734 chroma_h,
15735 crate::decode::bit_depth(fctx),
15736 block_q_idx(fctx),
15737 plane_q_delta(2, fctx).0,
15738 plane_q_delta(2, fctx).1,
15739 v_tx_type,
15740 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
15741 );
15742 push_intra_rect(
15743 2,
15744 cpx,
15745 cpy,
15746 chroma_w,
15747 chroma_h,
15748 uv_predict_mode,
15749 angle_delta_uv,
15750 reach,
15751 &v_residual,
15752 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15753 None,
15754 smooth_neighbor_uv,
15755 fctx,
15756 );
15757 neighbours.record_rect(
15758 at,
15759 bw,
15760 bh,
15761 mode,
15762 uv_predict_mode,
15763 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
15764 );
15765 hit!(RECT_COEFF_HITS);
15766 }
15767 }
15768 let (py_size, py_colors) = palette_y
15769 .as_ref()
15770 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15771 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
15772 let (puv_size, puv_colors) = palette_uv
15773 .as_ref()
15774 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15775 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
15776 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
15777 neighbours.fill_lf_grid_rect(
15778 (mi_r, mi_c),
15779 bw / MI,
15780 bh / MI,
15781 tx_w as u8,
15782 tx_h as u8,
15783 0,
15784 fctx,
15785 );
15786 hit!(RECT_PARTITION_HITS);
15787 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15788 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
15789 }
15790 Ok(())
15791}
15792
15793/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
15794/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
15795/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
15796/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
15797/// the second strip of a HORZ/VERT split sits offset by half the 16x16
15798/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
15799/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
15800/// previous strip is directly above (same column, `mi_h` rows up) or
15801/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
15802/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
15803/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
15804/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
15805/// this strip's real position, never the coarse `record_rect` (which the
15806/// caller uses once, after both strips, exactly like the `VERT_B` arm next
15807/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
15808/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
15809/// chroma half (`TxbSet::ChromaRect8x4`) at 4:2:0 -- an 8x8 *square* chroma
15810/// plane (`TxbSet::Chroma8` + the default scan) at 4:2:2 (lane-av1-422e:
15811/// half-width, unhalved height), the two size classes one level
15812/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
15813#[allow(clippy::too_many_arguments)]
15814fn decode_leaf_rect(
15815 dec: &mut SymbolDecoder,
15816 cdfs: &mut Cdfs,
15817 neighbours: &mut Neighbours,
15818 outer_at: (usize, usize),
15819 leaf_mi: (usize, usize),
15820 bw: usize,
15821 bh: usize,
15822 prev_leaf: Option<((usize, usize), usize)>,
15823 y: &mut PlaneBuf<'static>,
15824 u: &mut PlaneBuf<'static>,
15825 v: &mut PlaneBuf<'static>,
15826 enable_filter_intra: bool,
15827 allow_screen_content_tools: bool,
15828 base_q_idx: u8,
15829 tx_select: bool,
15830 reduced_tx_set: bool,
15831 fctx: &crate::decode::FrameCtx,
15832) -> Result<usize> {
15833 let _ = base_q_idx;
15834 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15835 eprintln!(
15836 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
15837 dec.debug_state().0
15838 );
15839 }
15840 let (r, c) = outer_at;
15841 let mut above_mode = neighbours.above_mode[c];
15842 let mut left_mode = neighbours.left_mode[r];
15843 let (mi_w, mi_h) = (bw / MI, bh / MI);
15844 if let Some(((pr, pc), pmode)) = prev_leaf {
15845 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
15846 above_mode = pmode;
15847 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
15848 left_mode = pmode;
15849 }
15850 }
15851 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
15852 // cannot hold the modes a split (or a pair of strips) leaves behind, so
15853 // when the map holds the block at exactly this strip's above/left mi it
15854 // is the neighbour libaom's `above_mi`/`left_mi` reads.
15855 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
15856 // availability-correct -- four 16x8 strips share one coarse 16x16
15857 // `left_mode` cell too, so the fallback must not stand in for an absent
15858 // tile-edge neighbour.
15859 let (above_mode, left_mode) =
15860 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
15861 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
15862 if smooth_neighbor {
15863 hit!(SMOOTH_LUMA_HITS);
15864 }
15865 // The palette-Y mode CDF row is picked by the neighbours' palette use
15866 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
15867 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
15868 // a palette narrows the wrong interval and desyncs the tile even when the
15869 // decoded bit is the same. The cell is the 16px-SUB cell containing the
15870 // leaf (the palette neighbour arrays have no finer granularity).
15871 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
15872 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
15873 // exclusion and the neighbour palette lookup itself are mi-granular
15874 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
15875 let pal_at = leaf_mi;
15876 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
15877 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
15878 let (
15879 skip,
15880 mode,
15881 angle_delta_y,
15882 uv_mode,
15883 angle_delta_uv,
15884 alpha,
15885 filter_intra,
15886 palette_y,
15887 palette_uv,
15888 intrabc,
15889 ) = read_intra_mode_rect(
15890 dec,
15891 cdfs,
15892 above_mode,
15893 left_mode,
15894 true,
15895 true,
15896 bw,
15897 bh,
15898 enable_filter_intra,
15899 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
15900 allow_screen_content_tools,
15901 Some((palette_ctx, &palette_cache)),
15902 &palette_uv_cache,
15903 leaf_mi.0,
15904 leaf_mi.1,
15905 fctx,
15906 )?;
15907
15908 if let Some((dv_row, dv_col)) = intrabc {
15909 decode_intrabc_rect(
15910 dec,
15911 cdfs,
15912 neighbours,
15913 leaf_mi,
15914 (bw, bh),
15915 skip,
15916 (dv_row, dv_col),
15917 y,
15918 u,
15919 v,
15920 base_q_idx,
15921 fctx,
15922 )?;
15923 return Ok(DC_PRED);
15924 }
15925 // lane-kf900 r4: palette prediction on this shape, the same colour-index
15926 // map -> base colours buffer [`decode_block_rect`] hands each
15927 // `reconstruct_rect` through [`set_palette_pred`].
15928 if palette_y.is_some() || palette_uv.is_some() {
15929 hit!(RECT4_PALETTE_HITS);
15930 }
15931 let palette_y_buf: Option<Vec<u16>> = palette_y
15932 .as_ref()
15933 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
15934 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
15935 (
15936 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15937 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15938 )
15939 });
15940 let (pal_y_size, pal_y_colors) = palette_y
15941 .as_ref()
15942 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15943 let (pal_uv_size, pal_uv_colors) = palette_uv
15944 .as_ref()
15945 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15946 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
15947 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
15948 }
15949 if filter_intra.is_some() {
15950 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
15951 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
15952 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
15953 // below already makes; this refusal was square-only prose.
15954 hit!(FILTER_INTRA_RECT_HITS);
15955 hit!(FILTER_INTRA_RECT_SUB16_HITS);
15956 }
15957 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15958 DC_PRED
15959 } else {
15960 uv_mode
15961 };
15962 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
15963 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
15964 // a constant `false`.
15965 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
15966 let depth = if tx_select && !lossless(fctx) {
15967 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
15968 // every other rect reader now does -- a no-op on a key frame.
15969 // lane-av1mixloss: libaom `read_tx_size`'s first line
15970 // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return
15971 // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment
15972 // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4).
15973 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
15974 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
15975 // read was the leaf's own txb_skip.
15976 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
15977 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
15978 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
15979 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
15980 // count (3), different CDF row: a wrong-table read of a real symbol,
15981 // the class that cost lane-rectsplit r1 its 64x32 depth.
15982 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
15983 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
15984 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
15985 // function also decodes) sit at depth 2, so they read
15986 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
15987 // while `tx_size_cat2` belongs to the 32-level shapes
15988 // ([`decode_block_rect`]). Both tables carry three symbols, so the
15989 // wrong one decodes a plausible depth from the wrong probabilities:
15990 // the range diverges silently at the first such leaf and every later
15991 // symbol in the tile is read from the wrong place (class
15992 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
15993 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
15994 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15995 eprintln!(
15996 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
15997 leaf_mi.0,
15998 leaf_mi.1,
15999 dec.debug_state().0
16000 );
16001 }
16002 d
16003 } else {
16004 0
16005 };
16006 // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads
16007 // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
16008 publish_txfm_bands_if_in_inter(
16009 neighbours,
16010 leaf_mi,
16011 depth_to_tx_wh(bw, bh, depth, fctx),
16012 (bw, bh),
16013 fctx,
16014 );
16015 if depth != 0 || lossless(fctx) {
16016 // The same per-transform-unit walk the bigger strips take
16017 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
16018 // depth 2), addressed at this leaf's own mi position.
16019 hit!(TX_DEPTH_HITS);
16020 hit!(SUB16_SPLIT_HITS);
16021 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
16022 let modes = RectStripModes {
16023 skip,
16024 mode,
16025 angle_delta_y,
16026 uv_predict_mode,
16027 angle_delta_uv,
16028 alpha,
16029 filter_intra,
16030 smooth_neighbor,
16031 // lane-rectsplitx r3: the split arm hard-coded `false` here while
16032 // the unsplit arm below passes the real neighbour answer -- chroma
16033 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
16034 smooth_neighbor_uv,
16035 palette_y: palette_y_buf.clone(),
16036 palette_uv: palette_uv_bufs.clone(),
16037 };
16038 if palette_y.is_some() || palette_uv.is_some() {
16039 hit!(PALETTE_SPLIT_TX_HITS);
16040 }
16041 decode_rect_split(
16042 dec,
16043 cdfs,
16044 neighbours,
16045 leaf_mi,
16046 bw,
16047 bh,
16048 tx_w,
16049 tx_h,
16050 &modes,
16051 y,
16052 u,
16053 v,
16054 base_q_idx,
16055 reduced_tx_set,
16056 fctx,
16057 )?;
16058 record_strip_palette(
16059 neighbours,
16060 pal_at,
16061 bw,
16062 bh,
16063 pal_y_size,
16064 pal_y_colors,
16065 pal_uv_size,
16066 pal_uv_colors,
16067 );
16068 return Ok(mode);
16069 }
16070 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
16071 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16072 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
16073 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
16074 let (luma_levels, u_levels, v_levels);
16075 if skip {
16076 luma_levels = Grid::Zero(bw * bh);
16077 u_levels = Grid::Zero(chroma_w * chroma_h);
16078 v_levels = Grid::Zero(chroma_w * chroma_h);
16079 if let Some(b) = &palette_y_buf {
16080 set_palette_pred(b.clone(), fctx);
16081 }
16082 push_intra_rect(
16083 0,
16084 px,
16085 py,
16086 bw,
16087 bh,
16088 mode,
16089 angle_delta_y,
16090 reach,
16091 &luma_levels,
16092 None,
16093 filter_intra,
16094 smooth_neighbor,
16095 fctx,
16096 );
16097 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16098 if let Some((ub, _)) = &palette_uv_bufs {
16099 set_palette_pred(ub.clone(), fctx);
16100 }
16101 push_intra_rect(
16102 1,
16103 cpx,
16104 cpy,
16105 chroma_w,
16106 chroma_h,
16107 uv_predict_mode,
16108 angle_delta_uv,
16109 reach,
16110 &u_levels,
16111 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16112 None,
16113 smooth_neighbor_uv,
16114 fctx,
16115 );
16116 if let Some((_, vb)) = &palette_uv_bufs {
16117 set_palette_pred(vb.clone(), fctx);
16118 }
16119 push_intra_rect(
16120 2,
16121 cpx,
16122 cpy,
16123 chroma_w,
16124 chroma_h,
16125 uv_predict_mode,
16126 angle_delta_uv,
16127 reach,
16128 &v_levels,
16129 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16130 None,
16131 smooth_neighbor_uv,
16132 fctx,
16133 );
16134 } else {
16135 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
16136 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
16137 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
16138 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
16139 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
16140 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
16141 // lane-av1-422e: a 4:2:2 strip halves only the width, so the chroma
16142 // half of a 16x8/8x16 luma leaf is an 8x8 SQUARE (`TxbSet::Chroma8` +
16143 // the default scan -- the pairing any 8x8 chroma plane reads). 4:2:0
16144 // halves both axes (8x4/4x8 rect, `TxbSet::ChromaRect8x4`); 4:4:4
16145 // leaves the full 16x8/8x16 rect (`TxbSet::ChromaRect16x8`).
16146 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
16147 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 {
16148 if bw == 16 {
16149 (&SCAN_16X8, &SCAN_16X8)
16150 } else {
16151 (&SCAN_8X16, &SCAN_8X16)
16152 }
16153 } else if chroma_422 {
16154 if bw == 16 {
16155 (&SCAN_16X8, default_scan(8))
16156 } else {
16157 (&SCAN_8X16, default_scan(8))
16158 }
16159 } else if bw == 16 {
16160 (&SCAN_16X8, &SCAN_8X4)
16161 } else {
16162 (&SCAN_8X16, &SCAN_4X8)
16163 };
16164 let chroma_rect_set = if ss_x(fctx) == 0 {
16165 TxbSet::ChromaRect16x8
16166 } else if chroma_422 {
16167 TxbSet::Chroma8
16168 } else {
16169 TxbSet::ChromaRect8x4
16170 };
16171 // lane-av1422warp: at ss (1,0) this leaf's chroma is a SQUARE
16172 // (side/2, side) block, so `side` chroma 4-px cells above it spread
16173 // over `side` LUMA mi columns -- one chroma column per PAIR of luma
16174 // mi cells, and both carry the covering unit's whole-unit dc sign.
16175 // The per-mi rect gather therefore double-counts every chroma
16176 // column's sign. `around_mi_422_chroma`'s every-second above-cell
16177 // sampling is libaom's `txb_w_unit` sum, and every other 4:2:2 chroma
16178 // gather in this file already routes through it (see the gate at this
16179 // arm's siblings); this one did not, so a 4:2:2 rect leaf voted over
16180 // luma unit counts. Measured on the pinned 4:2:2 rotzoom stream
16181 // (a1.obu frame 0): the 16x8 leaf at mi(48,28) resolved its V plane's
16182 // dc sign from vote 0 (`dc_sign_cdf[0]`) where the oracle resolves a
16183 // negative vote (`dc_sign_cdf[1]`), which is the first bit-position
16184 // divergence in the frame (the bit offset is a clean constant through
16185 // coefficient unit 1418 and turns 6 bits at 1419). Luma keeps the
16186 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
16187 let mut around = neighbours.around_mi_rect(leaf_mi, bw, bh);
16188 if chroma_422 {
16189 let c = neighbours.around_mi_422_chroma(leaf_mi, bw, bh);
16190 around[1] = c[1];
16191 around[2] = c[2];
16192 }
16193 let luma_set = if reduced_tx_set {
16194 TxbSet::LumaRect16x8
16195 } else {
16196 TxbSet::LumaRect16x8Set1
16197 };
16198 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
16199 let (l_levels, luma_tx_type) = read_coeffs_rect(
16200 dec,
16201 &mut luma_coding,
16202 luma_scan,
16203 bw,
16204 bh,
16205 0,
16206 dc_sign_ctx(around[0].2),
16207 TxType::DctDct,
16208 0,
16209 )?;
16210 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
16211 let nz: Vec<(usize, i32)> = l_levels
16212 .iter()
16213 .copied()
16214 .enumerate()
16215 .filter(|(_, v)| *v != 0)
16216 .collect();
16217 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
16218 }
16219 luma_levels = l_levels;
16220 let luma_residual = dequant_and_inverse_typed_wh(
16221 &luma_levels,
16222 bw,
16223 bh,
16224 crate::decode::bit_depth(fctx),
16225 block_q_idx(fctx),
16226 plane_q_delta(0, fctx).0,
16227 plane_q_delta(0, fctx).1,
16228 luma_tx_type,
16229 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16230 );
16231 if let Some(b) = &palette_y_buf {
16232 set_palette_pred(b.clone(), fctx);
16233 }
16234 push_intra_rect(
16235 0,
16236 px,
16237 py,
16238 bw,
16239 bh,
16240 mode,
16241 angle_delta_y,
16242 reach,
16243 &luma_residual,
16244 None,
16245 filter_intra,
16246 smooth_neighbor,
16247 fctx,
16248 );
16249 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16250 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
16251 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
16252 let mut u_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
16253 let (u_l, u_tx_type) = read_chroma_coeffs_rect(
16254 dec,
16255 &mut u_coding,
16256 chroma_scan,
16257 chroma_w,
16258 chroma_h,
16259 u_skip_ctx,
16260 dc_sign_ctx(around[1].2),
16261 u_default_tx,
16262 fctx,
16263 1,
16264 )?;
16265 u_levels = u_l;
16266 let u_residual = dequant_and_inverse_typed_wh(
16267 &u_levels,
16268 chroma_w,
16269 chroma_h,
16270 crate::decode::bit_depth(fctx),
16271 block_q_idx(fctx),
16272 plane_q_delta(1, fctx).0,
16273 plane_q_delta(1, fctx).1,
16274 u_tx_type,
16275 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
16276 );
16277 if let Some((ub, _)) = &palette_uv_bufs {
16278 set_palette_pred(ub.clone(), fctx);
16279 }
16280 push_intra_rect(
16281 1,
16282 cpx,
16283 cpy,
16284 chroma_w,
16285 chroma_h,
16286 uv_predict_mode,
16287 angle_delta_uv,
16288 reach,
16289 &u_residual,
16290 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16291 None,
16292 smooth_neighbor_uv,
16293 fctx,
16294 );
16295 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
16296 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
16297 let mut v_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
16298 let (v_l, v_tx_type) = read_chroma_coeffs_rect(
16299 dec,
16300 &mut v_coding,
16301 chroma_scan,
16302 chroma_w,
16303 chroma_h,
16304 v_skip_ctx,
16305 dc_sign_ctx(around[2].2),
16306 v_default_tx,
16307 fctx,
16308 2,
16309 )?;
16310 v_levels = v_l;
16311 let v_residual = dequant_and_inverse_typed_wh(
16312 &v_levels,
16313 chroma_w,
16314 chroma_h,
16315 crate::decode::bit_depth(fctx),
16316 block_q_idx(fctx),
16317 plane_q_delta(2, fctx).0,
16318 plane_q_delta(2, fctx).1,
16319 v_tx_type,
16320 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
16321 );
16322 if let Some((_, vb)) = &palette_uv_bufs {
16323 set_palette_pred(vb.clone(), fctx);
16324 }
16325 push_intra_rect(
16326 2,
16327 cpx,
16328 cpy,
16329 chroma_w,
16330 chroma_h,
16331 uv_predict_mode,
16332 angle_delta_uv,
16333 reach,
16334 &v_residual,
16335 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16336 None,
16337 smooth_neighbor_uv,
16338 fctx,
16339 );
16340 hit!(RECT_LEAF_COEFF_HITS);
16341 }
16342 neighbours.record_mi_rect(
16343 leaf_mi,
16344 bw,
16345 bh,
16346 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16347 );
16348 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
16349 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16350 // The leaf's own palette state (`0` clears, as this site always did
16351 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
16352 // AXIS only until the pair's closing leaf: the coarse cell holds one
16353 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
16354 // real left neighbour leaf 1 reads (lane-kf900 r4).
16355 record_strip_palette(
16356 neighbours,
16357 pal_at,
16358 bw,
16359 bh,
16360 pal_y_size,
16361 pal_y_colors,
16362 pal_uv_size,
16363 pal_uv_colors,
16364 );
16365 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
16366 // rows -- record the whole span, not one cell.
16367 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
16368 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
16369 Ok(mode)
16370}
16371
16372/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
16373/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
16374/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
16375/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
16376/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
16377/// strip's mode so this one's mode context sees its true above/left
16378/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
16379///
16380/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
16381/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
16382/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
16383/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
16384/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
16385/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
16386/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
16387///
16388/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
16389/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
16390/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
16391/// unexamined.
16392#[allow(clippy::too_many_arguments)]
16393fn decode_block_rect4(
16394 dec: &mut SymbolDecoder,
16395 cdfs: &mut Cdfs,
16396 neighbours: &mut Neighbours,
16397 strip_mi: (usize, usize),
16398 bw: usize,
16399 bh: usize,
16400 prev_strip: Option<((usize, usize), usize)>,
16401 y: &mut PlaneBuf<'static>,
16402 u: &mut PlaneBuf<'static>,
16403 v: &mut PlaneBuf<'static>,
16404 enable_filter_intra: bool,
16405 allow_screen_content_tools: bool,
16406 base_q_idx: u8,
16407 tx_select: bool,
16408 fctx: &crate::decode::FrameCtx,
16409) -> Result<(usize, usize)> {
16410 let _ = base_q_idx;
16411 let (mi_r, mi_c) = strip_mi;
16412 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
16413 let (mi_w, mi_h) = (bw / MI, bh / MI);
16414 let mut above_mode = neighbours.above_mode[c];
16415 let mut left_mode = neighbours.left_mode[r];
16416 if let Some(((pr, pc), pmode)) = prev_strip {
16417 if pc == mi_c && mi_r == pr + mi_h {
16418 above_mode = pmode;
16419 } else if pr == mi_r && mi_c == pc + mi_w {
16420 left_mode = pmode;
16421 }
16422 }
16423 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
16424 // availability-correct neighbour modes (see
16425 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
16426 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
16427 let (above_mode, left_mode) =
16428 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
16429 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
16430 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
16431 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
16432 // wrong interval, so a screen-content tile desynced at the first strip
16433 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
16434 let pal_at = (mi_r, mi_c);
16435 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
16436 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
16437 let (
16438 skip,
16439 mode,
16440 angle_delta_y,
16441 uv_mode,
16442 angle_delta_uv,
16443 alpha,
16444 filter_intra,
16445 palette_y,
16446 palette_uv,
16447 intrabc,
16448 ) = read_intra_mode_rect(
16449 dec,
16450 cdfs,
16451 above_mode,
16452 left_mode,
16453 true,
16454 true,
16455 bw,
16456 bh,
16457 enable_filter_intra,
16458 neighbours.skip_txfm_ctx(mi_r, mi_c),
16459 allow_screen_content_tools,
16460 Some((palette_ctx, &palette_cache)),
16461 &palette_uv_cache,
16462 mi_r,
16463 mi_c,
16464 fctx,
16465 )?;
16466 if let Some((dv_row, dv_col)) = intrabc {
16467 decode_intrabc_rect(
16468 dec,
16469 cdfs,
16470 neighbours,
16471 strip_mi,
16472 (bw, bh),
16473 skip,
16474 (dv_row, dv_col),
16475 y,
16476 u,
16477 v,
16478 base_q_idx,
16479 fctx,
16480 )?;
16481 return Ok((DC_PRED, DC_PRED));
16482 }
16483 // lane-kf900 r4: palette prediction on this shape, exactly as
16484 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
16485 // mapped through the base colours IS the prediction (it reads no edge
16486 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
16487 if palette_y.is_some() || palette_uv.is_some() {
16488 hit!(RECT4_PALETTE_HITS);
16489 }
16490 let palette_y_buf: Option<Vec<u16>> = palette_y
16491 .as_ref()
16492 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
16493 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
16494 (
16495 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
16496 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
16497 )
16498 });
16499 let (pal_y_size, pal_y_colors) = palette_y
16500 .as_ref()
16501 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
16502 let (pal_uv_size, pal_uv_colors) = palette_uv
16503 .as_ref()
16504 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
16505 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
16506 if smooth_neighbor {
16507 hit!(SMOOTH_LUMA_HITS);
16508 }
16509 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
16510 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
16511 // `r * (SUB / MI)` names a different mi column and the chroma
16512 // edge-filter strength was read from the wrong neighbour (measured:
16513 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
16514 // with luma bit-exact).
16515 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
16516 if filter_intra.is_some() {
16517 hit!(FILTER_INTRA_RECT_HITS);
16518 if bw > bh {
16519 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
16520 } else {
16521 hit!(FILTER_INTRA_RECT4_VERT_HITS);
16522 }
16523 }
16524 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
16525 DC_PRED
16526 } else {
16527 uv_mode
16528 };
16529 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
16530 // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no
16531 // depth symbol here either (class sweep of the sub8 leaf's fix).
16532 let depth = if tx_select && !lossless(fctx) {
16533 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
16534 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
16535 // intra-only frame publishes them from every block too
16536 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
16537 // 1920x792 128-superblock stream,
16538 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
16539 // `tx_size_cat2` row 1 where libaom reads row 2.
16540 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
16541 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
16542 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
16543 eprintln!(
16544 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
16545 dec.debug_state().0
16546 );
16547 }
16548 d
16549 } else {
16550 0
16551 };
16552 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
16553 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
16554 publish_txfm_bands_if_in_inter(
16555 neighbours,
16556 (mi_r, mi_c),
16557 depth_to_tx_wh(bw, bh, depth, fctx),
16558 (bw, bh),
16559 fctx,
16560 );
16561 if depth != 0 || lossless(fctx) {
16562 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
16563 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
16564 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
16565 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
16566 // both interleave in every real stream.
16567 hit!(TX_DEPTH_HITS);
16568 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
16569 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
16570 // predicted -- depth 1 fires FIRST in every attempt that splits at
16571 // all, so a depth-2-only lift could never be gated. The r1 mismatch
16572 // was never the rect unit: it was the neighbour MODE the strip reads
16573 // (see `modes_above_left_mi`).
16574 let which = if depth == 1 {
16575 &RECT4_SPLIT_DEPTH1_HITS
16576 } else {
16577 &RECT4_SPLIT_DEPTH2_HITS
16578 };
16579 hit_do! { which.with(|c| c.set(c.get() + 1)); }
16580 let modes = RectStripModes {
16581 skip,
16582 mode,
16583 angle_delta_y,
16584 uv_predict_mode,
16585 angle_delta_uv,
16586 alpha,
16587 filter_intra,
16588 smooth_neighbor,
16589 smooth_neighbor_uv,
16590 palette_y: palette_y_buf.clone(),
16591 palette_uv: palette_uv_bufs.clone(),
16592 };
16593 if palette_y.is_some() || palette_uv.is_some() {
16594 hit!(PALETTE_SPLIT_TX_HITS);
16595 }
16596 decode_rect_split(
16597 dec,
16598 cdfs,
16599 neighbours,
16600 (mi_r, mi_c),
16601 bw,
16602 bh,
16603 tx_w,
16604 tx_h,
16605 &modes,
16606 y,
16607 u,
16608 v,
16609 base_q_idx,
16610 false,
16611 fctx,
16612 )?;
16613 record_strip_palette(
16614 neighbours,
16615 pal_at,
16616 bw,
16617 bh,
16618 pal_y_size,
16619 pal_y_colors,
16620 pal_uv_size,
16621 pal_uv_colors,
16622 );
16623 if bw > bh {
16624 hit!(RECT4_32_HORZ_HITS);
16625 } else {
16626 hit!(RECT4_32_VERT_HITS);
16627 }
16628 if !skip {
16629 hit!(RECT4_COEFF_HITS);
16630 }
16631 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16632 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16633 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16634 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16635 // transform size in both TXFM_CONTEXT bands. Without it the next block
16636 // reads the row's stale value.
16637 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
16638 return Ok((mode, uv_predict_mode));
16639 }
16640 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
16641 // that is 8 px tall, so each strip stamps every cell it touches and the
16642 // LAST strip wins -- which is the right answer for the block below/right
16643 // of the 32x32, the only reader outside it. Written after this strip's
16644 // own context read above, never before.
16645 for cell in 0..bw.div_ceil(SUB) {
16646 neighbours.above_mode[c + cell] = mode;
16647 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
16648 neighbours.above_side[c + cell] = bw;
16649 }
16650 for cell in 0..bh.div_ceil(SUB) {
16651 neighbours.left_mode[r + cell] = mode;
16652 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
16653 neighbours.left_side[r + cell] = bh;
16654 }
16655 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
16656 // [`decode_leaf_rect`] does (the split arm above records these through
16657 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
16658 // `sub8_mode_row` holding the previous block, and the next 32x32's
16659 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
16660 // fixture).
16661 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
16662 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
16663 let (px, py) = (mi_c * MI, mi_r * MI);
16664 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
16665 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
16666 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16667 // lane-av1-444: the strip's chroma shape follows the subsampling.
16668 // 4:2:0 codes 16x4/4x16 (`TxbSet::Chroma8`); 4:4:4 codes the strip
16669 // itself, 32x8/8x32 (`get_txsize_entropy_ctx(TX_32X8)` =
16670 // `(wide_log2 + high_log2 + 1) >> 1` = the 16x16 set,
16671 // `TxbSet::Chroma16`). The caller set is closed -- this reader only
16672 // ever sees 32x8 / 8x32 luma and the sequence header admits ss 0/0
16673 // and 1/1 only -- so the table is exhaustive.
16674 let chroma422_rect32 = (chroma_w, chroma_h) == (4, 32) && ss_x(fctx) == 1 && ss_y(fctx) == 0;
16675 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
16676 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
16677 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
16678 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8[..]),
16679 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32[..]),
16680 // lane-av1-422: a 4:2:2 1:4 strip halves only the width, so the
16681 // landscape leaves (32x8, 16x4 luma) code their chroma as the RECT
16682 // (16,8)/(8,4) -- the same TxbSet/scan pair the (16,8)/(8,4) rows of
16683 // [`decode_rect_split`]'s chroma table use.
16684 // lane-av1-422p: the PORTRAIT leaf occurs too -- the pinned
16685 // fixture's frame 2 carries an 8x32 strip at ss(1,0), whose (4, 32)
16686 // chroma block `ss_size_lookup[BLOCK_8X32][1][0]` marks
16687 // BLOCK_INVALID (255, enums.h). BLOCK_INVALID does not mean
16688 // "uncodable": `av1_get_tx_size` reads `max_txsize_rect_lookup[255]`
16689 // OUT OF BOUNDS there, the byte at +255 in the pinned Release oracle
16690 // is 0x05 = TX_4X8 (the `decode_token_recon_block` copy at
16691 // 0xc0d030, objdump-measured), and `av1_get_adjusted_tx_size` has no
16692 // TX_4X8 case. libaom HAS the transform, so the shape CHUNKS (the
16693 // `chroma422_rect32` arm below) into FOUR stacked TX_4X8 units per
16694 // plane (`tx_size_high_unit[TX_4X8] = 2`: blk_row 0, 2, 4, 6)
16695 // instead of refusing; no coefficient-table row is added, because
16696 // BLOCK_4X32 is not a table libaom has. 4:2:0 and 4:4:4 never land
16697 // here (their 8x32 strips read (4, 16) and (8, 32)), so the row is
16698 // 4:2:2-only.
16699 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8[..]),
16700 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
16701 // lane-av1-422p: the units' own set/scan -- the whole-rect read
16702 // below never sees this row, the `chroma422_rect32` arm chunks
16703 // first. Anything else is still a named-lane gap.
16704 (4, 32) if ss_x(fctx) == 1 && ss_y(fctx) == 0 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
16705 _ => unreachable!("decode_block_rect4 chroma shape set is closed: {chroma_w}x{chroma_h}"),
16706 };
16707 let luma_scan: &[u16] = if bw > bh { &SCAN_32X8 } else { &SCAN_8X32 };
16708 let (luma_levels, u_levels, v_levels) = if skip {
16709 (
16710 vec![0i32; bw * bh],
16711 vec![0i32; chroma_w * chroma_h],
16712 vec![0i32; chroma_w * chroma_h],
16713 )
16714 } else if chroma422_rect32 {
16715 // lane-av1-422p: the (4, 32) plane as FOUR TX_4X8 units per plane,
16716 // plane-major (every U unit, then every V) -- the walk the pinned
16717 // oracle's `decode_token_recon_block` makes for the BLOCK_INVALID
16718 // plane block: TX_4X8, so stepr = `tx_size_high_unit[TX_4X8]` = 2
16719 // 4-px rows and stepc = 1, unit rows at chroma y 0, 8, 16, 24.
16720 // Luma is the same single TX_8X32 rect the general arm reads.
16721 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16722 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
16723 let (luma_levels, luma_tx_type) = read_coeffs_rect(
16724 dec,
16725 &mut luma_coding,
16726 luma_scan,
16727 bw,
16728 bh,
16729 0,
16730 dc_sign_ctx(around[0].2),
16731 TxType::DctDct,
16732 0,
16733 )?;
16734 hit!(RECT4_COEFF_HITS);
16735 let luma_residual = dequant_and_inverse_typed_wh(
16736 &luma_levels,
16737 bw,
16738 bh,
16739 crate::decode::bit_depth(fctx),
16740 block_q_idx(fctx),
16741 plane_q_delta(0, fctx).0,
16742 plane_q_delta(0, fctx).1,
16743 luma_tx_type,
16744 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16745 );
16746 if let Some(b) = &palette_y_buf {
16747 set_palette_pred(b.clone(), fctx);
16748 }
16749 push_intra_rect(
16750 0,
16751 px,
16752 py,
16753 bw,
16754 bh,
16755 mode,
16756 angle_delta_y,
16757 reach,
16758 &luma_residual,
16759 None,
16760 filter_intra,
16761 smooth_neighbor,
16762 fctx,
16763 );
16764 // CfL parameters are computed ONCE per block over the strip's luma
16765 // (`are_parameters_computed`) and shared by all four units, as in
16766 // every other chunk arm.
16767 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16768 let mut unit_grids: Vec<((usize, usize), usize, Grid)> = Vec::new();
16769 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
16770 for unit_row in 0..4usize {
16771 let unit_mi = (mi_r + unit_row * 2, mi_c);
16772 let unit_reach = tu_reach_rect(
16773 bw,
16774 bh,
16775 0,
16776 unit_row * 8,
16777 8,
16778 8,
16779 reach,
16780 px,
16781 py,
16782 y.width,
16783 y.height,
16784 fctx,
16785 );
16786 if let Some((ub, vb)) = &palette_uv_bufs {
16787 let pbuf = if plane == 1 { ub } else { vb };
16788 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
16789 }
16790 // Each unit is read and recorded IMMEDIATELY: unit row 0's
16791 // `txb_skip_ctx` still sees the real above/left neighbour
16792 // states, a lower unit sees this block's own upper unit's
16793 // (libaom's per-unit `set_entropy_context`), and the lower
16794 // unit predicts off the upper one's reconstructed samples.
16795 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
16796 let unit_grid = read_rect_chroma_unit(
16797 dec,
16798 cdfs,
16799 TxbSet::ChromaRect8x4,
16800 &SCAN_4X8,
16801 4,
16802 8,
16803 plane,
16804 chroma_around[plane],
16805 uv_predict_mode,
16806 angle_delta_uv,
16807 unit_reach,
16808 buf,
16809 cpx,
16810 cpy + unit_row * 8,
16811 base_q_idx,
16812 // `get_txb_ctx_general`'s chroma branch
16813 // (txb_common.h): plane_bsize is BLOCK_INVALID (255)
16814 // here, `num_pels_log2_lookup[255]` = 255 (the +255
16815 // byte of the decodetxb copy at 0xc0de70,
16816 // objdump-measured) exceeds `BLOCK_4X8`'s 5, so the
16817 // ctx_offset is 10 -- the port's offset-7-first
16818 // `txb_skip_chroma_8` stores the offset-10 rows at
16819 // rows 3..6, hence +3.
16820 Some(3),
16821 alpha
16822 .zip(ac)
16823 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16824 smooth_neighbor_uv,
16825 fctx,
16826 )?;
16827 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
16828 unit_grids.push((unit_mi, plane, unit_grid));
16829 }
16830 }
16831 // The whole-block stamp rewrites the chroma cells ONE state wide,
16832 // which would erase the unit boundary the next block reads (class
16833 // `override-slot-on-one-arm`), so it carries zero chroma grids and
16834 // the per-unit writes replay after it. Its luma cells and side
16835 // spans are this arm's own bookkeeping.
16836 let zero_chroma = vec![0i32; chroma_w * chroma_h];
16837 neighbours.record_mi_rect(
16838 (mi_r, mi_c),
16839 bw,
16840 bh,
16841 &[&luma_levels[..], &zero_chroma[..], &zero_chroma[..]],
16842 );
16843 for (unit_mi, plane, grid) in &unit_grids {
16844 neighbours.record_mi_chroma(*unit_mi, 8, 8, *plane, grid);
16845 }
16846 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16847 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16848 record_strip_palette(
16849 neighbours,
16850 pal_at,
16851 bw,
16852 bh,
16853 pal_y_size,
16854 pal_y_colors,
16855 pal_uv_size,
16856 pal_uv_colors,
16857 );
16858 if bw > bh {
16859 hit!(RECT4_32_HORZ_HITS);
16860 } else {
16861 hit!(RECT4_32_VERT_HITS);
16862 }
16863 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
16864 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
16865 // frame, so this 1:4 strip -- which is also the INTER frame's reader
16866 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
16867 // transform size in both TXFM_CONTEXT bands. Without it the next block
16868 // reads the row's stale value.
16869 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
16870 return Ok((mode, uv_predict_mode));
16871 } else {
16872 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
16873 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
16874 let (luma_levels, luma_tx_type) = read_coeffs_rect(
16875 dec,
16876 &mut luma_coding,
16877 luma_scan,
16878 bw,
16879 bh,
16880 0,
16881 dc_sign_ctx(around[0].2),
16882 TxType::DctDct,
16883 0,
16884 )?;
16885 let mut planes = Vec::with_capacity(2);
16886 for plane in 1..3 {
16887 // `av1_get_tx_type` (`blockd.h:1278`): the mode-indexed type
16888 // stands only while it is a member of this tx size's set; a
16889 // 32x8/8x32 chroma transform (4:4:4) squares up to TX_32X32,
16890 // whose intra set is `EXT_TX_SET_DCTONLY` -- every ADST clamps
16891 // to DCT_DCT there, and ADST is undefined at widths above 16.
16892 let default_tx = if chroma_w.max(chroma_h) >= 32 {
16893 TxType::DctDct
16894 } else {
16895 default_intra_tx_type(uv_predict_mode as u8)
16896 };
16897 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
16898 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
16899 let (levels, tx_type) = read_chroma_coeffs_rect(
16900 dec,
16901 &mut coding,
16902 chroma_scan,
16903 chroma_w,
16904 chroma_h,
16905 skip_ctx,
16906 dc_sign_ctx(around[plane].2),
16907 default_tx,
16908 fctx,
16909 plane,
16910 )?;
16911 planes.push((levels, tx_type));
16912 }
16913 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
16914 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
16915 hit!(RECT4_COEFF_HITS);
16916 let luma_residual = dequant_and_inverse_typed_wh(
16917 &luma_levels,
16918 bw,
16919 bh,
16920 crate::decode::bit_depth(fctx),
16921 block_q_idx(fctx),
16922 plane_q_delta(0, fctx).0,
16923 plane_q_delta(0, fctx).1,
16924 luma_tx_type,
16925 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
16926 );
16927 if let Some(b) = &palette_y_buf {
16928 set_palette_pred(b.clone(), fctx);
16929 }
16930 push_intra_rect(
16931 0,
16932 px,
16933 py,
16934 bw,
16935 bh,
16936 mode,
16937 angle_delta_y,
16938 reach,
16939 &luma_residual,
16940 None,
16941 filter_intra,
16942 smooth_neighbor,
16943 fctx,
16944 );
16945 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
16946 for (plane, _buf, levels, tx_type) in [
16947 (1usize, &mut *u, &u_levels, u_tx_type),
16948 (2, &mut *v, &v_levels, v_tx_type),
16949 ] {
16950 let residual = dequant_and_inverse_typed_wh(
16951 levels,
16952 chroma_w,
16953 chroma_h,
16954 crate::decode::bit_depth(fctx),
16955 block_q_idx(fctx),
16956 plane_q_delta(plane, fctx).0,
16957 plane_q_delta(plane, fctx).1,
16958 tx_type,
16959 block_iqmatrix(fctx, plane, chroma_w, chroma_h, tx_type),
16960 );
16961 if let Some((ub, vb)) = &palette_uv_bufs {
16962 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
16963 }
16964 push_intra_rect(
16965 plane,
16966 cpx,
16967 cpy,
16968 chroma_w,
16969 chroma_h,
16970 uv_predict_mode,
16971 angle_delta_uv,
16972 reach,
16973 &residual,
16974 alpha
16975 .zip(ac)
16976 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
16977 None,
16978 smooth_neighbor_uv,
16979 fctx,
16980 );
16981 }
16982 neighbours.record_mi_rect(
16983 (mi_r, mi_c),
16984 bw,
16985 bh,
16986 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
16987 );
16988 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
16989 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
16990 record_strip_palette(
16991 neighbours,
16992 pal_at,
16993 bw,
16994 bh,
16995 pal_y_size,
16996 pal_y_colors,
16997 pal_uv_size,
16998 pal_uv_colors,
16999 );
17000 if bw > bh {
17001 hit!(RECT4_32_HORZ_HITS);
17002 } else {
17003 hit!(RECT4_32_VERT_HITS);
17004 }
17005 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
17006 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
17007 // frame, so this 1:4 strip -- which is also the INTER frame's reader
17008 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
17009 // transform size in both TXFM_CONTEXT bands. Without it the next block
17010 // reads the row's stale value.
17011 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
17012 return Ok((mode, uv_predict_mode));
17013 };
17014 if let Some(b) = &palette_y_buf {
17015 set_palette_pred(b.clone(), fctx);
17016 }
17017 push_intra_rect(
17018 0,
17019 px,
17020 py,
17021 bw,
17022 bh,
17023 mode,
17024 angle_delta_y,
17025 reach,
17026 &luma_levels,
17027 None,
17028 filter_intra,
17029 smooth_neighbor,
17030 fctx,
17031 );
17032 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
17033 if chroma422_rect32 {
17034 // lane-av1-422p: `predict_and_reconstruct_intra_block` (decodeframe.c
17035 // ~1000) predicts EVERY unit regardless of `skip_txfm`, so the skip
17036 // arm walks the same four TX_4X8 units per plane -- the lower unit
17037 // predicts off the upper one's predicted samples. No coefficients
17038 // are coded; the tail's whole-block zero stamp below is the state
17039 // libaom's `set_entropy_context` leaves.
17040 for (plane, _buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
17041 for unit_row in 0..4usize {
17042 let unit_reach = tu_reach_rect(
17043 bw,
17044 bh,
17045 0,
17046 unit_row * 8,
17047 8,
17048 8,
17049 reach,
17050 px,
17051 py,
17052 y.width,
17053 y.height,
17054 fctx,
17055 );
17056 if let Some((ub, vb)) = &palette_uv_bufs {
17057 let pbuf = if plane == 1 { ub } else { vb };
17058 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
17059 }
17060 push_intra_rect(
17061 plane,
17062 cpx,
17063 cpy + unit_row * 8,
17064 4,
17065 8,
17066 uv_predict_mode,
17067 angle_delta_uv,
17068 unit_reach,
17069 &ZERO_RESIDUAL[..4 * 8],
17070 alpha
17071 .zip(ac)
17072 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
17073 None,
17074 smooth_neighbor_uv,
17075 fctx,
17076 );
17077 }
17078 }
17079 } else {
17080 if let Some((ub, _)) = &palette_uv_bufs {
17081 set_palette_pred(ub.clone(), fctx);
17082 }
17083 push_intra_rect(
17084 1,
17085 cpx,
17086 cpy,
17087 chroma_w,
17088 chroma_h,
17089 uv_predict_mode,
17090 angle_delta_uv,
17091 reach,
17092 &u_levels,
17093 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
17094 None,
17095 smooth_neighbor_uv,
17096 fctx,
17097 );
17098 if let Some((_, vb)) = &palette_uv_bufs {
17099 set_palette_pred(vb.clone(), fctx);
17100 }
17101 push_intra_rect(
17102 2,
17103 cpx,
17104 cpy,
17105 chroma_w,
17106 chroma_h,
17107 uv_predict_mode,
17108 angle_delta_uv,
17109 reach,
17110 &v_levels,
17111 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
17112 None,
17113 smooth_neighbor_uv,
17114 fctx,
17115 );
17116 }
17117 neighbours.record_mi_rect(
17118 (mi_r, mi_c),
17119 bw,
17120 bh,
17121 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
17122 );
17123 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
17124 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
17125 record_strip_palette(
17126 neighbours,
17127 pal_at,
17128 bw,
17129 bh,
17130 pal_y_size,
17131 pal_y_colors,
17132 pal_uv_size,
17133 pal_uv_colors,
17134 );
17135 if bw > bh {
17136 hit!(RECT4_32_HORZ_HITS);
17137 } else {
17138 hit!(RECT4_32_VERT_HITS);
17139 }
17140 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
17141 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
17142 // frame, so this 1:4 strip -- which is also the INTER frame's reader
17143 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
17144 // transform size in both TXFM_CONTEXT bands. Without it the next block
17145 // reads the row's stale value.
17146 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
17147 Ok((mode, uv_predict_mode))
17148}
17149
17150/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
17151/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
17152/// down, and the first shape here whose luma block is a single mi row (or
17153/// column).
17154///
17155/// What is new at this size is CHROMA. `is_chroma_reference`
17156/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
17157/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
17158/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
17159/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
17160/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
17161/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
17162/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
17163///
17164/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
17165/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
17166/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
17167/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
17168/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
17169/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
17170/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
17171/// shape's own CDF row.
17172///
17173/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
17174/// refuses by name rather than guess-decode.
17175#[allow(clippy::too_many_arguments)]
17176fn decode_rect4_16(
17177 dec: &mut SymbolDecoder,
17178 cdfs: &mut Cdfs,
17179 neighbours: &mut Neighbours,
17180 at16: (usize, usize),
17181 horz: bool,
17182 y: &mut PlaneBuf<'static>,
17183 u: &mut PlaneBuf<'static>,
17184 v: &mut PlaneBuf<'static>,
17185 enable_filter_intra: bool,
17186 allow_screen_content_tools: bool,
17187 base_q_idx: u8,
17188 tx_select: bool,
17189 reduced_tx_set: bool,
17190 fctx: &crate::decode::FrameCtx,
17191) -> Result<()> {
17192 let (r, c) = at16;
17193 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
17194 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
17195 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
17196 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
17197 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
17198 let mut prev: Option<((usize, usize), usize)> = None;
17199 let mut last_mode = DC_PRED;
17200 let mut last_uv_mode = DC_PRED;
17201 for i in 0..4usize {
17202 let lmi = if horz {
17203 (mi_row0 + i, mi_col0)
17204 } else {
17205 (mi_row0, mi_col0 + i)
17206 };
17207 // lane-av1-444: at 4:4:4 every strip is its own chroma reference
17208 // (no mi-parity test at ss 0/0, and the strip's own chroma block is
17209 // already >= 4x4) -- there is no 4:2:0 pair to close.
17210 // lane-av1-422o: the parity rule is per axis, straight out of
17211 // `is_chroma_reference`: a HORZ 16x4 strip (1 mi tall) keeps the
17212 // `ss_y == 0 -> every strip a reference` row rule, but a VERT 4x16
17213 // strip (1 mi wide) keeps the COLUMN clause `(mi_col & 1) || !(bw &
17214 // 1) || !ss_x`, which with bw == 1 mi reduces to `mi_col odd` for
17215 // every ss_x == 1 format -- the ODD strip closes the pair and reads
17216 // the chroma, exactly like 4:2:0. (VERT_4 partitions start on an
17217 // even mi_col, so `i % 2 == 1` is that clause.)
17218 let has_chroma = i % 2 == 1 || (horz && ss_y(fctx) == 0) || (!horz && ss_x(fctx) == 0);
17219 let (mode, uv, _tx) = decode_rect4_16_strip(
17220 dec,
17221 cdfs,
17222 neighbours,
17223 lmi,
17224 horz,
17225 has_chroma,
17226 prev,
17227 y,
17228 u,
17229 v,
17230 enable_filter_intra,
17231 allow_screen_content_tools,
17232 base_q_idx,
17233 tx_select,
17234 reduced_tx_set,
17235 fctx,
17236 )?;
17237 if let Some(m) = uv {
17238 last_uv_mode = m;
17239 }
17240 last_mode = mode;
17241 prev = Some((lmi, mode));
17242 }
17243 // The coarse 16-px cell holds one entry for the whole 16x16: the last
17244 // strip is what a block below (right) sees through it, the mi-exact maps
17245 // above answering everything finer.
17246 neighbours.above_mode[c] = last_mode;
17247 neighbours.left_mode[r] = last_mode;
17248 neighbours.above_uv_mode[c] = last_uv_mode;
17249 neighbours.left_uv_mode[r] = last_uv_mode;
17250 neighbours.above_side[c] = bw;
17251 neighbours.left_side[r] = bh;
17252 Ok(())
17253}
17254
17255/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
17256/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
17257/// block path can decode a SINGLE intra strip of a partition whose other
17258/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
17259/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
17260/// every strip publishes its own mi-exact mode). Returns
17261/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
17262/// Intrabc reconstruction for a rect strip that OWNS its chroma
17263/// (`bw/2 x bh/2` at the strip origin). 16x4/4x16 is not this shape -- that
17264/// pair goes through [`decode_rect4_16_intrabc`].
17265///
17266/// This is the same control flow as the unmerged lane's `decode_intrabc_rect`
17267/// (predict once, then one residual per transform unit on the INTER sets,
17268/// chroma inherits luma's `tx_type`), written against the helpers that exist
17269/// on this tree so a 2:1 strip no longer hides the 16x4 pair witness. The
17270/// merge with lane-av1-intrabc should keep one of the two bodies; the call
17271/// shape is the same.
17272#[allow(clippy::too_many_arguments)]
17273fn decode_intrabc_owned_rect(
17274 dec: &mut SymbolDecoder,
17275 cdfs: &mut Cdfs,
17276 neighbours: &mut Neighbours,
17277 (mi_r, mi_c): (usize, usize),
17278 (bw, bh): (usize, usize),
17279 skip: bool,
17280 (dv_row, dv_col): (i32, i32),
17281 y: &mut PlaneBuf<'static>,
17282 u: &mut PlaneBuf<'static>,
17283 v: &mut PlaneBuf<'static>,
17284 base_q_idx: u8,
17285 tx_select: bool,
17286 reduced_tx_set: bool,
17287 fctx: &crate::decode::FrameCtx,
17288) -> Result<()> {
17289 let _ = base_q_idx;
17290 let (px, py) = (mi_c * MI, mi_r * MI);
17291 // lane-av1chromarect: libaom does NOT halve a 128-root intra-BC strip's
17292 // chroma plane block. `av1_get_max_uv_txsize` (blockd.h:1372) is
17293 // `max_txsize_rect_lookup[get_plane_block_size(bsize, ss_x, ss_y)]` run
17294 // through `av1_get_adjusted_tx_size`, and `get_plane_block_size` is
17295 // `ss_size_lookup[bsize]` -- at 4:4:4 the chroma plane block is the block's
17296 // OWN footprint, so the extent below and the eight chroma MV origin pairs
17297 // that follow must be `>> ss_x` / `>> ss_y`, not `/ 2`. At 4:2:0
17298 // (`ss_x == ss_y == 1`) the two forms are the same arithmetic.
17299 // MEASURED on the 4:4:4 LOSSY witness `fixtures/r512.obu` (6948 B, 3
17300 // frames, 5 strips through this function): with the halving, frame 0
17301 // diverges from the aomdec oracle in 166229 Y / 155383 U / 153498 V
17302 // samples and both later frames keep luma byte-exact while 74708 U +
17303 // 73501 V (f1) and 9216 U + 8192 V (f2) are wrong -- chroma-only, which is
17304 // what makes this a chroma-sizing defect and not a block-geometry one.
17305 // Re-measured by this lane; see lanes/av1chromarect.report.md.
17306 if crate::envflags::env_flag!("EC_HALVSWEEP") {
17307 eprintln!("EC_HALV ibc_owned mi=({mi_r},{mi_c}) bw={bw} bh={bh} skip={skip}");
17308 }
17309 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
17310 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
17311 let side = bw.max(bh);
17312 let cside = cw.max(ch);
17313 if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
17314 hit!(IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS);
17315 }
17316 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
17317 let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get);
17318 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
17319 // `read_block_tx_size_rect` keys on this cell. A key frame forces it
17320 // false; the real bit is the caller's `tx_select`. Restored before return.
17321 fctx.tx_select_inter.with(|c| c.set(tx_select));
17322 let restore = ReducedTxRestore {
17323 fctx,
17324 saved_reduced,
17325 saved_tx,
17326 };
17327
17328 flush_recon(fctx, y, u, v);
17329 let pred_y = predict_intrabc_window(y, px, py, bw, bh, dv_col, dv_row, true, side, fctx);
17330 let pred_u = predict_intrabc_window(u, cpx, cpy, cw, ch, dv_col, dv_row, false, cside, fctx);
17331 let pred_v = predict_intrabc_window(v, cpx, cpy, cw, ch, dv_col, dv_row, false, cside, fctx);
17332
17333 let mi_cols = 2 * y.true_width.div_ceil(8);
17334 let mi_rows = 2 * y.true_height.div_ceil(8);
17335 let leaves = read_block_tx_size_rect(
17336 dec,
17337 cdfs,
17338 neighbours,
17339 (mi_r, mi_c),
17340 (bw, bh),
17341 (mi_cols, mi_rows),
17342 skip,
17343 fctx,
17344 )?;
17345 let mut luma_tx_type = TxType::DctDct;
17346 let luma_grid;
17347 let u_grid;
17348 let v_grid;
17349 if skip {
17350 // `reconstruct_mc_rect` indexes the residual at the square stride.
17351 // `bw * bh` underruns on a VERT strip (8x16: stride 16, 16 rows, index 136).
17352 push_mc_rect(
17353 0,
17354 px,
17355 py,
17356 side,
17357 bw,
17358 bh,
17359 Pred::Inline(&pred_y, side),
17360 &ZERO_RESIDUAL[..side * bh],
17361 fctx,
17362 );
17363 push_mc_rect(
17364 1,
17365 cpx,
17366 cpy,
17367 cside,
17368 cw,
17369 ch,
17370 Pred::Inline(&pred_u, cside),
17371 &ZERO_RESIDUAL[..cside * ch],
17372 fctx,
17373 );
17374 push_mc_rect(
17375 2,
17376 cpx,
17377 cpy,
17378 cside,
17379 cw,
17380 ch,
17381 Pred::Inline(&pred_v, cside),
17382 &ZERO_RESIDUAL[..cside * ch],
17383 fctx,
17384 );
17385 if let Some(ls) = leaves.as_ref() {
17386 // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`,
17387 // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its
17388 // whole entropy-band footprint. The non-skip arm below writes
17389 // those bands per transform unit and the tail's
17390 // `record_split_luma_rect_mi` writes chroma only, so without
17391 // this walk a skipped strip whose `leaves` resolved (every
17392 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
17393 // returns the 4x4 grid before it looks at `skip`) leaked the
17394 // PREVIOUS occupant's luma bands into the next block's
17395 // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped
17396 // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128
17397 // stream left a stale 7 in left[48] and mi(48,68)'s first
17398 // transform unit read `txb_skip_ctx` 3 where aomdec reads 1).
17399 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
17400 for &(row, col, tw, th) in ls {
17401 neighbours.record_mi_luma_rect(
17402 (mi_r + row, mi_c + col),
17403 tw,
17404 th,
17405 &ZERO_RESIDUAL[..tw * th],
17406 );
17407 }
17408 }
17409 luma_grid = Grid::Zero(side * side);
17410 u_grid = Grid::Zero(cside * cside);
17411 v_grid = Grid::Zero(cside * cside);
17412 } else if let Some(ls) = leaves.as_ref() {
17413 let mut leaf_types: Vec<(usize, usize, usize, usize, TxType)> =
17414 Vec::with_capacity(ls.len());
17415 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
17416 let tu_mi = (mi_r + row, mi_c + col);
17417 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
17418 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
17419 let (g, tt) = if tw == th {
17420 read_inter_plane(
17421 dec,
17422 cdfs,
17423 inter_txbset_for(tw, reduced_tx_set),
17424 &default_scan(tw.min(32)),
17425 0,
17426 neighbours.around_mi(tu_mi, tw)[0],
17427 0,
17428 y,
17429 tu_px,
17430 tu_py,
17431 tw,
17432 base_q_idx,
17433 tu_pred,
17434 None,
17435 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
17436 fctx,
17437 )?
17438 } else {
17439 read_inter_plane_rect(
17440 dec,
17441 cdfs,
17442 rect_inter_luma_set(tw, th, fctx)?,
17443 (tw, th),
17444 side,
17445 0,
17446 neighbours.around_mi_rect(tu_mi, tw, th)[0],
17447 0,
17448 y,
17449 tu_px,
17450 tu_py,
17451 tu_pred,
17452 None,
17453 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
17454 fctx,
17455 )?
17456 };
17457 leaf_types.push((row, col, tw, th, tt));
17458 if idx == 0 {
17459 luma_tx_type = tt;
17460 }
17461 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
17462 if tw != th {
17463 neighbours.fill_lf_grid_leaf_luma(
17464 (tu_mi.0, tu_mi.1),
17465 tw / MI,
17466 th / MI,
17467 tw as u8,
17468 th as u8,
17469 );
17470 }
17471 }
17472 luma_grid = Grid::Zero(side * side);
17473 if cw.min(32) != cw || ch.min(32) != ch {
17474 // lane-av1chromarect: more than one chroma transform unit (the
17475 // 4:4:4 32x64/64x32 plane block). See the helper.
17476 let (ug, vg) = read_intrabc_rect_chroma_split(
17477 dec,
17478 cdfs,
17479 neighbours,
17480 (mi_r, mi_c),
17481 (cpx, cpy),
17482 (cw, ch),
17483 cside,
17484 &pred_u,
17485 &pred_v,
17486 &leaf_types,
17487 luma_tx_type,
17488 u,
17489 v,
17490 fctx,
17491 )?;
17492 u_grid = ug;
17493 v_grid = vg;
17494 } else {
17495 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17496 let (ug, _) = read_inter_plane_rect(
17497 dec,
17498 cdfs,
17499 rect_inter_chroma_set(cw, ch)?,
17500 (cw, ch),
17501 cside,
17502 1,
17503 around[1],
17504 0,
17505 u,
17506 cpx,
17507 cpy,
17508 Pred::Inline(&pred_u, cside),
17509 Some(luma_tx_type),
17510 None,
17511 fctx,
17512 )?;
17513 let (vg, _) = read_inter_plane_rect(
17514 dec,
17515 cdfs,
17516 rect_inter_chroma_set(cw, ch)?,
17517 (cw, ch),
17518 cside,
17519 2,
17520 around[2],
17521 0,
17522 v,
17523 cpx,
17524 cpy,
17525 Pred::Inline(&pred_v, cside),
17526 Some(luma_tx_type),
17527 None,
17528 fctx,
17529 )?;
17530 u_grid = ug;
17531 v_grid = vg;
17532 }
17533 } else {
17534 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
17535 let (g, tt) = read_inter_plane_rect(
17536 dec,
17537 cdfs,
17538 rect_inter_luma_set(bw, bh, fctx)?,
17539 (bw, bh),
17540 side,
17541 0,
17542 around[0],
17543 0,
17544 y,
17545 px,
17546 py,
17547 Pred::Inline(&pred_y, side),
17548 None,
17549 None,
17550 fctx,
17551 )?;
17552 luma_tx_type = tt;
17553 luma_grid = g;
17554 if cw.min(32) != cw || ch.min(32) != ch {
17555 // lane-av1chromarect: more than one chroma transform unit (the
17556 // 4:4:4 32x64/64x32 plane block). See the helper.
17557 let (ug, vg) = read_intrabc_rect_chroma_split(
17558 dec,
17559 cdfs,
17560 neighbours,
17561 (mi_r, mi_c),
17562 (cpx, cpy),
17563 (cw, ch),
17564 cside,
17565 &pred_u,
17566 &pred_v,
17567 &[],
17568 luma_tx_type,
17569 u,
17570 v,
17571 fctx,
17572 )?;
17573 u_grid = ug;
17574 v_grid = vg;
17575 } else {
17576 let (ug, _) = read_inter_plane_rect(
17577 dec,
17578 cdfs,
17579 rect_inter_chroma_set(cw, ch)?,
17580 (cw, ch),
17581 cside,
17582 1,
17583 around[1],
17584 0,
17585 u,
17586 cpx,
17587 cpy,
17588 Pred::Inline(&pred_u, cside),
17589 Some(luma_tx_type),
17590 None,
17591 fctx,
17592 )?;
17593 let (vg, _) = read_inter_plane_rect(
17594 dec,
17595 cdfs,
17596 rect_inter_chroma_set(cw, ch)?,
17597 (cw, ch),
17598 cside,
17599 2,
17600 around[2],
17601 0,
17602 v,
17603 cpx,
17604 cpy,
17605 Pred::Inline(&pred_v, cside),
17606 Some(luma_tx_type),
17607 None,
17608 fctx,
17609 )?;
17610 u_grid = ug;
17611 v_grid = vg;
17612 }
17613 }
17614 drop(restore);
17615 // lane-av1chromarect: when the chroma plane block was walked as SEVERAL
17616 // transform units, each unit stamped its own span through
17617 // `record_mi_chroma` and the whole-block stamp below would overwrite them
17618 // with one state (class `override-slot-on-one-arm`). libaom keeps the
17619 // per-unit above/left contexts distinct; the next block's first unit
17620 // reads them.
17621 // `!skip` matters: a SKIPPED strip reads no chroma unit at all (its whole
17622 // chroma plane block is one `push_mc_rect` of `ZERO_RESIDUAL`), so no
17623 // per-unit `record_mi_chroma` ran and the whole-block chroma stamp below
17624 // is still the only one that happens.
17625 let chroma_split_units = !skip && (cw.min(32) != cw || ch.min(32) != ch);
17626 if leaves.is_some() {
17627 if chroma_split_units {
17628 neighbours.record_split_luma_rect_mi_modes((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED);
17629 } else {
17630 neighbours.record_split_luma_rect_mi(
17631 (mi_r, mi_c),
17632 bw,
17633 bh,
17634 DC_PRED,
17635 DC_PRED,
17636 [&u_grid, &v_grid],
17637 );
17638 }
17639 } else if chroma_split_units {
17640 neighbours.record_rect_mi_luma_only((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &luma_grid);
17641 } else {
17642 neighbours.record_rect_mi(
17643 (mi_r, mi_c),
17644 bw,
17645 bh,
17646 DC_PRED,
17647 DC_PRED,
17648 &[&luma_grid, &u_grid, &v_grid],
17649 );
17650 }
17651 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
17652 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
17653 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
17654 neighbours.fill_lf_grid_rect(
17655 (mi_r, mi_c),
17656 bw / MI,
17657 bh / MI,
17658 bw.min(64) as u8,
17659 bh.min(64) as u8,
17660 0,
17661 fctx,
17662 );
17663 record_intrabc_mi_rect(
17664 mi_r,
17665 mi_c,
17666 bw / MI,
17667 bh / MI,
17668 Some((dv_row, dv_col)),
17669 neighbours,
17670 fctx,
17671 );
17672 let _ = luma_tx_type;
17673 Ok(())
17674}
17675
17676/// The chroma plane block of a 128-root intra-BC HORZ/VERT strip when that
17677/// plane block needs MORE THAN ONE transform unit -- the 4:4:4 cell, and the
17678/// 4:2:0 cell of a strip with a 128-px axis.
17679///
17680/// libaom never forms a 64-point CHROMA transform. `get_vartx_max_txsize`
17681/// (blockd.h:1447) returns `av1_get_adjusted_tx_size(max_txsize_rect_lookup
17682/// [plane_bsize])` and `av1_get_adjusted_tx_size` maps `TX_32X64`/`TX_64X32`
17683/// to `TX_32X32`; `decode_token_recon_block` (decodeframe.c:994-1004) then
17684/// steps the plane block by that size's mi units, and
17685/// `decode_reconstruct_tx`'s `tx_size == plane_tx_size || plane` arm never
17686/// recurses for chroma -- the same statement from the other side. So a 4:4:4
17687/// 32x64 chroma plane block is TWO stacked `TX_32X32` units, each with its
17688/// own eob, its own scan and its own coefficient context, NOT one 32x64 unit
17689/// whose coded corner happens to be 32x32: `av1_get_max_eob`'s 64-axis
17690/// truncation is a LUMA rule, and a chroma plane block is never 64 points
17691/// long to begin with.
17692///
17693/// That is exactly the tiling [`read_inter_rect_chroma`] implements
17694/// (`(write_chroma_w.min(32), write_chroma_h.min(32))` and the `nx * ny`
17695/// walk); this is the same walk for a caller that keeps its own grid
17696/// assembly and neighbour recording. The single-unit case is deliberately
17697/// NOT routed through here, so at 4:2:0 and at every 4:4:4 shape below 64
17698/// the caller keeps its own one-unit read verbatim.
17699#[allow(clippy::too_many_arguments)]
17700fn read_intrabc_rect_chroma_split(
17701 dec: &mut SymbolDecoder,
17702 cdfs: &mut Cdfs,
17703 neighbours: &mut Neighbours,
17704 (mi_r, mi_c): (usize, usize),
17705 (cpx, cpy): (usize, usize),
17706 (cw, ch): (usize, usize),
17707 cside: usize,
17708 pred_u: &[u16],
17709 pred_v: &[u16],
17710 leaf_tx_types: &[(usize, usize, usize, usize, TxType)],
17711 luma_tx_type: TxType,
17712 u: &mut PlaneBuf<'static>,
17713 v: &mut PlaneBuf<'static>,
17714 fctx: &crate::decode::FrameCtx,
17715) -> Result<(Grid, Grid)> {
17716 let (uw, uh) = (cw.min(32), ch.min(32));
17717 let (nx, ny) = (cw / uw, ch / uh);
17718 let set = rect_inter_chroma_set(uw, uh)?;
17719 let assembled_h = ch.max(cside);
17720 let mut assembled: [Vec<i32>; 2] = [
17721 vec![0i32; cside * assembled_h],
17722 vec![0i32; cside * assembled_h],
17723 ];
17724 for plane_idx in 1..=2 {
17725 let (src, buf) = if plane_idx == 1 {
17726 (pred_u, &mut *u)
17727 } else {
17728 (pred_v, &mut *v)
17729 };
17730 for cu_row in 0..ny {
17731 for cu_col in 0..nx {
17732 let (span_x, span_y) = (uw << ss_x(fctx), uh << ss_y(fctx));
17733 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
17734 let cu_around = neighbours.around_mi_rect(cu_mi, span_x, span_y);
17735 let (cu_x, cu_y) = (cpx + cu_col * uw, cpy + cu_row * uh);
17736 let cu_pred = Pred::Inline(src, cside).offset(cu_row * uh * cside + cu_col * uw);
17737 // libaom's `av1_get_tx_type` (blockd.h:1287) reads
17738 // `xd->tx_type_map` at the chroma unit's OWN position scaled
17739 // back to luma, so a unit sitting over a luma leaf that coded
17740 // nothing takes that leaf's stamp, not the block-level one.
17741 let rel_mi = (cu_mi.0 - mi_r, cu_mi.1 - mi_c);
17742 let inherit_tx_type =
17743 covering_leaf_tx_type(leaf_tx_types, rel_mi).or(Some(luma_tx_type));
17744 let cu_grid = read_inter_plane_rect(
17745 dec,
17746 cdfs,
17747 set,
17748 (uw, uh),
17749 cside,
17750 plane_idx,
17751 cu_around[plane_idx],
17752 0,
17753 buf,
17754 cu_x,
17755 cu_y,
17756 cu_pred,
17757 inherit_tx_type,
17758 // `get_txb_ctx`: plus 10 when the plane block is bigger
17759 // than the transform -- the same offset-3 convention
17760 // `read_inter_rect_chroma` passes on this arm.
17761 Some(3),
17762 fctx,
17763 )?
17764 .0;
17765 // Immediately, so the next unit of this block reads this one's
17766 // coefficient context (libaom updates the chroma above/left
17767 // contexts per unit).
17768 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &cu_grid);
17769 let dst = &mut assembled[plane_idx - 1];
17770 for rr in 0..uh {
17771 let start = (cu_row * uh + rr) * cside + cu_col * uw;
17772 dst[start..start + uw].copy_from_slice(&cu_grid[rr * uw..][..uw]);
17773 }
17774 }
17775 }
17776 }
17777 let [ug, vg] = assembled;
17778 Ok((Grid::Own(ug), Grid::Own(vg)))
17779}
17780
17781fn predict_intrabc_window(
17782 plane: &PlaneBuf<'_>,
17783 px: usize,
17784 py: usize,
17785 w: usize,
17786 h: usize,
17787 dv_col: i32,
17788 dv_row: i32,
17789 luma: bool,
17790 stride: usize,
17791 fctx: &crate::decode::FrameCtx,
17792) -> Vec<u16> {
17793 let mut dense = vec![0u16; w * h];
17794 mc::predict_with_filter(
17795 &plane.data,
17796 plane.width,
17797 plane.true_width,
17798 plane.true_height,
17799 mv_to_q4(px, dv_col, if luma { 0 } else { ss_x(fctx) }),
17800 mv_to_q4(py, dv_row, if luma { 0 } else { ss_y(fctx) }),
17801 w,
17802 h,
17803 mc::InterpFilterKind::Bilinear,
17804 &mut dense,
17805 fctx,
17806 );
17807 let mut laid = vec![0u16; stride * stride];
17808 for row in 0..h {
17809 laid[row * stride..][..w].copy_from_slice(&dense[row * w..][..w]);
17810 }
17811 laid
17812}
17813
17814struct ReducedTxRestore<'a> {
17815 fctx: &'a crate::decode::FrameCtx,
17816 saved_reduced: bool,
17817 saved_tx: bool,
17818}
17819impl Drop for ReducedTxRestore<'_> {
17820 fn drop(&mut self) {
17821 self.fctx
17822 .reduced_tx_set_inter
17823 .with(|c| c.set(self.saved_reduced));
17824 self.fctx.tx_select_inter.with(|c| c.set(self.saved_tx));
17825 }
17826}
17827
17828/// Reconstruction of one intrabc 16x4 / 4x16 strip (lane-av1-rect14).
17829///
17830/// A 1:4 strip is a PAIR. Both children share one chroma block, and only the
17831/// odd-mi member codes it (`is_chroma_reference`, `av1_common_int.h:1454`:
17832/// the bottom strip of a `HORZ_4`, the right strip of a `VERT_4`). The chroma
17833/// plane block is `ss_size_lookup[BLOCK_16X4][1][1] == BLOCK_8X4` (and
17834/// `BLOCK_4X8` for `VERT_4`) at the PAIR origin -- `setup_pred_plane`'s
17835/// `mi_row -= 1` when the block is one mi tall on an odd row. Luma is this
17836/// strip's own footprint, copied from this strip's DV. The block is
17837/// `is_inter_block`, so the residual uses the INTER sets and chroma inherits
17838/// the luma unit's coded `tx_type`.
17839///
17840/// Not [`decode_intrabc_rect`]: that helper (lane-av1-intrabc, not on this
17841/// tree) predicts chroma at `bw/2 x bh/2` of the strip itself. At 16x4 that
17842/// is an 8x2 half-pair at the odd strip -- wrong size, wrong origin, and it
17843/// would code chroma on every strip.
17844#[allow(clippy::too_many_arguments)]
17845fn decode_rect4_16_intrabc(
17846 dec: &mut SymbolDecoder,
17847 cdfs: &mut Cdfs,
17848 neighbours: &mut Neighbours,
17849 lmi: (usize, usize),
17850 horz: bool,
17851 has_chroma: bool,
17852 skip: bool,
17853 (dv_row, dv_col): (i32, i32),
17854 y: &mut PlaneBuf<'static>,
17855 u: &mut PlaneBuf<'static>,
17856 v: &mut PlaneBuf<'static>,
17857 base_q_idx: u8,
17858 tx_select: bool,
17859 reduced_tx_set: bool,
17860 fctx: &crate::decode::FrameCtx,
17861) -> Result<(usize, Option<usize>, (usize, usize))> {
17862 let _ = base_q_idx;
17863 hit!(RECT4_16_INTRABC_HITS);
17864 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
17865 let (mi_w, mi_h) = (bw / MI, bh / MI);
17866 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
17867 let side = bw.max(bh);
17868 // `rect_inter_luma_set` reads the frame cell. A key frame's tile decoder
17869 // publishes `reduced_tx_set` into it; set it here too so a caller that
17870 // passed the bit explicitly cannot disagree with the set we read.
17871 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
17872 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
17873 let restored = scopeguard_reduced(fctx, saved_reduced);
17874
17875 flush_recon(fctx, y, u, v);
17876 let mut pred_y_dense = vec![0u16; bw * bh];
17877 mc::predict_with_filter(
17878 &y.data,
17879 y.width,
17880 y.true_width,
17881 y.true_height,
17882 mv_to_q4(px, dv_col, 0),
17883 mv_to_q4(py, dv_row, 0),
17884 bw,
17885 bh,
17886 mc::InterpFilterKind::Bilinear,
17887 &mut pred_y_dense,
17888 fctx,
17889 );
17890 let mut pred_y = vec![0u16; side * side];
17891 for row in 0..bh {
17892 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
17893 }
17894
17895 // lane-av1444rect r2 (the class this lane named, second instance): the
17896 // pair geometry below is the 4:2:0 one and was applied at every `ss`. At
17897 // ss (0,0) `is_chroma_reference` (av1_common_int.h:1454) is
17898 // unconditionally true -- the strip is its own chroma reference, there is
17899 // no pair, and its chroma plane block IS the strip: 16x4 (HORZ_4) / 4x16
17900 // (VERT_4) at the strip's own origin, with its coefficient context read
17901 // over that same extent. The old constants instead predicted and coded an
17902 // 8x4 block at `(lmi - 1) * MI / 2`, a quarter of the position.
17903 //
17904 // MEASURED on a `testsrc2` 640x480 `--tune-content=screen --enable-intrabc=1
17905 // --enable-palette=1 --cq-level=60 --min-partition-size=4
17906 // --max-partition-size=64 --sb-size=64 --profile=1` stream (1016 B, 17
17907 // intrabc 16x4 strips at ss (0,0)): 455240 of 921600 samples wrong, the
17908 // entropy fork at read 11750 (`decodetxb.c:158`, the chroma `txb_skip`).
17909 // `--enable-intrabc=0` at the same settings is byte-exact, and the 4:2:0
17910 // twin of the same recipe is byte-exact.
17911 //
17912 // 4:2:0 and 4:2:2 keep every constant below verbatim -- the arm is gated on
17913 // the full ss (0,0), not on a per-axis shift, so `pw / 2` and the literal
17914 // halving are untouched for both.
17915 let own444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
17916 if ss_x(fctx) == 0 && ss_y(fctx) == 0 && has_chroma {
17917 hit!(INTRABC_RECT4_OWN_CHROMA444_HITS);
17918 }
17919 let (pw, ph) = if own444 {
17920 (bw, bh)
17921 } else if horz {
17922 (16usize, 8usize)
17923 } else {
17924 (8, 16)
17925 };
17926 let (cw, ch) = if own444 { (bw, bh) } else { (pw / 2, ph / 2) };
17927 let pair_mi = if has_chroma {
17928 if own444 {
17929 lmi
17930 } else if horz {
17931 (lmi.0 - 1, lmi.1)
17932 } else {
17933 (lmi.0, lmi.1 - 1)
17934 }
17935 } else {
17936 lmi
17937 };
17938 let (cpx, cpy) = if has_chroma {
17939 if own444 {
17940 (px, py)
17941 } else {
17942 (pair_mi.1 * MI / 2, pair_mi.0 * MI / 2)
17943 }
17944 } else {
17945 (0, 0)
17946 };
17947 let cside = cw.max(ch);
17948 let (pred_u, pred_v) = if has_chroma {
17949 let mut ud = vec![0u16; cw * ch];
17950 mc::predict_with_filter(
17951 &u.data,
17952 u.width,
17953 u.true_width,
17954 u.true_height,
17955 mv_to_q4(cpx, dv_col, ss_x(fctx)),
17956 mv_to_q4(cpy, dv_row, ss_y(fctx)),
17957 cw,
17958 ch,
17959 mc::InterpFilterKind::Bilinear,
17960 &mut ud,
17961 fctx,
17962 );
17963 let mut us = vec![0u16; cside * cside];
17964 for row in 0..ch {
17965 us[row * cside..][..cw].copy_from_slice(&ud[row * cw..][..cw]);
17966 }
17967 let mut vd = vec![0u16; cw * ch];
17968 mc::predict_with_filter(
17969 &v.data,
17970 v.width,
17971 v.true_width,
17972 v.true_height,
17973 mv_to_q4(cpx, dv_col, ss_x(fctx)),
17974 mv_to_q4(cpy, dv_row, ss_y(fctx)),
17975 cw,
17976 ch,
17977 mc::InterpFilterKind::Bilinear,
17978 &mut vd,
17979 fctx,
17980 );
17981 let mut vs = vec![0u16; cside * cside];
17982 for row in 0..ch {
17983 vs[row * cside..][..cw].copy_from_slice(&vd[row * cw..][..cw]);
17984 }
17985 (us, vs)
17986 } else {
17987 (Vec::new(), Vec::new())
17988 };
17989
17990 // Key-frame `tx_select` is the parameter. `tx_select_inter` is forced
17991 // false for a key frame, so `read_block_tx_size_rect` would skip the
17992 // symbol; read it here against the parameter the intra path already uses.
17993 // A skipped intrabc block predicts the whole footprint once and codes
17994 // no residual (`decode_token_recon_block`'s inter branch). Lossless
17995 // still forces TX_4X4 when the block is coded.
17996 let leaves = if skip || (!lossless(fctx) && !tx_select) {
17997 None
17998 } else if lossless(fctx) {
17999 let mut leaves = Vec::new();
18000 for row in 0..bh / MI {
18001 for col in 0..bw / MI {
18002 leaves.push((row, col, 4usize, 4usize));
18003 }
18004 }
18005 Some(leaves)
18006 } else {
18007 let ctx = txfm_partition_ctx_rect(
18008 neighbours.above_txfm[lmi.1],
18009 neighbours.left_txfm[lmi.0],
18010 side,
18011 bw,
18012 bh,
18013 );
18014 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
18015 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18016 let (rng, _) = dec.debug_state();
18017 eprintln!(
18018 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
18019 lmi.0,
18020 lmi.1,
18021 u8::from(split)
18022 );
18023 }
18024 if !split {
18025 None
18026 } else {
18027 let (sub_w, sub_h) = sub_tx_size_map(bw, bh);
18028 let mi_cols = 2 * y.true_width.div_ceil(8);
18029 let mi_rows = 2 * y.true_height.div_ceil(8);
18030 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(lmi.1));
18031 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(lmi.0));
18032 let mut out = Vec::new();
18033 for row in (0..bh / MI).step_by(sub_h / MI) {
18034 for col in (0..bw / MI).step_by(sub_w / MI) {
18035 read_var_tx_size(
18036 dec,
18037 cdfs,
18038 neighbours,
18039 lmi,
18040 side,
18041 (max_w_mi, max_h_mi),
18042 (sub_w, sub_h),
18043 1,
18044 row,
18045 col,
18046 &mut out,
18047 );
18048 }
18049 }
18050 Some(out)
18051 }
18052 };
18053 let (tx_w, tx_h) = leaves
18054 .as_ref()
18055 .and_then(|ls| ls.first())
18056 .map_or((bw, bh), |l| (l.2, l.3));
18057
18058 let mut luma_tx_type = TxType::DctDct;
18059 let luma_grid;
18060 let mut u_grid = Grid::Zero(cw * ch);
18061 let mut v_grid = Grid::Zero(cw * ch);
18062 let chroma_stamped_per_unit;
18063
18064 if skip {
18065 push_mc_rect(
18066 0,
18067 px,
18068 py,
18069 side,
18070 bw,
18071 bh,
18072 Pred::Inline(&pred_y, side),
18073 &ZERO_RESIDUAL[..side * bh],
18074 fctx,
18075 );
18076 luma_grid = Grid::Zero(bw * bh);
18077 if has_chroma {
18078 push_mc_rect(
18079 1,
18080 cpx,
18081 cpy,
18082 cside,
18083 cw,
18084 ch,
18085 Pred::Inline(&pred_u, cside),
18086 &ZERO_RESIDUAL[..cside * ch],
18087 fctx,
18088 );
18089 push_mc_rect(
18090 2,
18091 cpx,
18092 cpy,
18093 cside,
18094 cw,
18095 ch,
18096 Pred::Inline(&pred_v, cside),
18097 &ZERO_RESIDUAL[..cside * ch],
18098 fctx,
18099 );
18100 }
18101 chroma_stamped_per_unit = false;
18102 } else if let Some(ls) = leaves.as_ref() {
18103 if lossless(fctx) {
18104 for &(row, col, _tw, _th) in ls {
18105 let tu_mi = (lmi.0 + row, lmi.1 + col);
18106 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
18107 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
18108 let (g, _) = read_inter_plane(
18109 dec,
18110 cdfs,
18111 if reduced_tx_set {
18112 TxbSet::Luma4Inter
18113 } else {
18114 TxbSet::Luma4InterSet1
18115 },
18116 &default_scan(4),
18117 0,
18118 neighbours.around_mi(tu_mi, 4)[0],
18119 0,
18120 y,
18121 tu_px,
18122 tu_py,
18123 4,
18124 base_q_idx,
18125 tu_pred,
18126 None,
18127 Some(neighbours.luma_skip_ctx(tu_mi, 1)),
18128 fctx,
18129 )?;
18130 neighbours.record_mi_luma_rect(tu_mi, 4, 4, &g);
18131 }
18132 } else {
18133 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
18134 let tu_mi = (lmi.0 + row, lmi.1 + col);
18135 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
18136 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
18137 let (g, tt) = if tw == th {
18138 read_inter_plane(
18139 dec,
18140 cdfs,
18141 inter_txbset_for(tw, reduced_tx_set),
18142 &default_scan(tw.min(32)),
18143 0,
18144 neighbours.around_mi(tu_mi, tw)[0],
18145 0,
18146 y,
18147 tu_px,
18148 tu_py,
18149 tw,
18150 base_q_idx,
18151 tu_pred,
18152 None,
18153 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)),
18154 fctx,
18155 )?
18156 } else {
18157 read_inter_plane_rect(
18158 dec,
18159 cdfs,
18160 rect_inter_luma_set(tw, th, fctx)?,
18161 (tw, th),
18162 side,
18163 0,
18164 neighbours.around_mi_rect(tu_mi, tw, th)[0],
18165 0,
18166 y,
18167 tu_px,
18168 tu_py,
18169 tu_pred,
18170 None,
18171 Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)),
18172 fctx,
18173 )?
18174 };
18175 if idx == 0 {
18176 luma_tx_type = tt;
18177 }
18178 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
18179 }
18180 }
18181 luma_grid = Grid::Zero(bw * bh);
18182 chroma_stamped_per_unit = has_chroma && lossless(fctx);
18183 if has_chroma && lossless(fctx) {
18184 let (mut uo, mut vo) = (Vec::new(), Vec::new());
18185 read_inter_chroma_lossless(
18186 dec,
18187 cdfs,
18188 neighbours,
18189 u,
18190 v,
18191 Pred::Inline(&pred_u, cside),
18192 Pred::Inline(&pred_v, cside),
18193 pair_mi,
18194 (cpx, cpy),
18195 (0, 0),
18196 (cw, ch),
18197 (cw, ch),
18198 cside,
18199 0,
18200 base_q_idx,
18201 &mut uo,
18202 &mut vo,
18203 fctx,
18204 )?;
18205 u_grid = if uo.is_empty() {
18206 Grid::Zero(cw * ch)
18207 } else {
18208 Grid::Own(uo)
18209 };
18210 v_grid = if vo.is_empty() {
18211 Grid::Zero(cw * ch)
18212 } else {
18213 Grid::Own(vo)
18214 };
18215 } else if has_chroma {
18216 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
18217 let (ug, _) = read_inter_plane_rect(
18218 dec,
18219 cdfs,
18220 rect_inter_chroma_set(cw, ch)?,
18221 (cw, ch),
18222 cside,
18223 1,
18224 around[1],
18225 0,
18226 u,
18227 cpx,
18228 cpy,
18229 Pred::Inline(&pred_u, cside),
18230 Some(luma_tx_type),
18231 None,
18232 fctx,
18233 )?;
18234 u_grid = ug;
18235 let (vg, _) = read_inter_plane_rect(
18236 dec,
18237 cdfs,
18238 rect_inter_chroma_set(cw, ch)?,
18239 (cw, ch),
18240 cside,
18241 2,
18242 around[2],
18243 0,
18244 v,
18245 cpx,
18246 cpy,
18247 Pred::Inline(&pred_v, cside),
18248 Some(luma_tx_type),
18249 None,
18250 fctx,
18251 )?;
18252 v_grid = vg;
18253 }
18254 } else {
18255 let around = neighbours.around_mi_rect(lmi, bw, bh);
18256 let (g, tt) = read_inter_plane_rect(
18257 dec,
18258 cdfs,
18259 rect_inter_luma_set(bw, bh, fctx)?,
18260 (bw, bh),
18261 side,
18262 0,
18263 around[0],
18264 0,
18265 y,
18266 px,
18267 py,
18268 Pred::Inline(&pred_y, side),
18269 None,
18270 None,
18271 fctx,
18272 )?;
18273 luma_tx_type = tt;
18274 luma_grid = g;
18275 chroma_stamped_per_unit = false;
18276 if has_chroma {
18277 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
18278 let (ug, _) = read_inter_plane_rect(
18279 dec,
18280 cdfs,
18281 rect_inter_chroma_set(cw, ch)?,
18282 (cw, ch),
18283 cside,
18284 1,
18285 around[1],
18286 0,
18287 u,
18288 cpx,
18289 cpy,
18290 Pred::Inline(&pred_u, cside),
18291 Some(luma_tx_type),
18292 None,
18293 fctx,
18294 )?;
18295 u_grid = ug;
18296 let (vg, _) = read_inter_plane_rect(
18297 dec,
18298 cdfs,
18299 rect_inter_chroma_set(cw, ch)?,
18300 (cw, ch),
18301 cside,
18302 2,
18303 around[2],
18304 0,
18305 v,
18306 cpx,
18307 cpy,
18308 Pred::Inline(&pred_v, cside),
18309 Some(luma_tx_type),
18310 None,
18311 fctx,
18312 )?;
18313 v_grid = vg;
18314 }
18315 }
18316 drop(restored);
18317
18318 if leaves.is_none() {
18319 neighbours.record_mi_luma_rect(lmi, bw, bh, &luma_grid);
18320 }
18321 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, DC_PRED);
18322 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
18323 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
18324 for cell in 0..mi_w {
18325 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
18326 *slot = bw as u8;
18327 }
18328 }
18329 for cell in 0..mi_h {
18330 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
18331 *slot = bh as u8;
18332 }
18333 }
18334 let mut last_uv = None;
18335 if has_chroma {
18336 hit!(RECT4_16_CHROMA_HITS);
18337 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, DC_PRED);
18338 if !chroma_stamped_per_unit {
18339 let u_state = neighbour_state(&u_grid);
18340 let v_state = neighbour_state(&v_grid);
18341 let round_up_even = |n: usize| n.div_ceil(2) * 2;
18342 let bound_h = round_up_even(neighbours.mi_rows);
18343 let bound_w = round_up_even(neighbours.mi_cols);
18344 for cell in 0..(ph / MI) {
18345 if pair_mi.0 + cell < bound_h
18346 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
18347 {
18348 slot[1] = u_state;
18349 slot[2] = v_state;
18350 }
18351 }
18352 for cell in 0..(pw / MI) {
18353 if pair_mi.1 + cell < bound_w
18354 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
18355 {
18356 slot[1] = u_state;
18357 slot[2] = v_state;
18358 }
18359 }
18360 }
18361 last_uv = Some(DC_PRED);
18362 }
18363 if horz {
18364 hit!(RECT4_16_HORZ_HITS);
18365 } else {
18366 hit!(RECT4_16_VERT_HITS);
18367 }
18368 record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]);
18369 if leaves.is_none() {
18370 // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs`
18371 // with `skip && is_inter`, or the unsplit unit). A split tree already
18372 // published per leaf inside `read_var_tx_size`.
18373 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
18374 }
18375 record_intrabc_mi_rect(
18376 lmi.0,
18377 lmi.1,
18378 mi_w,
18379 mi_h,
18380 Some((dv_row, dv_col)),
18381 neighbours,
18382 fctx,
18383 );
18384 Ok((DC_PRED, last_uv, (tx_w, tx_h)))
18385}
18386
18387/// Restores `reduced_tx_set_inter` when the intrabc pair reader returns,
18388/// including through `?`.
18389struct ReducedRestore<'a> {
18390 fctx: &'a crate::decode::FrameCtx,
18391 saved: bool,
18392}
18393impl Drop for ReducedRestore<'_> {
18394 fn drop(&mut self) {
18395 self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved));
18396 }
18397}
18398fn scopeguard_reduced(fctx: &crate::decode::FrameCtx, saved: bool) -> ReducedRestore<'_> {
18399 ReducedRestore { fctx, saved }
18400}
18401
18402#[allow(clippy::too_many_arguments)]
18403fn decode_rect4_16_strip(
18404 dec: &mut SymbolDecoder,
18405 cdfs: &mut Cdfs,
18406 neighbours: &mut Neighbours,
18407 lmi: (usize, usize),
18408 horz: bool,
18409 has_chroma: bool,
18410 prev: Option<((usize, usize), usize)>,
18411 y: &mut PlaneBuf<'static>,
18412 u: &mut PlaneBuf<'static>,
18413 v: &mut PlaneBuf<'static>,
18414 enable_filter_intra: bool,
18415 allow_screen_content_tools: bool,
18416 base_q_idx: u8,
18417 tx_select: bool,
18418 reduced_tx_set: bool,
18419 fctx: &crate::decode::FrameCtx,
18420) -> Result<(usize, Option<usize>, (usize, usize))> {
18421 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
18422 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
18423 let (mi_w, mi_h) = (bw / MI, bh / MI);
18424 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
18425 let mut last_uv_mode: Option<usize> = None;
18426 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
18427 // aliases all four strips onto one entry, so the mi-exact map wins and
18428 // the previous strip stands in on the split axis.
18429 let mut above_mode = neighbours.above_mode[c];
18430 let mut left_mode = neighbours.left_mode[r];
18431 if let Some(((pr, pc), pmode)) = prev {
18432 if pc == lmi.1 && lmi.0 == pr + mi_h {
18433 above_mode = pmode;
18434 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
18435 left_mode = pmode;
18436 }
18437 }
18438 let (above_mode, left_mode) =
18439 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
18440 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
18441 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
18442 // off CDF row 0 and every cache hit off an empty cache.
18443 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
18444 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
18445 let (
18446 skip,
18447 mode,
18448 angle_delta_y,
18449 uv_mode,
18450 angle_delta_uv,
18451 alpha,
18452 filter_intra,
18453 palette_y,
18454 palette_uv,
18455 intrabc,
18456 ) = read_intra_mode_rect(
18457 dec,
18458 cdfs,
18459 above_mode,
18460 left_mode,
18461 true,
18462 has_chroma,
18463 bw,
18464 bh,
18465 enable_filter_intra,
18466 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
18467 allow_screen_content_tools,
18468 Some((palette_ctx, &palette_cache)),
18469 &palette_uv_cache,
18470 lmi.0,
18471 lmi.1,
18472 fctx,
18473 )?;
18474 if let Some(dv) = intrabc {
18475 return decode_rect4_16_intrabc(
18476 dec,
18477 cdfs,
18478 neighbours,
18479 lmi,
18480 horz,
18481 has_chroma,
18482 skip,
18483 dv,
18484 y,
18485 u,
18486 v,
18487 base_q_idx,
18488 tx_select,
18489 reduced_tx_set,
18490 fctx,
18491 );
18492 }
18493 if palette_y.is_some() || palette_uv.is_some() {
18494 hit!(RECT4_PALETTE_HITS);
18495 }
18496 // The colour-index map through the base colours IS the prediction.
18497 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
18498 // chroma transform this closing strip codes.
18499 let palette_y_buf: Option<Vec<u16>> = palette_y
18500 .as_ref()
18501 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
18502 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
18503 (
18504 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
18505 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
18506 )
18507 });
18508 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
18509 if smooth_neighbor {
18510 hit!(SMOOTH_LUMA_HITS);
18511 }
18512 if filter_intra.is_some() {
18513 hit!(FILTER_INTRA_RECT_HITS);
18514 }
18515 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
18516 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
18517 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
18518 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
18519 // lane-av1mixloss: the lossless-segment early return
18520 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a
18521 // lossless-segment strip codes no depth symbol here either (class
18522 // sweep of the sub8 leaf's fix).
18523 let depth = if tx_select && !lossless(fctx) {
18524 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
18525 // (`get_tx_size_context`, libaom `pred_common.h:342`).
18526 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
18527 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
18528 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18529 eprintln!(
18530 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
18531 lmi.0,
18532 lmi.1,
18533 dec.debug_state().0
18534 );
18535 }
18536 d
18537 } else {
18538 0
18539 };
18540 if depth != 0 {
18541 hit!(TX_DEPTH_HITS);
18542 hit!(RECT4_16_SPLIT_HITS);
18543 }
18544 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
18545 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
18546 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
18547 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
18548 if depth != 0 || lossless(fctx) {
18549 // [`decode_rect_split`]'s per-unit walk, inlined because the
18550 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
18551 // the strip (that function codes one chroma transform per block).
18552 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
18553 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
18554 // unit predicts off the units before it in raster order.
18555 let rect_unit = tx_w != tx_h;
18556 let zero_tu = vec![0i32; tx_w * tx_h];
18557 for tu_row in 0..bh / tx_h {
18558 for tu_col in 0..bw / tx_w {
18559 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
18560 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
18561 let tu_reach =
18562 Reach::of_tu(bw, bh, tu_col * tx_w, tu_row * tx_h, tx_w, tx_h, reach);
18563 if let Some(b) = &palette_y_buf {
18564 let tu_buf: Vec<u16> = (0..tx_h)
18565 .flat_map(|i| {
18566 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
18567 b[base..base + tx_w].iter().copied()
18568 })
18569 .collect();
18570 set_palette_pred(tu_buf, fctx);
18571 }
18572 if skip {
18573 push_intra_rect(
18574 0,
18575 tu_px,
18576 tu_py,
18577 tx_w,
18578 tx_h,
18579 mode,
18580 angle_delta_y,
18581 tu_reach,
18582 &zero_tu,
18583 None,
18584 filter_intra,
18585 smooth_neighbor,
18586 fctx,
18587 );
18588 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
18589 } else if rect_unit {
18590 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
18591 // 32 coded positions and the `TX_4X4` `tx_type` row:
18592 // exactly [`TxbSet::LumaRect4x8`].
18593 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
18594 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
18595 let set = if reduced_tx_set {
18596 TxbSet::LumaRect4x8
18597 } else {
18598 TxbSet::LumaRect4x8Set1
18599 };
18600 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
18601 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
18602 let (tu_grid, tu_tx_type) = read_coeffs_rect(
18603 dec,
18604 &mut coding,
18605 tu_scan,
18606 tx_w,
18607 tx_h,
18608 tu_skip_ctx,
18609 dc_sign_ctx(tu_around.2),
18610 TxType::DctDct,
18611 0,
18612 )?;
18613 let residual = dequant_and_inverse_typed_wh(
18614 &tu_grid,
18615 tx_w,
18616 tx_h,
18617 crate::decode::bit_depth(fctx),
18618 block_q_idx(fctx),
18619 plane_q_delta(0, fctx).0,
18620 plane_q_delta(0, fctx).1,
18621 tu_tx_type,
18622 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
18623 );
18624 push_intra_rect(
18625 0,
18626 tu_px,
18627 tu_py,
18628 tx_w,
18629 tx_h,
18630 mode,
18631 angle_delta_y,
18632 tu_reach,
18633 &residual,
18634 None,
18635 filter_intra,
18636 smooth_neighbor,
18637 fctx,
18638 );
18639 if tu_grid.iter().any(|&l| l != 0) {
18640 hit!(RECT4_16_COEFF_HITS);
18641 }
18642 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
18643 } else {
18644 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
18645 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
18646 let tu_grid = read_plane(
18647 dec,
18648 cdfs,
18649 txbset_for(tx_w, reduced_tx_set),
18650 default_scan(tx_w),
18651 0,
18652 tu_around,
18653 mode,
18654 mode,
18655 angle_delta_y,
18656 tu_reach,
18657 y,
18658 tu_px,
18659 tu_py,
18660 tx_w,
18661 tx_w,
18662 base_q_idx,
18663 None,
18664 filter_intra,
18665 Some(tu_skip_ctx),
18666 smooth_neighbor,
18667 fctx,
18668 )?;
18669 if tu_grid.iter().any(|&l| l != 0) {
18670 hit!(RECT4_16_COEFF_HITS);
18671 }
18672 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
18673 }
18674 }
18675 }
18676 } else {
18677 let levels = if skip {
18678 let zeros = Grid::Zero(bw * bh);
18679 if let Some(b) = &palette_y_buf {
18680 set_palette_pred(b.clone(), fctx);
18681 }
18682 push_intra_rect(
18683 0,
18684 px,
18685 py,
18686 bw,
18687 bh,
18688 mode,
18689 angle_delta_y,
18690 reach,
18691 &zeros,
18692 None,
18693 filter_intra,
18694 smooth_neighbor,
18695 fctx,
18696 );
18697 zeros
18698 } else {
18699 // The strip's luma TU *is* the strip (`plane_bsize ==
18700 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
18701 // `txb_skip_ctx` at 0.
18702 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
18703 let set = if reduced_tx_set {
18704 TxbSet::LumaRect16x4
18705 } else {
18706 TxbSet::LumaRect16x4Set1
18707 };
18708 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
18709 let (levels, tx_type) = read_coeffs_rect(
18710 dec,
18711 &mut coding,
18712 scan,
18713 bw,
18714 bh,
18715 0,
18716 dc_sign_ctx(around.2),
18717 TxType::DctDct,
18718 0,
18719 )?;
18720 let residual = dequant_and_inverse_typed_wh(
18721 &levels,
18722 bw,
18723 bh,
18724 crate::decode::bit_depth(fctx),
18725 block_q_idx(fctx),
18726 plane_q_delta(0, fctx).0,
18727 plane_q_delta(0, fctx).1,
18728 tx_type,
18729 block_iqmatrix(fctx, 0, bw, bh, tx_type),
18730 );
18731 if let Some(b) = &palette_y_buf {
18732 set_palette_pred(b.clone(), fctx);
18733 }
18734 push_intra_rect(
18735 0,
18736 px,
18737 py,
18738 bw,
18739 bh,
18740 mode,
18741 angle_delta_y,
18742 reach,
18743 &residual,
18744 None,
18745 filter_intra,
18746 smooth_neighbor,
18747 fctx,
18748 );
18749 hit!(RECT4_16_COEFF_HITS);
18750 levels
18751 };
18752 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
18753 }
18754 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
18755 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
18756 // `update_partition_context` writes `partition_context_lookup[
18757 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
18758 // the left (mirrored under VERT_4).
18759 for cell in 0..mi_w {
18760 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
18761 *slot = bw as u8;
18762 }
18763 }
18764 for cell in 0..mi_h {
18765 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
18766 *slot = bh as u8;
18767 }
18768 }
18769 if has_chroma {
18770 hit!(RECT4_16_CHROMA_HITS);
18771 // lane-av1-444: at 4:4:4 there is no pair -- every strip is its
18772 // own chroma reference and codes its own 16x4 / 4x16 chroma
18773 // block. (`set_mi_offsets`'s chroma snap is the zero offset at
18774 // ss 0/0, so the neighbour reads below anchor at the strip.)
18775 let (pair_mi, pw, ph) = if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
18776 (lmi, bw, bh)
18777 } else if ss_y(fctx) == 0 && horz {
18778 // lane-av1-422: chroma height is NOT subsampled, so a HORZ
18779 // 16x4 strip is its own chroma reference (`is_chroma_reference`
18780 // at ss(1,0): bh == 1 mi, so the row clause reduces to
18781 // `!ss_y`) and codes its own `ss_size_lookup[BLOCK_16X4][1][0]`
18782 // = BLOCK_8X4 chroma block -- a valid transform, no pair.
18783 // (lane-av1-422o: a VERTICAL 4x16 strip now falls through to
18784 // the pair merge below -- its own chroma block
18785 // `ss_size_lookup[BLOCK_4X16][1][0]` is BLOCK_INVALID, the
18786 // walk proved such leaves exist, and libaom codes the pair's
18787 // chroma from the closing strip; the chunk lives in the
18788 // `chroma422_pair16` arm below.)
18789 (lmi, bw, bh)
18790 } else if horz {
18791 ((lmi.0 - 1, lmi.1), 16, 8)
18792 } else {
18793 ((lmi.0, lmi.1 - 1), 8, 16)
18794 };
18795 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
18796 let (cpx, cpy) = (ppx >> ss_x(fctx), ppy >> ss_y(fctx));
18797 let (cw, ch) = (pw >> ss_x(fctx), ph >> ss_y(fctx));
18798 // lane-av1-422o: the 4:2:2 pair's chroma of a VERT 4x16 strip
18799 // pair: (4, 16) at ss(1,0). The bsize is still BLOCK_4X16, whose
18800 // `ss_size_lookup[..][1][0]` is BLOCK_INVALID, so libaom's
18801 // `av1_get_tx_size` reads `max_txsize_rect_lookup[255]` -- the
18802 // out-of-bounds byte is TX_4X8 in the pinned Release oracle, and
18803 // `av1_get_adjusted_tx_size` has no TX_4X8 case to adjust it.
18804 // `decode_token_recon_block` walks unit_width =
18805 // ROUND_POWER_OF_TWO(1, 1) = 1, unit_height = 4, with stepr =
18806 // tx_size_high_unit[TX_4X8] = 2: TWO TX_4X8 units per plane
18807 // (chroma rows 0..8 and 8..16), plane-major. Even the skip arm
18808 // walks per unit: `predict_and_reconstruct_intra_block` predicts
18809 // every unit regardless of `skip_txfm`.
18810 let chroma422_pair16 = (cw, ch) == (4, 16) && ss_x(fctx) == 1;
18811 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
18812 DC_PRED
18813 } else {
18814 uv_mode
18815 };
18816 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
18817 hit!(RECT4_16_CHROMA_DIR_HITS);
18818 }
18819 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
18820 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
18821 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
18822 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
18823 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
18824 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
18825 // the pair's top-left luma mi, never this leaf's odd row/column.
18826 // Reading `lmi` here named the leaf directly above (a non-chroma
18827 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
18828 // SMOOTH neighbour: filt_type 0 instead of 1 turned
18829 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
18830 // directional chroma strip, moving 4 samples by 1.
18831 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c, fctx);
18832 // lane-av1422warp: `smooth_uv_neighbour_unsnapped` now takes the
18833 // frame's own `ss_x` -- the unsnapped read is the pair-merge witness
18834 // counter's mirror of the snapping form, and the shipped read offsets
18835 // the above COLUMN by `+ss_x` (libaom's `chroma_above_mi`).
18836 //
18837 // lane-av1leftwit: this mirror is NOT evidence about the left read's
18838 // `+ss_y` term, whatever a report once said. It reads the leaf's own
18839 // (odd) mi row, which no decode call site does -- every one of them
18840 // uses the snapping form, whose base row is even -- and its result
18841 // feeds `RECT4_16_UV_PAIR_FILT_HITS` only. What it measures is real
18842 // and worth keeping (the pair's chroma-reference read against the
18843 // leaf's own row: 51/24/121/0/1 hits on the five fixtures censused),
18844 // so it stays; the decode path's own reach for the `+ss_y` term is
18845 // `uv_left_1mi_split_hits()`.
18846 if smooth_neighbor_uv
18847 != neighbours.smooth_uv_neighbour_unsnapped(
18848 lmi.0,
18849 lmi.1,
18850 r,
18851 c,
18852 ss_x(fctx),
18853 ss_y(fctx),
18854 false,
18855 )
18856 {
18857 hit!(RECT4_16_UV_PAIR_FILT_HITS);
18858 }
18859 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane
18860 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is
18861 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major
18862 // (`decode_token_recon_block`), not one `ChromaRect8x4`. Reading
18863 // the rect here consumed one symbol block too few and desynced
18864 // the next strip's `skip` (measured: lossless sb128 320x240,
18865 // mi(1,20) uv_mode matched, the following skip did not).
18866 let lossless_pair = lossless(fctx);
18867 let (u_levels, v_levels) = if lossless_pair {
18868 hit!(RECT4_16_LOSSLESS_CHROMA_HITS);
18869 if skip {
18870 for plane in 1..3usize {
18871 for rr in 0..ch / 4 {
18872 for cc in 0..cw / 4 {
18873 let (ox, oy) = (cc * 4, rr * 4);
18874 // The unit's origin and extent in LUMA pixels: `<< ss`
18875 // at 4:2:0 (8x8 luma for a 4x4 chroma unit), identity
18876 // at 4:4:4 -- the same form as the block-walk sibling
18877 // at decode.rs:35342. The hardcoded `ox * 2 / 8` is
18878 // only right at ss (1,1): at 4:4:4 it claims a 4x4
18879 // chroma unit is 8x8 luma, so `of_tu`'s
18880 // `col_off + tx_w < bw` test answers against a
18881 // footprint twice the real one and every unit past
18882 // the block's midpoint wrongly reports
18883 // `above_right = false` -- a directional chroma
18884 // strip then predicts from a neighbour libaom
18885 // never reads (measured: key frame 0, 4:4:4 lossless
18886 // 16x4 strip at (104,26), U 29 + V 34 samples wrong,
18887 // entropy bit-identical over 351109 EC_SYMR reads).
18888 let cu_reach = tu_reach(
18889 pw,
18890 ph,
18891 ox << ss_x(fctx),
18892 oy << ss_y(fctx),
18893 4 << ss_x(fctx),
18894 pair_reach,
18895 ppx,
18896 ppy,
18897 y.width,
18898 y.height,
18899 fctx,
18900 );
18901 if let Some((ub, vb)) = &palette_uv_bufs {
18902 let buf = if plane == 1 { ub } else { vb };
18903 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
18904 }
18905 push_intra(
18906 plane,
18907 cpx + ox,
18908 cpy + oy,
18909 4,
18910 uv_predict_mode,
18911 angle_delta_uv,
18912 cu_reach,
18913 &ZERO_RESIDUAL[..16],
18914 None,
18915 None,
18916 smooth_neighbor_uv,
18917 fctx,
18918 );
18919 let cu_mi = (
18920 pair_mi.0 + (oy << ss_y(fctx)) / MI,
18921 pair_mi.1 + (ox << ss_x(fctx)) / MI,
18922 );
18923 neighbours.record_mi_chroma(
18924 cu_mi,
18925 4 << ss_x(fctx),
18926 4 << ss_y(fctx),
18927 plane,
18928 &ZERO_RESIDUAL[..16],
18929 );
18930 }
18931 }
18932 }
18933 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
18934 } else {
18935 let scan4 = default_scan(4);
18936 // `get_txb_ctx`: offset 10 (our tables store it at +3)
18937 // when the plane block is larger than the transform.
18938 let offset = Some(3usize);
18939 let mut uo = vec![0i32; cw * ch];
18940 let mut vo = vec![0i32; cw * ch];
18941 for plane in 1..3usize {
18942 for rr in 0..ch / 4 {
18943 for cc in 0..cw / 4 {
18944 let (ox, oy) = (cc * 4, rr * 4);
18945 if cpx + ox >= u.true_width || cpy + oy >= u.true_height {
18946 continue;
18947 }
18948 // The unit's stamp is its own span: aom
18949 // `av1_set_entropy_contexts` (blockd.c:29)
18950 // memsets exactly `tx_size_wide_unit` x
18951 // `tx_size_high_unit` cells at the unit's own
18952 // `(aoff, loff)` -- for TX_4X4 ONE above cell
18953 // and ONE left cell. `(oy / 2, ox / 2)` +
18954 // `(8, 8)` is the 4:2:0 subsampled form (one
18955 // chroma cell = 8 luma px = 2 mi cells); at
18956 // 4:4:4 a unit is ONE mi cell, and the 2x2
18957 // smear let a 4-wide strip's later units
18958 // overwrite the NEXT COLUMN's above cell with
18959 // their own state -- a column aom never sees
18960 // this block write -- so the following block's
18961 // `all_zero` read the wrong `txb_skip` row
18962 // (frame-0 read #452, the llkf named gap).
18963 let cu_mi = (
18964 pair_mi.0 + (oy << ss_y(fctx)) / MI,
18965 pair_mi.1 + (ox << ss_x(fctx)) / MI,
18966 );
18967 // One luma-mi cell: the chroma entropy arrays
18968 // are subsampled, and our bands replicate that
18969 // one entry over the unit's two cells
18970 // (`read_intra_chroma_lossless`).
18971 let cu_around = neighbours.around_mi(cu_mi, MI);
18972 // Same ss-aware luma footprint as the skip arm
18973 // above -- `ox * 2 / 8` is the 4:2:0-only form and
18974 // mis-answers `of_tu` at 4:4:4 (see there).
18975 let cu_reach = tu_reach(
18976 pw,
18977 ph,
18978 ox << ss_x(fctx),
18979 oy << ss_y(fctx),
18980 4 << ss_x(fctx),
18981 pair_reach,
18982 ppx,
18983 ppy,
18984 y.width,
18985 y.height,
18986 fctx,
18987 );
18988 if let Some((ub, vb)) = &palette_uv_bufs {
18989 let buf = if plane == 1 { ub } else { vb };
18990 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
18991 }
18992 let buf: &mut PlaneBuf<'static> =
18993 if plane == 1 { &mut *u } else { &mut *v };
18994 let cu_grid = read_plane(
18995 dec,
18996 cdfs,
18997 TxbSet::Chroma4,
18998 &scan4,
18999 plane,
19000 cu_around[plane],
19001 mode,
19002 uv_predict_mode,
19003 angle_delta_uv,
19004 cu_reach,
19005 buf,
19006 cpx + ox,
19007 cpy + oy,
19008 4,
19009 4,
19010 base_q_idx,
19011 None,
19012 None,
19013 offset,
19014 smooth_neighbor_uv,
19015 fctx,
19016 )?;
19017 neighbours.record_mi_chroma(
19018 cu_mi,
19019 4 << ss_x(fctx),
19020 4 << ss_y(fctx),
19021 plane,
19022 &cu_grid,
19023 );
19024 hit!(CHROMA_SPLIT_TX_HITS);
19025 let dst = if plane == 1 { &mut uo } else { &mut vo };
19026 for row in 0..4 {
19027 let start = (oy + row) * cw + ox;
19028 dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]);
19029 }
19030 }
19031 }
19032 }
19033 (Grid::Own(uo), Grid::Own(vo))
19034 }
19035 } else if skip {
19036 let zeros = Grid::Zero(cw * ch);
19037 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
19038 // ~1000) predicts EVERY plane and only guards the residual on
19039 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
19040 // DC + alpha * luma-AC. Dropping the CfL term here left a
19041 // chroma-only bounded box on ReelC's key frames.
19042 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
19043 if alpha.is_some() {
19044 hit!(CHROMA_SKIP_CFL_HITS);
19045 }
19046 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
19047 if chroma422_pair16 {
19048 // lane-av1-422o: two TX_4X8 units, each predicted on
19049 // its own edges (the lower one off the upper one's
19050 // samples); no coefficients are coded, and libaom's
19051 // `set_entropy_context` zeroed the block's own cells,
19052 // so the pair-wide zero stamp below stays correct.
19053 for unit_row in 0..2usize {
19054 let unit_reach = tu_reach_rect(
19055 pw,
19056 ph,
19057 0,
19058 unit_row * 8,
19059 8,
19060 8,
19061 pair_reach,
19062 ppx,
19063 ppy,
19064 y.width,
19065 y.height,
19066 fctx,
19067 );
19068 if let Some((ub, vb)) = &palette_uv_bufs {
19069 let pbuf = if plane == 1 { ub } else { vb };
19070 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
19071 }
19072 push_intra_rect(
19073 plane,
19074 cpx,
19075 cpy + unit_row * 8,
19076 4,
19077 8,
19078 uv_predict_mode,
19079 angle_delta_uv,
19080 unit_reach,
19081 &ZERO_RESIDUAL[..4 * 8],
19082 alpha
19083 .zip(ac)
19084 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
19085 None,
19086 smooth_neighbor_uv,
19087 fctx,
19088 );
19089 }
19090 } else {
19091 if let Some((ub, vb)) = &palette_uv_bufs {
19092 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
19093 }
19094 push_intra_rect(
19095 plane,
19096 cpx,
19097 cpy,
19098 cw,
19099 ch,
19100 uv_predict_mode,
19101 angle_delta_uv,
19102 pair_reach,
19103 &zeros,
19104 alpha
19105 .zip(ac)
19106 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
19107 None,
19108 smooth_neighbor_uv,
19109 fctx,
19110 );
19111 }
19112 }
19113 (zeros.clone(), zeros)
19114 } else if chroma422_pair16 {
19115 // lane-av1-422o: the pair's 4x16 chroma as TWO TX_4X8 units
19116 // per plane, plane-major (every U unit, then every V). Each
19117 // unit: the `ChromaRect8x4` tables (`get_txsize_entropy_ctx`
19118 // squares TX_4X8 up to the 8x8 class), `SCAN_4X8`, and a
19119 // `txb_skip_ctx` of above+left in the OFFSET-10 rows -- the
19120 // offset comes from `num_pels_log2_lookup[plane_bsize] >
19121 // num_pels_log2_lookup[BLOCK_4X8]` with plane_bsize =
19122 // BLOCK_INVALID (255), and the byte at that table's +255 in
19123 // the pinned Release oracle is 255 (`cmpb` against the
19124 // `0xc0db70` copy decodetxb.c links), i.e. the bigger-plane
19125 // arm: +3 on the offset-7-first chroma tables. No tx_type
19126 // symbol (only y plane's is transmitted); the unit's type is
19127 // `intra_mode_to_tx_type(UV mode)` kept by the all-16 ext-tx
19128 // set -- [`read_rect_chroma_unit`]'s own default. CfL params
19129 // are computed ONCE per block (`are_parameters_computed`)
19130 // over the pair's luma, shared by both units. Each unit is
19131 // predicted and recorded immediately, so the lower unit
19132 // reads the upper one's coefficient context.
19133 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
19134 for (plane, buf) in [(1usize, &mut *u), (2usize, &mut *v)] {
19135 for unit_row in 0..2usize {
19136 let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1);
19137 let unit_reach = tu_reach_rect(
19138 pw,
19139 ph,
19140 0,
19141 unit_row * 8,
19142 8,
19143 8,
19144 pair_reach,
19145 ppx,
19146 ppy,
19147 y.width,
19148 y.height,
19149 fctx,
19150 );
19151 if let Some((ub, vb)) = &palette_uv_bufs {
19152 let pbuf = if plane == 1 { ub } else { vb };
19153 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
19154 }
19155 let chroma_around = neighbours.around_mi_422_chroma(unit_mi, 8, 8);
19156 let unit_grid = read_rect_chroma_unit(
19157 dec,
19158 cdfs,
19159 TxbSet::ChromaRect8x4,
19160 &SCAN_4X8,
19161 4,
19162 8,
19163 plane,
19164 chroma_around[plane],
19165 uv_predict_mode,
19166 angle_delta_uv,
19167 unit_reach,
19168 buf,
19169 cpx,
19170 cpy + unit_row * 8,
19171 base_q_idx,
19172 // lane-av1-422q: the offset-10 rows -- the same
19173 // measured rule as the 4x32 arm (plane_bsize
19174 // BLOCK_INVALID for the pair's BLOCK_4X16 too;
19175 // num_pels_log2_lookup[255] = 0xff at the
19176 // 0xc0de70 copy -> +3 on the offset-7-first
19177 // chroma tables; see lanes/av1422q.report.md).
19178 Some(3),
19179 alpha
19180 .zip(ac)
19181 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
19182 smooth_neighbor_uv,
19183 fctx,
19184 )?;
19185 neighbours.record_mi_chroma(unit_mi, 8, 8, plane, &unit_grid);
19186 }
19187 }
19188 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
19189 } else {
19190 // lane-av1422ctxgather: 4:2:2's chroma above votes sample
19191 // every second luma-mi cell
19192 // ([`Neighbours::around_mi_422_chroma`]: at ss_x 1 one
19193 // chroma 4-px column spans two luma mi columns, and the
19194 // plain per-mi gather counts each column's whole-unit dc
19195 // sign twice). The left extent is unsubsampled at ss_y 0,
19196 // so its per-mi cells already line up one-to-one.
19197 let around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
19198 neighbours.around_mi_422_chroma(pair_mi, pw, ph)
19199 } else {
19200 neighbours.around_mi_rect(pair_mi, pw, ph)
19201 };
19202 // lane-av1-444: the strip's own 16x4 / 4x16 chroma at ss 0/0
19203 // (`TxbSet::Chroma8`, `get_txsize_entropy_ctx(TX_16X4)` =
19204 // the 8x8 set); 4:2:0 keeps the pair's 8x4 / 4x8.
19205 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (cw, ch) {
19206 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
19207 (4, 8) => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
19208 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
19209 // lane-av1-444: 4:4:4's own-strip vert chroma is (4,16)
19210 // -- one TX_4X16. (lane-av1-422o: the 4:2:2 pair's
19211 // (4,16) never reaches this row; `chroma422_pair16`
19212 // intercepts it above and chunks it into TX_4X8 units.)
19213 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
19214 // lane-av1-422: a 4:2:2 HORZ pair (16x8 luma) keeps the
19215 // pair's height: an 8x8 SQUARE chroma block, the same
19216 // `TxbSet::Chroma8` set any 8x8 chroma plane reads. The
19217 // 4:2:0 pair's chroma is 8x4 and 4:4:4's is 16x4, so this
19218 // row is unreachable there. It is also the witness arm:
19219 // a restored `/2 chroma height` lands on (8,4) and the
19220 // counter reads 0.
19221 (8, 8) => {
19222 hit!(CHROMA422_SQUARE_HITS);
19223 (TxbSet::Chroma8, default_scan(8))
19224 }
19225 // lane-av1-422o: with the `chroma422_pair16` arm above,
19226 // the (2,16) own-strip shape and the 4:4:4 shapes are the
19227 // only residents; anything else is a named-lane gap.
19228 _ => unreachable!("decode_rect4_16_strip chroma shape set is closed"),
19229 };
19230 let mut planes = Vec::with_capacity(2);
19231 for plane in 1..3 {
19232 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
19233 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
19234 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
19235 let (levels, tx_type) = read_chroma_coeffs_rect(
19236 dec,
19237 &mut coding,
19238 chroma_scan,
19239 cw,
19240 ch,
19241 skip_ctx,
19242 dc_sign_ctx(around[plane].2),
19243 default_tx,
19244 fctx,
19245 plane,
19246 )?;
19247 planes.push((levels, tx_type));
19248 }
19249 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
19250 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
19251 // CfL averages the luma of the WHOLE pair, the region this one
19252 // chroma transform covers.
19253 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
19254 for (plane, _buf, levels, tx_type) in [
19255 (1usize, &mut *u, &u_levels, u_tx_type),
19256 (2, &mut *v, &v_levels, v_tx_type),
19257 ] {
19258 let residual = dequant_and_inverse_typed_wh(
19259 levels,
19260 cw,
19261 ch,
19262 crate::decode::bit_depth(fctx),
19263 block_q_idx(fctx),
19264 plane_q_delta(plane, fctx).0,
19265 plane_q_delta(plane, fctx).1,
19266 tx_type,
19267 block_iqmatrix(fctx, plane, cw, ch, tx_type),
19268 );
19269 if let Some((ub, vb)) = &palette_uv_bufs {
19270 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
19271 }
19272 push_intra_rect(
19273 plane,
19274 cpx,
19275 cpy,
19276 cw,
19277 ch,
19278 uv_predict_mode,
19279 angle_delta_uv,
19280 pair_reach,
19281 &residual,
19282 alpha
19283 .zip(ac)
19284 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
19285 None,
19286 smooth_neighbor_uv,
19287 fctx,
19288 );
19289 }
19290 (u_levels, v_levels)
19291 };
19292 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
19293 // A lossless pair already stamped each TX_4X4 (`record_mi_chroma`).
19294 // The single-state rewrite below is the non-lossless TX_8X4/TX_4X8.
19295 // lane-av1-422o: the chunked pair's cells are stamped PER UNIT in
19296 // the arm above (libaom's coefficient contexts are per
19297 // 4x4-cell); a pair-wide state would erase the unit boundary the
19298 // next block reads.
19299 if !lossless_pair && !chroma422_pair16 {
19300 // The chroma planes' coefficient context, over the PAIR's mi span
19301 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
19302 // the luma one rounded up to its 4x4 unit).
19303 let u_state = neighbour_state(&u_levels);
19304 let v_state = neighbour_state(&v_levels);
19305 let round_up_even = |n: usize| n.div_ceil(2) * 2;
19306 let bound_h = round_up_even(neighbours.mi_rows);
19307 let bound_w = round_up_even(neighbours.mi_cols);
19308 for cell in 0..(ph / MI) {
19309 if pair_mi.0 + cell < bound_h
19310 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
19311 {
19312 slot[1] = u_state;
19313 slot[2] = v_state;
19314 }
19315 }
19316 for cell in 0..(pw / MI) {
19317 if pair_mi.1 + cell < bound_w
19318 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
19319 {
19320 slot[1] = u_state;
19321 slot[2] = v_state;
19322 }
19323 }
19324 }
19325 last_uv_mode = Some(uv_predict_mode);
19326 }
19327 if horz {
19328 hit!(RECT4_16_HORZ_HITS);
19329 } else {
19330 hit!(RECT4_16_VERT_HITS);
19331 }
19332 let (pal_y_size, pal_y_colors) = palette_y
19333 .as_ref()
19334 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
19335 let (pal_uv_size, pal_uv_colors) = palette_uv
19336 .as_ref()
19337 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
19338 record_strip_palette(
19339 neighbours,
19340 lmi,
19341 bw,
19342 bh,
19343 pal_y_size,
19344 pal_y_colors,
19345 pal_uv_size,
19346 pal_uv_colors,
19347 );
19348 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
19349 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
19350 // frame): the above row records `tx_size_wide` over the block's width and
19351 // the left column `tx_size_high` over its height. This 1:4 strip reader is
19352 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
19353 // and it published neither band -- so the block after a 64x16 strip read
19354 // the row's init value 64 as its left transform height and took
19355 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
19356 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
19357 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
19358 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
19359 Ok((mode, last_uv_mode, (tx_w, tx_h)))
19360}
19361
19362/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
19363/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
19364/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
19365/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
19366/// cap, so LUMA needs the same corner truncation [`decode_block`] already
19367/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
19368/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
19369/// this function's own charter/report), so both strips read a real 32x32
19370/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
19371/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
19372/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
19373/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
19374/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
19375/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
19376/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
19377/// that function, only the single-transform-unit (`tx_depth == 0`) case is
19378/// supported: a split transform refuses by name rather than guess-decode.
19379#[allow(clippy::too_many_arguments)]
19380fn decode_block_rect64(
19381 dec: &mut SymbolDecoder,
19382 cdfs: &mut Cdfs,
19383 neighbours: &mut Neighbours,
19384 at: (usize, usize),
19385 bw: usize,
19386 bh: usize,
19387 y: &mut PlaneBuf<'static>,
19388 u: &mut PlaneBuf<'static>,
19389 v: &mut PlaneBuf<'static>,
19390 enable_filter_intra: bool,
19391 allow_screen_content_tools: bool,
19392 base_q_idx: u8,
19393 tx_select: bool,
19394 reduced_tx_set: bool,
19395 fctx: &crate::decode::FrameCtx,
19396) -> Result<()> {
19397 let (r, c) = at;
19398 let (px, py) = (c * SUB, r * SUB);
19399 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
19400 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
19401 let palette_uv_cache = neighbours.palette_uv_cache(at);
19402 let (
19403 skip,
19404 mode,
19405 angle_delta_y,
19406 uv_mode,
19407 angle_delta_uv,
19408 alpha,
19409 filter_intra,
19410 palette_y,
19411 palette_uv,
19412 intrabc,
19413 ) = read_intra_mode_rect(
19414 dec,
19415 cdfs,
19416 nb_above_mode,
19417 nb_left_mode,
19418 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
19419 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
19420 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
19421 // correct), CFL must never be offered here -- passing `true`
19422 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
19423 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
19424 // from this block's very first symbol (lane-sbpart r3 bisect).
19425 false,
19426 true,
19427 bw,
19428 bh,
19429 enable_filter_intra,
19430 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
19431 allow_screen_content_tools,
19432 Some((palette_ctx, &palette_cache)),
19433 &palette_uv_cache,
19434 r * (SUB / MI),
19435 c * (SUB / MI),
19436 fctx,
19437 )?;
19438 if let Some((dv_row, dv_col)) = intrabc {
19439 return decode_intrabc_owned_rect(
19440 dec,
19441 cdfs,
19442 neighbours,
19443 (r * (SUB / MI), c * (SUB / MI)),
19444 (bw, bh),
19445 skip,
19446 (dv_row, dv_col),
19447 y,
19448 u,
19449 v,
19450 base_q_idx,
19451 tx_select,
19452 reduced_tx_set,
19453 fctx,
19454 );
19455 }
19456 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
19457 // lane-t900 r34: a non-skip palette block on a superblock-level strip
19458 // -- counted so its gate cannot go vacuous (this was a refusal until
19459 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
19460 // decodes_pixel_exact`).
19461 hit!(PALETTE_SB_STRIP_HITS);
19462 }
19463 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
19464 if smooth_neighbor {
19465 hit!(SMOOTH_LUMA_HITS);
19466 }
19467 let smooth_neighbor_uv =
19468 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
19469 if filter_intra.is_some() {
19470 // `filter_intra_size_class_rect` already returns `None` for both
19471 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
19472 // 32 on both axes), so this symbol is never read at this level --
19473 // kept only as the same defensive refusal [`decode_block_rect`] has.
19474 return Err(unsupported(
19475 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
19476 av1_filter_intra_allowed_bsize caps at 32x32)",
19477 ));
19478 }
19479 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
19480 DC_PRED
19481 } else {
19482 uv_mode
19483 };
19484 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
19485 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
19486 // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes
19487 // no depth symbol here either (class sweep of the sub8 leaf's fix).
19488 let depth = if tx_select && !lossless(fctx) {
19489 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
19490 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
19491 // intra-only frame publishes them from every block too
19492 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
19493 // 1920x792 128-superblock stream,
19494 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
19495 // `tx_size_cat2` row 1 where libaom reads row 2.
19496 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
19497 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
19498 // counts `sub_tx_size_map` steps from the block's own max rect
19499 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
19500 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
19501 // steps, so this level's category is 3 (the same one a 64x64 square
19502 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
19503 // here was a wrong-table read of a real symbol.
19504 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
19505 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
19506 eprintln!(
19507 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
19508 dec.debug_state().0
19509 );
19510 }
19511 d
19512 } else {
19513 0
19514 };
19515 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
19516 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
19517 publish_txfm_bands_if_in_inter(
19518 neighbours,
19519 (mi_r, mi_c),
19520 depth_to_tx_wh(bw, bh, depth, fctx),
19521 (bw, bh),
19522 fctx,
19523 );
19524 if depth != 0 || lossless(fctx) {
19525 hit!(TX_DEPTH_HITS);
19526 // lane-rectsplit r1/r4: the superblock-level strip splits its
19527 // transform through the very same per-unit path as its 32x32-level
19528 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
19529 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
19530 // measured the old square formula mis-tiling exactly that strip).
19531 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
19532 if bw.max(bh) / bw.min(bh) == 4 {
19533 let which = if depth == 1 {
19534 &RECT4_SPLIT_DEPTH1_HITS
19535 } else {
19536 &RECT4_SPLIT_DEPTH2_HITS
19537 };
19538 hit_do! { which.with(|c| c.set(c.get() + 1)); }
19539 }
19540 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
19541 eprintln!(
19542 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
19543 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
19544 angle_y={angle_delta_y}"
19545 );
19546 }
19547 let modes = RectStripModes {
19548 skip,
19549 mode,
19550 angle_delta_y,
19551 uv_predict_mode,
19552 angle_delta_uv,
19553 alpha,
19554 filter_intra,
19555 smooth_neighbor,
19556 smooth_neighbor_uv,
19557 palette_y: palette_y
19558 .as_ref()
19559 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
19560 palette_uv: palette_uv.as_ref().map(|p| {
19561 (
19562 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
19563 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
19564 )
19565 }),
19566 };
19567 if palette_y.is_some() || palette_uv.is_some() {
19568 hit!(PALETTE_SPLIT_TX_HITS);
19569 }
19570 decode_rect_split(
19571 dec,
19572 cdfs,
19573 neighbours,
19574 (mi_r, mi_c),
19575 bw,
19576 bh,
19577 tx_w,
19578 tx_h,
19579 &modes,
19580 y,
19581 u,
19582 v,
19583 base_q_idx,
19584 reduced_tx_set,
19585 fctx,
19586 )?;
19587 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
19588 // (lane-palette2 r10): this return skips the fn's own tail, so a
19589 // split-tx superblock strip would otherwise leave the above/left
19590 // palette arrays holding a dead block's colours.
19591 let (py_size, py_colors) = palette_y
19592 .as_ref()
19593 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
19594 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
19595 let (puv_size, puv_colors) = palette_uv
19596 .as_ref()
19597 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
19598 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
19599 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
19600 // return skips the fn's own tail, so a SPLIT superblock-level strip
19601 // published no TXFM_CONTEXT band and the next block read the row's init
19602 // value 64 as its left transform height. Measured on the 10-bit
19603 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
19604 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
19605 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
19606 // bands carry the SPLIT unit's size, not the block's.
19607 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
19608 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
19609 hit!(RECT_PARTITION_HITS);
19610 return Ok(());
19611 }
19612 let (tx_w, tx_h) = (bw, bh);
19613 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
19614 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
19615 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
19616 if let Some(ref pyv) = palette_y {
19617 let buf: Vec<u16> = pyv
19618 .map
19619 .iter()
19620 .map(|&idx| pyv.colors[idx as usize])
19621 .collect();
19622 set_palette_pred(buf, fctx);
19623 }
19624 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
19625 (
19626 puv.map
19627 .iter()
19628 .map(|&idx| puv.u_colors[idx as usize])
19629 .collect(),
19630 puv.map
19631 .iter()
19632 .map(|&idx| puv.v_colors[idx as usize])
19633 .collect(),
19634 )
19635 });
19636 if skip {
19637 push_intra_rect(
19638 0,
19639 px,
19640 py,
19641 bw,
19642 bh,
19643 mode,
19644 angle_delta_y,
19645 reach,
19646 &ZERO_RESIDUAL[..bw * bh],
19647 None,
19648 filter_intra,
19649 smooth_neighbor,
19650 fctx,
19651 );
19652 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
19653 if let Some((ub, _)) = &palette_uv_bufs {
19654 set_palette_pred(ub.clone(), fctx);
19655 }
19656 push_intra_rect(
19657 1,
19658 cpx,
19659 cpy,
19660 chroma_w,
19661 chroma_h,
19662 uv_predict_mode,
19663 angle_delta_uv,
19664 reach,
19665 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19666 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
19667 None,
19668 smooth_neighbor_uv,
19669 fctx,
19670 );
19671 if let Some((_, vb)) = &palette_uv_bufs {
19672 set_palette_pred(vb.clone(), fctx);
19673 }
19674 push_intra_rect(
19675 2,
19676 cpx,
19677 cpy,
19678 chroma_w,
19679 chroma_h,
19680 uv_predict_mode,
19681 angle_delta_uv,
19682 reach,
19683 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19684 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
19685 None,
19686 smooth_neighbor_uv,
19687 fctx,
19688 );
19689 neighbours.record_rect(
19690 at,
19691 bw,
19692 bh,
19693 mode,
19694 uv_predict_mode,
19695 &[
19696 &ZERO_RESIDUAL[..bw * bh],
19697 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19698 &ZERO_RESIDUAL[..chroma_w * chroma_h],
19699 ],
19700 );
19701 } else {
19702 let around = neighbours.around_rect(at, bw, bh);
19703 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
19704 // (see this function's own doc comment). A 64-length axis codes only
19705 // its low 32 coefficients, so the corner is `min(bw, 32)` x
19706 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
19707 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
19708 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
19709 let scan32 = default_scan(TX32);
19710 if coeff_trace_on() {
19711 let (rng, _) = dec.debug_state();
19712 eprintln!(
19713 "EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}"
19714 );
19715 }
19716 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
19717 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
19718 read_coeffs(
19719 dec,
19720 &mut luma_coding,
19721 &scan32,
19722 0,
19723 dc_sign_ctx(around[0].2),
19724 TxType::DctDct,
19725 Some((bw, bh)),
19726 )?
19727 } else {
19728 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
19729 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
19730 // (`scan.c`) gives both the very same `default_scan_32x16` /
19731 // `default_scan_16x32` the 2:1 sizes use ("Half of the
19732 // coefficients of tx64 at higher frequencies are set to zeros. So
19733 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
19734 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
19735 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
19736 // 512-position eob group) -- BOTH identical to TX_32X16, so the
19737 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
19738 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
19739 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
19740 // what `base_ctx_rect` computes at (32, 16).
19741 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
19742 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
19743 read_coeffs_rect(
19744 dec,
19745 &mut luma_coding,
19746 luma_scan,
19747 luma_cw,
19748 luma_ch,
19749 0,
19750 dc_sign_ctx(around[0].2),
19751 TxType::DctDct,
19752 0,
19753 )?
19754 };
19755 if coeff_trace_on() {
19756 let (rng, _) = dec.debug_state();
19757 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
19758 }
19759 let mut luma_levels = vec![0i32; bw * bh];
19760 for row in 0..luma_ch {
19761 luma_levels[row * bw..][..luma_cw]
19762 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
19763 }
19764 {
19765 let cur = block_q_idx(fctx);
19766 if cur != i32::from(base_q_idx) {
19767 hit!(RECT64_QIDX_DRIFT_HITS);
19768 }
19769 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19770 eprintln!(
19771 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
19772 );
19773 }
19774 }
19775 let luma_residual = dequant_and_inverse_typed_wh(
19776 &luma_levels,
19777 bw,
19778 bh,
19779 crate::decode::bit_depth(fctx),
19780 block_q_idx(fctx),
19781 plane_q_delta(0, fctx).0,
19782 plane_q_delta(0, fctx).1,
19783 luma_tx_type,
19784 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
19785 );
19786 push_intra_rect(
19787 0,
19788 px,
19789 py,
19790 bw,
19791 bh,
19792 mode,
19793 angle_delta_y,
19794 reach,
19795 &luma_residual,
19796 None,
19797 filter_intra,
19798 smooth_neighbor,
19799 fctx,
19800 );
19801 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
19802 let leftcol: Vec<u16> = if px > 0 {
19803 (py..py + bh)
19804 .map(|row| y.data[row * y.width + px - 1])
19805 .collect()
19806 } else {
19807 vec![]
19808 };
19809 eprintln!(
19810 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
19811 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
19812 luma_corner.iter().any(|&v| v != 0),
19813 &y.data[py * y.width + px..][..bw],
19814 leftcol,
19815 );
19816 }
19817 // CHROMA. At 4:2:0 the plane block is already one adjusted UV
19818 // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma
19819 // is larger than that, so it is tiled into 32-capped units.
19820 let _ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
19821 let (uw, uh) = (chroma_w.min(32), chroma_h.min(32));
19822 let (nw, nh) = (chroma_w / uw, chroma_h / uh);
19823 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (uw, uh) {
19824 (32, 32) => (TxbSet::Chroma32, default_scan(32)),
19825 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
19826 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
19827 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8),
19828 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
19829 _ => {
19830 return Err(unsupported(
19831 "a 64-axis strip whose chroma unit has no coefficient table",
19832 ));
19833 }
19834 };
19835 let bigger = nw * nh > 1;
19836 let mut u_levels = vec![0i32; chroma_w * chroma_h];
19837 let mut v_levels = vec![0i32; chroma_w * chroma_h];
19838 // The tiled units below stamp their own coefficient context
19839 // immediately, then the whole-strip `record_rect` rewrite paints
19840 // every chroma cell with ONE whole-strip state and the per-unit DC
19841 // signs and levels are lost (class `override-slot-on-one-arm`, same
19842 // shape as `decode_rect_split`'s chroma_tiled clobber). Collected
19843 // here and replayed after that record, the c8 `mu_chroma_units` way.
19844 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
19845 for plane_idx in 1..=2 {
19846 for cu_row in 0..nh {
19847 for cu_col in 0..nw {
19848 let cu_around = if nw == 1 && nh == 1 {
19849 around
19850 } else {
19851 let lsx = uw << ss_x(fctx);
19852 let lsy = uh << ss_y(fctx);
19853 let cu_mi = (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI));
19854 neighbours.around_mi_rect(cu_mi, lsx, lsy)
19855 };
19856 let lsx = uw << ss_x(fctx);
19857 let lsy = uh << ss_y(fctx);
19858 let cfl = alpha.map(|(au, av)| {
19859 let a = if plane_idx == 1 { au } else { av };
19860 (
19861 a,
19862 cfl_src_rect(px + cu_col * lsx, py + cu_row * lsy, lsx, lsy),
19863 )
19864 });
19865 let levels = if uw == uh {
19866 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
19867 if let Some((ub, vb)) = &palette_uv_bufs {
19868 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
19869 }
19870 read_plane(
19871 dec,
19872 cdfs,
19873 chroma_set,
19874 chroma_scan,
19875 plane_idx,
19876 cu_around[plane_idx],
19877 mode,
19878 uv_predict_mode,
19879 angle_delta_uv,
19880 reach,
19881 plane,
19882 cpx + cu_col * uw,
19883 cpy + cu_row * uh,
19884 uw,
19885 uw,
19886 base_q_idx,
19887 cfl,
19888 None,
19889 bigger.then_some(3),
19890 smooth_neighbor_uv,
19891 fctx,
19892 )?
19893 } else {
19894 let skip_ctx = usize::from(cu_around[plane_idx].0)
19895 + usize::from(cu_around[plane_idx].1)
19896 + usize::from(bigger) * 3;
19897 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
19898 let (levels, tx_type) = read_chroma_coeffs_rect(
19899 dec,
19900 &mut coding,
19901 chroma_scan,
19902 uw,
19903 uh,
19904 skip_ctx,
19905 dc_sign_ctx(cu_around[plane_idx].2),
19906 TxType::DctDct,
19907 fctx,
19908 plane_idx,
19909 )?;
19910 let residual = dequant_and_inverse_typed_wh(
19911 &levels,
19912 uw,
19913 uh,
19914 crate::decode::bit_depth(fctx),
19915 block_q_idx(fctx),
19916 plane_q_delta(plane_idx, fctx).0,
19917 plane_q_delta(plane_idx, fctx).1,
19918 tx_type,
19919 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
19920 );
19921 if let Some((ub, vb)) = &palette_uv_bufs {
19922 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
19923 }
19924 push_intra_rect(
19925 plane_idx,
19926 cpx + cu_col * uw,
19927 cpy + cu_row * uh,
19928 uw,
19929 uh,
19930 uv_predict_mode,
19931 angle_delta_uv,
19932 reach,
19933 &residual,
19934 cfl,
19935 None,
19936 smooth_neighbor_uv,
19937 fctx,
19938 );
19939 levels
19940 };
19941 let dst = if plane_idx == 1 {
19942 &mut u_levels
19943 } else {
19944 &mut v_levels
19945 };
19946 for row in 0..uh {
19947 let d = (cu_row * uh + row) * chroma_w + cu_col * uw;
19948 dst[d..d + uw].copy_from_slice(&levels[row * uw..][..uw]);
19949 }
19950 if bigger {
19951 neighbours.record_mi_chroma(
19952 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
19953 lsx,
19954 lsy,
19955 plane_idx,
19956 &levels,
19957 );
19958 tiled_chroma_units.push((
19959 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
19960 plane_idx,
19961 levels.clone(),
19962 lsx,
19963 lsy,
19964 ));
19965 }
19966 }
19967 }
19968 }
19969 neighbours.record_rect(
19970 at,
19971 bw,
19972 bh,
19973 mode,
19974 uv_predict_mode,
19975 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
19976 );
19977 // The per-unit re-stamp: `record_rect` above wrote the whole strip's
19978 // chroma cells from the assembled grids' one whole-strip state,
19979 // overwriting exactly the stamps the tiled loop just made.
19980 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
19981 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
19982 }
19983 hit!(RECT_COEFF_HITS);
19984 }
19985 let (py_size, py_colors) = palette_y
19986 .as_ref()
19987 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
19988 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
19989 let (puv_size, puv_colors) = palette_uv
19990 .as_ref()
19991 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
19992 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
19993 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
19994 neighbours.fill_lf_grid_rect(
19995 (mi_r, mi_c),
19996 bw / MI,
19997 bh / MI,
19998 tx_w as u8,
19999 tx_h as u8,
20000 0,
20001 fctx,
20002 );
20003 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
20004 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
20005 // frame): the above row records `tx_size_wide` over the block's width and
20006 // the left column `tx_size_high` over its height. This 1:4 strip reader is
20007 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
20008 // and it published neither band -- so the block after a 64x16 strip read
20009 // the row's init value 64 as its left transform height and took
20010 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
20011 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
20012 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
20013 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
20014 hit!(SB_RECT_HITS);
20015 match (bw, bh) {
20016 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
20017 (16, 64) => hit!(SB_RECT4_VERT_HITS),
20018 _ => {}
20019 }
20020 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20021 let (rng, _) = dec.debug_state();
20022 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
20023 }
20024 Ok(())
20025}
20026
20027/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
20028/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
20029/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
20030/// it lands away from zero, for gate tests to prove a real stream fired one.
20031fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
20032 let symbol = dec.symbol(cdf);
20033 if symbol != ANGLE_DELTA_ZERO {
20034 hit!(ANGLE_DELTA_HITS);
20035 }
20036 symbol as i32 - ANGLE_DELTA_ZERO as i32
20037}
20038
20039#[allow(clippy::too_many_arguments)]
20040fn read_intra_mode(
20041 dec: &mut SymbolDecoder,
20042 cdfs: &mut Cdfs,
20043 above_mode: usize,
20044 left_mode: usize,
20045 cfl: bool,
20046 side: usize,
20047 enable_filter_intra: bool,
20048 skip_ctx: usize,
20049 allow_screen_content_tools: bool,
20050 allow_intrabc: bool,
20051 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
20052 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
20053 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
20054 // `None` at the excluded call sites (the 8x8-leaf path), which still read
20055 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
20056 // decoder reads either way -- but refuse by name the moment it fires,
20057 // exactly the old behaviour.
20058 palette: Option<(usize, &[u16])>,
20059 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
20060 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
20061 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
20062 // `use_palette_y`, not a neighbour lookup).
20063 palette_uv_cache: &[u16],
20064 mi_r: usize,
20065 mi_c: usize,
20066 fctx: &crate::decode::FrameCtx,
20067) -> Result<(
20068 bool,
20069 usize,
20070 i32,
20071 usize,
20072 i32,
20073 Option<(i32, i32)>,
20074 Option<usize>,
20075 Option<PaletteY>,
20076 Option<PaletteUv>,
20077)> {
20078 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
20079 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
20080 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
20081 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
20082 // line against the instrumented aomdec, not just `tell()`.
20083 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
20084 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
20085 if ec_istep {
20086 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
20087 // (decodemv.c:818), printed at the same point: before the first
20088 // mode-info symbol of the block, so a cross-decoder range ladder can
20089 // be keyed on the BLOCK, not just on the symbol sequence.
20090 eprintln!(
20091 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}",
20092 dec.debug_state().0
20093 );
20094 }
20095 macro_rules! istep {
20096 ($name:literal, $val:expr) => {
20097 if ec_istep {
20098 let (rng, _) = dec.debug_state();
20099 eprintln!(
20100 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
20101 $name, $val
20102 );
20103 }
20104 };
20105 }
20106 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
20107 // point every square caller routes through (see `read_intra_mode_rect`).
20108 let cfl = if cfl && side > 32 {
20109 hit!(NOCFL_UV_MODE_HITS);
20110 false
20111 } else {
20112 cfl
20113 };
20114 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
20115 // `skip` when `SegIdPreSkip`, and after it otherwise.
20116 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
20117 if seg_id_pre_skip(fctx) {
20118 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
20119 }
20120 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
20121 if trace {
20122 eprintln!(
20123 "TRACE skip value={} rng={}",
20124 skip as i32,
20125 dec.debug_state().0
20126 );
20127 }
20128 istep!("skip", skip as i32);
20129 if !seg_id_pre_skip(fctx) {
20130 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
20131 }
20132 // spec order (see the comment below on `read_intrabc_info`): `skip`,
20133 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
20134 maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
20135 istep!("cdef", 0);
20136 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
20137 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
20138 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
20139 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
20140 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
20141 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
20142 istep!("dq", 0);
20143 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
20144 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
20145 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
20146 // intra frame whose header set `allow_intrabc`. Actual intra block copy
20147 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
20148 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
20149 // draws the line at consuming this one flag symbol and refusing by name
20150 // when it fires, so the arithmetic decoder still resyncs for a stream
20151 // that merely allows (but never uses) intrabc.
20152 if allow_intrabc {
20153 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
20154 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
20155 eprintln!(
20156 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
20157 u8::from(use_intrabc),
20158 dec.debug_state().0
20159 );
20160 }
20161 if trace {
20162 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
20163 }
20164 if use_intrabc {
20165 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);
20166 if trace {
20167 eprintln!("TRACE intrabc dv={dv:?}");
20168 }
20169 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
20170 hit!(INTRABC_HITS);
20171 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
20172 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
20173 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
20174 // `DC_PRED` (which is also what the neighbour mode contexts and
20175 // the loop filter then see).
20176 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
20177 }
20178 }
20179 let above_ctx = INTRA_MODE_CTX[above_mode];
20180 let left_ctx = INTRA_MODE_CTX[left_mode];
20181 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
20182 if trace {
20183 eprintln!(
20184 "TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
20185 dec.debug_state().0
20186 );
20187 }
20188 istep!("mode", mode as i32);
20189 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
20190 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
20191 if trace {
20192 eprintln!(
20193 "TRACE angle_delta value={}",
20194 delta + ANGLE_DELTA_ZERO as i32
20195 );
20196 }
20197 delta
20198 } else {
20199 0
20200 };
20201 istep!("angle_y", angle_delta_y);
20202 // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette
20203 // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref`
20204 // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader
20205 // gates its chroma symbols on.
20206 let has_chroma = !mono(fctx);
20207 let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx);
20208 let uv_mode = if !has_chroma {
20209 DC_PRED
20210 } else if cfl {
20211 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
20212 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
20213 } else {
20214 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
20215 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
20216 };
20217 if trace {
20218 eprintln!(
20219 "TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}",
20220 dec.debug_state().0
20221 );
20222 }
20223 istep!("uv_mode", uv_mode as i32);
20224 let alpha = if cfl && uv_mode == UV_CFL_PRED {
20225 Some(read_cfl_alphas(dec, cdfs))
20226 } else {
20227 None
20228 };
20229 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
20230 // from this lane's directional chroma: a corner block with neither
20231 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
20232 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
20233 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
20234 // bug in that fallback this lane's own scope does not cover. Keep it
20235 // refused here rather than ship a silently-wrong decode.
20236 if (9..=12).contains(&uv_mode) {
20237 hit!(SMOOTH_UV_HITS);
20238 }
20239 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
20240 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
20241 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
20242 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
20243 // the `else` branch below and never reads one either way.
20244 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
20245 hit!(DIRECTIONAL_UV_HITS);
20246 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
20247 } else {
20248 0
20249 };
20250 istep!("angle_uv", angle_delta_uv);
20251 if angle_delta_uv != 0 {
20252 hit!(UV_ANGLE_DELTA_HITS);
20253 }
20254 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
20255 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
20256 // gated by `av1_allow_palette` (blockd.h -- size bound only,
20257 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
20258 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
20259 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
20260 // read the same CDF row whenever every neighbour really is non-palette).
20261 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
20262 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
20263 // neighbour lookup at all), so it is exact even at the excluded call
20264 // sites once Y decodes real syntax there too.
20265 //
20266 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
20267 // inline from `read_palette_mode_info` -- it runs later, from
20268 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
20269 // after the WHOLE mode-info read for the block, including UV palette
20270 // mode_info (`read_palette_mode_info`'s own second half, right below)
20271 // and `read_filter_intra_mode_info`. So this branch now only reads
20272 // mode/size/colours for both planes (deferring the two colour-index-map
20273 // decodes to after `filter_intra`, below) -- r6's range trace pinned
20274 // this exact ordering bug (`compare-range-not-tell`: ranges matched
20275 // bit-for-bit through the Y colours, diverged only at the old inline
20276 // `decode_color_index_map` call).
20277 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
20278 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
20279 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) {
20280 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
20281 if mode == DC_PRED {
20282 if trace {
20283 let (rng, _) = dec.debug_state();
20284 eprintln!(
20285 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
20286 );
20287 }
20288 }
20289 let use_palette_y =
20290 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
20291 if mode == DC_PRED && trace {
20292 let (rng, _) = dec.debug_state();
20293 eprintln!(
20294 "TRACE palette_y_mode value={} rng={rng}",
20295 use_palette_y as i32
20296 );
20297 }
20298 if use_palette_y {
20299 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
20300 if trace {
20301 let (rng, _) = dec.debug_state();
20302 eprintln!("TRACE palette_y_size n={n} rng={rng}");
20303 }
20304 let colors = read_palette_colors_y(dec, n, cache, fctx);
20305 if trace {
20306 let (rng, _) = dec.debug_state();
20307 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
20308 }
20309 palette_y_pending = Some((n, colors));
20310 }
20311 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
20312 // unconditionally at this bit position whenever `uv_mode ==
20313 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
20314 // scope always reconstructs chroma alongside luma (`decode_block`
20315 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
20316 // is always true here and does not need threading in.
20317 //
20318 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
20319 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a
20320 // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size`
20321 // symbol even at this chroma-owning square block.
20322 let palette_uv_mode_ctx = usize::from(use_palette_y);
20323 if has_chroma
20324 && uv_mode == DC_PRED
20325 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
20326 {
20327 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
20328 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
20329 palette_uv_pending = Some((n, u_colors, v_colors));
20330 }
20331 }
20332 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
20333 // `use_filter_intra` symbol this decoder never read at all until
20334 // lane-av1real r10 -- silently skipping it left every bit past a
20335 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
20336 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
20337 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
20338 // symbol's bits were never consumed).
20339 let mut filter_intra = None;
20340 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
20341 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
20342 // `use_filter_intra` symbol for a Y-palette block, and reading one here
20343 // desynced every screen-content stream from the first palette block on
20344 // (it surfaced as a bogus "partition below 8x8" refusal further down the
20345 // tile).
20346 if mode == DC_PRED
20347 && enable_filter_intra
20348 && palette_y_pending.is_none()
20349 && let Some(class) = filter_intra_size_class(side)
20350 {
20351 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
20352 if trace {
20353 eprintln!(
20354 "TRACE use_filter_intra side={side} rng={} value={}",
20355 dec.debug_state().0,
20356 use_filter_intra as i32
20357 );
20358 }
20359 istep!("use_filter_intra", use_filter_intra as i32);
20360 if use_filter_intra {
20361 hit!(FILTER_INTRA_HITS);
20362 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
20363 if trace {
20364 eprintln!("TRACE filter_intra_mode value={fi_mode}");
20365 }
20366 istep!("filter_intra_mode", fi_mode as i32);
20367 filter_intra = Some(fi_mode);
20368 }
20369 }
20370 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
20371 // shared U/V map) -- the same order libaom's own loop visits them in.
20372 let palette_y = palette_y_pending.map(|(n, colors)| {
20373 let map = decode_color_index_map(
20374 dec,
20375 cdfs,
20376 n,
20377 side,
20378 palette_onscreen(mi_r, mi_c, side, side, fctx),
20379 false,
20380 );
20381 hit!(PALETTE_HITS);
20382 if trace {
20383 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
20384 }
20385 PaletteY {
20386 size: n,
20387 colors,
20388 map,
20389 }
20390 });
20391 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
20392 let on = palette_onscreen_uv(
20393 (side, side),
20394 palette_onscreen(mi_r, mi_c, side, side, fctx),
20395 (side >> ss_x(fctx), side >> ss_y(fctx)),
20396 (ss_x(fctx), ss_y(fctx)),
20397 );
20398 // lane-av1-422d: the chroma map's extent is the PLANE BLOCK
20399 // `(side >> ss_x) x (side >> ss_y)` -- 4x8 at ss (1,0), not the
20400 // square call's `(side >> ss_x)`-squared (4x4), which left a
20401 // 16-entry map for a 32-sample unit and panicked the reconstruct.
20402 let map = decode_color_index_map_wh(
20403 dec,
20404 cdfs,
20405 n,
20406 side >> ss_x(fctx),
20407 side >> ss_y(fctx),
20408 on,
20409 true,
20410 );
20411 hit!(PALETTE_UV_HITS);
20412 if trace {
20413 eprintln!(
20414 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
20415 &u_colors[..n],
20416 &v_colors[..n]
20417 );
20418 }
20419 PaletteUv {
20420 size: n,
20421 u_colors,
20422 v_colors,
20423 map,
20424 }
20425 });
20426 Ok((
20427 skip,
20428 mode,
20429 angle_delta_y,
20430 uv_mode,
20431 angle_delta_uv,
20432 alpha,
20433 filter_intra,
20434 palette_y,
20435 palette_uv,
20436 ))
20437}
20438
20439/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
20440/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
20441/// intra modes.
20442const UV_CFL_PRED: usize = 13;
20443
20444/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
20445/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
20446/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
20447/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
20448/// joint sign the same way. Returns each plane's final signed `alpha_q3`
20449/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
20450fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
20451 hit!(CFL_BLOCK_HITS);
20452 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
20453 let sign_u = ((joint_sign + 1) * 11) >> 5;
20454 let sign_v = (joint_sign + 1) - 3 * sign_u;
20455 let alpha_u = if sign_u == 0 {
20456 0
20457 } else {
20458 let ctx_u = (joint_sign + 1 - 3) as usize;
20459 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
20460 if sign_u == 2 { mag } else { -mag }
20461 };
20462 let alpha_v = if sign_v == 0 {
20463 0
20464 } else {
20465 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
20466 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
20467 if sign_v == 2 { mag } else { -mag }
20468 };
20469 (alpha_u, alpha_v)
20470}
20471
20472/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
20473/// the reconstructed luma samples under a `side`-square block, subsampled
20474/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
20475/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
20476/// to give the AC values [`cfl_scaled`] scales by alpha.
20477fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
20478 cfl_ac_q3_at(px, py, side, side, |lx, ly| {
20479 i32::from(y.data[ly * y.width + lx])
20480 })
20481}
20482
20483/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
20484/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
20485/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
20486/// reconstruction through THIS function rather than a second transcription of
20487/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
20488/// CfL AC at the frame's subsampling. 4:2:0 keeps the 2x2 average; 4:4:4
20489/// copies each luma sample shifted to Q3 (`cfl_luma_subsampling_444_lbd`).
20490fn cfl_ac_ss(
20491 y: &PlaneBuf<'_>,
20492 px: usize,
20493 py: usize,
20494 bw: usize,
20495 bh: usize,
20496 ss_x: usize,
20497 ss_y: usize,
20498) -> Vec<i32> {
20499 if ss_x == 0 && ss_y == 0 {
20500 hit!(CFL_AC_444_HITS);
20501 let mut ac = vec![0i32; bw * bh];
20502 let mut sum = 0i32;
20503 for row in 0..bh {
20504 for col in 0..bw {
20505 let q3 = i32::from(y.data[(py + row) * y.width + px + col]) << 3;
20506 ac[row * bw + col] = q3;
20507 sum += q3;
20508 }
20509 }
20510 let num_pel = (bw * bh) as i32;
20511 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
20512 ac.iter_mut().for_each(|v| *v -= avg);
20513 ac
20514 } else if ss_x == 1 && ss_y == 0 {
20515 // lane-av1-422: `cfl_luma_subsampling_422_lbd_c` -- each chroma sample
20516 // averages the HORIZONTAL luma pair above it, at full chroma height
20517 // (`(a + b) >> 1` in Q3 is `(a + b) << 2`). A rect luma strip's chroma
20518 // is square here, and the 4:2:0 rect/square helpers below would halve
20519 // the height it must keep.
20520 hit!(CFL_AC_422_HITS);
20521 let (cw, ch) = (bw >> 1, bh);
20522 let mut ac = vec![0i32; cw * ch];
20523 let mut sum = 0i32;
20524 for row in 0..ch {
20525 for col in 0..cw {
20526 let (lx, ly) = (px + col * 2, py + row);
20527 let q3 = (i32::from(y.data[ly * y.width + lx])
20528 + i32::from(y.data[ly * y.width + lx + 1]))
20529 << 2;
20530 ac[row * cw + col] = q3;
20531 sum += q3;
20532 }
20533 }
20534 let num_pel = (cw * ch) as i32;
20535 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
20536 ac.iter_mut().for_each(|v| *v -= avg);
20537 ac
20538 } else if bw == bh {
20539 hit!(CFL_AC_420_SQ_HITS);
20540 cfl_ac_q3(y, px, py, bw)
20541 } else {
20542 hit!(CFL_AC_420_RECT_HITS);
20543 cfl_ac_q3_rect(y, px, py, bw, bh)
20544 }
20545}
20546
20547pub(crate) fn cfl_ac_q3_at(
20548 px: usize,
20549 py: usize,
20550 bw: usize,
20551 bh: usize,
20552 sample: impl Fn(usize, usize) -> i32,
20553) -> Vec<i32> {
20554 hit!(CFL_AC_Q3_AT_HITS);
20555 if crate::envflags::env_flag!("EC_HALVSWEEP") {
20556 eprintln!("EC_HALV cfl_ac_q3_at px={px} py={py} bw={bw} bh={bh}");
20557 }
20558 let (cw, ch) = (bw / 2, bh / 2);
20559 let mut ac = vec![0i32; cw * ch];
20560 let mut sum = 0i32;
20561 for cy in 0..ch {
20562 for cx in 0..cw {
20563 let (lx, ly) = (px + cx * 2, py + cy * 2);
20564 let q3 =
20565 (sample(lx, ly) + sample(lx + 1, ly) + sample(lx, ly + 1) + sample(lx + 1, ly + 1))
20566 << 1;
20567 ac[cy * cw + cx] = q3;
20568 sum += q3;
20569 }
20570 }
20571 let num_pel = (cw * ch) as i32;
20572 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
20573 ac.iter_mut().for_each(|v| *v -= avg);
20574 ac
20575}
20576
20577/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
20578/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
20579/// ties away from zero on the shifted-out sign).
20580pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
20581 let v = alpha_q3 * ac_q3;
20582 if v >= 0 {
20583 (v + 32) >> 6
20584 } else {
20585 -((-v + 32) >> 6)
20586 }
20587}
20588
20589/// One plane's reconstruction buffer, `width * height` samples, and the
20590/// prediction/residual reads and writes into it — the decode-side twin of
20591/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
20592/// (own-edge and reach clamps both), passing what it gathers straight to
20593/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
20594/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
20595/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
20596/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
20597/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
20598/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
20599/// lane-mc64 r1: the decode-order index the stage dumps below key their file
20600/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
20601/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
20602/// without this every frame overwrote `.f0` and a per-frame bisection silently
20603/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
20604#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
20605fn stage_dump_idx() -> usize {
20606 PREFILT_PICTURE_IDX
20607 .load(std::sync::atomic::Ordering::SeqCst)
20608 .saturating_sub(1)
20609}
20610
20611fn dump_stage16(
20612 var: &str,
20613 y: &PlaneBuf<'_>,
20614 u: &PlaneBuf<'_>,
20615 v: &PlaneBuf<'_>,
20616 fw: usize,
20617 fh: usize,
20618) {
20619 use std::io::Write;
20620 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
20621 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
20622 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
20623 // not be read out at all.
20624 if let Ok(path) = crate::envflags::var(var)
20625 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
20626 {
20627 for (p, w, h) in [
20628 (y, fw, fh),
20629 (u, fw.div_ceil(2), fh.div_ceil(2)),
20630 (v, fw.div_ceil(2), fh.div_ceil(2)),
20631 ] {
20632 for row in 0..h {
20633 let mut bytes = Vec::with_capacity(w * 2);
20634 for &s in &p.data[row * p.width..][..w] {
20635 bytes.extend_from_slice(&s.to_le_bytes());
20636 }
20637 let _ = f.write_all(&bytes);
20638 }
20639 }
20640 }
20641}
20642
20643/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
20644/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
20645/// every frame overwrote the previous one and only the LAST frame survived,
20646/// which silently defeats any per-frame filter-stage bisection.
20647fn dump_stage_idx(var: &str) -> usize {
20648 use std::collections::HashMap;
20649 use std::sync::{Mutex, OnceLock};
20650 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
20651 let mut m = IDX
20652 .get_or_init(|| Mutex::new(HashMap::new()))
20653 .lock()
20654 .unwrap();
20655 let e = m.entry(var.to_string()).or_insert(0);
20656 let i = *e;
20657 *e += 1;
20658 i
20659}
20660
20661fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
20662 use std::io::Write;
20663 if let Ok(path) = crate::envflags::var(var)
20664 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
20665 {
20666 for p in [y, u, v] {
20667 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
20668 let _ = f.write_all(&narrow);
20669 }
20670 }
20671}
20672
20673/// `EC_AV1_PREFILT_WIDE_DUMP=<prefix>` -> `<prefix>.f<N>`, the pre-loop-filter
20674/// reconstruction cropped to each plane's mi-ALIGNED true extent, byte for
20675/// byte the shape aomdec's own rung 7 writes (`y_width`/`y_height`,
20676/// `uv_width`/`uv_height`), so the two can be diffed directly.
20677///
20678/// lane-av1444edge: this used to be an inline block in the KEY-frame tile path
20679/// only, with a FUNCTION-LOCAL `static IDX2` as its counter. Both facts were
20680/// measurement traps, and the second one is why the first went unnoticed:
20681/// the inter-frame path (`decode_inter_frame_tile_with_cdfs`) had no wide
20682/// prefilter dump at all, so every 4:4:4 lossy divergence localized to an
20683/// inter frame had no pre-filter rung to compare against and got attributed to
20684/// reconstruction when the oracle could not see it. The `static` also restarted
20685/// per monomorphisation, so every frame after the first overwrote `.f0` -- a
20686/// per-frame bisection silently compared the LAST decoded frame. The counter
20687/// is now the shared per-var [`dump_stage_idx`] map, and the call also sits on
20688/// the inter path (skipped when the filter pipeline is active, which has
20689/// already deblocked by the time the tile tail runs -- same condition
20690/// `capture_filter_replay` guards itself with).
20691fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
20692 let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") else {
20693 return;
20694 };
20695 use std::io::Write;
20696 let idx = dump_stage_idx("EC_AV1_PREFILT_WIDE_DUMP");
20697 let crop = |plane: &PlaneBuf<'_>| -> Vec<u8> {
20698 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
20699 for row in 0..plane.true_height {
20700 out.extend(
20701 plane.data[row * plane.width..][..plane.true_width]
20702 .iter()
20703 .map(|&s| s as u8),
20704 );
20705 }
20706 out
20707 };
20708 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
20709 let _ = f.write_all(&crop(y));
20710 let _ = f.write_all(&crop(u));
20711 let _ = f.write_all(&crop(v));
20712 }
20713}
20714
20715/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
20716/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
20717/// at most 4095), so a decode that hashes identically under the flag proves
20718/// the output does not depend on the plane buffer's initial content.
20719const PLANE_SENTINEL: u16 = 0xDEAD;
20720
20721/// A frame plane's own backing store, `n` samples, UNINITIALISED.
20722///
20723/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
20724/// by the tile walk's reconstruction before anything reads it, so the
20725/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
20726/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
20727/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
20728/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
20729/// ways (see the lane report) and the two agree, which is the proof that no
20730/// unwritten sample reaches the output.
20731fn fresh_plane(n: usize) -> Vec<u16> {
20732 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
20733 return vec![PLANE_SENTINEL; n];
20734 }
20735 let mut v: Vec<u16> = Vec::with_capacity(n);
20736 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
20737 // capacity was just reserved, so the vector owns `n` initialised-or-not
20738 // `u16` slots. Every one is written by reconstruction before it is read
20739 // (proven by the sentinel gate above).
20740 #[allow(unsafe_code)]
20741 unsafe {
20742 v.set_len(n);
20743 }
20744 v
20745}
20746
20747#[derive(Clone)]
20748struct PlaneBuf<'a> {
20749 data: std::borrow::Cow<'a, [u16]>,
20750 width: usize,
20751 height: usize,
20752 /// The frame's true, decodable extent in this plane's own units — past
20753 /// this, samples are the padded coding surface's invented tail, never a
20754 /// real decoder's edge or reach reads.
20755 true_width: usize,
20756 true_height: usize,
20757 /// This plane's own tile's top-left pixel origin (spec: intra prediction
20758 /// never reaches across a tile boundary even though an earlier-decoded
20759 /// tile's real pixels sit right there in the shared buffer) — set via
20760 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
20761 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
20762 /// is threaded (the two-tile column-split stage 1 fixture's tile always
20763 /// ends at the frame's own right/bottom edge); a non-last tile's own
20764 /// right/bottom reach bound is still open, tracked in the report.
20765 tile_x0: usize,
20766 tile_y0: usize,
20767 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
20768 /// (exclusive) -- a non-last tile column/row's own reach must stop at
20769 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
20770 /// full padded extent) for the single-tile/last-tile case, matching the
20771 /// old unclipped behaviour exactly.
20772 tile_x1: usize,
20773 tile_y1: usize,
20774}
20775
20776/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
20777/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
20778/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
20779/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
20780/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
20781/// `ALTREF2`/`ALTREF`).
20782// lane-av1pixprobe: env-gated one-sample write probe -- `EC_AV1_PIXPROBE=x,y`
20783// prints one PIXWRITE line per reconstruction store landing on that sample,
20784// naming the store site, the value it replaces and the one it leaves. Re-anchored
20785// from `lane-av1-ibcwrite` @ 25f5c729 onto the main-shape sites (the two mc stores
20786// now live in `reconstruct_mc_rect`).
20787static PIXPROBE_ON: std::sync::LazyLock<bool> =
20788 std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_PIXPROBE").is_some());
20789
20790static PIXPROBE: std::sync::LazyLock<Option<(usize, usize)>> = std::sync::LazyLock::new(|| {
20791 crate::envflags::var("EC_AV1_PIXPROBE").ok().and_then(|v| {
20792 let (x, y) = v.split_once(',')?;
20793 Some((
20794 x.trim().parse::<usize>().ok()?,
20795 y.trim().parse::<usize>().ok()?,
20796 ))
20797 })
20798});
20799
20800#[inline]
20801fn pix_write(
20802 site: &str,
20803 bx: usize,
20804 by: usize,
20805 bside: usize,
20806 x: usize,
20807 y: usize,
20808 prev: u16,
20809 val: u16,
20810) {
20811 if *PIXPROBE_ON && Some((x, y)) == *PIXPROBE {
20812 eprintln!(
20813 "PIXWRITE {site} block=({bx},{by})+{bside} px=({x},{y}) prev={prev} val={val} at {}",
20814 std::panic::Location::caller()
20815 );
20816 }
20817}
20818
20819impl PlaneBuf<'_> {
20820 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
20821 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
20822 /// are already in this plane's own units (luma pixels for `y`, chroma
20823 /// pixels — halved — for `u`/`v`).
20824 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
20825 self.tile_x0 = x0;
20826 self.tile_y0 = y0;
20827 self.tile_x1 = x1;
20828 self.tile_y1 = y1;
20829 }
20830
20831 fn edges(
20832 &self,
20833 x: usize,
20834 y: usize,
20835 side: usize,
20836 reach: Reach,
20837 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
20838 let own_across = x + side.min(self.true_width.saturating_sub(x));
20839 let across = if reach.above_right {
20840 own_across + side.min(self.true_width.saturating_sub(own_across))
20841 } else {
20842 own_across
20843 }
20844 .min(self.width)
20845 .min(self.tile_x1);
20846 let own_down = y + side.min(self.true_height.saturating_sub(y));
20847 let down = if reach.below_left {
20848 own_down + side.min(self.true_height.saturating_sub(own_down))
20849 } else {
20850 own_down
20851 }
20852 .min(self.height)
20853 .min(self.tile_y1);
20854 let above = (y > self.tile_y0 && across > x)
20855 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
20856 let left = (x > self.tile_x0 && down > y).then(|| {
20857 (y..down)
20858 .map(|row| self.data[row * self.width + x - 1])
20859 .collect::<Vec<_>>()
20860 });
20861 let corner =
20862 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
20863 (above, left, corner)
20864 }
20865
20866 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
20867 /// the above/left reach each extend by their OWN axis (`bw` across,
20868 /// `bh` down), not one shared `side`.
20869 fn edges_rect(
20870 &self,
20871 x: usize,
20872 y: usize,
20873 bw: usize,
20874 bh: usize,
20875 reach: Reach,
20876 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
20877 let own_across = x + bw.min(self.true_width.saturating_sub(x));
20878 let across = if reach.above_right {
20879 own_across + bw.min(self.true_width.saturating_sub(own_across))
20880 } else {
20881 own_across
20882 }
20883 .min(self.width)
20884 .min(self.tile_x1);
20885 let own_down = y + bh.min(self.true_height.saturating_sub(y));
20886 let down = if reach.below_left {
20887 own_down + bh.min(self.true_height.saturating_sub(own_down))
20888 } else {
20889 own_down
20890 }
20891 .min(self.height)
20892 .min(self.tile_y1);
20893 let above = (y > self.tile_y0 && across > x)
20894 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
20895 let left = (x > self.tile_x0 && down > y).then(|| {
20896 (y..down)
20897 .map(|row| self.data[row * self.width + x - 1])
20898 .collect::<Vec<_>>()
20899 });
20900 let corner =
20901 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
20902 if matches!((bw, bh), (16, 8) | (8, 16)) {
20903 hit!(RECT_STRIP_PRED_HITS);
20904 if across > own_across || down > own_down {
20905 hit!(RECT_STRIP_REACH_HITS);
20906 }
20907 }
20908 (above, left, corner)
20909 }
20910
20911 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
20912 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
20913 /// already-rect-capable `(bw, bh)` pair.
20914 #[allow(clippy::too_many_arguments)]
20915 #[track_caller]
20916 fn reconstruct_rect(
20917 &mut self,
20918 x: usize,
20919 y: usize,
20920 bw: usize,
20921 bh: usize,
20922 mode: usize,
20923 angle_delta: i32,
20924 reach: Reach,
20925 residual: &[i32],
20926 cfl: Option<(i32, &[i32])>,
20927 filter_intra: Option<usize>,
20928 smooth_neighbor: bool,
20929 // lane-wave1 step (i): the palette/intrabc prediction override, taken
20930 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
20931 // than by this replay.
20932 pred: Option<Vec<u16>>,
20933 fctx: &crate::decode::FrameCtx,
20934 ) {
20935 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
20936 // (lane-palette2 r4): a palette block's prediction is the
20937 // reconstructed colour-index map, needing no edge pixels at all.
20938 let prediction = if let Some(buf) = pred {
20939 buf
20940 } else {
20941 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
20942 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
20943 eprintln!(
20944 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
20945 above.as_ref().map(|a| (a.len(), a[0])),
20946 left.as_ref().map(|l| l.len()),
20947 left.as_ref().map(|l| l[0]),
20948 self.tile_x0,
20949 self.tile_y0,
20950 self.true_width,
20951 self.true_height
20952 );
20953 }
20954 let mut prediction = vec![0u16; bw * bh];
20955 if let Some(fi_mode) = filter_intra {
20956 crate::intra::predict_filter_intra(
20957 fi_mode,
20958 above.as_deref(),
20959 left.as_deref(),
20960 corner,
20961 bw,
20962 bh,
20963 &mut prediction,
20964 fctx,
20965 );
20966 } else {
20967 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
20968 predict(
20969 mode as u8,
20970 angle_delta,
20971 above.as_deref(),
20972 left.as_deref(),
20973 corner,
20974 bw,
20975 bh,
20976 enable_edge_filter,
20977 smooth_neighbor,
20978 &mut prediction,
20979 fctx,
20980 );
20981 }
20982 prediction
20983 };
20984 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
20985 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
20986 if crate::envflags::env_flag!("EC_PRED") {
20987 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
20988 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
20989 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
20990 eprintln!(
20991 "@{} OUR_PRED x={x} y={y} plane={} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
20992 std::panic::Location::caller(),
20993 recon_plane(),
20994 i32::from(smooth_neighbor)
20995 );
20996 }
20997 let residual = dense_residual(residual, bw * bh);
20998 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
20999 let res0: Vec<i32> = residual[..bw.min(8)].to_vec();
21000 let pred0: Vec<u16> = prediction[..bw.min(8)].to_vec();
21001 eprintln!(
21002 "DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}"
21003 );
21004 }
21005 for row in 0..bh {
21006 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
21007 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
21008 // whose padded width is not superblock aligned hangs past it.
21009 if y + row >= self.height {
21010 break;
21011 }
21012 for col in 0..bw {
21013 if x + col >= self.width {
21014 break;
21015 }
21016 let idx = row * bw + col;
21017 let mut base = i32::from(prediction[idx]);
21018 if let Some((alpha_q3, ac_q3)) = cfl {
21019 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
21020 }
21021 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
21022 pix_write(
21023 "reconstruct_rect",
21024 x,
21025 y,
21026 bw,
21027 x + col,
21028 y + row,
21029 self.data[(y + row) * self.width + x + col],
21030 sample,
21031 );
21032 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
21033 }
21034 }
21035 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
21036 // -- a block whose prediction matches the oracle's but whose written
21037 // samples do not is either a residual defect or a later overwrite, and
21038 // only this print separates the two.
21039 if crate::envflags::env_flag!("EC_PRED") {
21040 let row0: Vec<u16> = (0..bw.min(8))
21041 .map(|c| self.data[y * self.width + x + c])
21042 .collect();
21043 let col0: Vec<u16> = (0..bh.min(8))
21044 .map(|r| self.data[(y + r) * self.width + x])
21045 .collect();
21046 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
21047 }
21048 }
21049
21050 /// Predicts under `mode` then adds `residual` (side*side, raster),
21051 /// writing the clamped reconstruction back into the plane at `(x, y)`.
21052 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
21053 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
21054 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
21055 /// order (cfl.c).
21056 #[track_caller]
21057 fn reconstruct(
21058 &mut self,
21059 x: usize,
21060 y: usize,
21061 side: usize,
21062 mode: usize,
21063 angle_delta: i32,
21064 reach: Reach,
21065 residual: &[i32],
21066 cfl: Option<(i32, &[i32])>,
21067 filter_intra: Option<usize>,
21068 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
21069 // libaom `get_filt_type`): true when the block's above OR left
21070 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
21071 // Callers pass their own plane's neighbour-mode check
21072 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
21073 // callers until a smooth/paeth `uv_mode` can reach this call at all
21074 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
21075 // keeps `false` exact for chroma without this fn needing to know why.
21076 smooth_neighbor: bool,
21077 // lane-wave1 step (i): the palette/intrabc prediction override, taken
21078 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
21079 // than by this replay.
21080 pred: Option<Vec<u16>>,
21081 fctx: &crate::decode::FrameCtx,
21082 ) {
21083 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
21084 // takes priority over `predict()`/`predict_filter_intra` entirely --
21085 // palette prediction needs no edge pixels at all.
21086 let prediction = if let Some(buf) = pred {
21087 buf
21088 } else {
21089 let (above, left, corner) = self.edges(x, y, side, reach);
21090 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
21091 eprintln!(
21092 "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}",
21093 above.as_deref(),
21094 left.as_deref(),
21095 );
21096 }
21097 let mut prediction = vec![0u16; side * side];
21098 if let Some(fi_mode) = filter_intra {
21099 crate::intra::predict_filter_intra(
21100 fi_mode,
21101 above.as_deref(),
21102 left.as_deref(),
21103 corner,
21104 side,
21105 side,
21106 &mut prediction,
21107 fctx,
21108 );
21109 } else {
21110 // `enable_intra_edge_filter` is the sequence header's own flag
21111 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
21112 // call, never per-block) -- threading it through every
21113 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
21114 // dozen sites for a value that never changes mid-decode, so it
21115 // rides a thread-local instead (this decoder is single-threaded
21116 // per stream).
21117 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
21118 predict(
21119 mode as u8,
21120 angle_delta,
21121 above.as_deref(),
21122 left.as_deref(),
21123 corner,
21124 side,
21125 side,
21126 enable_edge_filter,
21127 smooth_neighbor,
21128 &mut prediction,
21129 fctx,
21130 );
21131 }
21132 prediction
21133 };
21134 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
21135 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
21136 if crate::envflags::env_flag!("EC_PRED") {
21137 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
21138 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
21139 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
21140 eprintln!(
21141 "@{} OUR_PRED x={x} y={y} plane={} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
21142 std::panic::Location::caller(),
21143 recon_plane(),
21144 i32::from(smooth_neighbor)
21145 );
21146 }
21147 let residual = dense_residual(residual, side * side);
21148 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
21149 let res0: Vec<i32> = residual[..side.min(8)].to_vec();
21150 let pred0: Vec<u16> = prediction[..side.min(8)].to_vec();
21151 eprintln!(
21152 "DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}",
21153 cfl.is_some()
21154 );
21155 }
21156 for row in 0..side {
21157 // lane-sb128c r8: libaom's frame buffer is superblock
21158 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
21159 // transform unit of a 128x64 block at the BOTTOM frame edge
21160 // can hang past the last padded row (1920x792: a unit at
21161 // y=768 wants 832 rows of an 800-row buffer, which panicked
21162 // the film's key frames). Those samples are outside the
21163 // frame: never output, and no block below ever references
21164 // them.
21165 if y + row >= self.height {
21166 break;
21167 }
21168 for col in 0..side {
21169 if x + col >= self.width {
21170 break;
21171 }
21172 let idx = row * side + col;
21173 let mut base = i32::from(prediction[idx]);
21174 if let Some((alpha_q3, ac_q3)) = cfl {
21175 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
21176 }
21177 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
21178 pix_write(
21179 "reconstruct",
21180 x,
21181 y,
21182 side,
21183 x + col,
21184 y + row,
21185 self.data[(y + row) * self.width + x + col],
21186 sample,
21187 );
21188 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
21189 }
21190 }
21191 }
21192}
21193
21194/// Reads one plane's transform block, reconstructs it into `plane` at
21195/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
21196#[allow(clippy::too_many_arguments)]
21197
21198fn read_plane(
21199 dec: &mut SymbolDecoder,
21200 cdfs: &mut Cdfs,
21201 set: TxbSet,
21202 scan: &[u16],
21203 plane_idx: usize,
21204 around: (bool, bool, i32),
21205 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
21206 // it for every plane's `txb` lookup (it is what an intra transform type's
21207 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
21208 tx_mode: usize,
21209 predict_mode: usize,
21210 angle_delta: i32,
21211 reach: Reach,
21212 // lane-wave1 step (i): unread -- this reader records its write
21213 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
21214 // stays in the signature so every call site still proves the plane is
21215 // exclusively held while its coefficients are parsed.
21216 _plane: &mut PlaneBuf<'static>,
21217 x: usize,
21218 y: usize,
21219 side: usize,
21220 tx_side: usize,
21221 base_q_idx: u8,
21222 cfl: Option<(i32, CflSrc)>,
21223 filter_intra: Option<usize>,
21224 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
21225 // smaller than its own block (spec `get_txb_ctx_general`'s
21226 // `plane_bsize != tx_size` branch), carrying the already-looked-up
21227 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
21228 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
21229 // formula below.
21230 luma_skip_ctx: Option<usize>,
21231 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
21232 smooth_neighbor: bool,
21233 fctx: &crate::decode::FrameCtx,
21234) -> Result<Grid> {
21235 // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's
21236 // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`)
21237 // never reaches a chroma plane -- no u/v coefficient symbol is coded and
21238 // no chroma write is recorded. Return the all-zero grid the caller's
21239 // neighbour bookkeeping reads, without consuming a bit.
21240 if plane_idx > 0 && mono(fctx) {
21241 return Ok(Grid::Zero(side * side));
21242 }
21243 // lane-av1readcensus: the units read from here on are this plane's.
21244 set_census_plane(plane_idx);
21245 let skip_ctx = if plane_idx == 0 {
21246 luma_skip_ctx.unwrap_or(0)
21247 } else {
21248 // libaom `get_txb_ctx`: a chroma unit's context is
21249 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
21250 // plane block is bigger than the transform. Our chroma tables hold the
21251 // offset-7 rows first, so the caller adds 3 for the bigger-block case
21252 // (every chroma unit of a plane block above TX_4X4 -- lane-sb128b r3,
21253 // and lane-av1h5 measured the 4:4:4 lossless 128 root's TX_4X4 chroma
21254 // units reading the offset-10 rows too, against aomdec's `EC_DBGCTX`).
21255 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
21256 };
21257 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
21258 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
21259 // not by the block's ordinary `mode` (which is always DC_PRED whenever
21260 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
21261 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
21262 // filter-intra in AV1).
21263 let tx_mode = if plane_idx == 0 {
21264 fi_tx_row(tx_mode, filter_intra)
21265 } else {
21266 tx_mode
21267 };
21268 let mut coding = cdfs.txb(set, tx_mode);
21269 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
21270 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
21271 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
21272 // plane of a lossless block (the residual then goes through the WHT, so
21273 // the type only picks the scan, which is the default one).
21274 if lossless(fctx) {
21275 coding.tx_type = None;
21276 }
21277 // A chroma plane's `tx_type` is *never* its own coded symbol
21278 // (`coding.tx_type` is always `None` for every `TxbSet::Chroma*`), so it is
21279 // resolved, not read. Three cases, in libaom's own order
21280 // (`av1_get_tx_type` / `av1_get_ext_tx_set_type`, `blockd.h`):
21281 //
21282 // * **intra** chroma: `intra_mode_to_tx_type(mbmi, PLANE_TYPE_UV)` -- the
21283 // plane's own predicted mode (`default_intra_tx_type`) -- then clamped by
21284 // `av1_get_ext_tx_set_type`. At 32 points and up that set is
21285 // `EXT_TX_SET_DCTONLY` (the `is_inter ? EXT_TX_SET_DCT_IDTX :
21286 // EXT_TX_SET_DCTONLY` line), which forces `DCT_DCT` no matter what the
21287 // mode-indexed table said. `TxbSet::Chroma8`/`Chroma16` never hit this --
21288 // every value `default_intra_tx_type` can produce is already a member of
21289 // both `TX_SET_INTRA_1`/`_2`, so nothing narrows there -- only
21290 // `Chroma32` and up do.
21291 // * **inter** chroma, i.e. [`INTRABC_CHROMA_TX`]: the same
21292 // `xd->tx_type_map` cell the luma unit stamped (`blk_row <<=
21293 // pd->subsampling_y`, `blk_col <<= pd->subsampling_x`), reduced by the
21294 // INTER transform set. At **32 points** that set is
21295 // `EXT_TX_SET_DCT_IDTX`, NOT `EXT_TX_SET_DCTONLY` -- so a 32-point
21296 // inter chroma unit inherits the luma's coded `IDTX`, and the identity
21297 // transform (a plain copy) is what libaom actually runs.
21298 // [`reduce_inherited_chroma_tx_type`] is that reduction verbatim.
21299 // * 64 points and up is `EXT_TX_SET_DCTONLY` for both, which the same
21300 // reduction already yields.
21301 //
21302 // The `side >= 32` -> `DCT_DCT` clamp this replaces was written for the
21303 // intra case (and read as libaom's clamp at `tx_size_sqr_up >= TX_32X32`),
21304 // but libaom's cap is `txsize_sqr_up_map[tx_size] > TX_32X32` -- 64 and up
21305 // -- so it also swallowed a 32-point INTER chroma unit's inherited `IDTX`
21306 // and ran `DCT_DCT` where libaom ran the identity transform.
21307 // Sub-32 units keep the raw inherited type exactly as before.
21308 let default_tx_type = if plane_idx == 0 {
21309 TxType::DctDct
21310 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
21311 if side >= 32 {
21312 reduce_inherited_chroma_tx_type(inherited, side, side, fctx)
21313 } else {
21314 inherited
21315 }
21316 } else if side >= 32 {
21317 TxType::DctDct
21318 } else {
21319 default_intra_tx_type(predict_mode as u8)
21320 };
21321 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
21322 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
21323 let default_tx_type = if lossless(fctx) {
21324 TxType::DctDct
21325 } else {
21326 default_tx_type
21327 };
21328 let (grid, tx_type) = read_coeffs(
21329 dec,
21330 &mut coding,
21331 scan,
21332 skip_ctx,
21333 dc_sign_ctx(around.2),
21334 default_tx_type,
21335 None,
21336 )?;
21337 note_chroma_class1(plane_idx, tx_type);
21338 if plane_idx == 0 {
21339 fctx.luma_tx_type.with(|c| c.set(tx_type));
21340 }
21341 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
21342 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
21343 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
21344 // guard also assumes.
21345 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
21346 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
21347 // keyed by that true size, not the coded corner's -- so the corner
21348 // goes into the top-left of a `side`-sized grid, not the reverse.
21349 let levels = extend_corner(grid, tx_side, tx_side, side, side);
21350 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
21351 let tx = TxParams {
21352 w: side,
21353 h: side,
21354 bit_depth: bit_depth(fctx),
21355 q_idx: block_q_idx(fctx),
21356 dc_delta,
21357 ac_delta,
21358 tx_type,
21359 qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type),
21360 stride: 0,
21361 lossless: lossless(fctx),
21362 };
21363 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21364 let residual = tx.run(&levels);
21365 eprintln!(
21366 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}",
21367 &*levels,
21368 );
21369 }
21370 push_intra_tx(
21371 plane_idx,
21372 x,
21373 y,
21374 side,
21375 side,
21376 false,
21377 predict_mode,
21378 angle_delta,
21379 reach,
21380 tx,
21381 &levels,
21382 cfl,
21383 filter_intra,
21384 smooth_neighbor,
21385 fctx,
21386 );
21387 // `record`'s neighbour state only reads whether *the coded grid* (not the
21388 // residual) has nonzero entries, so the levels this function already
21389 // built are what it wants back -- both arms of the old `tx_side == side`
21390 // branch returned exactly that, one of them through a full `to_vec` copy
21391 // of the grid per intra transform unit (lane-coefbuf).
21392 Ok(levels)
21393}
21394
21395/// [`push_intra`] when the unit is square, [`push_intra_rect`] when it is a
21396/// rect (lane-av1-422f): a 4:2:2 square-block chroma unit is the plane
21397/// block's own rect shape, and the `rect` flag selects
21398/// [`PlaneBuf::reconstruct_rect`]'s two-dimensional loop.
21399#[allow(clippy::too_many_arguments)]
21400fn push_intra_unit(
21401 plane: usize,
21402 x: usize,
21403 y: usize,
21404 w: usize,
21405 h: usize,
21406 mode: usize,
21407 angle_delta: i32,
21408 reach: Reach,
21409 residual: &[i32],
21410 cfl: Option<(i32, CflSrc)>,
21411 filter_intra: Option<usize>,
21412 smooth_neighbor: bool,
21413 fctx: &crate::decode::FrameCtx,
21414) {
21415 if w == h {
21416 push_intra(
21417 plane,
21418 x,
21419 y,
21420 w,
21421 mode,
21422 angle_delta,
21423 reach,
21424 residual,
21425 cfl,
21426 filter_intra,
21427 smooth_neighbor,
21428 fctx,
21429 );
21430 } else {
21431 push_intra_rect(
21432 plane,
21433 x,
21434 y,
21435 w,
21436 h,
21437 mode,
21438 angle_delta,
21439 reach,
21440 residual,
21441 cfl,
21442 filter_intra,
21443 smooth_neighbor,
21444 fctx,
21445 );
21446 }
21447}
21448
21449/// ONE RECT chroma transform unit of a square block's uv plane
21450/// (lane-av1-422f) -- a 4:2:2 frame's plane block is `(side/2, side)` and
21451/// `av1_get_max_uv_txsize` fills it with a single rect unit below side 64
21452/// (TX_4X8 / TX_8X16 / TX_16X32), which the square-shaped [`read_plane`]
21453/// cannot express. Same shape as [`leaf8_chroma422_unit`]'s proven read: the
21454/// [`TxbSet`] whose entropy class the unit squares up to, the unit-shaped
21455/// scan, `txb_skip_ctx` = above + left in the offset-7 rows (the unit covers
21456/// the plane block exactly, so no `+3` bigger-plane term -- that one lives in
21457/// the square multi-unit walks' `chroma_ctx_offset`), and the plane's
21458/// predicted mode supplies the mode-derived default `tx_type` unless an armed
21459/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own -- except at an
21460/// entropy class of 32x32 and up, where the spec forces `DCT_DCT`
21461/// ([`read_plane`]'s `side >= 32` clamp).
21462#[allow(clippy::too_many_arguments)]
21463fn read_rect_chroma_unit(
21464 dec: &mut SymbolDecoder,
21465 cdfs: &mut Cdfs,
21466 set: TxbSet,
21467 scan: &[u16],
21468 w: usize,
21469 h: usize,
21470 plane_idx: usize,
21471 around: (bool, bool, i32),
21472 uv_predict_mode: usize,
21473 angle_delta_uv: i32,
21474 reach: Reach,
21475 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
21476 // the plane exclusively while the unit's coefficients are parsed.
21477 _plane: &mut PlaneBuf<'static>,
21478 x: usize,
21479 y: usize,
21480 // Signature parity with [`read_plane`]; the dequant reads its q index
21481 // off `block_q_idx(fctx)` like every other reader here.
21482 _base_q_idx: u8,
21483 // lane-av1-422p: `get_txb_ctx_general`'s chroma branch
21484 // (txb_common.h) reads `txb_skip_ctx = above + left + ctx_offset`,
21485 // where `ctx_offset` is 10 when the plane block is bigger than the
21486 // transform and 7 otherwise. The port stores the offset-7 rows at
21487 // `txb_skip_chroma_8` rows 0..3 and the offset-10 rows at rows 3..6
21488 // (lane-av1-422b), so a unit SMALLER than its plane block passes
21489 // `Some(3)` to reach the offset-10 rows. Every unit that IS the whole
21490 // plane block stays `None` -- 4:2:2 plane blocks never shrink to a
21491 // rect unit except in the chunk arms.
21492 chroma_skip_offset: Option<usize>,
21493 cfl: Option<(i32, CflSrc)>,
21494 smooth_neighbor_uv: bool,
21495 fctx: &crate::decode::FrameCtx,
21496) -> Result<Grid> {
21497 if ss_x(fctx) == 1 && ss_y(fctx) == 0 && w != h {
21498 hit!(CHROMA422_RECT_HITS);
21499 }
21500 // The same three cases as [`read_plane`], for the same reason: at 32 points
21501 // an INTER chroma unit's transform set is `EXT_TX_SET_DCT_IDTX` (the luma's
21502 // coded `IDTX` survives) where the intra set is `EXT_TX_SET_DCTONLY`, and
21503 // an armed [`INTRABC_CHROMA_TX`] slot means the block IS an inter block.
21504 let default_tx = if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
21505 if w.max(h) >= 32 {
21506 reduce_inherited_chroma_tx_type(inherited, w, h, fctx)
21507 } else {
21508 inherited
21509 }
21510 } else if w.max(h) >= 32 {
21511 TxType::DctDct
21512 } else {
21513 default_intra_tx_type(uv_predict_mode as u8)
21514 };
21515 let mut coding = cdfs.txb(set, uv_predict_mode);
21516 let (levels, tx_type) = read_coeffs_rect(
21517 dec,
21518 &mut coding,
21519 scan,
21520 w,
21521 h,
21522 usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0),
21523 dc_sign_ctx(around.2),
21524 default_tx,
21525 plane_idx,
21526 )?;
21527 let residual = dequant_and_inverse_typed_wh(
21528 &levels,
21529 w,
21530 h,
21531 crate::decode::bit_depth(fctx),
21532 block_q_idx(fctx),
21533 plane_q_delta(plane_idx, fctx).0,
21534 plane_q_delta(plane_idx, fctx).1,
21535 tx_type,
21536 block_iqmatrix(fctx, plane_idx, w, h, tx_type),
21537 );
21538 push_intra_rect(
21539 plane_idx,
21540 x,
21541 y,
21542 w,
21543 h,
21544 uv_predict_mode,
21545 angle_delta_uv,
21546 reach,
21547 &residual,
21548 cfl,
21549 None,
21550 smooth_neighbor_uv,
21551 fctx,
21552 );
21553 Ok(levels)
21554}
21555
21556/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
21557/// three planes, reconstructing them into `y`/`u`/`v` and updating
21558/// `neighbours`.
21559#[allow(clippy::too_many_arguments)]
21560fn decode_block(
21561 dec: &mut SymbolDecoder,
21562 cdfs: &mut Cdfs,
21563 neighbours: &mut Neighbours,
21564 at: (usize, usize),
21565 side: usize,
21566 luma_set: TxbSet,
21567 chroma_set: TxbSet,
21568 luma_tx: usize,
21569 chroma_tx: usize,
21570 scans: (&[u16], &[u16]),
21571 cfl: bool,
21572 y: &mut PlaneBuf<'static>,
21573 u: &mut PlaneBuf<'static>,
21574 v: &mut PlaneBuf<'static>,
21575 base_q_idx: u8,
21576 enable_filter_intra: bool,
21577 allow_screen_content_tools: bool,
21578 allow_intrabc: bool,
21579 scan32: &[u16],
21580 scan16: &[u16],
21581 scan8: &[u16],
21582 scan4: &[u16],
21583 tx_select: bool,
21584 reduced_tx_set: bool,
21585 fctx: &crate::decode::FrameCtx,
21586) -> Result<()> {
21587 let (r, c) = at;
21588 let (px, py) = (c * SUB, r * SUB);
21589 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
21590 let palette_uv_cache = neighbours.palette_uv_cache(at);
21591 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
21592 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
21593 let (
21594 skip,
21595 mode,
21596 angle_delta_y,
21597 uv_mode,
21598 angle_delta_uv,
21599 alpha,
21600 filter_intra,
21601 palette_y,
21602 palette_uv,
21603 ) = read_intra_mode(
21604 dec,
21605 cdfs,
21606 nb_above_mode,
21607 nb_left_mode,
21608 cfl,
21609 side,
21610 enable_filter_intra,
21611 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
21612 allow_screen_content_tools,
21613 allow_intrabc,
21614 Some((palette_ctx, &palette_cache)),
21615 &palette_uv_cache,
21616 r * (SUB / MI),
21617 c * (SUB / MI),
21618 fctx,
21619 )?;
21620 if at_tile_left && palette_y.is_some() {
21621 hit!(PALETTE_TILE_LEFT_HITS);
21622 }
21623 // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane
21624 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
21625 // tables/scans are replaced by the 4x4 ones and the block always takes the
21626 // multi-transform-unit path below. lane-av1mixloss: this rewrite used to
21627 // sit at the TOP of the function -- before `read_intra_mode`, which is
21628 // where the block's own `segment_id` is read -- so a mixed frame resolved
21629 // every block's geometry against the PREVIOUS block's segment (a lossless
21630 // neighbour forced 4x4 units on a lossy block; a lossy one handed the
21631 // lossless TxParams an 8x8 grid). libaom's order is the opposite one:
21632 // `decode_mbmi_block` (segment id included) runs before any tx-size rule.
21633 // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this
21634 // rewrite (which sat above `read_intra_mode`) rides along here -- same
21635 // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own
21636 // segment like the lossless arm above it.
21637 let (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx_h, scans) = if lossless(fctx) {
21638 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, 4, (scan4, scan4))
21639 } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
21640 let tx = if side >= 64 { 32 } else { side };
21641 let (set, scan): (TxbSet, &[u16]) = match tx {
21642 32 => (TxbSet::Chroma32, scan32),
21643 16 => (TxbSet::Chroma16, scan16),
21644 8 => (TxbSet::Chroma8, scan8),
21645 _ => (TxbSet::Chroma4, scan4),
21646 };
21647 (luma_set, set, luma_tx, tx, tx, (scans.0, scan))
21648 } else if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
21649 // lane-av1-422f: the uv plane block is the (side/2, side) rect
21650 // (`ss_size_lookup[..][1][0]`), and `av1_get_max_uv_txsize` is
21651 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[plane_bsize])` --
21652 // the RECT that fills the plane block, NOT the square transform of
21653 // the smaller side (the oracle reads ONE TX_8X16 for a 16x16 block's
21654 // 8x16 plane where the old model read two 8x8 units): 4 -> TX_4X4
21655 // (the 2x4 plane rounds up to BLOCK_4X4), 8 -> TX_4X8, 16 ->
21656 // TX_8X16, 32 -> TX_16X32 (one unit per plane, the whole plane
21657 // block), 64 -> TX_32X64 adjusts to TX_32X32 and 128 -> TX_64X64
21658 // adjusts to TX_32X32 (square units, a 1x2 / 2x4 grid).
21659 // `chroma_tx` is the unit WIDTH, `chroma_tx_h` its HEIGHT; the
21660 // chroma walks below read one (chroma_tx, chroma_tx_h) unit per grid
21661 // cell and key their rect reads on `chroma_tx != chroma_tx_h`.
21662 let (tx_w, tx_h) = match side {
21663 4 => (4, 4),
21664 8 => (4, 8),
21665 16 => (8, 16),
21666 32 => (16, 32),
21667 // 64 and 128: TX_32X64 / TX_64X64 adjust down to TX_32X32.
21668 _ => (32, 32),
21669 };
21670 let (set, scan): (TxbSet, &[u16]) = match side {
21671 4 => (TxbSet::Chroma4, scan4),
21672 8 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
21673 16 => (TxbSet::ChromaRect16x8, &SCAN_8X16[..]),
21674 32 => (TxbSet::ChromaRect32x16, &SCAN_16X32[..]),
21675 _ => (TxbSet::Chroma32, scan32),
21676 };
21677 (luma_set, set, luma_tx, tx_w, tx_h, (scans.0, scan))
21678 } else {
21679 (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx, scans)
21680 };
21681 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
21682 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
21683 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
21684 // actual chroma-from-luma correlation, same as this decoder always did.
21685 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
21686 DC_PRED
21687 } else {
21688 uv_mode
21689 };
21690 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
21691 if smooth_neighbor {
21692 hit!(SMOOTH_LUMA_HITS);
21693 }
21694 let smooth_neighbor_uv =
21695 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
21696 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21697 eprintln!(
21698 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
21699 angle_delta_uv={angle_delta_uv}"
21700 );
21701 }
21702 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
21703 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
21704 // block, skipped or not. `logical_tx` is what the loop filter's edge
21705 // lookup and the next block's own `get_tx_size_context` want (the *nominal*
21706 // transform size -- 64 even for the 64x64 corner-scanned case, spec
21707 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
21708 // which only differs from it at that one corner case.
21709 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
21710 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
21711 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
21712 // intrabc block reads NO tx-size symbol at all -- it takes
21713 // `maxRectTxSize` -- while every ordinary skipped intra block does read
21714 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
21715 // the tile from that block on (class `equal-range-means-unread`).
21716 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
21717 // tree instead (`read_var_tx_size`), the same syntax the inter block path
21718 // has always read -- libaom's `parse_decode_block` dispatches on
21719 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
21720 // intrabc block as inter.
21721 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
21722 // libaom `parse_decode_block`'s var-tx tree condition carries
21723 // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc
21724 // block inside a LOSSLESS segment of a mixed frame reads NO
21725 // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line
21726 // hands back TX_4X4. Invisible while every lossless frame was also
21727 // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which
21728 // is why the mixed frame is the first stream to reach it.
21729 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx);
21730 let intrabc_leaves = if intrabc_vartx {
21731 let max_tx = side.min(64);
21732 // `max_block_wide`/`max_block_high`: the frame's own mi grid
21733 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
21734 // right/bottom edge reads no split symbol for the units outside it.
21735 let mi_cols = 2 * y.true_width.div_ceil(8);
21736 let mi_rows = 2 * y.true_height.div_ceil(8);
21737 let side_mi = side / MI;
21738 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
21739 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
21740 let mut leaves = Vec::new();
21741 for row in (0..side_mi).step_by(max_tx / MI) {
21742 for col in (0..side_mi).step_by(max_tx / MI) {
21743 read_var_tx_size(
21744 dec,
21745 cdfs,
21746 neighbours,
21747 (mi_r, mi_c),
21748 side,
21749 (max_w_mi, max_h_mi),
21750 (max_tx, max_tx),
21751 0,
21752 row,
21753 col,
21754 &mut leaves,
21755 );
21756 }
21757 }
21758 hit!(INTRABC_VARTX_HITS);
21759 // lane-t900 r33 census: the t900 recipes resolved every tree UNIFORM.
21760 // lane-av1-ibcvtx: a tree that resolved to mixed leaf sizes is no
21761 // longer refused -- the luma reconstruct below walks the tree's own
21762 // leaf list per leaf (libaom `decode_token_recon_block`, whose token
21763 // loop reconstructs whatever `read_tx_size_vartx` resolved, per
21764 // transform unit), so mixed sizes reconstruct at their own stride.
21765 // The counter marks the shape so a gate can prove a witness actually
21766 // carries a mixed tree and not merely another uniform one.
21767 let uniform = leaves.first().is_some_and(|f| {
21768 leaves
21769 .iter()
21770 .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)
21771 });
21772 if !uniform {
21773 hit!(INTRABC_VARTX_MIXED_LEAVES_HITS);
21774 if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") {
21775 eprintln!(
21776 "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \
21777 dv={intrabc_dv:?} leaves={leaves:?}"
21778 );
21779 }
21780 }
21781 Some(leaves)
21782 } else {
21783 None
21784 };
21785 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves.as_ref().map(|l| l[0].2) {
21786 (tx, if tx == 64 { 32 } else { tx })
21787 } else if tx_select && !intrabc_skip_tx {
21788 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx);
21789 (resolved, if resolved == 64 { 32 } else { resolved })
21790 } else {
21791 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
21792 // TX_64X64, so a 128x128 block is always FOUR luma transform units
21793 // even with `tx_select` off -- the TU loop below, never the
21794 // single-unit path.
21795 (lossless_tx(side.min(64), fctx), luma_tx)
21796 };
21797 if tx_select && logical_tx < side && uv_mode != DC_PRED {
21798 hit!(SQ_CHROMA_TX_HITS);
21799 }
21800 let luma_set = if tx_select {
21801 txbset_for(logical_tx, reduced_tx_set)
21802 } else {
21803 luma_set
21804 };
21805 let luma_set = if intrabc_dv.is_some() {
21806 inter_txbset_for(logical_tx, reduced_tx_set)
21807 } else {
21808 luma_set
21809 };
21810 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
21811 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
21812 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
21813 let chroma_side = side >> ss_x(fctx);
21814 // lane-av1-422b: chroma extent per axis, `side` at ss_y 0 (4:2:2/4:4:4),
21815 // `side / 2` at 4:2:0.
21816 let chroma_height = side >> ss_y(fctx);
21817 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
21818 // frame's own pre-loop-filter reconstruction (all loop filters are off
21819 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
21820 // block vector, with the BILINEAR kernel libaom forces for intrabc --
21821 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
21822 // odd, which is exactly what the bilinear taps then interpolate.
21823 flush_recon(fctx, y, u, v);
21824 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
21825 let mut yb = vec![0u16; side * side];
21826 mc::predict_with_filter(
21827 &y.data,
21828 y.width,
21829 y.true_width,
21830 y.true_height,
21831 mv_to_q4(px, dv_col, 0),
21832 mv_to_q4(py, dv_row, 0),
21833 side,
21834 side,
21835 mc::InterpFilterKind::Bilinear,
21836 &mut yb,
21837 fctx,
21838 );
21839 let mut ub = vec![0u16; chroma_side * chroma_height];
21840 mc::predict_with_filter(
21841 &u.data,
21842 u.width,
21843 u.true_width,
21844 u.true_height,
21845 mv_to_q4(cpx, dv_col, ss_x(fctx)),
21846 mv_to_q4(cpy, dv_row, ss_y(fctx)),
21847 chroma_side,
21848 chroma_height,
21849 mc::InterpFilterKind::Bilinear,
21850 &mut ub,
21851 fctx,
21852 );
21853 let mut vb = vec![0u16; chroma_side * chroma_height];
21854 mc::predict_with_filter(
21855 &v.data,
21856 v.width,
21857 v.true_width,
21858 v.true_height,
21859 mv_to_q4(cpx, dv_col, ss_x(fctx)),
21860 mv_to_q4(cpy, dv_row, ss_y(fctx)),
21861 chroma_side,
21862 chroma_height,
21863 mc::InterpFilterKind::Bilinear,
21864 &mut vb,
21865 fctx,
21866 );
21867 (yb, ub, vb)
21868 });
21869 // A palette-Y block's own prediction is the reconstructed colour-index
21870 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
21871 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
21872 // parameter through this function's dozen `y.reconstruct`/`read_plane`
21873 // sites. A split luma transform (`tx_select && logical_tx != side`)
21874 // would need the map sliced per-TU -- untested against a real
21875 // `--enable-palette=1` stream this round, so refuse by name rather than
21876 // guess at the slicing (charter's own named-acceptable fallback).
21877 let palette_y_buf: Option<Vec<u16>> = palette_y
21878 .as_ref()
21879 .map(|py| py.map.iter().map(|&idx| py.colors[idx as usize]).collect());
21880 // lane-t900 r32: the intrabc luma prediction rides the very same
21881 // whole-block override slot, so the multi-TU loop below windows it per
21882 // transform unit exactly like a palette map -- setting it once up front
21883 // handed the whole `side`x`side` buffer to the FIRST unit and left every
21884 // later one predicting off block edges (the var-tx tree above is what
21885 // first makes `logical_tx < side` reachable for an intrabc block).
21886 let palette_y_buf = match &intrabc_bufs {
21887 Some((yb, _, _)) => Some(yb.clone()),
21888 None => palette_y_buf,
21889 };
21890 // With one luma transform unit the whole `side`x`side` map is the
21891 // prediction; with several (`logical_tx != side`) each unit takes its own
21892 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
21893 // below (lane-palette2 r7) -- setting the full-block buffer here would be
21894 // taken by the FIRST unit and indexed at the wrong stride.
21895 // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call
21896 // (the `else` arm below -- a palette/intrabc block never takes the per-unit
21897 // `split_tx_skip` walk), so its map must be armed here even when the
21898 // transform is split. Gating the arm on `logical_tx == side` alone left a
21899 // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC
21900 // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen
21901 // key frame; class override-slot-on-one-arm). Neither prediction is
21902 // edge-derived, so the whole-block buffer at the block's own stride is
21903 // exactly what that single call wants.
21904 // Counted on the SHAPE, not on the arm below, so a gate can tell a stream
21905 // that reaches this block apart from one that never does (class
21906 // gate-blind-to-feature).
21907 if palette_y_buf.is_some() && skip && logical_tx < side {
21908 hit!(SKIP_SPLIT_TX_OVERRIDE_HITS);
21909 }
21910 if let Some(buf) = &palette_y_buf
21911 && (logical_tx == side || skip)
21912 {
21913 set_palette_pred(buf.clone(), fctx);
21914 }
21915 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
21916 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
21917 // plane's own `reconstruct`/`read_plane` call below (never both planes at
21918 // once), since Y's own set-then-take already emptied the slot by the time
21919 // either of these run.
21920 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
21921 (
21922 puv.map
21923 .iter()
21924 .map(|&idx| puv.u_colors[idx as usize])
21925 .collect(),
21926 puv.map
21927 .iter()
21928 .map(|&idx| puv.v_colors[idx as usize])
21929 .collect(),
21930 )
21931 });
21932 // The chroma half of the intrabc prediction rides the same per-plane
21933 // override slot the UV-palette buffers do (set fresh before each plane's
21934 // own `reconstruct`/`read_plane` call below).
21935 let palette_uv_bufs = match &intrabc_bufs {
21936 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
21937 None => palette_uv_bufs,
21938 };
21939 if skip {
21940 // A skipped block codes no residual syntax at all (spec 5.11.34):
21941 // straight prediction, on every plane.
21942 //
21943 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
21944 // is skipped (only an INTER skip forces the largest transform), and
21945 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
21946 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
21947 // already written left/above of it inside this same block. Predicting
21948 // the whole `side`x`side` at once gives a different (uniformly off by
21949 // ~1) answer, which is exactly the residue this lane was chasing.
21950 // The palette/intrabc override path keeps the single-call shape (its
21951 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
21952 // untested for skip and unreachable in these streams).
21953 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
21954 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
21955 // per-unit prediction is keyed on the transform being smaller than
21956 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
21957 // narrower meaning (a READ split tx depth).
21958 let split_tx_skip = logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
21959 if split_tx_skip {
21960 if tx_select {
21961 hit!(SKIP_SPLIT_TX_HITS);
21962 }
21963 let n_axis = side / logical_tx;
21964 for tu_row in 0..n_axis {
21965 for tu_col in 0..n_axis {
21966 let tu_px = px + tu_col * logical_tx;
21967 let tu_py = py + tu_row * logical_tx;
21968 if tu_px >= y.true_width || tu_py >= y.true_height {
21969 continue;
21970 }
21971 let tu_reach = tu_reach(
21972 side,
21973 side,
21974 tu_col * logical_tx,
21975 tu_row * logical_tx,
21976 logical_tx,
21977 reach,
21978 px,
21979 py,
21980 y.width,
21981 y.height,
21982 fctx,
21983 );
21984 push_intra(
21985 0,
21986 tu_px,
21987 tu_py,
21988 logical_tx,
21989 mode,
21990 angle_delta_y,
21991 tu_reach,
21992 &ZERO_RESIDUAL[..logical_tx * logical_tx],
21993 None,
21994 filter_intra,
21995 smooth_neighbor,
21996 fctx,
21997 );
21998 }
21999 }
22000 } else {
22001 push_intra(
22002 0,
22003 px,
22004 py,
22005 side,
22006 mode,
22007 angle_delta_y,
22008 reach,
22009 &ZERO_RESIDUAL[..side * side],
22010 None,
22011 filter_intra,
22012 smooth_neighbor,
22013 fctx,
22014 );
22015 }
22016 let ac = alpha.map(|_| cfl_src(px, py, side));
22017 // lane-av1-422b: the chroma unit grid is `cn_cols` x `cn_rows` --
22018 // square at 4:2:0/4:4:4, at 4:2:2 `(side/2)/tx` units wide by
22019 // `side/tx` tall (the plane block is (side/2, side)). A unit's LUMA
22020 // anchor follows the per-axis shifts: `chroma_tx << ss_x` wide,
22021 // `chroma_tx_h << ss_y` tall (lane-av1-422f: the unit itself is the
22022 // (chroma_tx, chroma_tx_h) rect, so a 4:2:2 frame below side 64
22023 // reads ONE unit per plane, the whole plane block).
22024 let cn_cols = (chroma_side / chroma_tx).max(1);
22025 let cn_rows = (chroma_height / chroma_tx_h).max(1);
22026 let luma_span_x = chroma_tx << ss_x(fctx);
22027 let luma_span_y = chroma_tx_h << ss_y(fctx);
22028 for cu_row in 0..cn_rows {
22029 for cu_col in 0..cn_cols {
22030 let cu_r = if cn_rows == 1 && cn_cols == 1 {
22031 reach
22032 } else {
22033 tu_reach_rect(
22034 side,
22035 side,
22036 cu_col * luma_span_x,
22037 cu_row * luma_span_y,
22038 luma_span_x,
22039 luma_span_y,
22040 reach,
22041 px,
22042 py,
22043 y.width,
22044 y.height,
22045 fctx,
22046 )
22047 };
22048 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
22049 // lane-av1chromadc: the chroma override is a whole
22050 // `chroma_side x chroma_height` buffer and
22051 // `PlaneBuf::reconstruct` uses the buffer it takes as the
22052 // UNIT's own `chroma_tx x chroma_tx_h` prediction, so a
22053 // multi-unit plane block must hand each unit its own window of
22054 // it. Handing the whole buffer (the pre-fix shape) made every
22055 // unit predict from the top-left one: at 4:2:0 the chroma plane
22056 // block is a single 32x32 unit, so the whole buffer IS that
22057 // unit's window and the bug is invisible -- which is why every
22058 // 4:2:0 gate stayed green -- and at 4:4:4 a 64x64 block's 64x64
22059 // plane block is a 2x2 grid whose right and bottom columns were
22060 // a copy of its top-left unit.
22061 // MEASURED on `fixtures/r512.obu` (4:4:4 8-bit 512x512, three
22062 // frames): frame 0's skipped 64x64 intra-BC block at
22063 // `mi=(112,80)` `px=(320,448)` reconstructed its `cu=(1,0)`
22064 // unit at `px=(352,448)` as a flat 241 where the oracle has
22065 // 202 -- byte-identical to its `cu=(0,0)` prediction, sum
22066 // 882176 and all -- and the coded 64x64 to its right then read
22067 // 202/175 against the oracle's 165/166. Gate:
22068 // `a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit`.
22069 let chroma_window = |buf: &[u16]| -> Vec<u16> {
22070 if cn_cols == 1 && cn_rows == 1 {
22071 return buf.to_vec();
22072 }
22073 let mut window = Vec::with_capacity(chroma_tx * chroma_tx_h);
22074 for row in 0..chroma_tx_h {
22075 let at = (cu_row * chroma_tx_h + row) * chroma_side + cu_col * chroma_tx;
22076 window.extend_from_slice(&buf[at..at + chroma_tx]);
22077 }
22078 window
22079 };
22080 if let Some((ub, _)) = &palette_uv_bufs {
22081 if cn_cols * cn_rows > 1 {
22082 hit!(SKIP_CHROMA_OVERRIDE_WINDOW_HITS);
22083 }
22084 set_palette_pred(chroma_window(ub), fctx);
22085 }
22086 push_intra_unit(
22087 1,
22088 cu_x,
22089 cu_y,
22090 chroma_tx,
22091 chroma_tx_h,
22092 uv_predict_mode,
22093 angle_delta_uv,
22094 cu_r,
22095 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
22096 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22097 None,
22098 smooth_neighbor_uv,
22099 fctx,
22100 );
22101 if let Some((_, vb)) = &palette_uv_bufs {
22102 set_palette_pred(chroma_window(vb), fctx);
22103 }
22104 push_intra_unit(
22105 2,
22106 cu_x,
22107 cu_y,
22108 chroma_tx,
22109 chroma_tx_h,
22110 uv_predict_mode,
22111 angle_delta_uv,
22112 cu_r,
22113 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
22114 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22115 None,
22116 smooth_neighbor_uv,
22117 fctx,
22118 );
22119 }
22120 }
22121 let luma_grid = vec![0i32; side * side];
22122 let u_grid = vec![0i32; chroma_side * chroma_side];
22123 let v_grid = vec![0i32; chroma_side * chroma_side];
22124 neighbours.record(
22125 at,
22126 side,
22127 mode,
22128 uv_predict_mode,
22129 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
22130 );
22131 } else if logical_tx == side {
22132 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
22133 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
22134 // that arm was redundant -- and wrong at 128, where
22135 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
22136 // block is four units whether or not `tx_select` is on.
22137 // A single luma transform unit -- the old path, unchanged (including
22138 // the 64x64 corner case, `logical_tx == side == 64` with
22139 // `coeff_tx_side == 32`).
22140 let around = neighbours.around(at, side);
22141 let luma_grid = read_plane(
22142 dec,
22143 cdfs,
22144 luma_set,
22145 luma_scan,
22146 0,
22147 around[0],
22148 mode,
22149 mode,
22150 angle_delta_y,
22151 reach,
22152 y,
22153 px,
22154 py,
22155 side,
22156 coeff_tx_side,
22157 base_q_idx,
22158 None,
22159 filter_intra,
22160 None,
22161 smooth_neighbor,
22162 fctx,
22163 )?;
22164 let ac = alpha.map(|_| cfl_src(px, py, side));
22165 // Armed for exactly this block's two chroma reads (see
22166 // [`INTRABC_CHROMA_TX`]); the luma call above just set
22167 // [`LUMA_TX_TYPE`] to the type it coded.
22168 if intrabc_dv.is_some() {
22169 fctx.intrabc_chroma_tx
22170 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
22171 }
22172 // lane-av1-444: this arm is one luma TU (`logical_tx == side`), including
22173 // the 64x64 case whose coefficient grid is 32. At 4:4:4 the chroma plane
22174 // is the same size as luma and `av1_get_max_uv_txsize` caps it at
22175 // TX_32X32, so a 64x64 block codes four chroma units, plane-major
22176 // (every U, then every V) — the same loop the multi-TU arm runs.
22177 // At 4:2:0 `chroma_side == chroma_tx`, so it stays one read.
22178 // lane-av1-422b: 4:2:2 never collapses to one read above a 4x4 luma
22179 // block -- the unit grid is `(side/2)/tx` wide by `side/tx` tall.
22180 // lane-av1-422f: `chroma_tx` is the unit WIDTH and `chroma_tx_h` its
22181 // HEIGHT, so below side 64 a 4:2:2 frame's grid is 1x1 and the one
22182 // unit is the plane block's own rect.
22183 let cn_cols = (chroma_side / chroma_tx).max(1);
22184 let cn_rows = (chroma_height / chroma_tx_h).max(1);
22185 let luma_span_x = chroma_tx << ss_x(fctx);
22186 let luma_span_y = chroma_tx_h << ss_y(fctx);
22187 let (u_grid, v_grid, chroma_units) = if cn_rows == 1 && cn_cols == 1 {
22188 if chroma_tx == chroma_tx_h {
22189 if let Some((ub, _)) = &palette_uv_bufs {
22190 set_palette_pred(ub.clone(), fctx);
22191 }
22192 let u_grid = read_plane(
22193 dec,
22194 cdfs,
22195 chroma_set,
22196 scans.1,
22197 1,
22198 around[1],
22199 mode,
22200 uv_predict_mode,
22201 angle_delta_uv,
22202 reach,
22203 u,
22204 cpx,
22205 cpy,
22206 chroma_side,
22207 chroma_tx,
22208 base_q_idx,
22209 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22210 None,
22211 None,
22212 smooth_neighbor_uv,
22213 fctx,
22214 )?;
22215 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22216 eprintln!(
22217 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
22218 &u.data[cpy * u.width + cpx..][..chroma_side]
22219 );
22220 }
22221 if let Some((_, vb)) = &palette_uv_bufs {
22222 set_palette_pred(vb.clone(), fctx);
22223 }
22224 let v_grid = read_plane(
22225 dec,
22226 cdfs,
22227 chroma_set,
22228 scans.1,
22229 2,
22230 around[2],
22231 mode,
22232 uv_predict_mode,
22233 angle_delta_uv,
22234 reach,
22235 v,
22236 cpx,
22237 cpy,
22238 chroma_side,
22239 chroma_tx,
22240 base_q_idx,
22241 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22242 None,
22243 None,
22244 smooth_neighbor_uv,
22245 fctx,
22246 )?;
22247 (u_grid, v_grid, Vec::new())
22248 } else {
22249 // lane-av1-422f: the one unit is a RECT filling the plane
22250 // block -- the square-shaped [`read_plane`] cannot express
22251 // it, so both planes go through [`read_rect_chroma_unit`]
22252 // (U, then V, the same order the square arm reads). The
22253 // chroma context reads per chroma 4-px cell (see
22254 // [`Neighbours::around_mi_422_chroma`]).
22255 let chroma_around = neighbours.around_mi_422_chroma((mi_r, mi_c), side, side);
22256 if let Some((ub, _)) = &palette_uv_bufs {
22257 set_palette_pred(ub.clone(), fctx);
22258 }
22259 let u_grid = read_rect_chroma_unit(
22260 dec,
22261 cdfs,
22262 chroma_set,
22263 scans.1,
22264 chroma_tx,
22265 chroma_tx_h,
22266 1,
22267 chroma_around[1],
22268 uv_predict_mode,
22269 angle_delta_uv,
22270 reach,
22271 u,
22272 cpx,
22273 cpy,
22274 base_q_idx,
22275 None,
22276 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
22277 smooth_neighbor_uv,
22278 fctx,
22279 )?;
22280 if let Some((_, vb)) = &palette_uv_bufs {
22281 set_palette_pred(vb.clone(), fctx);
22282 }
22283 let v_grid = read_rect_chroma_unit(
22284 dec,
22285 cdfs,
22286 chroma_set,
22287 scans.1,
22288 chroma_tx,
22289 chroma_tx_h,
22290 2,
22291 chroma_around[2],
22292 uv_predict_mode,
22293 angle_delta_uv,
22294 reach,
22295 v,
22296 cpx,
22297 cpy,
22298 base_q_idx,
22299 None,
22300 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
22301 smooth_neighbor_uv,
22302 fctx,
22303 )?;
22304 (u_grid, v_grid, Vec::new())
22305 }
22306 } else {
22307 let chroma_ctx_offset = Some(3);
22308 let mut u_pass: Vec<Grid> = Vec::new();
22309 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
22310 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
22311 for plane_pass in 1..=2usize {
22312 let mut pass_idx = 0usize;
22313 for cu_row in 0..cn_rows {
22314 for cu_col in 0..cn_cols {
22315 let cu_mi = (
22316 mi_r + cu_row * (luma_span_y / MI),
22317 mi_c + cu_col * (luma_span_x / MI),
22318 );
22319 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22320 // lane-av1-422f: chroma-only loop; per-chroma-cell
22321 // above votes (see [`Neighbours::around_mi_422_chroma`]).
22322 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
22323 } else {
22324 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
22325 };
22326 let cu_reach = tu_reach_rect(
22327 side,
22328 side,
22329 cu_col * luma_span_x,
22330 cu_row * luma_span_y,
22331 luma_span_x,
22332 luma_span_y,
22333 reach,
22334 px,
22335 py,
22336 y.width,
22337 y.height,
22338 fctx,
22339 );
22340 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
22341 if let Some((ub, vb)) = &palette_uv_bufs {
22342 let pbuf = if plane_pass == 1 { ub } else { vb };
22343 set_palette_pred(
22344 palette_window(
22345 pbuf,
22346 chroma_side,
22347 cu_col * chroma_tx,
22348 cu_row * chroma_tx_h,
22349 chroma_tx,
22350 chroma_tx_h,
22351 ),
22352 fctx,
22353 );
22354 }
22355 let buf: &mut PlaneBuf<'static> =
22356 if plane_pass == 1 { &mut *u } else { &mut *v };
22357 let cu_grid = read_plane(
22358 dec,
22359 cdfs,
22360 chroma_set,
22361 scans.1,
22362 plane_pass,
22363 cu_around[plane_pass],
22364 mode,
22365 uv_predict_mode,
22366 angle_delta_uv,
22367 cu_reach,
22368 buf,
22369 cu_x,
22370 cu_y,
22371 chroma_tx,
22372 chroma_tx,
22373 base_q_idx,
22374 alpha
22375 .zip(ac)
22376 .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)),
22377 None,
22378 chroma_ctx_offset,
22379 smooth_neighbor_uv,
22380 fctx,
22381 )?;
22382 hit!(CHROMA_SPLIT_TX_HITS);
22383 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22384 hit!(CHROMA422_SQUARE_HITS);
22385 }
22386 // Immediately, so the next unit of this block reads this
22387 // one's coefficient context. `record` below stamps one
22388 // chroma state across the whole block; the replay after
22389 // it puts the per-unit state back.
22390 neighbours.record_mi_chroma(
22391 cu_mi,
22392 luma_span_x,
22393 luma_span_y,
22394 plane_pass,
22395 &cu_grid,
22396 );
22397 if plane_pass == 1 {
22398 u_pass.push(cu_grid);
22399 } else {
22400 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
22401 units.push((
22402 cu_mi,
22403 luma_span_x,
22404 luma_span_y,
22405 u_grid.clone(),
22406 cu_grid.clone(),
22407 ));
22408 last_grids = [u_grid, cu_grid];
22409 }
22410 pass_idx += 1;
22411 }
22412 }
22413 }
22414 (last_grids[0].clone(), last_grids[1].clone(), units)
22415 };
22416 fctx.intrabc_chroma_tx.with(|c| c.set(None));
22417 neighbours.record(
22418 at,
22419 side,
22420 mode,
22421 uv_predict_mode,
22422 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
22423 );
22424 for (cu_mi, sw, sh, u_unit, v_unit) in &chroma_units {
22425 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_unit);
22426 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_unit);
22427 }
22428 } else {
22429 // Several luma transform units, raster order (spec
22430 // `transform_block`'s loop): the block's resolved transform is
22431 // genuinely smaller than its own side, so each tile of it predicts
22432 // and codes independently, its own context read fresh off whatever
22433 // the earlier tiles in this same block already wrote -- the same
22434 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
22435 let n_axis = side / logical_tx;
22436 // lane-av1-422f: unit width/height per axis, like walk 2 above --
22437 // a 4:2:2 frame below side 64 reads ONE rect unit per plane per
22438 // chunk, the whole plane block.
22439 let cn_cols = (chroma_side / chroma_tx).max(1);
22440 let cn_rows = (chroma_height / chroma_tx_h).max(1);
22441 let luma_span_x = chroma_tx << ss_x(fctx);
22442 let luma_span_y = chroma_tx_h << ss_y(fctx);
22443 // libaom's transform-block loop is over 64x64 luma "mu" chunks
22444 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
22445 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
22446 // before moving to the next one. Below 128 a block is a single chunk,
22447 // so this is byte-for-byte the all-luma-then-all-chroma order that has
22448 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
22449 // and reading all four luma units first desyncs the tile at the second
22450 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
22451 let nchunk = (side / 64).max(1);
22452 // `cn > 1` means the uv plane block is larger than the uv transform,
22453 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
22454 let chroma_ctx_offset = if cn_rows * cn_cols > 1 { Some(3) } else { None };
22455 let tpc = (n_axis / nchunk).max(1);
22456 let cpc_rows = (cn_rows / nchunk).max(1);
22457 let cpc_cols = (cn_cols / nchunk).max(1);
22458 // The block's luma transform units, raster order inside each mu
22459 // chunk. lane-av1-ibcvtx: an intrabc block's units are the var-tx
22460 // tree's own leaf list -- mixed sizes included, exactly what libaom's
22461 // `decode_token_recon_block` token loop reconstructs (one
22462 // `av1_read_coeffs_txb` + inverse transform per resolved unit) --
22463 // while every other block's list is the uniform `logical_tx` grid
22464 // this loop has always walked, generated here in the same order.
22465 let mut chunk_tus: Vec<Vec<(usize, usize, usize)>> = vec![Vec::new(); nchunk * nchunk];
22466 if let Some(leaves) = &intrabc_leaves {
22467 for &(lr, lc, tw, _th) in leaves {
22468 let (off_y, off_x) = (lr * MI, lc * MI);
22469 chunk_tus[(off_y / 64) * nchunk + (off_x / 64)].push((off_y, off_x, tw));
22470 }
22471 } else {
22472 for tu_row in 0..n_axis {
22473 for tu_col in 0..n_axis {
22474 chunk_tus[(tu_row / tpc) * nchunk + (tu_col / tpc)].push((
22475 tu_row * logical_tx,
22476 tu_col * logical_tx,
22477 logical_tx,
22478 ));
22479 }
22480 }
22481 }
22482 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
22483 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
22484 for ch_row in 0..nchunk {
22485 for ch_col in 0..nchunk {
22486 // lane-av1-ibcvtx: the chunk's chroma units inherit the CHROMA tx
22487 // type of the co-located luma position (`av1_get_tx_type`,
22488 // blockd.h:1278: a non-Y plane of an inter-classified block -- and
22489 // intrabc is one -- reads `tx_type_map`, i.e. the coded type of the
22490 // luma unit covering it). Inside a mu chunk that is the chunk's
22491 // FIRST luma unit in raster order (the chunk origin is always the
22492 // first leaf's own origin). Captured right after that unit's read;
22493 // the single-TU arm below does the same for a whole-block unit.
22494 let mut first_leaf_tx: Option<TxType> = None;
22495 for &(tu_off_y, tu_off_x, tu_tx) in &chunk_tus[ch_row * nchunk + ch_col] {
22496 let tu_mi = (mi_r + tu_off_y / MI, mi_c + tu_off_x / MI);
22497 let tu_px = px + tu_off_x;
22498 let tu_py = py + tu_off_y;
22499 // Same libaom clip as `decode_rect_split`'s loop above; a
22500 // square block only hangs off the frame when the frame's mi
22501 // dimensions are odd at the block's own level.
22502 if tu_px >= y.true_width || tu_py >= y.true_height {
22503 continue;
22504 }
22505 let tu_around = neighbours.around_mi(tu_mi, tu_tx)[0];
22506 // A transform unit inside a block is NOT a block at that
22507 // position (lane-palette2 r12): `Reach::of` granted the
22508 // top-right 8x8 unit of a 16x16 D203 block bottom-left
22509 // pixels libaom refuses outright (`col_off > 0`), which is
22510 // the diagonal wedge seed 46 reconstructed wrong.
22511 let tu_reach = tu_reach(
22512 side, side, tu_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height,
22513 fctx,
22514 );
22515 // This transform unit's own bsize (`tu_tx`) is smaller
22516 // than the block it sits in (`side`), so `txb_skip_ctx` is
22517 // the neighbour-magnitude table, not the lone-TU 0 (spec
22518 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
22519 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tu_tx / MI);
22520 // An intrabc unit's CDF set and scan follow the unit's OWN
22521 // resolved size (`get_txsize_entropy_ctx` /
22522 // `av1_get_scan` per `av1_read_coeffs_txb` call); the
22523 // uniform grid's precomputed pair already matches because
22524 // `tu_tx == logical_tx` there.
22525 let (tu_set, tu_scan) = if intrabc_dv.is_some() {
22526 (
22527 inter_txbset_for(tu_tx, reduced_tx_set),
22528 scan_for(
22529 if tu_tx == 64 { 32 } else { tu_tx },
22530 scan32,
22531 scan16,
22532 scan8,
22533 scan4,
22534 ),
22535 )
22536 } else {
22537 (luma_set, luma_scan)
22538 };
22539 if let Some(buf) = &palette_y_buf {
22540 hit!(PALETTE_SPLIT_TX_HITS);
22541 let mut window = vec![0u16; tu_tx * tu_tx];
22542 for row in 0..tu_tx {
22543 let src = (tu_off_y + row) * side + tu_off_x;
22544 window[row * tu_tx..][..tu_tx].copy_from_slice(&buf[src..][..tu_tx]);
22545 }
22546 set_palette_pred(window, fctx);
22547 }
22548 let tu_grid = read_plane(
22549 dec,
22550 cdfs,
22551 tu_set,
22552 tu_scan,
22553 0,
22554 tu_around,
22555 mode,
22556 mode,
22557 angle_delta_y,
22558 tu_reach,
22559 y,
22560 tu_px,
22561 tu_py,
22562 tu_tx,
22563 // The unit's own COEFFICIENT grid, half its side at
22564 // TX_64X64 (a 64-point transform codes nothing past 32);
22565 // identical to `tu_tx` at every smaller size
22566 // (lane-sb128b r1).
22567 if tu_tx == 64 { 32 } else { tu_tx },
22568 base_q_idx,
22569 None,
22570 filter_intra,
22571 Some(tu_skip_ctx),
22572 smooth_neighbor,
22573 fctx,
22574 )?;
22575 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22576 eprintln!(
22577 "TRACE tu_bitpos mi=({},{}) tell={}",
22578 tu_mi.0,
22579 tu_mi.1,
22580 dec.debug_bitpos()
22581 );
22582 }
22583 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);
22584 if first_leaf_tx.is_none() {
22585 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
22586 }
22587 }
22588 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
22589 // this still runs after every luma unit of the block.
22590 let ac = alpha.map(|_| cfl_src(px, py, side));
22591 // lane-av1-ibcvtx: an intrabc block's chroma rides the luma's coded
22592 // tx type (see `first_leaf_tx` above) -- the same arm the single-TU
22593 // branch sets before its own chroma reads.
22594 if intrabc_dv.is_some() {
22595 if let Some(t) = first_leaf_tx {
22596 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
22597 }
22598 }
22599 // The block's uv plane block is `chroma_side` across but its uv
22600 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
22601 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
22602 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
22603 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
22604 // FOUR units (lane-sb128b r2) -- one per mu chunk.
22605 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
22606 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
22607 // the chunk, then every V unit. At one unit per plane per chunk --
22608 // every non-lossless case this decoder reaches -- that is the same
22609 // symbol order as the interleaved pair this loop used to read; a
22610 // lossless frame's 4x4 chroma units are the case where it differs
22611 // (lane-lossless2).
22612 let mut u_pass: Vec<Grid> = Vec::new();
22613 for plane_pass in 1..=2usize {
22614 let mut pass_idx = 0usize;
22615 for cu_row in ch_row * cpc_rows..(ch_row + 1) * cpc_rows {
22616 for cu_col in ch_col * cpc_cols..(ch_col + 1) * cpc_cols {
22617 // libaom `decode_reconstruct_tx`'s frame-edge clip
22618 // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col
22619 // >= max_blocks_wide` returns before ANY symbol is read): a
22620 // transform unit whose 4x4 origin sits outside the frame's mi
22621 // grid is not coded at all. The luma loop above carries the
22622 // same clip; its absence here read `txb_skip` (+coeffs) for
22623 // chroma units libaom never wrote -- the lossless 64x64 block
22624 // at mi(48,0) of a 320x240 frame overhangs the bottom edge by
22625 // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not
22626 // eight (lane-av1-loss64; 48 chroma units per plane in
22627 // aomdec's EC_COEFF census vs the 64 this loop read).
22628 // `max_block_wide/high` (av1_common_int.h:1565): the plane
22629 // block's pixel span (4:2:0 halves the luma span, clamped to
22630 // 4 by `set_plane_n4`) plus the negative overhang
22631 // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4
22632 // units.
22633 let span_mi = side / MI;
22634 let over_w_mi = (2 * y.true_width.div_ceil(8)) as i32
22635 - mi_c as i32
22636 - span_mi as i32;
22637 let over_h_mi = (2 * y.true_height.div_ceil(8)) as i32
22638 - mi_r as i32
22639 - span_mi as i32;
22640 // `max_block_wide/high` in chroma pixels: the plane block's
22641 // own span (`side` at 4:4:4, `side / 2` at 4:2:0 -- the old
22642 // hardcoded `span_mi * 2` clipped three quarters of a 4:4:4
22643 // block's coded units and desynced the tile) plus the
22644 // negative overhang (`mb_to_*_edge >> (3 + ss)`), whose
22645 // chroma-px scale is `MI >> ss` per mi.
22646 let plane_px = (((span_mi * MI) >> ss_x(fctx)).max(4)) as i32;
22647 let over_w_px = over_w_mi.min(0) * (MI >> ss_x(fctx)) as i32;
22648 let over_h_px = over_h_mi.min(0) * (MI >> ss_y(fctx)) as i32;
22649 let max_units_w = ((plane_px + over_w_px) >> 2).max(0) as usize;
22650 // lane-av1-422f: the shared halved formula in the `else` counts
22651 // the plane span in 4-px units through the 2-px-per-mi
22652 // subsampled height, which a 4:2:2 plane does not have (ss_y
22653 // 0) -- its span is the full luma mi count, so a keyed
22654 // formula clips the same units libaom's `max_block_high`
22655 // does. 4:2:0 and 4:4:4 keep the proven shared rows (at 4:2:0
22656 // `MI >> ss_y` is 2, the same `2 * over_h_mi.min(0)` the
22657 // pre-ss form spelled).
22658 let max_units_h = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22659 (span_mi as i32 + over_h_mi.min(0)).max(0) as usize
22660 } else {
22661 ((plane_px + over_h_px) >> 2).max(0) as usize
22662 };
22663 let (unit_w, unit_h) = (chroma_tx / 4, chroma_tx_h / 4);
22664 if cu_col * unit_w >= max_units_w || cu_row * unit_h >= max_units_h {
22665 hit!(CHROMA_EDGE_TU_CLIP_HITS);
22666 continue;
22667 }
22668 // The chroma context arrays are indexed in LUMA mi, so this
22669 // unit's anchor is its own luma quadrant (lane-av1-422b: the
22670 // quadrant spans `chroma_tx << ss_x` luma px wide by
22671 // `chroma_tx_h << ss_y` tall -- at 4:2:2 below side 64 the
22672 // one unit's quadrant is the whole block).
22673 let cu_mi = (
22674 mi_r + cu_row * (luma_span_y / MI),
22675 mi_c + cu_col * (luma_span_x / MI),
22676 );
22677 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22678 // lane-av1-422f: chroma-only loop; per-chroma-cell above
22679 // votes (see [`Neighbours::around_mi_422_chroma`]).
22680 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
22681 } else {
22682 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
22683 };
22684 let cu_reach = if cn_rows == 1 && cn_cols == 1 {
22685 reach
22686 } else {
22687 tu_reach_rect(
22688 side,
22689 side,
22690 cu_col * luma_span_x,
22691 cu_row * luma_span_y,
22692 luma_span_x,
22693 luma_span_y,
22694 reach,
22695 px,
22696 py,
22697 y.width,
22698 y.height,
22699 fctx,
22700 )
22701 };
22702 let (cu_x, cu_y) =
22703 (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
22704 if let Some((ub, vb)) = &palette_uv_bufs {
22705 let pbuf = if plane_pass == 1 { ub } else { vb };
22706 set_palette_pred(
22707 palette_window(
22708 pbuf,
22709 chroma_side,
22710 cu_col * chroma_tx,
22711 cu_row * chroma_tx_h,
22712 chroma_tx,
22713 chroma_tx_h,
22714 ),
22715 fctx,
22716 );
22717 }
22718 let buf: &mut PlaneBuf<'static> =
22719 if plane_pass == 1 { &mut *u } else { &mut *v };
22720 let cu_grid = if chroma_tx == chroma_tx_h {
22721 read_plane(
22722 dec,
22723 cdfs,
22724 chroma_set,
22725 scans.1,
22726 plane_pass,
22727 cu_around[plane_pass],
22728 mode,
22729 uv_predict_mode,
22730 angle_delta_uv,
22731 cu_reach,
22732 buf,
22733 cu_x,
22734 cu_y,
22735 chroma_tx,
22736 chroma_tx,
22737 base_q_idx,
22738 alpha.zip(ac).map(|((au, av), ac)| {
22739 (if plane_pass == 1 { au } else { av }, ac)
22740 }),
22741 None,
22742 chroma_ctx_offset,
22743 smooth_neighbor_uv,
22744 fctx,
22745 )?
22746 } else {
22747 // lane-av1-422f: the whole plane block as one rect unit;
22748 // `chroma_ctx_offset` is `None` there (the unit covers
22749 // the plane block, so the offset-7 skip rows are right).
22750 read_rect_chroma_unit(
22751 dec,
22752 cdfs,
22753 chroma_set,
22754 scans.1,
22755 chroma_tx,
22756 chroma_tx_h,
22757 plane_pass,
22758 cu_around[plane_pass],
22759 uv_predict_mode,
22760 angle_delta_uv,
22761 cu_reach,
22762 buf,
22763 cu_x,
22764 cu_y,
22765 base_q_idx,
22766 None,
22767 alpha.zip(ac).map(|((au, av), ac)| {
22768 (if plane_pass == 1 { au } else { av }, ac)
22769 }),
22770 smooth_neighbor_uv,
22771 fctx,
22772 )?
22773 };
22774 if cn_rows * cn_cols > 1 {
22775 hit!(CHROMA_SPLIT_TX_HITS);
22776 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
22777 hit!(CHROMA422_SQUARE_HITS);
22778 }
22779 // Immediately, so the NEXT unit of this same block reads
22780 // this one's coefficient context (libaom's chroma
22781 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
22782 // 1 from this left neighbour -- measured against aomdec).
22783 // The same writes are replayed after `record_split_luma`
22784 // below, which would otherwise clobber them whole-block.
22785 neighbours.record_mi_chroma(
22786 cu_mi,
22787 luma_span_x,
22788 luma_span_y,
22789 plane_pass,
22790 &cu_grid,
22791 );
22792 }
22793 if plane_pass == 1 {
22794 u_pass.push(cu_grid);
22795 } else {
22796 let u_grid =
22797 std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
22798 if cn_rows * cn_cols > 1 {
22799 units.push((
22800 cu_mi,
22801 luma_span_x,
22802 luma_span_y,
22803 u_grid.clone(),
22804 cu_grid.clone(),
22805 ));
22806 }
22807 last_grids = [u_grid, cu_grid];
22808 }
22809 pass_idx += 1;
22810 }
22811 }
22812 }
22813 }
22814 if intrabc_dv.is_some() {
22815 fctx.intrabc_chroma_tx.with(|c| c.set(None));
22816 }
22817 }
22818 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
22819 // context write; at `cn > 1` the per-unit writes above are what the
22820 // next block reads, so they run after this (last writer wins).
22821 neighbours.record_split_luma(
22822 at,
22823 side,
22824 mode,
22825 uv_predict_mode,
22826 [&last_grids[0], &last_grids[1]],
22827 );
22828 for (cu_mi, sw, sh, u_grid, v_grid) in &units {
22829 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_grid);
22830 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_grid);
22831 }
22832 }
22833 // Unconditional, `size == 0` for a non-palette block: clears any stale
22834 // neighbour palette state the same way [`Neighbours::record`] always
22835 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
22836 // (the split-luma-TU branch above always refuses before reaching here
22837 // when `palette_y` is `Some`, so it is never live for that branch).
22838 let (py_size, py_colors) = palette_y
22839 .as_ref()
22840 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
22841 neighbours.record_palette_y(at, side, py_size, py_colors);
22842 let (puv_size, puv_colors) = palette_uv
22843 .as_ref()
22844 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
22845 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
22846 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
22847 neighbours.fill_lf_grid(
22848 (r * (SUB / MI), c * (SUB / MI)),
22849 side / MI,
22850 logical_tx as u8,
22851 0,
22852 fctx,
22853 );
22854 // lane-t900 r32 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size,
22855 // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY
22856 // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM
22857 // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express
22858 // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED
22859 // intrabc block publish its BLOCK size instead, intrabc being the only
22860 // "inter" block an intra-only frame codes (`blockd.h:373`). So this call
22861 // stays the authority wherever one can appear; with `allow_intrabc` unset
22862 // it writes exactly what the grid already did.
22863 if allow_intrabc {
22864 set_txfm_ctxs(
22865 neighbours,
22866 (mi_r, mi_c),
22867 logical_tx,
22868 side / MI,
22869 side / MI,
22870 skip && intrabc_dv.is_some(),
22871 );
22872 }
22873 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, neighbours, fctx);
22874 Ok(())
22875}
22876
22877thread_local! {
22878 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
22879 /// root's HORZ arm, and 64x128 ones at its VERT arm.
22880 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22881 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22882 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
22883 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
22884 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
22885 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
22886 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
22887 /// inter frame) -- (128x64, 64x128).
22888 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
22889 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
22890 /// handed back var-tx leaves, so the per-transform-unit luma publication
22891 /// loop never ran and the block has to clear its own luma coefficient
22892 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
22893 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
22894 /// non-vacuous.
22895 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22896 /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded
22897 /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the
22898 /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this
22899 /// shape non-vacuous -- a stream that never codes one reads 0.
22900 pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22901 /// lane-av1-128rectspan: chroma transform units of a 128-root HORZ/VERT
22902 /// intra block re-stamped by the end-of-block replay
22903 /// (`record_split_luma_rect` clobbers the per-unit contexts the chroma
22904 /// walk published, so every unit replays its own state after it). A
22905 /// non-skip 128x64/64x128 block codes `nch_x * cn * 2 + nch_y * cn_h * 2`
22906 /// of them, so this reads 0 on any stream that never codes one -- the
22907 /// non-vacuity anchor for the replay's own gate.
22908 pub(crate) static SB128RECT_CHROMA_REPLAY_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22909 /// ... and the number of non-skip 128-root rect BLOCKS whose replay
22910 /// height differs from the unit's own LUMA-MI height -- the signature of the
22911 /// width passed to both axes (`luma_span` where the in-loop stamp used
22912 /// `luma_span_h`). Zero on every stream this decoder admits: both
22913 /// supported chroma formats have `ss_x == ss_y` (4:2:0 and 4:4:4), and
22914 /// 4:2:2 -- the one format whose two spans differ -- is refused by name
22915 /// at the sequence header (`stream::decode_frame`), so the arm is
22916 /// defensive until that format is ported. The counter turns a future
22917 /// 4:2:2 admission (or any hardcoded span) into a named red gate instead
22918 /// of silent mi-state corruption.
22919 pub(crate) static SB128RECT_REPLAY_SPAN_MISMATCH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
22920}
22921
22922/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
22923pub fn skip_vartx_luma_reset_hits() -> usize {
22924 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
22925}
22926
22927/// [`INTRA128_LOSSLESS_HITS`], for a gate's own before/after delta.
22928pub(crate) fn intra128_lossless_hits() -> usize {
22929 INTRA128_LOSSLESS_HITS.with(std::cell::Cell::get)
22930}
22931
22932/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
22933pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
22934 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
22935}
22936
22937/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
22938/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
22939pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
22940 (
22941 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
22942 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
22943 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
22944 )
22945}
22946
22947/// [`SB128RECT_CHROMA_REPLAY_HITS`] (chroma units re-stamped by
22948/// `decode_block_128rect`'s end-of-block replay) and
22949/// [`SB128RECT_REPLAY_SPAN_MISMATCH_HITS`] (replays whose stamped height was
22950/// not the unit's own), for a gate's own before/after delta.
22951pub(crate) fn sb128rect_chroma_replay_hits() -> (usize, usize) {
22952 (
22953 SB128RECT_CHROMA_REPLAY_HITS.with(std::cell::Cell::get),
22954 SB128RECT_REPLAY_SPAN_MISMATCH_HITS.with(std::cell::Cell::get),
22955 )
22956}
22957
22958/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
22959/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
22960/// `decode_inter_block`'s own rect path).
22961///
22962/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
22963/// transform unit, with the 128-specific geometry:
22964/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
22965/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
22966/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
22967/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
22968/// same CDF a 64x64 square block reads).
22969/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
22970/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
22971/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
22972/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
22973/// a chunk before moving to the next (the interleave lane-sb128b r3
22974/// measured at the 128x128 NONE root).
22975/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
22976/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
22977/// No CfL, no filter intra (both cap at 32x32) and no palette
22978/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
22979/// reader's own size gates already say so, and the guard below is defensive.
22980///
22981/// lane-lossless128: on a LOSSLESS frame every one of those sizes collapses to
22982/// TX_4X4 -- `read_tx_mode` returns `ONLY_4X4` before the frame codes a tx-size
22983/// symbol and `read_tx_size` returns `TX_4X4` before it looks at anything
22984/// (`decodeframe.c:141`, `:1183`) -- so the block is tiled into 4x4 luma units
22985/// and (because a lossless frame forces `TX_4X4` on CHROMA too) 4x4 chroma
22986/// units, plane-major inside each 64x64 mu chunk exactly as
22987/// `decode_token_recon_block` codes them. Reading the 64-point geometry there
22988/// reconstructs into a `side`-sized plane with a 16-sample residual (the panic
22989/// this lane closed); the geometry and the unit walks below are normalized on
22990/// `lossless_frame`.
22991#[allow(clippy::too_many_arguments)]
22992fn decode_block_128rect(
22993 dec: &mut SymbolDecoder,
22994 cdfs: &mut Cdfs,
22995 neighbours: &mut Neighbours,
22996 at: (usize, usize),
22997 bw: usize,
22998 bh: usize,
22999 y: &mut PlaneBuf<'static>,
23000 u: &mut PlaneBuf<'static>,
23001 v: &mut PlaneBuf<'static>,
23002 base_q_idx: u8,
23003 enable_filter_intra: bool,
23004 allow_screen_content_tools: bool,
23005 tx_select: bool,
23006 reduced_tx_set: bool,
23007 fctx: &crate::decode::FrameCtx,
23008) -> Result<()> {
23009 let (r, c) = at;
23010 let (px, py) = (c * SUB, r * SUB);
23011 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
23012 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
23013 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
23014 let palette_uv_cache = neighbours.palette_uv_cache(at);
23015 let (
23016 skip,
23017 mode,
23018 angle_delta_y,
23019 uv_mode,
23020 angle_delta_uv,
23021 alpha,
23022 filter_intra,
23023 palette_y,
23024 palette_uv,
23025 intrabc,
23026 ) = read_intra_mode_rect(
23027 dec,
23028 cdfs,
23029 nb_above_mode,
23030 nb_left_mode,
23031 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
23032 // 13-symbol no-CFL CDF here, never the 14-symbol one.
23033 false,
23034 true,
23035 bw,
23036 bh,
23037 enable_filter_intra,
23038 neighbours.skip_txfm_ctx(mi_r, mi_c),
23039 allow_screen_content_tools,
23040 Some((palette_ctx, &palette_cache)),
23041 &palette_uv_cache,
23042 mi_r,
23043 mi_c,
23044 fctx,
23045 )?;
23046 if let Some((dv_row, dv_col)) = intrabc {
23047 // lane-av1-ibcrect: the reconstruction is ported -- an intrabc block
23048 // is is_inter_block, so libaom predicts the whole 128x64/64x128 strip
23049 // from this frame's own reconstruction and runs the INTER residual
23050 // walk (`decode_token_recon_block`'s else arm) over it.
23051 return decode_intrabc_128rect(
23052 dec,
23053 cdfs,
23054 neighbours,
23055 (mi_r, mi_c),
23056 (bw, bh),
23057 skip,
23058 (dv_row, dv_col),
23059 y,
23060 u,
23061 v,
23062 base_q_idx,
23063 fctx,
23064 );
23065 }
23066 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
23067 return Err(unsupported(
23068 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
23069 their size gates caps at 64x64 or below, so none of these symbols exists there)",
23070 ));
23071 }
23072 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
23073 DC_PRED
23074 } else {
23075 uv_mode
23076 };
23077 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
23078 if smooth_neighbor {
23079 hit!(SMOOTH_LUMA_HITS);
23080 }
23081 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
23082 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
23083 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
23084 // lane-lossless128: a LOSSLESS frame codes no tx-size symbol at all --
23085 // libaom's `read_tx_mode` returns `ONLY_4X4` for a `coded_lossless` frame
23086 // before the symbol is even considered (`decodeframe.c:141`) and
23087 // `read_tx_size` returns `TX_4X4` before it looks at anything
23088 // (`decodeframe.c:1183`). So `tx_select` is off, every plane is walked as
23089 // TX_4X4 transform units, and no `tx_size_cat3` symbol may be consumed.
23090 let lossless_frame = lossless(fctx);
23091 let in_inter = fctx
23092 .intra_in_inter_mode
23093 .with(std::cell::Cell::get)
23094 .is_some();
23095 let depth = if tx_select && !lossless_frame {
23096 // lane-inter128intra r1: `get_tx_size_context` compares the bands
23097 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --
23098 // TX_64X64 for every 128-axis block, hence the `min(64)`.
23099 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
23100 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
23101 } else {
23102 0
23103 };
23104 if depth != 0 {
23105 hit!(TX_DEPTH_HITS);
23106 }
23107 hit_do! {
23108 INTRA_SB128_DEPTH_HITS.with(|c| {
23109 let mut h = c.get();
23110 h[depth.min(2)] += 1;
23111 c.set(h);
23112 });
23113 }
23114 let logical_tx = if lossless_frame { 4 } else { 64 >> depth };
23115 if lossless_frame {
23116 hit!(INTRA128_LOSSLESS_HITS);
23117 }
23118 // A 64-point transform codes nothing past its low 32 coefficients.
23119 let coeff_tx_side = logical_tx.min(32);
23120 let luma_set = if lossless_frame {
23121 TxbSet::Luma4
23122 } else {
23123 txbset_for(logical_tx, reduced_tx_set)
23124 };
23125 let luma_scan = default_scan(coeff_tx_side);
23126 // `av1_get_max_uv_txsize` caps at TX_32X32 normally; a lossless frame
23127 // forces every plane to TX_4X4 (its own `Chroma4` set and 4x4 scan).
23128 let chroma_tx = if lossless_frame { 4 } else { 32 };
23129 let chroma_set = if lossless_frame {
23130 TxbSet::Chroma4
23131 } else {
23132 TxbSet::Chroma32
23133 };
23134 let chroma_scan = default_scan(chroma_tx);
23135 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
23136 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
23137 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
23138 let (nch_x, nch_y) = (bw / 64, bh / 64);
23139 // The frame's own mi grid (`av1_calc_mi_size`, 8-px aligned): libaom's
23140 // `decode_token_recon_block` clips each vector's walk to
23141 // `max_block_wide/high`, so a chroma unit whose top-left is off the frame
23142 // codes nothing.
23143 let mi_cols = 2 * y.true_width.div_ceil(8);
23144 let mi_rows = 2 * y.true_height.div_ceil(8);
23145 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
23146 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
23147 // Non-lossless: per mu chunk, `(64 >> ss) / chroma_tx` chroma units per
23148 // axis -- one 32x32 at 4:2:0, two stacked on the tall axis at 4:2:2
23149 // (lane-av1-422bigblock: the chunk's chroma plane block is 32x64 there),
23150 // four at 4:4:4 (lane-av1-444sb's own finding on this same walk).
23151 debug_assert!(
23152 lossless_frame
23153 || (chroma_w / chroma_tx, chroma_h / chroma_tx)
23154 == (
23155 nch_x * ((64 >> ss_x(fctx)) / chroma_tx),
23156 nch_y * ((64 >> ss_y(fctx)) / chroma_tx)
23157 )
23158 );
23159 let tpc = 64 / logical_tx;
23160 let zero_tu = vec![0i32; logical_tx * logical_tx];
23161 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
23162 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
23163 let mut units: Vec<(usize, (usize, usize), Grid)> = Vec::new();
23164 // The chroma context arrays are indexed in LUMA mi; every chroma unit of
23165 // every chunk shares this luma span (2 chroma pixels per luma unit).
23166 let luma_span = chroma_tx << ss_x(fctx);
23167 let luma_span_h = chroma_tx << ss_y(fctx);
23168 for ch_row in 0..nch_y {
23169 for ch_col in 0..nch_x {
23170 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
23171 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
23172 let tu_mi = (
23173 mi_r + tu_row * (logical_tx / MI),
23174 mi_c + tu_col * (logical_tx / MI),
23175 );
23176 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
23177 // libaom clips the transform loop to
23178 // `max_blocks_wide/high`: a unit whose top-left sample is
23179 // outside the frame is never coded.
23180 if tu_px >= y.true_width || tu_py >= y.true_height {
23181 continue;
23182 }
23183 // Edge availability of a unit INSIDE a block, with the
23184 // 128 geometry -- `has_top_right` is false for a block
23185 // whose largest side is > 64, which [`Reach::of_rect`]
23186 // already answered for the block and [`tu_reach`] carries
23187 // down to the units on its own top row.
23188 let tu_r = tu_reach(
23189 bw,
23190 bh,
23191 tu_col * logical_tx,
23192 tu_row * logical_tx,
23193 logical_tx,
23194 reach,
23195 px,
23196 py,
23197 y.width,
23198 y.height,
23199 fctx,
23200 );
23201 if skip {
23202 push_intra(
23203 0,
23204 tu_px,
23205 tu_py,
23206 logical_tx,
23207 mode,
23208 angle_delta_y,
23209 tu_r,
23210 &zero_tu,
23211 None,
23212 None,
23213 smooth_neighbor,
23214 fctx,
23215 );
23216 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
23217 continue;
23218 }
23219 // The unit is smaller than its block, so `txb_skip_ctx`
23220 // is the neighbour-magnitude table, never the lone-TU 0.
23221 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
23222 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
23223 let tu_grid = read_plane(
23224 dec,
23225 cdfs,
23226 luma_set,
23227 &luma_scan,
23228 0,
23229 tu_around,
23230 mode,
23231 mode,
23232 angle_delta_y,
23233 tu_r,
23234 y,
23235 tu_px,
23236 tu_py,
23237 logical_tx,
23238 coeff_tx_side,
23239 base_q_idx,
23240 None,
23241 None,
23242 Some(tu_skip_ctx),
23243 smooth_neighbor,
23244 fctx,
23245 )?;
23246 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
23247 }
23248 }
23249 // Transform units per axis inside this mu chunk's chroma span:
23250 // a 64x64 luma chunk covers `64 >> ss` chroma pixels per axis,
23251 // so it holds `(64 >> ss) / chroma_tx` units -- one 32x32 at
23252 // 4:2:0, four at 4:4:4 (lane-av1-444sb), TWO STACKED TX_32X32 on
23253 // the tall axis at 4:2:2 (lane-av1-422bigblock: the chunk's
23254 // chroma plane block is 32x64 there, so the two axes' counts
23255 // part ways -- 1 x 2); 8x8 TX_4X4 units when lossless.
23256 let cn = ((64 >> ss_x(fctx)) / chroma_tx).max(1);
23257 let cn_h = ((64 >> ss_y(fctx)) / chroma_tx).max(1);
23258 // libaom's per-chunk `unit_width/height` (plane-mi units of the
23259 // luma mi grid): `min(mu_blocks + col, max_blocks) >> ss`.
23260 let unit_w = ((ch_col + 1) * 16).min(max_w_mi) >> ss_x(fctx);
23261 let unit_h = ((ch_row + 1) * 16).min(max_h_mi) >> ss_y(fctx);
23262 let stepc = (chroma_tx / 4).max(1);
23263 // `decode_token_recon_block` codes a mu chunk PLANE-MAJOR: every U
23264 // unit of the chunk, then every V unit. At one unit per plane per
23265 // chunk (every non-lossless 128-axis block) that is the same
23266 // symbol order the interleaved pair used to read; a lossless
23267 // frame's 4x4 chroma units are where it becomes observable.
23268 for plane_pass in 1..=2usize {
23269 for ci_row in 0..cn_h {
23270 for ci_col in 0..cn {
23271 // The clamp strides are the CHUNK's chroma mi extent
23272 // per axis: 16 luma mi >> the axis's own ss.
23273 if ch_col * (16 >> ss_x(fctx)) + ci_col * stepc >= unit_w
23274 || ch_row * (16 >> ss_y(fctx)) + ci_row * stepc >= unit_h
23275 {
23276 continue;
23277 }
23278 let cu_x = cpx + ch_col * (64 >> ss_x(fctx)) + ci_col * chroma_tx;
23279 let cu_y = cpy + ch_row * (64 >> ss_y(fctx)) + ci_row * chroma_tx;
23280 let cu_mi = (
23281 mi_r + ch_row * 16 + ci_row * ((chroma_tx << ss_y(fctx)) / 4),
23282 mi_c + ch_col * 16 + ci_col * ((chroma_tx << ss_x(fctx)) / 4),
23283 );
23284 let cu_r = tu_reach_rect(
23285 bw,
23286 bh,
23287 ch_col * 64 + ci_col * luma_span,
23288 ch_row * 64 + ci_row * luma_span_h,
23289 luma_span,
23290 luma_span_h,
23291 reach,
23292 px,
23293 py,
23294 y.width,
23295 y.height,
23296 fctx,
23297 );
23298 if skip {
23299 push_intra(
23300 plane_pass,
23301 cu_x,
23302 cu_y,
23303 chroma_tx,
23304 uv_predict_mode,
23305 angle_delta_uv,
23306 cu_r,
23307 &zero_cu,
23308 None,
23309 None,
23310 smooth_neighbor_uv,
23311 fctx,
23312 );
23313 continue;
23314 }
23315 let cu_around = neighbours.around_mi_rect(cu_mi, luma_span, luma_span_h);
23316 let buf: &mut PlaneBuf<'static> =
23317 if plane_pass == 1 { &mut *u } else { &mut *v };
23318 let grid = read_plane(
23319 dec,
23320 cdfs,
23321 chroma_set,
23322 &chroma_scan,
23323 plane_pass,
23324 cu_around[plane_pass],
23325 mode,
23326 uv_predict_mode,
23327 angle_delta_uv,
23328 cu_r,
23329 buf,
23330 cu_x,
23331 cu_y,
23332 chroma_tx,
23333 chroma_tx,
23334 base_q_idx,
23335 None,
23336 None,
23337 Some(3),
23338 smooth_neighbor_uv,
23339 fctx,
23340 )?;
23341 last_grids[plane_pass - 1] = grid.clone();
23342 // Immediately, so the NEXT unit of this same block
23343 // reads this one's coefficient context; replayed after
23344 // `record_split_luma_rect` below, which would otherwise
23345 // clobber them whole-block.
23346 neighbours.record_mi_chroma(
23347 cu_mi,
23348 luma_span,
23349 luma_span_h,
23350 plane_pass,
23351 &grid,
23352 );
23353 units.push((plane_pass, cu_mi, grid));
23354 }
23355 }
23356 }
23357 if !skip {
23358 hit!(CHROMA_SPLIT_TX_HITS);
23359 }
23360 }
23361 }
23362 if skip {
23363 neighbours.record_rect(
23364 at,
23365 bw,
23366 bh,
23367 mode,
23368 uv_predict_mode,
23369 &[
23370 &ZERO_RESIDUAL[..bw * bh],
23371 &ZERO_RESIDUAL[..chroma_w * chroma_h],
23372 &ZERO_RESIDUAL[..chroma_w * chroma_h],
23373 ],
23374 );
23375 } else {
23376 neighbours.record_split_luma_rect(
23377 at,
23378 bw,
23379 bh,
23380 mode,
23381 uv_predict_mode,
23382 [&last_grids[0], &last_grids[1]],
23383 );
23384 // lane-av1-128rectspan: the replay must re-stamp each unit over the
23385 // SAME cells the walk above stamped it over -- `record_mi_chroma`'s
23386 // height drives `left[]` and its width `above[]`, and the walk used
23387 // the per-axis `luma_span_h`. Passing the width on both axes doubled
23388 // the `left[]` run wherever the two differ (4:2:2), reaching 8 mi
23389 // rows below the block on the last unit of a 128x64/64x128 strip and
23390 // smearing a neighbour chunk's unit over its neighbour's rows.
23391 //
23392 // DEFENSIVE at the decoder's current capability set: both admitted
23393 // chroma formats have `ss_x == ss_y` (4:2:0 ss (1,1), 4:4:4 ss
23394 // (0,0)), so the two spans are equal and this line is a no-op on
23395 // every stream `decode_stream` accepts; 4:2:2 (ss (1,0)) -- the one
23396 // format where they differ -- is refused by name at the sequence
23397 // header, so the arm is unreachable there. It stays per-axis because
23398 // the walk it replays is per-axis, and a 4:2:2 port must not have to
23399 // re-derive this. `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` names the
23400 // day that changes.
23401 if luma_span != luma_span_h {
23402 hit!(SB128RECT_REPLAY_SPAN_MISMATCH_HITS);
23403 }
23404 for (plane, cu_mi, grid) in &units {
23405 neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span_h, *plane, grid);
23406 hit!(SB128RECT_CHROMA_REPLAY_HITS);
23407 }
23408 }
23409 // No palette exists at this size; the unconditional stamp clears any
23410 // stale neighbour palette state, as every other block path does.
23411 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
23412 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
23413 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
23414 neighbours.fill_lf_grid_rect(
23415 (mi_r, mi_c),
23416 bw / MI,
23417 bh / MI,
23418 logical_tx as u8,
23419 logical_tx as u8,
23420 0,
23421 fctx,
23422 );
23423 if in_inter || allow_intrabc_frame(fctx) {
23424 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
23425 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
23426 // inter frame, intra ones included: an intra block stamps its
23427 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
23428 // A key frame reads those bands only when it allows intrabc
23429 // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom
23430 // stamps here too -- lane-av1-intrabc r3.
23431 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (logical_tx, logical_tx), (bw, bh));
23432 }
23433 if in_inter {
23434 hit_do! {
23435 INTRA128_IN_INTER_HITS.with(|c| {
23436 let mut h = c.get();
23437 h[usize::from(bw < bh)] += 1;
23438 c.set(h);
23439 });
23440 }
23441 } else if bw > bh {
23442 hit!(INTRA_SB128_HORZ_HITS);
23443 } else {
23444 hit!(INTRA_SB128_VERT_HITS);
23445 }
23446 Ok(())
23447}
23448
23449/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
23450/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
23451/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
23452/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
23453/// just-decoded mode, not the enclosing slot's stale one, is the true
23454/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
23455/// units, which is what its coefficient context (finer than [`SUB`]) is read
23456/// at. Returns the mode this leaf decoded, for the caller's own
23457/// `prev_leaf`/final mode-writeback bookkeeping.
23458#[allow(clippy::too_many_arguments)]
23459/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
23460/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
23461/// `above_mode[col]`, and its true above neighbour is the mi directly above
23462/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
23463/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
23464/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
23465/// (bottom-right) into both, as this path did, is right only when all four
23466/// leaves happen to share a mode. `done` may be short at the true frame edge
23467/// (the straddle caller filters positions off the frame), so each side falls
23468/// back to the last leaf actually decoded.
23469fn write_back_split_modes(
23470 neighbours: &mut Neighbours,
23471 done: &[((usize, usize), usize)],
23472 parent_mi: (usize, usize),
23473 slot: (usize, usize),
23474) {
23475 let (sr, sc) = slot;
23476 let Some(&(_, last)) = done.last() else {
23477 return;
23478 };
23479 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
23480 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
23481 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
23482}
23483
23484fn decode_leaf8(
23485 dec: &mut SymbolDecoder,
23486 cdfs: &mut Cdfs,
23487 neighbours: &mut Neighbours,
23488 outer_at: (usize, usize),
23489 leaf_mi: (usize, usize),
23490 scans: (&[u16], &[u16]),
23491 prev_leaf: Option<((usize, usize), usize)>,
23492 y: &mut PlaneBuf<'static>,
23493 u: &mut PlaneBuf<'static>,
23494 v: &mut PlaneBuf<'static>,
23495 base_q_idx: u8,
23496 enable_filter_intra: bool,
23497 allow_screen_content_tools: bool,
23498 allow_intrabc: bool,
23499 tx_select: bool,
23500 reduced_tx_set: bool,
23501 fctx: &crate::decode::FrameCtx,
23502) -> Result<usize> {
23503 let (r, c) = outer_at;
23504 // lane-modectx r1: the group's own availability-correct fallback pair, not
23505 // the raw coarse bands (which leak across a tile edge -- see
23506 // `modes_above_left`).
23507 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
23508 if let Some(((pr, pc), pmode)) = prev_leaf {
23509 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
23510 above_mode = pmode;
23511 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
23512 left_mode = pmode;
23513 }
23514 }
23515 // The mi-exact neighbour wins over both the coarse 16x16 slot and
23516 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
23517 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
23518 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
23519 // lane-rectsplitx r2 swept this arm into
23520 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
23521 // "no neighbour" at a tile edge, where the coarse cell holds the block
23522 // above/left of it inside the same 16x16.
23523 let (above_mode, left_mode) =
23524 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
23525 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
23526 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
23527 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
23528 // this leaf's `smooth_neighbor` is built from -- passing `false` here
23529 // filtered a directional chroma block's edge at the wrong strength
23530 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
23531 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
23532 // with the coarse [`SUB`] slot as the fallback when no block recorded
23533 // that exact mi cell.
23534 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
23535 if smooth_neighbor {
23536 hit!(SMOOTH_LUMA_HITS);
23537 }
23538 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
23539 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
23540 // `decode_block` caller at 16x16 and up.
23541 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
23542 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
23543 // `read_palette_mode_info`), at its REAL mi position -- passing
23544 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
23545 // moment a real 8x8 palette block fired, which is where every 8-bit
23546 // `--tune-content=screen --min-partition-size=8` stream stopped.
23547 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
23548 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
23549 let (
23550 skip,
23551 mode,
23552 angle_delta_y,
23553 uv_mode,
23554 angle_delta_uv,
23555 alpha,
23556 filter_intra,
23557 palette_y,
23558 palette_uv,
23559 ) = read_intra_mode(
23560 dec,
23561 cdfs,
23562 above_mode,
23563 left_mode,
23564 true,
23565 8,
23566 enable_filter_intra,
23567 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
23568 allow_screen_content_tools,
23569 allow_intrabc,
23570 Some((palette_ctx, &palette_cache)),
23571 &palette_uv_cache,
23572 leaf_mi.0,
23573 leaf_mi.1,
23574 fctx,
23575 )?;
23576 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
23577 // `read_intra_mode` and then decoded the block as if it were ordinary
23578 // intra. libaom's `is_inter_block` counts an intrabc block
23579 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
23580 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
23581 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
23582 // same value with a different interval, so the tile desynced at the very
23583 // next symbol (class `wrong-alphabet-same-value`). Everything below
23584 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
23585 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
23586 if intrabc_dv.is_some() {
23587 hit!(LEAF8_INTRABC_HITS);
23588 }
23589 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
23590 // index map, mapped through the base colours, IS the block's prediction --
23591 // carried to the next `reconstruct`/`read_plane` through the same
23592 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
23593 let palette_y_buf: Option<Vec<u16>> = palette_y
23594 .as_ref()
23595 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
23596 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
23597 (
23598 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
23599 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
23600 )
23601 });
23602 let (pal_y_size, pal_y_colors) = palette_y
23603 .as_ref()
23604 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
23605 let (pal_uv_size, pal_uv_colors) = palette_uv
23606 .as_ref()
23607 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
23608 if palette_y.is_some() || palette_uv.is_some() {
23609 hit!(PALETTE_LEAF8_HITS);
23610 }
23611 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
23612 DC_PRED
23613 } else {
23614 uv_mode
23615 };
23616 neighbours.above_uv_mode[c] = uv_predict_mode;
23617 neighbours.left_uv_mode[r] = uv_predict_mode;
23618 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
23619 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
23620 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
23621 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
23622 // transform units, same raster-order per-TU pattern `decode_block`'s
23623 // multi-TU branch runs).
23624 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
23625 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
23626 // intrabc block, so a SKIPPED one takes the largest transform and an
23627 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
23628 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
23629 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
23630 // `parse_decode_block`'s tree condition carries
23631 // `!xd->lossless[mbmi->segment_id]` (see [`decode_block`]'s own copy):
23632 // a lossless segment's intrabc leaf reads no tree, TX_4X4 via
23633 // `read_tx_size`'s first line (lane-av1mixloss).
23634 let resolved = if tx_select && intrabc_dv.is_some() && !skip && !lossless(fctx) {
23635 let mut leaves = Vec::new();
23636 let mi_cols = 2 * y.true_width.div_ceil(8);
23637 let mi_rows = 2 * y.true_height.div_ceil(8);
23638 read_var_tx_size(
23639 dec,
23640 cdfs,
23641 neighbours,
23642 leaf_mi,
23643 8,
23644 (
23645 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
23646 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
23647 ),
23648 (8, 8),
23649 0,
23650 0,
23651 0,
23652 &mut leaves,
23653 );
23654 hit!(INTRABC_VARTX_HITS);
23655 leaves.first().map_or(8, |l| l.2)
23656 } else if tx_select && intrabc_dv.is_none() {
23657 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, fctx)
23658 } else {
23659 // lane-lossless: TX_4X4 on a lossless frame, no symbol
23660 // (libaom `read_tx_size`).
23661 lossless_tx(8, fctx)
23662 };
23663 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
23664 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
23665 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
23666 // 4:4:4: this 8x8 block's chroma plane block is 8x8 (same scan as luma,
23667 // `scans.0`). 4:2:0 stays the 4x4 unit this leaf was written for.
23668 // lane-av1-422d: 4:2:2 (ss 1/0) halves only the width, so the plane block
23669 // is 4x8 -- ONE rect transform unit per plane (`av1_get_max_uv_txsize(
23670 // BLOCK_8X8)` at ss (1,0) is `max_txsize_rect_lookup[BLOCK_4X8]` ==
23671 // TX_4X8): one txb_skip + one scan per plane in the
23672 // [`TxbSet::ChromaRect8x4`] class [`decode_rect_split`] proves for the
23673 // shape, read through [`leaf8_chroma422_unit`] in each arm below. The
23674 // `(csz, cset, cscan)` selection keeps serving the square arms (444's
23675 // 8x8, 420's 4x4); the rect arms branch on [`chroma_422`] instead.
23676 let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
23677 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
23678 let (csz, cset, cscan) = if chroma_444 {
23679 (8usize, TxbSet::Chroma8, scans.0)
23680 } else {
23681 (4usize, TxbSet::Chroma4, scans.1)
23682 };
23683 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
23684 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
23685 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
23686 // the full-pel block vector, with the BILINEAR kernel libaom forces.
23687 flush_recon(fctx, y, u, v);
23688 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
23689 let mut yb = vec![0u16; 8 * 8];
23690 mc::predict_with_filter(
23691 &y.data,
23692 y.width,
23693 y.true_width,
23694 y.true_height,
23695 mv_to_q4(px, dv_col, 0),
23696 mv_to_q4(py, dv_row, 0),
23697 8,
23698 8,
23699 mc::InterpFilterKind::Bilinear,
23700 &mut yb,
23701 fctx,
23702 );
23703 // The chroma extent is THIS frame's subsampled size of the 8x8 luma
23704 // leaf (`get_plane_block_size`): 4x4 at 4:2:0, 4x8 at 4:2:2, 8x8 at
23705 // 4:4:4. The literal 4x4 this replaces hardcoded the 4:2:0 halving --
23706 // at 4:4:4 the 16-sample override fed this leaf's own 8x8 chroma
23707 // reconstruct, which indexed `prediction[16]` of a 16-sample buffer
23708 // (len 16, index 16 at `PlaneBuf::reconstruct`), and at 4:2:2 it
23709 // covered half the leaf's 4x8 chroma plane block (lane-av1-422d's
23710 // `if chroma_422 { (4, 8) }` arm, which the ss-derived form subsumes:
23711 // `8 >> ss_x` is 4 and `8 >> ss_y` is 8 there). The same buffers
23712 // are windowed at stride 8 by `read_intra_chroma_lossless` (the TX4
23713 // 4:4:4-lossless arm) and consumed whole by the TX8 and skip arms,
23714 // so all three heal with this one sizing.
23715 let (cw, ch) = (8 >> ss_x(fctx), 8 >> ss_y(fctx));
23716 let mut ub = vec![0u16; cw * ch];
23717 mc::predict_with_filter(
23718 &u.data,
23719 u.width,
23720 u.true_width,
23721 u.true_height,
23722 mv_to_q4(cpx, dv_col, ss_x(fctx)),
23723 mv_to_q4(cpy, dv_row, ss_y(fctx)),
23724 cw,
23725 ch,
23726 mc::InterpFilterKind::Bilinear,
23727 &mut ub,
23728 fctx,
23729 );
23730 let mut vb = vec![0u16; cw * ch];
23731 mc::predict_with_filter(
23732 &v.data,
23733 v.width,
23734 v.true_width,
23735 v.true_height,
23736 mv_to_q4(cpx, dv_col, ss_x(fctx)),
23737 mv_to_q4(cpy, dv_row, ss_y(fctx)),
23738 cw,
23739 ch,
23740 mc::InterpFilterKind::Bilinear,
23741 &mut vb,
23742 fctx,
23743 );
23744 (yb, ub, vb)
23745 });
23746 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
23747 // `decode_block` uses: set fresh right before each plane's own
23748 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
23749 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
23750 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
23751 // first shape that reaches that loop with an override set).
23752 let palette_y_buf = match &intrabc_bufs {
23753 Some((yb, _, _)) => Some(yb.clone()),
23754 None => palette_y_buf,
23755 };
23756 // lane-av1intrapred: the chroma twin of the `palette_y_buf` wrap above --
23757 // `decode_block` does the same for its own `palette_uv_bufs`
23758 // (decode.rs's single-TU and multi-TU chroma reads). Without it, an
23759 // intrabc leaf whose var-tx tree split to TX_4X4 reached the TX4 arm's
23760 // chroma reads with the override unset: the unit predicted INTRA from
23761 // the UV mode (intrabc's is DC) instead of copying the frame at the DV,
23762 // R5 first differing pixel U(184,4), block mi (2,92).
23763 let palette_uv_bufs = match &intrabc_bufs {
23764 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
23765 None => palette_uv_bufs,
23766 };
23767 let (luma_grid, u_grid, v_grid);
23768 if skip {
23769 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
23770 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
23771 // transform units, each off the units already written left/above of
23772 // it inside this same leaf -- an intra block's transform size is read
23773 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
23774 // A palette block's prediction is the whole-block index map, never
23775 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
23776 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
23777 // even when `tx_depth` resolved to TX_4X4.
23778 if resolved == 4 && palette_y_buf.is_none() {
23779 hit!(SKIP_SPLIT_TX_HITS);
23780 for tu_row in 0..2 {
23781 for tu_col in 0..2 {
23782 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
23783 if tu_px >= y.true_width || tu_py >= y.true_height {
23784 continue;
23785 }
23786 let tu_reach = tu_reach(
23787 8,
23788 8,
23789 tu_col * 4,
23790 tu_row * 4,
23791 4,
23792 reach,
23793 px,
23794 py,
23795 y.width,
23796 y.height,
23797 fctx,
23798 );
23799 push_intra(
23800 0,
23801 tu_px,
23802 tu_py,
23803 4,
23804 mode,
23805 angle_delta_y,
23806 tu_reach,
23807 &ZERO_RESIDUAL[..16],
23808 None,
23809 filter_intra,
23810 smooth_neighbor,
23811 fctx,
23812 );
23813 }
23814 }
23815 } else {
23816 if let Some(buf) = &palette_y_buf {
23817 set_palette_pred(buf.clone(), fctx);
23818 }
23819 push_intra(
23820 0,
23821 px,
23822 py,
23823 8,
23824 mode,
23825 angle_delta_y,
23826 reach,
23827 &ZERO_RESIDUAL[..64],
23828 None,
23829 filter_intra,
23830 smooth_neighbor,
23831 fctx,
23832 );
23833 }
23834 let ac = alpha.map(|_| cfl_src(px, py, 8));
23835 // Three skip-arm shapes, dispatched on THIS frame's subsampling.
23836 // lane-av1-422d: at 4:2:2 a skipped leaf still predicts its 4x8 rect
23837 // unit per plane (CfL keeps its contribution, [`decode_block`]'s own
23838 // skip-arm rule); no coefficient symbol exists, so the entropy
23839 // context never enters the rect read.
23840 if chroma_422 {
23841 u_grid = leaf8_chroma422_unit(
23842 dec,
23843 cdfs,
23844 (false, false, 0),
23845 uv_predict_mode,
23846 angle_delta_uv,
23847 reach,
23848 1,
23849 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23850 true,
23851 intrabc_bufs
23852 .as_ref()
23853 .map(|(_, ub, _)| ub.clone())
23854 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
23855 u,
23856 cpx,
23857 cpy,
23858 smooth_neighbor_uv,
23859 fctx,
23860 )?;
23861 v_grid = leaf8_chroma422_unit(
23862 dec,
23863 cdfs,
23864 (false, false, 0),
23865 uv_predict_mode,
23866 angle_delta_uv,
23867 reach,
23868 2,
23869 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23870 true,
23871 intrabc_bufs
23872 .as_ref()
23873 .map(|(_, _, vb)| vb.clone())
23874 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
23875 v,
23876 cpx,
23877 cpy,
23878 smooth_neighbor_uv,
23879 fctx,
23880 )?;
23881 luma_grid = Grid::Zero(64);
23882 } else {
23883 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster of
23884 // TX_4X4 units (`av1_get_tx_size`: lossless forces TX_4X4 on EVERY
23885 // plane), so a skipped leaf predicts per unit -- each from its own
23886 // edges -- like the luma `SKIP_SPLIT_TX` loop above. CfL never fires
23887 // here (`is_cfl_allowed` at lossless needs plane_bsize == 4x4; this
23888 // chroma plane block is 8x8), and intrabc/palette keep the
23889 // whole-plane-block prediction they already run. The guard also
23890 // requires `chroma_444`, so it can never reach the 4:2:2 arm above.
23891 let chroma_units_444 =
23892 chroma_444 && lossless(fctx) && intrabc_bufs.is_none() && palette_uv_bufs.is_none();
23893 if let Some((_, ub, _)) = &intrabc_bufs {
23894 set_palette_pred(ub.clone(), fctx);
23895 } else if let Some((ub, _)) = &palette_uv_bufs {
23896 set_palette_pred(ub.clone(), fctx);
23897 }
23898 if chroma_units_444 {
23899 for cu_row in 0..2 {
23900 for cu_col in 0..2 {
23901 let cu_reach = tu_reach(
23902 8,
23903 8,
23904 cu_col * 4,
23905 cu_row * 4,
23906 4,
23907 reach,
23908 px,
23909 py,
23910 y.width,
23911 y.height,
23912 fctx,
23913 );
23914 push_intra(
23915 1,
23916 cpx + cu_col * 4,
23917 cpy + cu_row * 4,
23918 4,
23919 uv_predict_mode,
23920 angle_delta_uv,
23921 cu_reach,
23922 &ZERO_RESIDUAL[..16],
23923 None,
23924 None,
23925 smooth_neighbor_uv,
23926 fctx,
23927 );
23928 }
23929 }
23930 } else {
23931 push_intra(
23932 1,
23933 cpx,
23934 cpy,
23935 csz,
23936 uv_predict_mode,
23937 angle_delta_uv,
23938 reach,
23939 &ZERO_RESIDUAL[..csz * csz],
23940 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
23941 None,
23942 smooth_neighbor_uv,
23943 fctx,
23944 );
23945 }
23946 if let Some((_, _, vb)) = &intrabc_bufs {
23947 set_palette_pred(vb.clone(), fctx);
23948 } else if let Some((_, vb)) = &palette_uv_bufs {
23949 set_palette_pred(vb.clone(), fctx);
23950 }
23951 if chroma_units_444 {
23952 for cu_row in 0..2 {
23953 for cu_col in 0..2 {
23954 let cu_reach = tu_reach(
23955 8,
23956 8,
23957 cu_col * 4,
23958 cu_row * 4,
23959 4,
23960 reach,
23961 px,
23962 py,
23963 y.width,
23964 y.height,
23965 fctx,
23966 );
23967 push_intra(
23968 2,
23969 cpx + cu_col * 4,
23970 cpy + cu_row * 4,
23971 4,
23972 uv_predict_mode,
23973 angle_delta_uv,
23974 cu_reach,
23975 &ZERO_RESIDUAL[..16],
23976 None,
23977 None,
23978 smooth_neighbor_uv,
23979 fctx,
23980 );
23981 }
23982 }
23983 } else {
23984 push_intra(
23985 2,
23986 cpx,
23987 cpy,
23988 csz,
23989 uv_predict_mode,
23990 angle_delta_uv,
23991 reach,
23992 &ZERO_RESIDUAL[..csz * csz],
23993 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
23994 None,
23995 smooth_neighbor_uv,
23996 fctx,
23997 );
23998 }
23999 luma_grid = Grid::Zero(64);
24000 u_grid = Grid::Zero(csz * csz);
24001 v_grid = Grid::Zero(csz * csz);
24002 }
24003 } else if resolved != 4 {
24004 let around = neighbours.around_mi(leaf_mi, 8);
24005 // lane-av1-422h: the 4:2:2 chroma rect unit's `get_txb_ctx_general`
24006 // reads its above votes over CHROMA 4-px cells -- at ss_x 1 one chroma
24007 // cell spans TWO luma mi columns, so the per-luma-mi sum counts each
24008 // above chroma column twice and `dc_sign_ctx`'s signum flips whenever
24009 // the doubled sum crosses zero (the same class
24010 // [`Neighbours::around_mi_422_chroma`] fixes for the rect readers;
24011 // measured at mi(2,24) plane 2: ours dc_sign row 0, oracle row 2).
24012 // The left extent is unsubsquared at ss_y 0 and stays one-to-one.
24013 let chroma_around = if chroma_422 {
24014 neighbours.around_mi_422_chroma(leaf_mi, 8, 8)
24015 } else {
24016 around
24017 };
24018 if let Some(buf) = &palette_y_buf {
24019 set_palette_pred(buf.clone(), fctx);
24020 }
24021 luma_grid = read_plane(
24022 dec,
24023 cdfs,
24024 if intrabc_dv.is_some() {
24025 inter_txbset_for(8, reduced_tx_set)
24026 } else if reduced_tx_set {
24027 TxbSet::Luma8
24028 } else {
24029 TxbSet::Luma8Set1
24030 },
24031 scans.0,
24032 0,
24033 around[0],
24034 mode,
24035 mode,
24036 angle_delta_y,
24037 reach,
24038 y,
24039 px,
24040 py,
24041 8,
24042 TX8,
24043 base_q_idx,
24044 None,
24045 filter_intra,
24046 None,
24047 smooth_neighbor,
24048 fctx,
24049 )?;
24050 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
24051 // an intrabc block's chroma tx_type is the colocated LUMA transform's
24052 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
24053 if intrabc_dv.is_some() {
24054 fctx.intrabc_chroma_tx
24055 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
24056 }
24057 let ac = alpha.map(|_| cfl_src(px, py, 8));
24058 if chroma_422 {
24059 // lane-av1-422d: ONE 4x8 rect unit per plane (`av1_get_max_uv_txsize`
24060 // at ss (1,0) == TX_4X8), covering the plane block exactly, off the
24061 // leaf's own 8x8-span entropy context (`chroma_tiled`'s convention).
24062 u_grid = leaf8_chroma422_unit(
24063 dec,
24064 cdfs,
24065 chroma_around[1],
24066 uv_predict_mode,
24067 angle_delta_uv,
24068 reach,
24069 1,
24070 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
24071 false,
24072 intrabc_bufs
24073 .as_ref()
24074 .map(|(_, ub, _)| ub.clone())
24075 .or_else(|| palette_uv_bufs.as_ref().map(|(ub, _)| ub.clone())),
24076 u,
24077 cpx,
24078 cpy,
24079 smooth_neighbor_uv,
24080 fctx,
24081 )?;
24082 v_grid = leaf8_chroma422_unit(
24083 dec,
24084 cdfs,
24085 chroma_around[2],
24086 uv_predict_mode,
24087 angle_delta_uv,
24088 reach,
24089 2,
24090 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
24091 false,
24092 intrabc_bufs
24093 .as_ref()
24094 .map(|(_, _, vb)| vb.clone())
24095 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())),
24096 v,
24097 cpx,
24098 cpy,
24099 smooth_neighbor_uv,
24100 fctx,
24101 )?;
24102 } else {
24103 if let Some((_, ub, _)) = &intrabc_bufs {
24104 set_palette_pred(ub.clone(), fctx);
24105 } else if let Some((ub, _)) = &palette_uv_bufs {
24106 set_palette_pred(ub.clone(), fctx);
24107 }
24108 u_grid = read_plane(
24109 dec,
24110 cdfs,
24111 cset,
24112 cscan,
24113 1,
24114 around[1],
24115 mode,
24116 uv_predict_mode,
24117 angle_delta_uv,
24118 reach,
24119 u,
24120 cpx,
24121 cpy,
24122 csz,
24123 csz,
24124 base_q_idx,
24125 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
24126 None,
24127 None,
24128 smooth_neighbor_uv,
24129 fctx,
24130 )?;
24131 if let Some((_, _, vb)) = &intrabc_bufs {
24132 set_palette_pred(vb.clone(), fctx);
24133 } else if let Some((_, vb)) = &palette_uv_bufs {
24134 set_palette_pred(vb.clone(), fctx);
24135 }
24136 v_grid = read_plane(
24137 dec,
24138 cdfs,
24139 cset,
24140 cscan,
24141 2,
24142 around[2],
24143 mode,
24144 uv_predict_mode,
24145 angle_delta_uv,
24146 reach,
24147 v,
24148 cpx,
24149 cpy,
24150 csz,
24151 csz,
24152 base_q_idx,
24153 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
24154 None,
24155 None,
24156 smooth_neighbor_uv,
24157 fctx,
24158 )?;
24159 }
24160 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
24161 // two chroma reads (`decode_block`'s own tail does the same) -- left
24162 // set, every later chroma block would inherit this luma tx_type,
24163 // which picks the scan and the inverse transform.
24164 fctx.intrabc_chroma_tx.with(|c| c.set(None));
24165 } else {
24166 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
24167 // grid of 4x4 transform units, each predicted from the leaf's own
24168 // 8x8 `mode` and reading its own fresh context off the earlier
24169 // units in this same leaf (the same per-TU pattern `decode_block`'s
24170 // multi-TU branch runs at bigger blocks).
24171 let mut first_leaf_tx: Option<TxType> = None;
24172 for tu_row in 0..2 {
24173 for tu_col in 0..2 {
24174 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
24175 let tu_px = px + tu_col * 4;
24176 let tu_py = py + tu_row * 4;
24177 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
24178 if crate::encode::Reach::in_vert_ab() {
24179 hit!(VERT_AB_TX4_HITS);
24180 }
24181 let tu_reach = tu_reach(
24182 8,
24183 8,
24184 tu_col * 4,
24185 tu_row * 4,
24186 4,
24187 reach,
24188 px,
24189 py,
24190 y.width,
24191 y.height,
24192 fctx,
24193 );
24194 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
24195 // Each 4x4 unit predicts from its own window of the block's
24196 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
24197 // 16x16 and up) -- the whole-block buffer would be taken by
24198 // the FIRST unit and indexed at the wrong stride.
24199 if let Some(buf) = &palette_y_buf {
24200 hit!(PALETTE_SPLIT_TX_HITS);
24201 let mut window = vec![0u16; 16];
24202 for row in 0..4 {
24203 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
24204 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
24205 }
24206 set_palette_pred(window, fctx);
24207 }
24208 let tu_grid = read_plane(
24209 dec,
24210 cdfs,
24211 if intrabc_dv.is_some() {
24212 inter_txbset_for(4, reduced_tx_set)
24213 } else if reduced_tx_set {
24214 TxbSet::Luma4
24215 } else {
24216 TxbSet::Luma4Set1
24217 },
24218 scans.1,
24219 0,
24220 tu_around,
24221 mode,
24222 mode,
24223 angle_delta_y,
24224 tu_reach,
24225 y,
24226 tu_px,
24227 tu_py,
24228

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