forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBddf43e8Tahinli2 months ago3186 commits

decode.rs23186 lines, 2.0 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.set(if on { 128 } else { crate::encode::SUPERBLOCK });
309 ctx
310 }
311}
312
313/// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)`
314/// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent
315/// `with` still wins for the scratch pools and gate counters that stay
316/// thread-local.
317pub(crate) trait WithRef {
318 fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
319 f(self)
320 }
321}
322impl<T: ?Sized> WithRef for T {}
323
324/// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads.
325///
326/// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread),
327/// and the post-decode filter chain reads exactly these fields: the bit depth
328/// (every kernel's clamp and threshold shift), the segmentation table
329/// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state
330/// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s
331/// default -- a field that turns out to be read after all shows up as a hash
332/// mismatch in
333/// `a_real_stream_filters_identically_with_one_and_four_filter_threads`.
334pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
335 let out = FrameCtx::new();
336 out.bit_depth.set(fctx.bit_depth.get());
337 out.mono_chrome.set(fctx.mono_chrome.get());
338 out.subsampling_x.set(fctx.subsampling_x.get());
339 out.subsampling_y.set(fctx.subsampling_y.get());
340 out.interp_filter.set(fctx.interp_filter.get());
341 out.grain_bit_depth.set(fctx.grain_bit_depth.get());
342 out.superres.set(fctx.superres.get());
343 out.seg_mi_dims.set(fctx.seg_mi_dims.get());
344 out.seg.replace(fctx.seg.borrow().clone());
345 out.seg_ids.replace(fctx.seg_ids.borrow().clone());
346 // lane-b128m: the superblock size travels with the copy. A tile SEARCH
347 // worker (`encode::search_tiles`) gets its context from here, so dropping
348 // it made every worker search at 64 while the calling thread searched at
349 // 128 -- the bytes a frame came out as then depended on the tile thread
350 // count under `EC_AV1_SB128`.
351 out.sb128_flag.set(fctx.sb128_flag.get());
352 out.reach_sb_px.set(fctx.reach_sb_px.get());
353 out
354}
355
356use crate::cdf;
357use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
358use crate::encode::{Picture, Reach};
359use crate::intra::predict;
360use crate::mc;
361use crate::msac::SymbolDecoder;
362use crate::mvstack::{
363 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
364 MiGrid, MiInfo, NO_REF1, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
365 find_mv_stack_with_sign_bias, mv16, mv32, reference_mode_ctx,
366 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
367 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
368};
369use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
370use crate::transform::{TxType, dequant_and_inverse_typed_wh};
371
372const PARTITION_NONE: usize = 0;
373const PARTITION_HORZ: usize = 1;
374const PARTITION_VERT: usize = 2;
375const PARTITION_SPLIT: usize = 3;
376const PARTITION_HORZ_A: usize = 4;
377const PARTITION_HORZ_B: usize = 5;
378const PARTITION_VERT_A: usize = 6;
379const PARTITION_VERT_B: usize = 7;
380const PARTITION_HORZ_4: usize = 8;
381const PARTITION_VERT_4: usize = 9;
382const SB_MI: u32 = 16;
383const BLOCK_MI: u32 = 8;
384
385// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
386// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
387// superblock's own top-left mi?", the loop-restoration read's unit span, the
388// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
389// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
390// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
391// inside a 128 superblock).
392thread_local! {
393 /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the
394 /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream
395 /// prints gigabytes otherwise). Unset = every frame, as before.
396 static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
397 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
398}
399
400/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
401/// that frame's DECODE-order index.
402pub fn set_coeff_trace_frame(idx: usize) {
403 COEFF_TRACE_FRAME.with(|c| {
404 if c.get().is_none() {
405 let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
406 Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
407 // unset: keep tracing every frame, as before this rung existed
408 Err(_) => usize::MAX - 1,
409 };
410 c.set(Some(want));
411 }
412 });
413 COEFF_TRACE_CUR.with(|c| c.set(idx));
414 if crate::envflags::env_flag!("EC_TRACE_COEFF") {
415 eprintln!("EC_COEFF_FRAME decode_idx={idx}");
416 }
417}
418
419pub(crate) fn coeff_trace_on() -> bool {
420 if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
421 return false;
422 }
423 match COEFF_TRACE_FRAME.with(|c| c.get()) {
424 // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
425 // env var unset: trace every frame.
426 None => true,
427 Some(w) if w >= usize::MAX - 1 => true,
428 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
429 }
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(
442 table: [bool; MAX_SEGMENTS],
443 fctx: &crate::decode::FrameCtx,
444) {
445 fctx.lossless_per_seg.with(|c| c.set(table));
446}
447
448/// The BLOCK's own lossless bit: libaom's `xd->lossless[mbmi->segment_id]`.
449/// The table is computed once per frame (libaom `decodeframe.c:5205`:
450/// `qindex == 0` with every plane delta 0, `av1_get_qindex` applying the
451/// segment's `SEG_LVL_ALT_Q`), but the frame never carries ONE lossless rule
452/// -- `read_tx_size`, `read_tx_type` and `is_cfl_allowed` all index it by the
453/// BLOCK's own segment id, which the spec-order `segment_id` read sets before
454/// any mode/transform symbol of the block. A frame whose segments disagree
455/// codes TX_4X4/WHT blocks and normal blocks side by side.
456pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool {
457 let seg_id = usize::from(fctx.cur_segment_id.with(|c| c.get()));
458 fctx.lossless_per_seg.with(|c| c.get())[seg_id]
459}
460
461/// Sets [`FrameCtx::disable_cdf_update`] (called once per frame from
462/// `stream.rs`).
463pub(crate) fn set_disable_cdf_update(v: bool, fctx: &crate::decode::FrameCtx) {
464 fctx.disable_cdf_update.with(|c| c.set(v));
465}
466
467/// This frame's `disable_cdf_update`, for the tile readers --
468/// [`msac::SymbolDecoder::set_cdf_update`](crate::msac::SymbolDecoder::set_cdf_update).
469pub(crate) fn cdf_update_disabled(fctx: &crate::decode::FrameCtx) -> bool {
470 fctx.disable_cdf_update.with(|c| c.get())
471}
472
473/// The transform side a block of `side` pixels codes: its own (capped at the
474/// caller's own largest) normally, 4 on a lossless BLOCK, where libaom's
475/// `read_tx_size` returns TX_4X4 before it looks at anything else
476/// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return
477/// TX_4X4;`).
478pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize {
479 if lossless(fctx) { 4 } else { px }
480}
481
482/// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to
483/// 32x32 -- but on a LOSSLESS BLOCK only when the block's CHROMA plane block
484/// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller.
485/// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom
486/// picks the 13-symbol one (class `wrong-alphabet-same-value`).
487pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool {
488 if lossless(fctx) {
489 // `is_cfl_allowed`: at lossless CfL is available only when the
490 // partition size equals the transform size -- the CHROMA plane block
491 // must be a single TX_4X4. True for an 8x8 partition at 4:2:0 (its
492 // plane block is 4x4) and for 4x4 partitions; FALSE for an 8x8
493 // partition at 4:4:4, whose plane block is 8x8 -- that partition
494 // reads the 13-symbol uv_mode CDF, and reading the CFL alphabet
495 // there desynced the tile from the leaf's own uv_mode symbol (class
496 // `wrong-alphabet-same-value`).
497 (bw >> ss_x(fctx)).max(4) == 4 && (bh >> ss_y(fctx)).max(4) == 4
498 } else {
499 bw <= 32 && bh <= 32
500 }
501}
502
503fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
504 fctx.sb128_flag.with(|c| c.get())
505}
506
507/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
508pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
509 if sb128(fctx) { SB_MI * 2 } else { SB_MI }
510}
511
512// How many real 128-level partition symbols this decoder has read, and how
513// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
514// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
515thread_local! {
516 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
517 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
518 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
519}
520
521/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
522/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
523/// 5.11.4), which this decoder used to read and throw away.
524#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
525pub(crate) fn part128_gathered_symbols() -> usize {
526 PART128_GATHERED_SYMBOLS.with(|c| c.get())
527}
528
529/// Current value of [`PART128_SYMBOLS`].
530#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
531pub(crate) fn part128_symbols() -> usize {
532 PART128_SYMBOLS.with(|c| c.get())
533}
534
535/// Current value of [`PART128_SPLIT_HITS`].
536#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
537pub(crate) fn part128_split_hits() -> usize {
538 PART128_SPLIT_HITS.with(|c| c.get())
539}
540
541/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
542/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
543/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
544/// the 64/32 levels sum 6.
545pub(crate) fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
546 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
547 [32768 - split, 32768, 0]
548}
549
550/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
551pub(crate) const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
552pub(crate) const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
553
554// How many `use_filter_intra` symbols this decoder has read as `1`, across
555// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
556// tests read (before/after, not the absolute value) to prove a stream
557// actually exercised the filter-intra predictor rather than silently
558// skipping it.
559thread_local! {
560 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
561 const { std::cell::Cell::new(0) };
562}
563
564/// Current value of [`FILTER_INTRA_HITS`].
565#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
566pub(crate) fn filter_intra_hits() -> usize {
567 FILTER_INTRA_HITS.with(|c| c.get())
568}
569
570// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
571// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
572// `read_filter_intra_mode_info` call), which no gate exercised before this
573// round -- every inter gate recipe passed `--enable-filter-intra=0`.
574thread_local! {
575 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
576 const { std::cell::Cell::new(0) };
577}
578
579/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
580#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
581pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
582 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
583}
584
585// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a
586// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both
587// arms refused a nonzero luma delta before this round, and no inter gate
588// enabled `--enable-angle-delta` (aomenc's own default is 1).
589thread_local! {
590 static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> =
591 const { std::cell::Cell::new(0) };
592 static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> =
593 const { std::cell::Cell::new(0) };
594}
595
596/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`].
597#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
598pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize {
599 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get())
600}
601
602/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`].
603#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
604pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize {
605 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get())
606}
607
608// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside
609// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm
610// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and
611// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block.
612thread_local! {
613 static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
614 static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
615 static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
616}
617
618thread_local! {
619 static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
620}
621
622/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame
623/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm.
624#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
625pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize {
626 INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get())
627}
628
629/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
630/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
631#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
632pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
633 (
634 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
635 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
636 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
637 )
638}
639
640// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
641// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
642// frame-level flag through the recursive block decode -- `0` (the default)
643// makes every call a true no-op, matching every existing gate stream's
644// `cdef_bits == 0` behaviour exactly.
645// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
646// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
647// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
648// blocks every non-8-bit stream from reaching a decode call, so this is `8`
649// on every path that runs today -- threading it now (rather than the literal
650// `8`) is stage 1 of widening past that refusal without re-deriving every
651// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
652// depth (this decoder's own internal choice, matches dav1d/libaom).
653/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
654/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
655pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
656 (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
657}
658/// The current stream's bit depth, for callers (e.g. dequant) that need the
659/// raw value rather than the derived clamp bound.
660pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
661 fctx.bit_depth.with(std::cell::Cell::get)
662}
663/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
664/// [`crate::stream`]'s decode loop.
665pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
666 fctx.bit_depth.with(|c| c.set(bit_depth));
667}
668
669/// This stream's `mono_chrome` (see [`FrameCtx::mono_chrome`]): a
670/// monochrome frame has `NumPlanes == 1`, so no block codes any chroma
671/// symbol or chroma coefficient and the output picture is luma only.
672pub(crate) fn mono(fctx: &crate::decode::FrameCtx) -> bool {
673 fctx.mono_chrome.with(std::cell::Cell::get)
674}
675
676/// Sets [`mono`] for the current thread, called once per frame from
677/// [`crate::stream`]'s decode loop like [`set_bit_depth`].
678pub(crate) fn set_mono(mono_chrome: bool, fctx: &crate::decode::FrameCtx) {
679 fctx.mono_chrome.with(|c| c.set(mono_chrome));
680}
681
682/// Sequence subsampling. Set once per frame from stream.rs, like set_mono.
683pub(crate) fn set_subsampling(ss_x: u8, ss_y: u8, fctx: &crate::decode::FrameCtx) {
684 fctx.subsampling_x.set(ss_x);
685 fctx.subsampling_y.set(ss_y);
686}
687
688#[inline]
689pub(crate) fn ss_x(fctx: &crate::decode::FrameCtx) -> usize {
690 fctx.subsampling_x.get() as usize
691}
692
693#[inline]
694pub(crate) fn ss_y(fctx: &crate::decode::FrameCtx) -> usize {
695 fctx.subsampling_y.get() as usize
696}
697
698/// libaom ROUND_POWER_OF_TWO. At ss=1 equals div_ceil(dim, 2); at ss=0 is dim.
699#[inline]
700pub(crate) fn round_ss(dim: usize, ss: usize) -> usize {
701 (dim + ((1usize << ss) >> 1)) >> ss
702}
703
704
705 /// This frame's superres state: `(upscaled_width, superres_denom)`, or
706 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
707 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
708 /// `read_lr`'s unit corners and the pixel filters themselves -- works in
709 /// UPSCALED coordinates while deblock and CDEF work in downscaled ones
710 /// (libaom `av1_superres_upscale` in `decodeframe.c`, and
711 /// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x`
712 /// superres arms). Set once per frame from [`crate::stream`]'s decode
713 /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
714 /// so a later frame never inherits it.
715
716/// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
717/// `denom` 8) for a frame that is not superres-scaled.
718pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
719 fctx.superres.with(|c| c.set((upscaled_width, denom)));
720}
721
722/// `(upscaled_width, superres_denom)` when this frame is superres-scaled
723/// (libaom `av1_superres_scaled`), else `None`.
724pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
725 let (w, d) = fctx.superres.with(std::cell::Cell::get);
726 (w > 0 && d != 8).then_some((w, d))
727}
728// Whether this superblock's single CDEF unit (this decoder has no 128x128
729// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
730// read -- reset to `false` at the top of each superblock in the two tile
731// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
732// Number of superblock columns in the current tile's grid, so
733// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
734// [`CDEF_IDX_GRID`].
735// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
736// which of the header's `1 << cdef.bits` strength pairs applies to that
737// superblock's samples.
738// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
739// has read, across every call on the current thread -- the gate's proof that a
740// `cdef_bits > 0` stream actually reached the new reader rather than every
741// superblock coincidentally being all-skip.
742thread_local! {
743 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
744}
745
746// How many times a warp was suppressed for one PLANE because that plane's own
747// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out,
748// reconinter.c) -- the gate's proof that a stream really carries the shape,
749// since the square `side`/`chroma_side` can be 8 or more while the plane's
750// true block is 4 wide (an 8x16 luma block's 4x8 chroma).
751thread_local! {
752 static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
753}
754
755/// Current value of [`WARP_PLANE_SUPPRESS_HITS`].
756#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
757pub(crate) fn warp_plane_suppress_hits() -> usize {
758 WARP_PLANE_SUPPRESS_HITS.with(|c| c.get())
759}
760
761/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
762/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
763/// block dimensions decide it -- never the square `side`/`chroma_side`, which
764/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
765/// bigger than the real block in one axis.
766pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool {
767 if w >= 8 && h >= 8 {
768 return true;
769 }
770 hit!(WARP_PLANE_SUPPRESS_HITS);
771 false
772}
773
774/// Current value of [`CDEF_IDX_HITS`].
775#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
776pub(crate) fn cdef_idx_hits() -> usize {
777 CDEF_IDX_HITS.with(|c| c.get())
778}
779
780// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no
781// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the
782// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient
783// contexts alone, and the intra-edge filter neighbour pair taken mi-exact
784// instead of from the coarse 16x16 cell.
785thread_local! {
786 static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
787 static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
788 static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
789}
790
791/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`].
792#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
793pub(crate) fn intra_in_inter_txctx_hits() -> usize {
794 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get())
795}
796
797/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`].
798#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
799pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize {
800 NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get())
801}
802
803/// Current value of [`EDGE_FILTER_MI_FIX_HITS`].
804#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
805pub(crate) fn edge_filter_mi_fix_hits() -> usize {
806 EDGE_FILTER_MI_FIX_HITS.with(|c| c.get())
807}
808
809// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
810// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
811// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
812// true no-op, matching every existing gate stream's `delta_q_present == 0`
813// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
814// The running quantizer index (spec `CurrentQIndex`, libaom
815// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
816// top of every tile (spec `decode_tile`), carried across superblocks within
817// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
818// dequantization call sites instead of the frame-constant `base_q_idx`.
819// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
820// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
821// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
822// back at every dequantization call site keyed on which plane it is doing.
823// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
824// read, across every call on the current thread -- the gate's proof that a
825// `delta_q_present` stream actually reached the new reader.
826thread_local! {
827 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
828}
829
830/// Current value of [`DELTA_Q_HITS`].
831#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
832pub(crate) fn delta_q_hits() -> usize {
833 DELTA_Q_HITS.with(|c| c.get())
834}
835
836/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
837/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
838/// one), so it is always `0` here.
839fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
840 let d = fctx.quant_deltas.with(|c| c.get());
841 match plane_idx {
842 0 => (d.y_dc, 0),
843 1 => (d.u_dc, d.u_ac),
844 _ => (d.v_dc, d.v_ac),
845 }
846}
847
848/// lane-av1-qmatrix: records this FRAME's quantisation-matrix levels
849/// ([`crate::decode::FrameCtx::qm_levels`]) from the parsed
850/// `quantization_params`. Called from `stream.rs` at the frame header, where
851/// the refusal this lane lifted used to sit.
852pub(crate) fn set_qm_levels(levels: [u8; 3], fctx: &crate::decode::FrameCtx) {
853 fctx.qm_levels.with(|c| c.set(levels));
854}
855
856/// This block's inverse quantisation matrix -- libaom `av1_get_iqmatrix`
857/// (`av1/common/quant_common.c:243`) plus `setup_segmentation_dequant`'s
858/// `av1_use_qmatrix` gate, evaluated per dequantisation call site the same
859/// way the site already evaluates its quantizer index. `None` dequantises
860/// flat (the only behaviour before lane-av1-qmatrix):
861/// - a level of 15, which is both libaom's flat sentinel and what every
862/// `using_qmatrix == 0` frame's levels are parked at;
863/// - a 1D/identity transform (`is_2d_transform` false: libaom's
864/// `av1_get_iqmatrix` reads the NULL slot for those);
865/// - a LOSSLESS block (libaom `av1_use_qmatrix`'s `!xd->lossless[seg]`: the
866/// segment-adjusted quantizer index clamped to 0 with all five plane
867/// deltas zero -- the same `block_q_idx` every other dequant site reads).
868fn block_iqmatrix(
869 fctx: &crate::decode::FrameCtx,
870 plane_idx: usize,
871 w: usize,
872 h: usize,
873 tx_type: TxType,
874) -> Option<crate::qm::Iqm> {
875 let levels = fctx.qm_levels.with(|c| c.get());
876 let level = levels[plane_idx.min(2)];
877 if usize::from(level) >= crate::qm::NUM_QM_LEVELS - 1 {
878 return None;
879 }
880 if !tx_type.is_2d_transform() {
881 return None;
882 }
883 let d = fctx.quant_deltas.with(|c| c.get());
884 if block_q_idx(fctx) == 0
885 && d.y_dc == 0
886 && d.u_dc == 0
887 && d.u_ac == 0
888 && d.v_dc == 0
889 && d.v_ac == 0
890 {
891 return None;
892 }
893 crate::qm::iwt_matrix(usize::from(level), plane_idx != 0, w, h)
894}
895
896/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
897/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
898/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
899/// A no-op when `delta_q_present` is unset, or when this block is not at the
900/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
901/// libaom, collapsed here to a position check since a partition tree's
902/// top-left leaf is the only block that can ever land there), or when that
903/// leaf both *is* the whole superblock and is `skip` (the one case libaom
904/// itself skips the read, state carrying over unchanged).
905fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool, fctx: &crate::decode::FrameCtx) {
906 if !fctx.delta_q_present.with(|c| c.get()) {
907 return;
908 }
909 let sb_mi = sb_mi_cur(fctx) as usize;
910 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
911 return;
912 }
913 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
914 // computed against the sequence's own superblock size (lane-sb128b r1:
915 // it used to be hardcoded against 64 and disabled under `sb128`, which a
916 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
917 // wrong).
918 if is_whole_sb && skip {
919 return;
920 }
921 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
922 const DELTA_Q_SMALL: i32 = 3;
923 if abs >= DELTA_Q_SMALL {
924 let rem_bits = dec.literal(3) + 1;
925 let thr = (1i32 << rem_bits) + 1;
926 abs = dec.literal(rem_bits) as i32 + thr;
927 }
928 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
929 let reduced = if sign_negative { -abs } else { abs };
930 hit!(DELTA_Q_HITS);
931 let res = fctx.delta_q_res.with(|c| c.get());
932 fctx.current_q_idx.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
933}
934
935// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
936// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
937// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
938// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
939// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
940// updates index 0 and every reader treats that as the value for all 4
941// indices (spec `read_delta_lf_params`'s own single-cdf branch).
942// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
943// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
944thread_local! {
945 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
946}
947
948/// Current value of [`DELTA_LF_HITS`].
949#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
950pub(crate) fn delta_lf_hits() -> usize {
951 DELTA_LF_HITS.with(|c| c.get())
952}
953
954/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
955/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
956/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
957/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
958/// read once into index 0 otherwise.
959fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool, fctx: &crate::decode::FrameCtx) {
960 if !fctx.delta_lf_present.with(|c| c.get()) {
961 return;
962 }
963 let sb_mi = sb_mi_cur(fctx) as usize;
964 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
965 return;
966 }
967 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
968 // computed against the sequence's own superblock size (lane-sb128b r1:
969 // it used to be hardcoded against 64 and disabled under `sb128`, which a
970 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
971 // wrong).
972 if is_whole_sb && skip {
973 return;
974 }
975 let multi = fctx.delta_lf_multi.with(|c| c.get());
976 let res = fctx.delta_lf_res.with(|c| c.get());
977 let count = if multi { 4 } else { 1 };
978 let mut cur = fctx.current_delta_lf.with(|c| c.get());
979 for i in 0..count {
980 let mut abs = if multi {
981 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
982 } else {
983 dec.symbol(&mut cdfs.delta_lf) as i32
984 };
985 const DELTA_LF_SMALL: i32 = 3;
986 if abs >= DELTA_LF_SMALL {
987 let rem_bits = dec.literal(3) + 1;
988 let thr = (1i32 << rem_bits) + 1;
989 abs = dec.literal(rem_bits) as i32 + thr;
990 }
991 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
992 let reduced = if sign_negative { -abs } else { abs };
993 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
994 hit!(DELTA_LF_HITS);
995 }
996 fctx.current_delta_lf.with(|c| c.set(cur));
997}
998
999/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
1000/// after `skip` is known at every block-decode call site. A no-op at
1001/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
1002/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
1003/// `allow_intrabc`, so neither needs a separate check here. Reads once per
1004/// superblock, at the first non-skip block.
1005fn maybe_read_cdef_idx(
1006 dec: &mut SymbolDecoder,
1007 mi_r: usize,
1008 mi_c: usize,
1009 // The reading BLOCK's own span in 4x4 mode-info units: a block wider or
1010 // taller than one 64x64 CDEF unit is the first non-skip block of EVERY
1011 // unit it covers, so its one literal drives all of them (lane-b128r).
1012 (w_mi, h_mi): (usize, usize),
1013 skip: bool,
1014 fctx: &crate::decode::FrameCtx,
1015) {
1016 let bits = fctx.cdef_bits.with(|c| c.get());
1017 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
1018 return;
1019 }
1020 let idx = dec.literal(u32::from(bits)) as u8;
1021 fctx.cdef_transmitted.with(|c| c.set(true));
1022 hit!(CDEF_IDX_HITS);
1023 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
1024 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
1025 if sb_cols > 0 {
1026 // lane-b128r: libaom's four CDEF units of a 128 superblock all read
1027 // their strength off the MB_MODE_INFO of the first non-skip block in
1028 // their own unit -- and a block that COVERS several units (the 128
1029 // root's own 128x128 block, the only one there is) is that block for
1030 // every unit it covers, so one literal drives all four. This grid is
1031 // per 64x64 unit, so the read stamps every unit the block covers; one
1032 // that is smaller than a unit stamps exactly the cell it always did.
1033 let (rows, cols) = (
1034 (h_mi / SB_MI as usize).max(1),
1035 (w_mi / SB_MI as usize).max(1),
1036 );
1037 fctx.cdef_idx_grid.with(|g| {
1038 let mut g = g.borrow_mut();
1039 for dr in 0..rows {
1040 for dc in 0..cols {
1041 let i = (sb_r + dr) * sb_cols + sb_c + dc;
1042 if sb_c + dc < sb_cols && i < g.len() {
1043 g[i] = idx;
1044 }
1045 }
1046 }
1047 });
1048 }
1049}
1050
1051// ---------------------------------------------------------------------------
1052// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
1053// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
1054// the two consumers a real stream exercises: the per-segment quantizer index
1055// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
1056// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
1057// `read_intra_segment_id`/`read_inter_segment_id` and
1058// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
1059// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
1060// is what the oracle every gate here compares against actually does.
1061thread_local! {
1062 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
1063 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
1064 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
1065 /// this frame has no primary reference (spec `load_previous_segment_ids`).
1066 /// `(mi_rows, mi_cols)` for both maps above.
1067 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
1068 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
1069 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
1070 /// The block currently being decoded -- read back by [`block_q_idx`].
1071 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
1072 /// How many real `segment_id` symbols were read, and the set of segment
1073 /// ids any block ended up with -- the gate's proof the feature fired.
1074 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1075 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
1076 /// lane-golomb2: the (lowest, highest) quantizer index any block has been
1077 /// dequantized with, i.e. `block_q_idx`'s own span. A gate that means to
1078 /// exercise `SEG_LVL_ALT_Q` needs a stream where this span is WIDER than
1079 /// zero (class `gate-blind-to-feature`): segmentation being enabled says
1080 /// nothing about the segments carrying distinct quantizers.
1081 static BLOCK_Q_SPAN: std::cell::Cell<(i32, i32)> = const { std::cell::Cell::new((i32::MAX, i32::MIN)) };
1082 /// How many `seg_id_predicted` symbols were read (temporal update).
1083 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1084}
1085
1086/// Installs this frame's segmentation parameters and allocates its map, with
1087/// `prev` the primary reference frame's saved map (spec
1088/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
1089/// slot). Called once per frame, whether or not segmentation is enabled.
1090pub(crate) fn set_segmentation(
1091 seg: SegmentationParams,
1092 mi_rows: usize,
1093 mi_cols: usize,
1094 prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx,
1095) {
1096 if crate::envflags::env_flag!("EC_HDR") {
1097 eprintln!(
1098 "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}",
1099 seg.enabled, seg.update_map, seg.temporal_update, seg.seg_id_pre_skip, seg.last_active_seg_id, seg.feature_data
1100 );
1101 }
1102 fctx.seg.with(|s| *s.borrow_mut() = seg);
1103 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
1104 fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
1105 fctx.prev_seg_ids.with(|m| {
1106 let mut m = m.borrow_mut();
1107 m.clear();
1108 if let Some(p) = prev {
1109 if p.len() == mi_rows * mi_cols {
1110 m.extend_from_slice(p);
1111 }
1112 }
1113 });
1114 fctx.above_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
1115 fctx.left_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
1116 fctx.cur_segment_id.with(|c| c.set(0));
1117}
1118
1119/// This frame's decoded segment map, to be stored into whichever reference
1120/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
1121pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
1122 fctx.seg_ids.with(|m| m.borrow().clone())
1123}
1124
1125/// How many `segment_id` symbols have been read (never reset per frame).
1126#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1127pub(crate) fn segment_id_hits() -> usize {
1128 SEG_ID_HITS.with(|c| c.get())
1129}
1130
1131/// How many distinct segment ids any decoded block has carried.
1132#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1133pub(crate) fn segment_ids_seen() -> usize {
1134 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
1135}
1136
1137/// The lowest and highest quantizer index any decoded block was dequantized
1138/// with (`(i32::MAX, i32::MIN)` when nothing decoded).
1139#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1140pub(crate) fn block_q_span() -> (i32, i32) {
1141 BLOCK_Q_SPAN.with(|c| c.get())
1142}
1143
1144/// How many `seg_id_predicted` symbols have been read (temporal update).
1145#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1146pub(crate) fn segment_pred_hits() -> usize {
1147 SEG_PRED_HITS.with(|c| c.get())
1148}
1149
1150/// Resets the segmentation hit counters (gate setup).
1151#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1152pub(crate) fn reset_segment_hits() {
1153 SEG_ID_HITS.with(|c| c.set(0));
1154 SEG_IDS_SEEN.with(|c| c.set(0));
1155 SEG_PRED_HITS.with(|c| c.set(0));
1156 BLOCK_Q_SPAN.with(|c| c.set((i32::MAX, i32::MIN)));
1157}
1158
1159/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
1160/// being decoded, with its `FeatureData` value.
1161fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
1162 fctx.seg.with(|s| {
1163 let s = s.borrow();
1164 s.feature_active(segment_id, feature)
1165 .then(|| i32::from(s.feature_data[segment_id][feature]))
1166 })
1167}
1168
1169/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
1170/// `av1_get_qindex`) for the block currently being decoded: the running
1171/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
1172/// Every dequant call site reads the block's quantizer through here.
1173fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
1174 let base = fctx.current_q_idx.with(|c| c.get());
1175 let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
1176 let q = match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
1177 Some(data) => (base + data).clamp(0, 255),
1178 None => base,
1179 };
1180 // lane-d792: which SEGMENT a block's quantizer came out of, beside the
1181 // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels
1182 // already proven equal is a segment-id defect, not a quantizer one.
1183 if crate::envflags::env_flag!("EC_DQCOEFF") {
1184 eprintln!("OUR_Q base={base} seg={seg_id} q={q}");
1185 }
1186 hit_do!(BLOCK_Q_SPAN.with(|c| {
1187 let (lo, hi) = c.get();
1188 c.set((lo.min(q), hi.max(q)));
1189 }););
1190 q
1191}
1192
1193/// The segment id recorded for one mi cell of the current frame's map.
1194fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
1195 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1196 if mi_r >= mi_rows || mi_c >= mi_cols {
1197 return 0;
1198 }
1199 fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
1200}
1201
1202/// `set_segment_id`: stamps `id` over every mi cell this block covers.
1203fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, fctx: &crate::decode::FrameCtx) {
1204 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1205 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
1206 fctx.seg_ids.with(|m| {
1207 let mut m = m.borrow_mut();
1208 for y in 0..y_mis {
1209 for x in 0..x_mis {
1210 m[(mi_r + y) * mi_cols + mi_c + x] = id;
1211 }
1212 }
1213 });
1214 fctx.cur_segment_id.with(|c| c.set(id));
1215 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1216}
1217
1218/// `copy_segment_id` (libaom `decodemv.c:342`): the previous frame's map is
1219/// inherited VERBATIM over this block's own mi footprint -- per-cell copies,
1220/// not the minified id [`predicted_segment_id`] hands the block. Without a
1221/// previous map the footprint is zeroed, exactly as the C NULL branch does.
1222fn copy_segment_ids(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) {
1223 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1224 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
1225 fctx.seg_ids.with(|m| {
1226 let mut m = m.borrow_mut();
1227 fctx.prev_seg_ids.with(|p| {
1228 let p = p.borrow();
1229 for y in 0..y_mis {
1230 for x in 0..x_mis {
1231 let idx = (mi_r + y) * mi_cols + mi_c + x;
1232 m[idx] = p.get(idx).copied().unwrap_or(0);
1233 }
1234 }
1235 });
1236 });
1237}
1238
1239/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
1240/// `last_frame_seg_map`): the minimum previous-frame segment id over the
1241/// block's own mi footprint. `0` when there is no previous map.
1242fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) -> u8 {
1243 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1244 fctx.prev_seg_ids.with(|m| {
1245 let m = m.borrow();
1246 if m.is_empty() {
1247 return 0;
1248 }
1249 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
1250 let mut id = u8::MAX;
1251 for y in 0..y_mis {
1252 for x in 0..x_mis {
1253 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
1254 }
1255 }
1256 if id == u8::MAX { 0 } else { id }
1257 })
1258}
1259
1260/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
1261fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
1262 if reference == 0 {
1263 return diff;
1264 }
1265 if reference >= max - 1 {
1266 return max - diff - 1;
1267 }
1268 let half = if 2 * reference < max {
1269 diff <= 2 * reference
1270 } else {
1271 diff <= 2 * (max - reference - 1)
1272 };
1273 if half {
1274 return if diff & 1 != 0 {
1275 reference + ((diff + 1) >> 1)
1276 } else {
1277 reference - (diff >> 1)
1278 };
1279 }
1280 if 2 * reference < max { diff } else { max - (diff + 1) }
1281}
1282
1283/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
1284/// frame's already-decoded above/left/above-left neighbours.
1285fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
1286 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1287 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
1288 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
1289 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
1290 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
1291 let ctx = match prev_ul {
1292 None => 0,
1293 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
1294 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
1295 Some(_) => 0,
1296 };
1297 let pred = match (prev_u, prev_l) {
1298 (None, l) => l.unwrap_or(0),
1299 (Some(u), None) => u,
1300 (Some(u), Some(l)) => {
1301 if prev_ul == Some(u) {
1302 u
1303 } else {
1304 l
1305 }
1306 }
1307 };
1308 (pred, ctx)
1309}
1310
1311/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
1312/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
1313/// that prediction. Does NOT write the map -- callers do.
1314fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) -> u8 {
1315 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
1316 if skip {
1317 return pred as u8;
1318 }
1319 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
1320 hit!(SEG_ID_HITS);
1321 let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
1322 let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active);
1323 // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..`
1324 // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff.
1325 if crate::envflags::env_flag!("EC_TRACE_SEG") {
1326 eprintln!("EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}", dec.debug_state().0);
1327 }
1328 id as u8
1329}
1330
1331/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
1332/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
1333/// caller decides which by passing `pre_skip`).
1334fn intra_segment_id(
1335 dec: &mut SymbolDecoder,
1336 cdfs: &mut Cdfs,
1337 mi_r: usize,
1338 mi_c: usize,
1339 w_mi: usize,
1340 h_mi: usize,
1341 skip: bool, fctx: &crate::decode::FrameCtx,
1342) {
1343 if !fctx.seg.with(|s| s.borrow().enabled) {
1344 return;
1345 }
1346 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
1347 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1348}
1349
1350/// Whether this frame's intra blocks read their `segment_id` before `skip`
1351/// (`SegIdPreSkip`); `false` also when segmentation is off.
1352fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
1353 fctx.seg.with(|s| {
1354 let s = s.borrow();
1355 s.enabled && s.seg_id_pre_skip
1356 })
1357}
1358
1359/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
1360/// Called at both spec positions of an inter frame's block: `pre_skip = true`
1361/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
1362fn inter_segment_id(
1363 dec: &mut SymbolDecoder,
1364 cdfs: &mut Cdfs,
1365 mi_r: usize,
1366 mi_c: usize,
1367 w_mi: usize,
1368 h_mi: usize,
1369 skip: bool,
1370 pre_skip: bool, fctx: &crate::decode::FrameCtx,
1371) {
1372 let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
1373 let s = s.borrow();
1374 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
1375 });
1376 if !enabled {
1377 return;
1378 }
1379 if !update_map {
1380 // The map is inherited from the previous frame, and libaom's
1381 // `copy_segment_id` (decodemv.c:342) does that VERBATIM -- a memcpy of
1382 // the previous map over the block's own footprint, mixed ids intact --
1383 // while the id the BLOCK itself carries is the min over that footprint
1384 // (`get_predicted_segment_id`). Stamping the min here flattened mixed
1385 // footprints into the saved map, and every later frame whose
1386 // `update_map == 0` copy or temporal prediction read that position
1387 // dequantized with the wrong segment's `SEG_LVL_ALT_Q` (class
1388 // `simplified-inheritance`).
1389 copy_segment_ids(mi_r, mi_c, w_mi, h_mi, fctx);
1390 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
1391 fctx.cur_segment_id.with(|c| c.set(id));
1392 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1393 return;
1394 }
1395 if pre_skip && !pre_skip_frame {
1396 return;
1397 }
1398 if !pre_skip && skip {
1399 // libaom: a skipped block never codes `seg_id_predicted`, and its
1400 // segment id is the spatial prediction.
1401 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
1402 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
1403 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1404 return;
1405 }
1406 let id = if temporal_update {
1407 let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
1408 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
1409 hit!(SEG_PRED_HITS);
1410 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
1411 if predicted {
1412 predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
1413 } else {
1414 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1415 }
1416 } else {
1417 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1418 };
1419 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1420}
1421
1422/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
1423fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
1424 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
1425 // so contribute 0) outside the tile -- the availability check here is
1426 // what keeps a previous tile's stamps out of this tile's context.
1427 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1428 let above = if mi_r > row0 {
1429 fctx.above_seg_pred.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
1430 } else {
1431 0
1432 };
1433 let left = if mi_c > col0 {
1434 fctx.left_seg_pred.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
1435 } else {
1436 0
1437 };
1438 usize::from(above + left)
1439}
1440
1441/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
1442fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8, fctx: &crate::decode::FrameCtx) {
1443 fctx.above_seg_pred.with(|m| {
1444 let mut m = m.borrow_mut();
1445 for i in 0..w_mi {
1446 if let Some(cell) = m.get_mut(mi_c + i) {
1447 *cell = value;
1448 }
1449 }
1450 });
1451 fctx.left_seg_pred.with(|m| {
1452 let mut m = m.borrow_mut();
1453 for i in 0..h_mi {
1454 if let Some(cell) = m.get_mut(mi_r + i) {
1455 *cell = value;
1456 }
1457 }
1458 });
1459}
1460
1461// How many key-frame luma blocks resolved `smooth_neighbor` (spec
1462// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
1463// counter, proving a stream actually put a directional block next to a
1464// smooth-predicted neighbour rather than every block reading the (previously
1465// hardcoded `false`) edge-filter strength bucket unchanged.
1466thread_local! {
1467 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
1468 const { std::cell::Cell::new(0) };
1469}
1470
1471/// Current value of [`SMOOTH_LUMA_HITS`].
1472#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1473pub(crate) fn smooth_luma_hits() -> usize {
1474 SMOOTH_LUMA_HITS.with(|c| c.get())
1475}
1476
1477thread_local! {
1478 /// lane-band46 r1: how many split-transform units answered their intra
1479 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
1480 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
1481 /// apply to them (class reach-is-per-transform-unit). Every hit is a
1482 /// transform unit whose above-right / below-left reference samples would
1483 /// be wrong without that fix.
1484 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
1485 const { std::cell::Cell::new(0) };
1486}
1487
1488/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
1489#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1490pub(crate) fn split_tu_reach_fix_hits() -> usize {
1491 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
1492}
1493
1494/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
1495/// answer differs from the standalone-block answer the call sites used before
1496/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
1497/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
1498/// block's top-left `(px, py)`.
1499#[allow(clippy::too_many_arguments)]
1500fn tu_reach(
1501 bw: usize,
1502 bh: usize,
1503 col_off: usize,
1504 row_off: usize,
1505 tx: usize,
1506 block: Reach,
1507 px: usize,
1508 py: usize,
1509 width: usize,
1510 height: usize, fctx: &crate::decode::FrameCtx,
1511) -> Reach {
1512 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
1513 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
1514 if fixed != standalone {
1515 hit!(SPLIT_TU_REACH_FIX_HITS);
1516 }
1517 fixed
1518}
1519
1520// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
1521// across every call on the current thread -- lane-chroma r3's own before/after
1522// counter, proving a stream actually exercised chroma's smooth/paeth
1523// predictor (the previously-refused round-2 gap) rather than every block
1524// landing on DC/CFL/directional.
1525thread_local! {
1526 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
1527 const { std::cell::Cell::new(0) };
1528}
1529
1530/// Current value of [`SMOOTH_UV_HITS`].
1531#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1532pub(crate) fn smooth_uv_hits() -> usize {
1533 SMOOTH_UV_HITS.with(|c| c.get())
1534}
1535
1536// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
1537// full superblock walk over, across every call on the current thread --
1538// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
1539// multi-tile stream must prove more than one tile actually fired, not just
1540// that the stream carried tile_info.cols > 1.
1541thread_local! {
1542 static TILE_HITS: std::cell::Cell<usize> =
1543 const { std::cell::Cell::new(0) };
1544}
1545/// Current value of [`TILE_HITS`].
1546#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1547pub(crate) fn tile_hits() -> usize {
1548 TILE_HITS.with(|c| c.get())
1549}
1550
1551// How many 4-pixel deblocking edge groups [`edge_params`] has actually
1552// selected for filtering, across every call on the current thread -- the same
1553// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1554// exercised `apply_deblock` rather than every edge landing on level 0.
1555thread_local! {
1556 static DEBLOCK_HITS: std::cell::Cell<usize> =
1557 const { std::cell::Cell::new(0) };
1558}
1559/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1560/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1561/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1562static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
1563 std::sync::atomic::AtomicUsize::new(0);
1564
1565/// Current value of [`DEBLOCK_HITS`].
1566#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1567pub(crate) fn deblock_hits() -> usize {
1568 DEBLOCK_HITS.with(|c| c.get())
1569}
1570
1571// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1572// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1573// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1574// stream built with `--enable-onesided-comp=1` really exercised the
1575// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1576thread_local! {
1577 static UNI_COMP_HITS: std::cell::Cell<usize> =
1578 const { std::cell::Cell::new(0) };
1579}
1580
1581/// Current value of [`UNI_COMP_HITS`].
1582#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1583pub(crate) fn uni_comp_hits() -> usize {
1584 UNI_COMP_HITS.with(|c| c.get())
1585}
1586
1587// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1588// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1589// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1590// blend and not only the wedge arm.
1591thread_local! {
1592 static DIFFWTD_HITS: std::cell::Cell<usize> =
1593 const { std::cell::Cell::new(0) };
1594}
1595
1596/// Current value of [`DIFFWTD_HITS`].
1597#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1598pub(crate) fn diffwtd_hits() -> usize {
1599 DIFFWTD_HITS.with(|c| c.get())
1600}
1601
1602// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1603// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1604// this decoder's square inter path reaches), so no `compound_type` symbol is
1605// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1606// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1607thread_local! {
1608 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1609 const { std::cell::Cell::new(0) };
1610}
1611
1612/// Current value of [`DIFFWTD_INFERRED_HITS`].
1613#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1614pub(crate) fn diffwtd_inferred_hits() -> usize {
1615 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1616}
1617
1618// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1619// with `show_frame == 0`, output later by a `show_existing_frame` header
1620// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1621// `stream::decode_stream`, which is where the frame header is consumed; the
1622// gate's proof that the on-value really reached the bitstream rather than
1623// being dropped by the rate control.
1624thread_local! {
1625 static FWD_KF_HITS: std::cell::Cell<usize> =
1626 const { std::cell::Cell::new(0) };
1627}
1628
1629/// Current value of [`FWD_KF_HITS`].
1630#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1631pub(crate) fn fwd_kf_hits() -> usize {
1632 FWD_KF_HITS.with(|c| c.get())
1633}
1634
1635/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1636pub(crate) fn note_fwd_kf() {
1637 hit!(FWD_KF_HITS);
1638}
1639
1640// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1641// the block's own side, across every call on the current thread -- the same
1642// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1643// actually exercised a *split* transform under `TxMode::Select` rather than
1644// every block coincidentally resolving `depth=0` (indistinguishable from
1645// `TxMode::Largest` pixel-wise).
1646thread_local! {
1647 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1648 const { std::cell::Cell::new(0) };
1649}
1650
1651// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1652// transform smaller than their own side (`tx_depth != 0`) while coding a
1653// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1654// only exercises with aomenc's tx-size search left ON (its default), which
1655// every older recipe in this file pins off. Counted at the block, so a stream
1656// where RD happened to give every split-transform block a DC chroma mode
1657// reads as zero rather than silently passing for free.
1658thread_local! {
1659 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1660 const { std::cell::Cell::new(0) };
1661}
1662
1663/// Current value of [`SQ_CHROMA_TX_HITS`].
1664#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1665pub(crate) fn sq_chroma_tx_hits() -> usize {
1666 SQ_CHROMA_TX_HITS.with(|c| c.get())
1667}
1668
1669/// Current value of [`TX_DEPTH_HITS`].
1670#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1671pub(crate) fn tx_depth_hits() -> usize {
1672 TX_DEPTH_HITS.with(|c| c.get())
1673}
1674
1675// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1676// read, and how many of those actually took the split, on the current thread
1677// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1678// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1679// coincidentally coding one whole-block transform.
1680thread_local! {
1681 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1682 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1683 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1684 // strips coded one whole-block rect transform unit, and how many split
1685 // their rect max transform into square sub-transforms.
1686 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1687 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1688 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1689 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1690 // truncated low-32 corner.
1691 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1692 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1693 // inter strip, `[32x8, 8x32]`.
1694 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1695 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1696 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1697 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1698 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1699 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1700 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1701 // frame -- 16x8 and 8x16 inter leaves.
1702 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1703 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1704 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1705 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1706 // `decode_inter_block` already carries forty parameters and both are
1707 // frame-constant.
1708 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1709 // frame-constant like the two above and stashed the same way -- an intra
1710 // block inside an inter frame reads `use_filter_intra` under it.
1711}
1712
1713/// Current value of [`TXFM_SPLIT_READS`].
1714#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1715pub(crate) fn txfm_split_reads() -> usize {
1716 TXFM_SPLIT_READS.with(|c| c.get())
1717}
1718
1719/// Current value of [`TXFM_SPLIT_HITS`].
1720#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1721pub(crate) fn txfm_split_hits() -> usize {
1722 TXFM_SPLIT_HITS.with(|c| c.get())
1723}
1724
1725/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1726#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1727pub(crate) fn inter_leaf16_horz_hits() -> usize {
1728 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1729}
1730
1731/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1732#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1733pub(crate) fn inter_leaf16_vert_hits() -> usize {
1734 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1735}
1736
1737/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1738pub(crate) fn rect_inter_tu_hits() -> usize {
1739 RECT_INTER_TU_HITS.with(|c| c.get())
1740}
1741
1742/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1743pub(crate) fn rect_inter_txsplit_hits() -> usize {
1744 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1745}
1746
1747/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1748pub(crate) fn rect64_inter_tu_hits() -> usize {
1749 RECT64_INTER_TU_HITS.with(|c| c.get())
1750}
1751
1752/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1753/// whole-block luma units of a 32x32-level 1:4 inter strip.
1754pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1755 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1756}
1757
1758/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1759/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1760pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1761 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1762}
1763
1764/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1765/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1766pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1767 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1768}
1769
1770/// Records one rectangular var-tx leaf.
1771fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1772 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1773 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1774 }
1775 let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS };
1776 cell.with(|c| {
1777 let mut h = c.get();
1778 h[usize::from(th > tw)] += 1;
1779 c.set(h);
1780 });
1781}
1782
1783/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1784/// [`ENABLE_FILTER_INTRA_INTER`].
1785pub(crate) fn set_inter_tx_mode(
1786 tx_select: bool,
1787 reduced_tx_set: bool,
1788 enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,
1789) {
1790 fctx.tx_select_inter.with(|c| c.set(tx_select));
1791 fctx.intra_only.with(|c| c.set(false));
1792 fctx.tx_select_frame.with(|c| c.set(tx_select));
1793 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1794 fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra));
1795}
1796
1797// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1798// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1799// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1800// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1801// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1802// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1803// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1804// path above).
1805thread_local! {
1806 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1807 const { std::cell::Cell::new(0) };
1808}
1809
1810/// Current value of [`VERT_B_INTRA_HITS`].
1811#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1812pub(crate) fn vert_b_intra_hits() -> usize {
1813 VERT_B_INTRA_HITS.with(|c| c.get())
1814}
1815
1816// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1817// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1818// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1819// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1820// every arm separately so a run where aomenc's RD only picked one cannot
1821// pass as proof of four.
1822thread_local! {
1823 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1824}
1825
1826// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1827thread_local! {
1828 /// 4x4 transform units decoded inside an 8x8 square of a
1829 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1830 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1831 /// a real `--enable-tx-size-search=1` stream reaches it.
1832 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1833}
1834
1835#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1836pub(crate) fn vert_ab_tx4_hits() -> usize {
1837 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1838}
1839
1840#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1841pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1842 AB16_HITS.with(std::cell::Cell::get)
1843}
1844
1845fn bump_ab16(arm: usize) {
1846 hit_do! {
1847 AB16_HITS.with(|c| {
1848 let mut v = c.get();
1849 v[arm] += 1;
1850 c.set(v);
1851 });
1852 }
1853}
1854
1855// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1856// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1857// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1858// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1859// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1860// superblock's z-order recursion, not raster mi position).
1861thread_local! {
1862 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1863 const { std::cell::Cell::new(0) };
1864}
1865
1866/// Current value of [`HORZ_VERT_INTRA_HITS`].
1867#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1868pub(crate) fn horz_vert_intra_hits() -> usize {
1869 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1870}
1871
1872// How many blocks were decoded as a frame-edge rect strip -- the single
1873// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1874// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1875// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1876// paths share the counter.
1877thread_local! {
1878 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1879 const { std::cell::Cell::new(0) };
1880}
1881
1882/// Current value of [`EDGE_RECT_STRIP_HITS`].
1883#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
1884pub(crate) fn edge_rect_strip_hits() -> usize {
1885 EDGE_RECT_STRIP_HITS.with(|c| c.get())
1886}
1887
1888// lane-interedge r1: frame-edge half strips on the INTER path, per partition
1889// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
1890// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
1891// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
1892// are height mod 16 == 8, so every inter frame crosses these nodes.
1893thread_local! {
1894 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
1895 const { std::cell::Cell::new([0; 6]) };
1896}
1897
1898/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1899pub(crate) fn bump_inter_edge_strip(idx: usize) {
1900 hit_do! {
1901 INTER_EDGE_STRIP_HITS.with(|c| {
1902 let mut v = c.get();
1903 v[idx] += 1;
1904 c.set(v);
1905 });
1906 }
1907}
1908
1909// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
1910// forced split -- libaom `decode_partition` (decodeframe.c):
1911// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
1912// straddle case that reads NO symbol at all. Indexed by level:
1913// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
1914thread_local! {
1915 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
1916 const { std::cell::Cell::new([0; 4]) };
1917}
1918
1919fn bump_edge_both_cut(level: usize) {
1920 hit_do! {
1921 EDGE_BOTH_CUT_HITS.with(|c| {
1922 let mut v = c.get();
1923 v[level] += 1;
1924 c.set(v);
1925 });
1926 }
1927}
1928
1929/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
1930pub fn inter_edge_strip_hits() -> [usize; 6] {
1931 INTER_EDGE_STRIP_HITS.with(|c| c.get())
1932}
1933
1934/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
1935/// into the next one (class `counter-from-refused-stream`).
1936pub fn reset_inter_edge_strip_hits() {
1937 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
1938}
1939
1940/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
1941#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1942pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
1943 EDGE_BOTH_CUT_HITS.with(|c| c.get())
1944}
1945
1946/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
1947#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1948pub(crate) fn reset_edge_both_cut_hits() {
1949 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
1950}
1951
1952// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1953// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1954// the case every rect path here refused by name before, and the first
1955// refusal the user's ReelB extract (600s in) stops at.
1956thread_local! {
1957 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1958 const { std::cell::Cell::new(0) };
1959}
1960
1961/// Current value of [`RECT_SPLIT_TX_HITS`].
1962#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1963pub(crate) fn rect_split_tx_hits() -> usize {
1964 RECT_SPLIT_TX_HITS.with(|c| c.get())
1965}
1966
1967// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1968// side 64) AND split past the first depth, i.e. tiled more than one unit in
1969// each axis -- the only shape with a transform unit that has neighbours on
1970// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1971// no gate fired before lane-rectsplit r2 (the shared counter above also
1972// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1973thread_local! {
1974 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1975 const { std::cell::Cell::new(0) };
1976}
1977
1978/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1979#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1980pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1981 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1982}
1983
1984// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1985// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1986// chroma half takes that had no coefficient tables before (index order:
1987// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1988// proves the pair it happens to hit cannot catch a transposed scan/context
1989// table (class scan-weights-cross-axis).
1990thread_local! {
1991 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1992 const { std::cell::Cell::new([0; 4]) };
1993}
1994
1995/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1996#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1997pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1998 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1999}
2000
2001// How many HORZ/VERT intra strips actually predicted with filter intra
2002// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
2003// ("this decoder predicts square-only") until `predict_filter_intra` took
2004// `bw`x`bh`.
2005thread_local! {
2006 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
2007 const { std::cell::Cell::new(0) };
2008}
2009
2010/// Current value of [`FILTER_INTRA_RECT_HITS`].
2011#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2012pub(crate) fn filter_intra_rect_hits() -> usize {
2013 FILTER_INTRA_RECT_HITS.with(|c| c.get())
2014}
2015
2016// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
2017// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
2018// was never read at all before that round, so a gate needs to prove the flag
2019// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
2020// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
2021// carry different probabilities (18101 vs 20229), so a transposed pair is
2022// only caught by a gate that sees the flag fire on BOTH shapes (class
2023// scan-weights-cross-axis).
2024thread_local! {
2025 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
2026 const { std::cell::Cell::new(0) };
2027 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
2028 const { std::cell::Cell::new(0) };
2029}
2030
2031/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
2032#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2033pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
2034 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
2035}
2036
2037/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
2038#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2039pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
2040 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
2041}
2042
2043// How many rectangular transform units actually coded coefficients through
2044// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
2045// exercised the rect coefficient reader at all rather than passing on
2046// all-skip blocks.
2047thread_local! {
2048 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2049 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2050}
2051
2052/// Current value of [`RECT_COEFF_TU_HITS`].
2053#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2054pub(crate) fn rect_coeff_tu_hits() -> usize {
2055 RECT_COEFF_TU_HITS.with(|c| c.get())
2056}
2057
2058/// Rectangular transform units whose resolved `tx_type` is a 1D class
2059/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
2060/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
2061/// for the square reader's own 1D types.
2062#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2063pub(crate) fn rect_class1_hits() -> usize {
2064 RECT_CLASS1_HITS.with(|c| c.get())
2065}
2066
2067// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
2068// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
2069// shapes whose `use_filter_intra` symbol had no CDF class before this round.
2070// A gate asserting the wider counter would be satisfied by a 32x16 strip and
2071// prove nothing about the new shapes.
2072thread_local! {
2073 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
2074 const { std::cell::Cell::new(0) };
2075}
2076
2077/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
2078#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2079pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
2080 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
2081}
2082
2083// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
2084// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
2085// counter would be satisfied by a 16x8 strip and prove nothing here.
2086thread_local! {
2087 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
2088 const { std::cell::Cell::new(0) };
2089}
2090
2091/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
2092#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2093pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
2094 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
2095}
2096
2097// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
2098// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
2099// call on the current thread -- the same before/after counter pattern as
2100// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
2101// `eob_pt`/1D-neighbour context path rather than every block coincidentally
2102// landing on `DCT_DCT`.
2103thread_local! {
2104 static TX_CLASS1_HITS: std::cell::Cell<usize> =
2105 const { std::cell::Cell::new(0) };
2106}
2107
2108// How many `uv_mode` reads resolved to a directional chroma mode (neither
2109// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
2110// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
2111// actually exercised chroma's own directional predictor.
2112thread_local! {
2113 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
2114 const { std::cell::Cell::new(0) };
2115}
2116
2117/// Current value of [`DIRECTIONAL_UV_HITS`].
2118#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2119pub(crate) fn directional_uv_hits() -> usize {
2120 DIRECTIONAL_UV_HITS.with(|c| c.get())
2121}
2122
2123// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
2124// something other than [`ANGLE_DELTA_ZERO`], across every call in the
2125// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
2126// proving a stream actually exercised a nonzero angle delta.
2127thread_local! {
2128 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
2129 const { std::cell::Cell::new(0) };
2130}
2131
2132// How many [`read_single_ref`] reads resolved to a reference other than
2133// `LAST_FRAME`, across every call on the current thread -- the same before/after
2134// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
2135// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
2136// only other supported one so far) rather than every block coincidentally
2137// resolving `LAST_FRAME`.
2138thread_local! {
2139 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
2140 const { std::cell::Cell::new(0) };
2141}
2142
2143/// Current value of [`NON_LAST_REF_HITS`].
2144#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2145pub(crate) fn non_last_ref_hits() -> usize {
2146 NON_LAST_REF_HITS.with(|c| c.get())
2147}
2148
2149// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
2150// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
2151// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
2152// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
2153// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
2154// `GOLDEN_FRAME` draw it did not ask for.
2155thread_local! {
2156 static LAST2_HITS: std::cell::Cell<usize> =
2157 const { std::cell::Cell::new(0) };
2158}
2159thread_local! {
2160 static LAST3_HITS: std::cell::Cell<usize> =
2161 const { std::cell::Cell::new(0) };
2162}
2163thread_local! {
2164 static GOLDEN_HITS: std::cell::Cell<usize> =
2165 const { std::cell::Cell::new(0) };
2166}
2167thread_local! {
2168 static BWDREF_HITS: std::cell::Cell<usize> =
2169 const { std::cell::Cell::new(0) };
2170}
2171thread_local! {
2172 static ALTREF2_HITS: std::cell::Cell<usize> =
2173 const { std::cell::Cell::new(0) };
2174}
2175thread_local! {
2176 static ALTREF_HITS: std::cell::Cell<usize> =
2177 const { std::cell::Cell::new(0) };
2178}
2179
2180// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
2181// -- proves a `reference_select` stream actually reached a block that picked
2182// compound, not just that the header bit was set. Every such block is
2183// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
2184// so this only ever counts attempted reads, never a completed decode.
2185thread_local! {
2186 static COMP_MODE_HITS: std::cell::Cell<usize> =
2187 const { std::cell::Cell::new(0) };
2188}
2189
2190/// Current value of [`COMP_MODE_HITS`].
2191#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2192pub(crate) fn comp_mode_hits() -> usize {
2193 COMP_MODE_HITS.with(|c| c.get())
2194}
2195
2196// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
2197// use for, across every call on the current thread -- the same before/after
2198// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
2199// exercised palette reconstruction rather than only reading and refusing the
2200// `palette_y_mode` symbol.
2201thread_local! {
2202 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2203}
2204
2205/// Current value of [`PALETTE_HITS`].
2206#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2207pub(crate) fn palette_hits() -> usize {
2208 PALETTE_HITS.with(|c| c.get())
2209}
2210
2211// lane-tiles r12: of those, how many sat at their own TILE's left column --
2212// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
2213// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
2214// palette gate that never hits one proves nothing about the tile guard.
2215thread_local! {
2216 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2217}
2218
2219/// Current value of [`PALETTE_TILE_LEFT_HITS`].
2220#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2221pub(crate) fn palette_tile_left_hits() -> usize {
2222 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
2223}
2224
2225// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
2226// palette use -- proves a stream actually reconstructed UV palette pixels,
2227// not just read and refused the `palette_uv_mode` symbol.
2228thread_local! {
2229 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2230}
2231
2232/// Current value of [`PALETTE_UV_HITS`].
2233#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2234pub(crate) fn palette_uv_hits() -> usize {
2235 PALETTE_UV_HITS.with(|c| c.get())
2236}
2237
2238// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
2239// decoded a real palette-Y use -- proves the rect strip's own palette syntax
2240// (not just the square path's) actually fired.
2241thread_local! {
2242 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2243}
2244
2245/// Current value of [`PALETTE_RECT_HITS`].
2246#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2247pub(crate) fn palette_rect_hits() -> usize {
2248 PALETTE_RECT_HITS.with(|c| c.get())
2249}
2250
2251// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
2252// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
2253// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
2254// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
2255// RD, almost always refused-on-use because the block doesn't end up USING a
2256// palette -- see r5's report). This is the site the removed refusal
2257// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
2258// fired here whether or not the block picked a palette, so this is the
2259// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
2260// never observes.
2261thread_local! {
2262 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2263}
2264
2265/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
2266#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2267pub(crate) fn rect_screen_content_hits() -> usize {
2268 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
2269}
2270
2271// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
2272// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
2273// windowing actually ran, not just that the whole-block path stayed exact.
2274// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
2275// first actually incremented in r7, when the refusal it guarded was lifted.
2276thread_local! {
2277 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2278}
2279
2280thread_local! {
2281 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
2282 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
2283 /// (16x8/8x16), the two shapes the lifted refusals named.
2284 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2285}
2286
2287/// Current value of [`RECT4_PALETTE_HITS`].
2288#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2289pub(crate) fn rect4_palette_hits() -> usize {
2290 RECT4_PALETTE_HITS.with(|c| c.get())
2291}
2292
2293/// Current value of [`PALETTE_SPLIT_TX_HITS`].
2294#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2295pub(crate) fn palette_split_tx_hits() -> usize {
2296 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
2297}
2298
2299thread_local! {
2300 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
2301 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
2302 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
2303 /// `--min-partition-size=8` puts them on this leaf path.
2304 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2305}
2306
2307/// Current value of [`PALETTE_LEAF8_HITS`].
2308#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2309pub(crate) fn palette_leaf8_hits() -> usize {
2310 PALETTE_LEAF8_HITS.with(|c| c.get())
2311}
2312
2313/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
2314#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2315pub(crate) fn reset_palette_leaf8_hits() {
2316 PALETTE_LEAF8_HITS.with(|c| c.set(0));
2317}
2318
2319thread_local! {
2320 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
2321 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
2322 /// block that also carries a real, corner-cropped luma transform.
2323 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2324}
2325
2326/// Current value of [`PALETTE_SB_STRIP_HITS`].
2327#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2328pub(crate) fn palette_sb_strip_hits() -> usize {
2329 PALETTE_SB_STRIP_HITS.with(|c| c.get())
2330}
2331
2332/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
2333#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2334pub(crate) fn reset_palette_sb_strip_hits() {
2335 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
2336}
2337
2338// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
2339// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
2340// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
2341// capability rather than the key frame's, which every screen stream also
2342// carries.
2343thread_local! {
2344 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2345 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2346}
2347
2348// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
2349// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
2350// shared counter too, so only this one proves a gate really reached the leaf
2351// where the refusal used to sit.
2352thread_local! {
2353 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
2354 const { std::cell::Cell::new((0, 0)) };
2355}
2356
2357/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
2358pub(crate) fn inter8_palette_hits() -> (usize, usize) {
2359 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
2360}
2361
2362/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
2363pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
2364 (
2365 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
2366 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
2367 )
2368}
2369
2370// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
2371// and which are therefore predicted one transform unit at a time (a skipped
2372// block codes no coefficients, so nothing else in the stream witnesses this
2373// path -- only the pixels do).
2374thread_local! {
2375 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2376}
2377
2378/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
2379pub fn skip_split_tx_hits() -> usize {
2380 SKIP_SPLIT_TX_HITS.with(|c| c.get())
2381}
2382
2383// lane-svt1: SKIPPED square blocks carrying a palette/intrabc prediction whose
2384// `tx_depth` split the luma transform -- the arm that predicted DC off the
2385// block edges before the fix. Like [`SKIP_SPLIT_TX_HITS`] only the pixels
2386// witness this path, so a gate that wants it needs the counter.
2387thread_local! {
2388 static SKIP_SPLIT_TX_OVERRIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2389}
2390
2391/// Current value of [`SKIP_SPLIT_TX_OVERRIDE_HITS`] (blocks).
2392pub fn skip_split_tx_override_hits() -> usize {
2393 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.get())
2394}
2395
2396/// Zeroes [`SKIP_SPLIT_TX_OVERRIDE_HITS`] before a gate's own decode attempt.
2397pub fn reset_skip_split_tx_override_hits() {
2398 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.set(0));
2399}
2400
2401// lane-svtinter: palette colour-index maps whose block is cut by the frame's
2402// bottom/right mi edge, so spec 5.11.50's `onscreenWidth`/`onscreenHeight`
2403// really are smaller than the block and FEWER symbols are read than the
2404// block has cells (class map-read-past-frame-edge).
2405thread_local! {
2406 static PALETTE_ONSCREEN_CUT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2407}
2408
2409/// Current value of [`PALETTE_ONSCREEN_CUT_HITS`] (colour-index maps).
2410pub fn palette_onscreen_cut_hits() -> usize {
2411 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.get())
2412}
2413
2414/// Zeroes [`PALETTE_ONSCREEN_CUT_HITS`] before a gate's own decode attempt.
2415pub fn reset_palette_onscreen_cut_hits() {
2416 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.set(0));
2417}
2418
2419/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
2420pub fn reset_skip_split_tx_hits() {
2421 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
2422}
2423
2424// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
2425// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
2426// the gate's proof that the lifted path actually ran, per size.
2427thread_local! {
2428 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
2429 const { std::cell::Cell::new([0; 4]) };
2430}
2431
2432/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
2433#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2434pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
2435 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2436}
2437
2438 /// A just-decoded palette-Y block's own predicted pixels
2439 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
2440 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
2441 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
2442 /// per-block override through `read_plane`'s two dozen call sites is the
2443 /// alternative this avoids). Always empty again once that call consumes
2444 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
2445 /// sees stale state.
2446
2447
2448/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
2449/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
2450/// site whose reconstruct never runs would be picked up by the NEXT block's
2451/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
2452/// lane-lossless2: one transform unit's window on a block-sized palette
2453/// prediction buffer. A unit reads its prediction at ITS OWN stride, so
2454/// handing it the whole-block buffer makes every unit reconstruct the block's
2455/// top-left corner (the luma split-transform paths already window; the chroma
2456/// ones did not, which is invisible until a lossless frame codes a palette
2457/// block as 4x4 chroma units).
2458fn palette_window(buf: &[u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize) -> Vec<u16> {
2459 (0..h)
2460 .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied())
2461 .collect()
2462}
2463
2464/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
2465#[track_caller]
2466fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
2467 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2468 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
2469 eprintln!(
2470 "PALSET len={} stale={stale} at {}",
2471 buf.len(),
2472 std::panic::Location::caller()
2473 );
2474 }
2475 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
2476}
2477
2478#[track_caller]
2479fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
2480 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
2481 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2482 eprintln!(
2483 "PALTAKE len={:?} at {}",
2484 got.as_ref().map(Vec::len),
2485 std::panic::Location::caller()
2486 );
2487 }
2488 got
2489}
2490
2491/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
2492/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
2493/// pixels, because at parse time this block's own luma is still queued.
2494#[derive(Clone, Copy, Debug)]
2495pub(crate) struct CflSrc {
2496 px: usize,
2497 py: usize,
2498 bw: usize,
2499 bh: usize,
2500}
2501
2502fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
2503 CflSrc { px, py, bw: side, bh: side }
2504}
2505
2506fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
2507 CflSrc { px, py, bw, bh }
2508}
2509
2510/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
2511/// instead of executed. Each variant is the resolved argument tuple of the
2512/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
2513/// order performs exactly the same writes in exactly the same order --
2514/// entropy parsing no longer touches the frame's own planes (except the two
2515/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
2516/// the replay on a superblock-row wavefront worker.
2517/// The dequantization + inverse transform of one transform unit, kept as its
2518/// INPUTS so that a recorded write carries the work instead of its result
2519/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
2520/// recon worker, not on the parsing thread. `stride == 0` means the dense
2521/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
2522/// `reconstruct_mc_rect` reads both of its buffers at.
2523#[derive(Clone, Copy)]
2524pub(crate) struct TxParams {
2525 pub(crate) w: usize,
2526 pub(crate) h: usize,
2527 pub(crate) bit_depth: u8,
2528 pub(crate) q_idx: i32,
2529 pub(crate) dc_delta: i32,
2530 pub(crate) ac_delta: i32,
2531 pub(crate) tx_type: TxType,
2532 /// lane-av1-qmatrix: this unit's inverse quantisation matrix, selected
2533 /// on the parse thread by [`block_iqmatrix`] and captured here so the
2534 /// recon worker scales identically without touching frame state.
2535 pub(crate) qm: Option<crate::qm::Iqm>,
2536 pub(crate) stride: usize,
2537 /// lane-lossless: this transform unit belongs to a lossless BLOCK (its
2538 /// segment's `xd->lossless[segment_id]` bit), so the residual comes off
2539 /// the 4x4 Walsh-Hadamard
2540 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
2541 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
2542 pub(crate) lossless: bool,
2543}
2544
2545/// lane-av1mixloss: Walsh-Hadamard transform units actually reconstructed.
2546/// The mixed-lossless witness's proof the per-segment lossless path really
2547/// ran on a frame that is NOT `CodedLossless`. Atomic because the wavefront
2548/// workers run this on their own threads.
2549static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize =
2550 std::sync::atomic::AtomicUsize::new(0);
2551
2552/// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after
2553/// delta around one decode.
2554#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2555pub(crate) fn lossless_wht_units() -> usize {
2556 LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
2557}
2558
2559impl TxParams {
2560 /// The one copy of the produce-the-residual code: the inline path calls it
2561 /// on the parse thread, the wavefront worker calls it on its own, so both
2562 /// are the same function on the same inputs and byte-identical.
2563 fn run(self, grid: &[i32]) -> Vec<i32> {
2564 let residual = if self.lossless {
2565 LOSSLESS_WHT_UNITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2566 debug_assert_eq!((self.w, self.h), (4, 4));
2567 debug_assert_eq!(self.tx_type, TxType::DctDct);
2568 crate::transform::dequant_and_inverse_wht4x4(
2569 grid, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2570 )
2571 } else {
2572 dequant_and_inverse_typed_wh(
2573 grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2574 self.tx_type,
2575 self.qm,
2576 )
2577 };
2578 // An all-zero grid transforms to the empty marker, and a strided copy
2579 // of zeros is still zeros: the marker passes straight through.
2580 if residual.is_empty() {
2581 return residual;
2582 }
2583 if self.stride == 0 {
2584 return residual;
2585 }
2586 let mut strided = vec![0i32; self.stride * self.stride];
2587 for row in 0..self.h {
2588 strided[row * self.stride..][..self.w]
2589 .copy_from_slice(&residual[row * self.w..][..self.w]);
2590 }
2591 strided
2592 }
2593}
2594
2595/// A recorded write's residual: already transformed, or the coefficients and
2596/// [`TxParams`] the worker transforms itself.
2597pub(crate) enum Residual {
2598 /// An already-transformed residual in the arena, `(offset, len)`; a zero
2599 /// `len` is the all-zero marker [`dense_residual`] expands.
2600 Done(u32, u32),
2601 /// The coefficients live in the pushing tile's arena
2602 /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
2603 /// len)` in it.
2604 Coeffs(TxParams, u32, u32),
2605}
2606
2607impl Residual {
2608 /// The record for a transform unit whose coefficient grid is all zero:
2609 /// the empty marker, so neither the grid nor the residual is cloned and
2610 /// the worker never runs the transform (60% of the 4K segment's units).
2611 fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2612 if is_zero_grid(grid) {
2613 return Self::Done(0, 0);
2614 }
2615 Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
2616 }
2617
2618 /// A residual the parse thread already transformed, kept in the arena
2619 /// instead of its own `Vec`.
2620 fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2621 // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself,
2622 // which is exactly the all-zero marker -- one pointer compare instead
2623 // of copying up to 64 KB of zeros into the arena per block.
2624 if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) {
2625 return Self::Done(0, 0);
2626 }
2627 Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
2628 }
2629
2630 /// The residual to reconstruct with; `scratch` is where a transform run
2631 /// on this thread lands, so the caller owns that buffer.
2632 fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
2633 match self {
2634 Self::Done(off, len) => &arena[off as usize..][..len as usize],
2635 Self::Coeffs(p, off, len) => {
2636 *scratch = p.run(&arena[off as usize..][..len as usize]);
2637 scratch
2638 }
2639 }
2640 }
2641}
2642
2643/// Appends to the tile's coefficient arena, returning the offset the record
2644/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
2645fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
2646 fctx.coeff_arena.with(|a| {
2647 let mut a = a.borrow_mut();
2648 let off = a.len();
2649 a.extend_from_slice(v);
2650 off as u32
2651 })
2652}
2653
2654/// [`push_coeffs`] for a recorded prediction.
2655fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
2656 fctx.pred_arena.with(|a| {
2657 let mut a = a.borrow_mut();
2658 let off = a.len();
2659 a.extend_from_slice(v);
2660 off as u32
2661 })
2662}
2663
2664/// An all-zero residual, for the transform units that code no coefficient:
2665/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
2666/// and the reconstruction loops below read this instead of a per-unit
2667/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
2668/// (a 128-wide inter block's prediction stride).
2669pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
2670
2671/// lane-blockscratch: one plane's coefficient levels as the block-tail
2672/// neighbour writes want them. A plane that coded nothing (a skipped block, a
2673/// strip with no chroma, luma under a var-tx split whose units already wrote
2674/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
2675/// zeroing up to 64 KB of its own per block.
2676#[derive(Clone)]
2677enum Grid {
2678 Zero(usize),
2679 Own(Vec<i32>),
2680}
2681
2682/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
2683/// unit that writes into it. Only a block wider or taller than 64 px codes its
2684/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
2685/// collectors per block and then drop them untouched.
2686fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
2687 if v.is_empty() {
2688 *v = vec![0i32; n];
2689 }
2690 v
2691}
2692
2693impl std::ops::Deref for Grid {
2694 type Target = [i32];
2695 fn deref(&self) -> &[i32] {
2696 match self {
2697 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
2698 Grid::Own(v) => v,
2699 }
2700 }
2701}
2702
2703/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
2704/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
2705/// transform units that code no coefficient without the scan (lane-coefgrid).
2706pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
2707 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
2708}
2709
2710/// `residual`, or `n` zeros when it is the empty all-zero marker.
2711fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
2712 if residual.is_empty() { &ZERO_RESIDUAL[..n] } else { residual }
2713}
2714
2715/// Where a recorded motion-compensated write reads its prediction from.
2716///
2717/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
2718/// the parse thread's single biggest reconstruction cost, so at
2719/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
2720/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
2721/// runs it into its own three-plane slot, and every transform unit of that
2722/// block then reads its window out of that slot ([`Pred::Cur`]).
2723#[derive(Clone, Copy)]
2724pub(crate) enum Pred<'a> {
2725 /// A prediction the parse thread already built, at its own stride
2726 /// (`stride == 0` means "the reader's own `stride` argument").
2727 Inline(&'a [u16], usize),
2728 /// The current block's deferred prediction: plane, its stride, and this
2729 /// unit's offset into it.
2730 Cur { plane: usize, stride: usize, off: usize },
2731}
2732
2733impl<'a> Pred<'a> {
2734 /// The same prediction read at an explicit stride.
2735 fn view(self, stride: usize) -> Self {
2736 match self {
2737 Self::Inline(b, _) => Self::Inline(b, stride),
2738 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
2739 }
2740 }
2741 /// The materialised buffer and the stride to read it at (`stride` is the
2742 /// reader's own when this prediction was built dense); `None` for a
2743 /// deferred prediction, which only a recorded op can carry.
2744 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
2745 match self {
2746 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
2747 Self::Cur { .. } => None,
2748 }
2749 }
2750 /// This prediction's window starting `n` samples in.
2751 fn offset(self, n: usize) -> Self {
2752 match self {
2753 Self::Inline(b, s) => Self::Inline(&b[n..], s),
2754 Self::Cur { plane, stride, off } => Self::Cur { plane, stride, off: off + n },
2755 }
2756 }
2757}
2758
2759/// [`Pred`], resolved into what a recorded op carries.
2760pub(crate) enum PredSrc {
2761 /// A prediction window in the tile's prediction arena, `(offset, len)`.
2762 Owned(u32, u32),
2763 /// A window of the block prediction: its plane, its offset, and the
2764 /// stride it is read at -- which is the block's, not necessarily the
2765 /// op's (a transform unit's residual stays dense, so the worker takes
2766 /// its window out of the block prediction itself).
2767 Cur { plane: usize, off: usize, src: usize },
2768}
2769
2770/// One block's whole-block prediction build, deferred to a recon worker.
2771///
2772/// The closure borrows the tile's reference pictures and its own frame-level
2773/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
2774/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
2775/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
2776pub(crate) struct PredBuild(
2777 Box<
2778 dyn FnOnce(
2779 &mut PlaneBuf<'static>,
2780 &mut PlaneBuf<'static>,
2781 &mut PlaneBuf<'static>,
2782 &crate::decode::FrameCtx,
2783 // lane-blockmem: the previous block's three prediction buffers,
2784 // refilled in place -- the build used to return three fresh
2785 // `Vec`s per block and drop these.
2786 &mut [Vec<u16>; 3],
2787 ),
2788 >,
2789);
2790
2791// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
2792// pictures and frame tables, and the closure runs on exactly one worker.
2793#[allow(unsafe_code)]
2794unsafe impl Send for PredBuild {}
2795
2796/// `true` when this tile's writes are recorded for the wavefront instead of
2797/// performed at the push site, i.e. when a prediction may be deferred.
2798fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
2799 fctx.recon_planes.with(std::cell::Cell::get).is_none()
2800}
2801
2802/// The previous block's prediction buffer, cleared and zero-filled to `n`
2803/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
2804/// without the per-block allocation and free.
2805fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
2806 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
2807 // than resized element by element -- which is every block on the inline
2808 // path, where there is no previous buffer to reuse.
2809 if v.capacity() < n {
2810 return vec![0u16; n];
2811 }
2812 v.clear();
2813 v.resize(n, 0);
2814 v
2815}
2816
2817/// Records one block's prediction build for the worker that reconstructs it.
2818#[allow(unsafe_code)]
2819fn push_pred<'a>(
2820 fctx: &crate::decode::FrameCtx,
2821 f: impl FnOnce(
2822 &mut PlaneBuf<'static>,
2823 &mut PlaneBuf<'static>,
2824 &mut PlaneBuf<'static>,
2825 &crate::decode::FrameCtx,
2826 &mut [Vec<u16>; 3],
2827 ) + 'a,
2828) {
2829 type Dyn<'x> = dyn FnOnce(
2830 &mut PlaneBuf<'static>,
2831 &mut PlaneBuf<'static>,
2832 &mut PlaneBuf<'static>,
2833 &crate::decode::FrameCtx,
2834 &mut [Vec<u16>; 3],
2835 ) + 'x;
2836 let boxed: Box<Dyn<'a>> = Box::new(f);
2837 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
2838 // before the borrows the closure holds go out of scope.
2839 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
2840 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
2841}
2842
2843/// One superblock's recorded writes plus the two arenas they index -- the
2844/// unit a wavefront worker takes off the queue (lane-recoparse).
2845pub(crate) struct ReconJob {
2846 ops: Vec<ReconOp>,
2847 coeffs: Vec<i32>,
2848 preds: Vec<u16>,
2849}
2850
2851pub(crate) enum ReconOp {
2852 /// lane-wave4: build this block's prediction into the worker's slot.
2853 Pred(PredBuild),
2854 Intra {
2855 plane: usize,
2856 x: usize,
2857 y: usize,
2858 bw: usize,
2859 bh: usize,
2860 /// `true` when the parse site called `reconstruct_rect` (whose
2861 /// `edges_rect` differs from `edges` even at `bw == bh`).
2862 rect: bool,
2863 mode: usize,
2864 angle_delta: i32,
2865 reach: Reach,
2866 residual: Residual,
2867 cfl: Option<(i32, CflSrc)>,
2868 filter_intra: Option<usize>,
2869 smooth_neighbor: bool,
2870 /// The palette/intrabc prediction override, taken off
2871 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
2872 /// from that slot by the replay.
2873 pred: Option<Vec<u16>>,
2874 },
2875 Mc {
2876 plane: usize,
2877 x: usize,
2878 y: usize,
2879 stride: usize,
2880 w: usize,
2881 h: usize,
2882 prediction: PredSrc,
2883 residual: Residual,
2884 },
2885}
2886
2887/// The three planes of the tile currently being decoded, as raw pointers.
2888///
2889/// corner-cut: at one reconstruction thread a recorded write must cost
2890/// nothing -- deferring it to the end of the superblock is +1.2%
2891/// instructions and +4.5% wall on 4K, because the residual is written at
2892/// parse and read back cache-cold at replay. So the recorded op is performed
2893/// at the push site instead, through the pointers the tile decoder registers
2894/// once ([`ReconInline`]), which is the same thread, the same order and the
2895/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
2896/// stack still holds aliases them, exactly the [`crate::par::Shared`]
2897/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
2898/// threading the three planes down every `read_plane`/`read_inter_plane`
2899/// call site (~40) so the push site owns the borrow it writes through.
2900#[derive(Clone, Copy)]
2901pub(crate) struct ReconPlanes(
2902 *mut PlaneBuf<'static>,
2903 *mut PlaneBuf<'static>,
2904 *mut PlaneBuf<'static>,
2905);
2906
2907// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
2908// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
2909// value travelling is `None`; the pointers never leave the tile decoder's
2910// own thread.
2911#[allow(unsafe_code)]
2912unsafe impl Send for ReconPlanes {}
2913// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
2914// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
2915// contract, one superblock per band instead of one row band.
2916#[allow(unsafe_code)]
2917unsafe impl Sync for ReconPlanes {}
2918
2919/// Registers the tile's planes for inline reconstruction and unregisters them
2920/// on every exit from the tile decoder, including the `?` ones -- a stale
2921/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
2922/// tile.
2923pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
2924
2925#[allow(unsafe_code)]
2926impl<'a> ReconInline<'a> {
2927 /// Installs the guard for this tile when reconstruction is inline
2928 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
2929 /// to the queue instead, for the wavefront workers to replay.
2930 fn install(
2931 fctx: &'a crate::decode::FrameCtx,
2932 y: &mut PlaneBuf<'static>,
2933 u: &mut PlaneBuf<'static>,
2934 v: &mut PlaneBuf<'static>,
2935 ) -> Option<Self> {
2936 if crate::par::recon_threads() != 1 {
2937 return None;
2938 }
2939 // SAFETY: the planes are locals of the tile decoder and outlive the
2940 // guard, which is dropped on every exit from it (including `?`); see
2941 // [`ReconPlanes`] for the aliasing trade-off.
2942 let planes = ReconPlanes(
2943 std::ptr::from_mut(y),
2944 std::ptr::from_mut(u),
2945 std::ptr::from_mut(v),
2946 );
2947 fctx.recon_planes.with(|c| c.set(Some(planes)));
2948 Some(Self(fctx))
2949 }
2950}
2951
2952impl Drop for ReconInline<'_> {
2953 fn drop(&mut self) {
2954 self.0.recon_planes.with(|c| c.set(None));
2955 }
2956}
2957
2958#[allow(unsafe_code)]
2959fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
2960 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
2961 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
2962 // the parse site would have performed itself before lane-wave1.
2963 // The inline path never records coefficients (the transform runs at
2964 // the push site), so the arena is not read here.
2965 unsafe {
2966 exec_op(op, &mut *y, &mut *u, &mut *v, &mut Default::default(), &[], &[], fctx)
2967 };
2968 return;
2969 }
2970 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
2971}
2972
2973/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
2974/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
2975///
2976/// The parser keeps parsing and never touches the planes; each superblock's
2977/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
2978/// `(row, column)` inside the tile (128x128 superblocks are one job for all
2979/// four of their 64x64 visits, since a 128 block writes across quadrants).
2980/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
2981/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
2982/// every pixel an intra predictor can read (its edges reach one block right
2983/// along the row above and one block down the column to the left, both
2984/// inside those two neighbours) and every CfL AC read (this block's own
2985/// luma, written by this same job). Jobs are handed out in raster order, so
2986/// the oldest outstanding one always has its dependencies met: no deadlock.
2987///
2988/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
2989/// `thread_local!` and miss every worker, which is why the default is 1.
2990pub(crate) struct WaveState {
2991 q: std::sync::Mutex<WaveQueue>,
2992 cv: std::sync::Condvar,
2993 planes: ReconPlanes,
2994 /// The [`FrameCtx`] fields reconstruction reads (`sample_max` is
2995 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
2996 bit_depth: u8,
2997 enable_edge_filter: bool,
2998 /// lane-av1wavefront: the sequence's chroma subsampling. The replay-side
2999 /// readers -- the deferred chroma builds' `mv_to_q4(.., ss_x(fctx))`
3000 /// positions and `exec_intra`'s CfL AC signal -- must see the FRAME's
3001 /// pair, not [`FrameCtx::new`]'s 4:2:0 default: on a 4:4:4 stream the
3002 /// default halved every worker's chroma reference position and lost the
3003 /// chroma planes (the 444_sb128rect witness, U 17504 / V 3 at PREFILT on
3004 /// frame 1) while every 4:2:0 gate stream stayed accidentally exact.
3005 subsampling: (u8, u8),
3006 last_col: usize,
3007}
3008
3009struct WaveQueue {
3010 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
3011 /// row's front job can ever be runnable -- a job waits on its own left
3012 /// neighbour -- so a worker takes the lowest row whose front job's
3013 /// dependencies are met. Popping the raster-oldest job instead (what
3014 /// this replaced) put every worker on the SAME row, where the wavefront
3015 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
3016 rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
3017 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
3018 /// walking it.
3019 queued: usize,
3020 /// Per superblock row, the last column reconstructed (-1 = none yet).
3021 done: Vec<isize>,
3022 /// Per superblock row, the last column PARSED (submitted, whether or not
3023 /// it recorded any write) and the last column actually pushed as a job
3024 /// (-1 = none). A row is fully reconstructed once it has been parsed to
3025 /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
3026 /// reads that to release the row's filters (see [`wave_rows_complete`]).
3027 last_sub: Vec<isize>,
3028 last_push: Vec<isize>,
3029 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
3030 active: usize,
3031 closed: bool,
3032 /// lane-sballoc: the three per-superblock buffers a finished job hands
3033 /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no
3034 /// first-touch page faults) instead of the `Vec::with_capacity` it used
3035 /// to make per superblock -- 3 allocations and 3 frees per superblock,
3036 /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives
3037 /// inside the queue's own mutex, which both sides already take.
3038 free: Vec<JobBufs>,
3039 free_cap: usize,
3040}
3041
3042/// One recycled set of [`ReconJob`] buffers (lane-sballoc).
3043type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>);
3044
3045impl WaveQueue {
3046 /// The lowest-row queued job whose wavefront dependencies are satisfied,
3047 /// or `None` (with the blocking condition counted when instrumented).
3048 fn take_runnable(
3049 &mut self,
3050 last_col: usize,
3051 stats: bool,
3052 ) -> Option<(usize, usize, ReconJob)> {
3053 let mut blocked: Option<bool> = None;
3054 for r in 0..self.rows.len() {
3055 let Some(front) = self.rows[r].front() else {
3056 continue;
3057 };
3058 let c = front.0;
3059 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
3060 let left = c == 0 || self.done[r] >= c as isize - 1;
3061 if above && left {
3062 let (c, job) = self.rows[r].pop_front().expect("front checked above");
3063 self.queued -= 1;
3064 return Some((r, c, job));
3065 }
3066 if blocked.is_none() {
3067 blocked = Some(above);
3068 }
3069 }
3070 if stats {
3071 match blocked {
3072 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
3073 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
3074 None => 0,
3075 };
3076 }
3077 None
3078 }
3079}
3080
3081/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
3082/// worker's time goes (busy replaying, waiting for a dependency, idle on an
3083/// empty queue), how far ahead the parse thread is, and how often the two
3084/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
3085/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
3086/// whole run.
3087const WS_SLOTS: usize = 16;
3088use std::sync::atomic::AtomicU64;
3089use std::sync::atomic::Ordering::Relaxed;
3090static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3091static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3092static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3093static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
3094static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
3095static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
3096/// Parse-thread time between two submits, i.e. everything parse still does
3097/// itself (symbol decode plus the predictions not deferred).
3098static WS_PARSE: AtomicU64 = AtomicU64::new(0);
3099/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
3100/// (the intrabc/interintra reads) and at the tile's end.
3101static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
3102static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
3103static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
3104static WS_TILES: AtomicU64 = AtomicU64::new(0);
3105
3106fn wave_stats() -> bool {
3107 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
3108 match ON.load(Relaxed) {
3109 0 => {
3110 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
3111 .map(|v| v.trim() == "1")
3112 .unwrap_or(false);
3113 ON.store(1 + u8::from(on), Relaxed);
3114 on
3115 }
3116 n => n == 2,
3117 }
3118}
3119
3120fn wave_stats_dump() {
3121 let ms = |n: u64| n as f64 / 1e6;
3122 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
3123 for i in 0..WS_SLOTS {
3124 let jobs = WS_JOBS[i].load(Relaxed);
3125 if jobs == 0 {
3126 continue;
3127 }
3128 s += &format!(
3129 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
3130 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
3131 ms(WS_BUSY[i].load(Relaxed)),
3132 ms(WS_WAIT[i].load(Relaxed)),
3133 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
3134 );
3135 }
3136 s += &format!(
3137 " | pipe={}/{}",
3138 PIPE_FRAMES.load(Relaxed),
3139 PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
3140 );
3141 s += &format!(
3142 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
3143 ms(WS_PARSE.load(Relaxed)),
3144 ms(WS_BARRIER.load(Relaxed)),
3145 WS_BARRIERS.load(Relaxed),
3146 ms(WS_DRAIN.load(Relaxed)),
3147 WS_BLOCK_ABOVE.load(Relaxed),
3148 WS_BLOCK_LEFT.load(Relaxed),
3149 );
3150 eprintln!("{s}");
3151}
3152
3153#[allow(unsafe_code)]
3154fn wave_worker(st: &WaveState, idx: usize) {
3155 let fctx = FrameCtx::new();
3156 fctx.bit_depth.set(st.bit_depth);
3157 fctx.enable_edge_filter.set(st.enable_edge_filter);
3158 let (sx, sy) = st.subsampling;
3159 fctx.subsampling_x.set(sx);
3160 fctx.subsampling_y.set(sy);
3161 let stats = wave_stats();
3162 let slot = idx.min(WS_SLOTS - 1);
3163 loop {
3164 let t0 = std::time::Instant::now();
3165 let mut q = st.q.lock().unwrap();
3166 let (r, c, job) = loop {
3167 if let Some(job) = q.take_runnable(st.last_col, stats) {
3168 break job;
3169 }
3170 if q.closed && q.queued == 0 {
3171 return;
3172 }
3173 q = st.cv.wait(q).unwrap();
3174 };
3175 q.active += 1;
3176 drop(q);
3177 if stats {
3178 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3179 WS_JOBS[slot].fetch_add(1, Relaxed);
3180 WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
3181 }
3182 let t1 = std::time::Instant::now();
3183 let ReconPlanes(y, u, v) = st.planes;
3184 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
3185 // every superblock that could have written or be reading them is
3186 // complete by the wavefront rule above.
3187 let mut cur: [Vec<u16>; 3] = Default::default();
3188 let ReconJob { mut ops, mut coeffs, mut preds } = job;
3189 unsafe {
3190 for op in ops.drain(..) {
3191 exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx);
3192 }
3193 }
3194 if stats {
3195 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
3196 }
3197 coeffs.clear();
3198 preds.clear();
3199 let mut q = st.q.lock().unwrap();
3200 // lane-sballoc: hand the three buffers back for the next submit.
3201 if q.free.len() < q.free_cap {
3202 q.free.push((ops, coeffs, preds));
3203 }
3204 q.done[r] = c as isize;
3205 q.active -= 1;
3206 st.cv.notify_all();
3207 }
3208}
3209
3210/// Installs the wavefront for one tile and joins its workers on every exit
3211/// from the tile decoder, including the `?` ones -- the jobs hold raw
3212/// pointers into the tile's planes, so no worker may outlive them.
3213/// (lane-pool1: the workers come from this thread's persistent pool, so a
3214/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
3215/// with fresh scratch.)
3216pub(crate) struct WaveGuard<'a>(
3217 &'a crate::decode::FrameCtx,
3218 Option<crate::par::Batch<'static>>,
3219);
3220
3221#[allow(unsafe_code)]
3222impl<'a> WaveGuard<'a> {
3223 fn install(
3224 fctx: &'a crate::decode::FrameCtx,
3225 y: &mut PlaneBuf<'static>,
3226 u: &mut PlaneBuf<'static>,
3227 v: &mut PlaneBuf<'static>,
3228 rows: usize,
3229 cols: usize,
3230 ) -> Option<Self> {
3231 let threads = crate::par::recon_threads();
3232 if threads == 1 || rows == 0 || cols == 0 {
3233 return None;
3234 }
3235 let st = std::sync::Arc::new(WaveState {
3236 q: std::sync::Mutex::new(WaveQueue {
3237 rows: (0..rows).map(|_| std::collections::VecDeque::new()).collect(),
3238 queued: 0,
3239 done: vec![-1; rows],
3240 last_sub: vec![-1; rows],
3241 last_push: vec![-1; rows],
3242 active: 0,
3243 closed: false,
3244 free: Vec::new(),
3245 free_cap: threads + 2,
3246 }),
3247 cv: std::sync::Condvar::new(),
3248 // SAFETY: the planes are locals of the tile decoder and outlive
3249 // this guard, which joins every worker in `drop`.
3250 planes: ReconPlanes(
3251 std::ptr::from_mut(y),
3252 std::ptr::from_mut(u),
3253 std::ptr::from_mut(v),
3254 ),
3255 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
3256 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
3257 subsampling: (
3258 fctx.subsampling_x.with(std::cell::Cell::get),
3259 fctx.subsampling_y.with(std::cell::Cell::get),
3260 ),
3261 last_col: cols - 1,
3262 });
3263 let batch = crate::par::Batch::new("ec-av1-recon");
3264 for idx in 0..threads {
3265 let st = std::sync::Arc::clone(&st);
3266 batch.submit(move || wave_worker(&st, idx));
3267 }
3268 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
3269 fctx.wave_mark.with(|c| c.set(Some(std::time::Instant::now())));
3270 Some(Self(fctx, Some(batch)))
3271 }
3272}
3273
3274impl Drop for WaveGuard<'_> {
3275 fn drop(&mut self) {
3276 let st = self.0.wave.with(|w| w.borrow_mut().take());
3277 if let Some(st) = st {
3278 st.q.lock().unwrap().closed = true;
3279 st.cv.notify_all();
3280 }
3281 let t0 = std::time::Instant::now();
3282 // Dropping the batch waits every worker out, as the joins did.
3283 drop(self.1.take());
3284 if wave_stats() {
3285 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3286 WS_TILES.fetch_add(1, Relaxed);
3287 wave_stats_dump();
3288 }
3289 }
3290}
3291
3292/// An empty buffer for the next superblock: the recycled one when it is at
3293/// least as big as the superblock just parsed, else a fresh sized one
3294/// (lane-sballoc; `v` is always empty).
3295fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> {
3296 if v.capacity() < cap {
3297 v.reserve_exact(cap - v.len());
3298 }
3299 v
3300}
3301
3302/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
3303/// when there is no wavefront (one reconstruction thread), in which case the
3304/// caller replays them itself.
3305fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
3306 let st = fctx.wave.with(|w| w.borrow().clone());
3307 let Some(st) = st else { return false };
3308 // lane-blockmem: the op list is replaced sized for the next superblock,
3309 // exactly as the two arenas below are -- taking it left a zero-capacity
3310 // `Vec` that regrew (and memmoved every recorded op) from nothing on
3311 // every superblock.
3312 // lane-sballoc: the replacement comes from the finished jobs' free list
3313 // when there is one (warm capacity, already faulted in); only the first
3314 // superblocks of a tile allocate.
3315 let mut q = st.q.lock().unwrap();
3316 let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default();
3317 let ops = fctx.recon_ops.with(|c| {
3318 let mut c = c.borrow_mut();
3319 let cap = c.len();
3320 std::mem::replace(&mut *c, reuse(sops, cap))
3321 });
3322 // The job owns its coefficients: the arena is replaced by an empty one
3323 // sized for the next superblock, so parse never regrows from nothing and
3324 // the worker frees this buffer once, instead of once per unit.
3325 let coeffs = fctx.coeff_arena.with(|c| {
3326 let mut c = c.borrow_mut();
3327 let cap = c.len();
3328 std::mem::replace(&mut *c, reuse(scoeffs, cap))
3329 });
3330 let preds = fctx.pred_arena.with(|c| {
3331 let mut c = c.borrow_mut();
3332 let cap = c.len();
3333 std::mem::replace(&mut *c, reuse(spreds, cap))
3334 });
3335 {
3336 if (c as isize) > q.last_sub[r] {
3337 q.last_sub[r] = c as isize;
3338 }
3339 if !ops.is_empty() {
3340 q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
3341 q.queued += 1;
3342 q.last_push[r] = c as isize;
3343 }
3344 drop(q);
3345 st.cv.notify_all();
3346 }
3347 if wave_stats() {
3348 let now = std::time::Instant::now();
3349 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
3350 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
3351 }
3352 }
3353 true
3354}
3355
3356/// Waits until every submitted job is reconstructed, so the parser may read
3357/// the planes itself (the intrabc source fetch and the interintra intra
3358/// predictor -- see [`flush_recon`]).
3359fn wave_barrier(fctx: &crate::decode::FrameCtx) {
3360 let st = fctx.wave.with(|w| w.borrow().clone());
3361 let Some(st) = st else { return };
3362 let stats = wave_stats();
3363 let t0 = std::time::Instant::now();
3364 let mut q = st.q.lock().unwrap();
3365 while q.queued > 0 || q.active > 0 {
3366 q = st.cv.wait(q).unwrap();
3367 }
3368 drop(q);
3369 if stats {
3370 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3371 WS_BARRIERS.fetch_add(1, Relaxed);
3372 }
3373}
3374
3375/// Performs an intra write at its push site when the tile registered its
3376/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
3377/// caller must record it for the wavefront workers instead.
3378#[allow(unsafe_code)]
3379#[allow(clippy::too_many_arguments)]
3380fn inline_intra(
3381 plane: usize,
3382 x: usize,
3383 oy: usize,
3384 bw: usize,
3385 bh: usize,
3386 rect: bool,
3387 mode: usize,
3388 angle_delta: i32,
3389 reach: Reach,
3390 residual: &[i32],
3391 cfl: Option<(i32, CflSrc)>,
3392 filter_intra: Option<usize>,
3393 smooth_neighbor: bool,
3394 fctx: &crate::decode::FrameCtx,
3395) -> bool {
3396 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3397 return false;
3398 };
3399 let pred = take_palette_pred(fctx);
3400 // SAFETY: see [`ReconPlanes`].
3401 unsafe {
3402 exec_intra(
3403 &mut *y, &mut *u, &mut *v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3404 residual, cfl, filter_intra, smooth_neighbor, pred, fctx,
3405 );
3406 }
3407 true
3408}
3409
3410/// [`inline_intra`] for a motion-compensated write.
3411#[allow(unsafe_code)]
3412#[allow(clippy::too_many_arguments)]
3413fn inline_mc(
3414 plane: usize,
3415 x: usize,
3416 oy: usize,
3417 stride: usize,
3418 w: usize,
3419 h: usize,
3420 prediction: &[u16],
3421 residual: &[i32],
3422 fctx: &crate::decode::FrameCtx,
3423) -> bool {
3424 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3425 return false;
3426 };
3427 // SAFETY: see [`ReconPlanes`].
3428 unsafe {
3429 exec_mc(&mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx);
3430 }
3431 true
3432}
3433
3434/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
3435#[allow(clippy::too_many_arguments)]
3436fn push_intra(
3437 plane: usize,
3438 x: usize,
3439 y: usize,
3440 side: usize,
3441 mode: usize,
3442 angle_delta: i32,
3443 reach: Reach,
3444 residual: &[i32],
3445 cfl: Option<(i32, CflSrc)>,
3446 filter_intra: Option<usize>,
3447 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3448) {
3449 if inline_intra(
3450 plane, x, y, side, side, false, mode, angle_delta, reach, residual, cfl, filter_intra,
3451 smooth_neighbor, fctx,
3452 ) {
3453 return;
3454 }
3455 let pred = take_palette_pred(fctx);
3456 push_op(fctx, ReconOp::Intra {
3457 plane, x, y, bw: side, bh: side, rect: false, mode, angle_delta, reach,
3458 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3459 });
3460}
3461
3462/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
3463#[allow(clippy::too_many_arguments)]
3464fn push_intra_rect(
3465 plane: usize,
3466 x: usize,
3467 y: usize,
3468 bw: usize,
3469 bh: usize,
3470 mode: usize,
3471 angle_delta: i32,
3472 reach: Reach,
3473 residual: &[i32],
3474 cfl: Option<(i32, CflSrc)>,
3475 filter_intra: Option<usize>,
3476 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3477) {
3478 if inline_intra(
3479 plane, x, y, bw, bh, true, mode, angle_delta, reach, residual, cfl, filter_intra,
3480 smooth_neighbor, fctx,
3481 ) {
3482 return;
3483 }
3484 let pred = take_palette_pred(fctx);
3485 push_op(fctx, ReconOp::Intra {
3486 plane, x, y, bw, bh, rect: true, mode, angle_delta, reach,
3487 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3488 });
3489}
3490
3491/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
3492fn push_mc(
3493 plane: usize,
3494 x: usize,
3495 y: usize,
3496 side: usize,
3497 prediction: Pred<'_>,
3498 residual: &[i32], fctx: &crate::decode::FrameCtx,
3499) {
3500 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
3501}
3502
3503/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
3504#[allow(clippy::too_many_arguments)]
3505fn push_mc_rect(
3506 plane: usize,
3507 x: usize,
3508 y: usize,
3509 stride: usize,
3510 w: usize,
3511 h: usize,
3512 prediction: Pred<'_>,
3513 residual: &[i32], fctx: &crate::decode::FrameCtx,
3514) {
3515 let (src, stride) = match prediction.inline(stride) {
3516 Some(v) => v,
3517 None => {
3518 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3519 push_op(fctx, ReconOp::Mc {
3520 plane, x, y, stride: ss, w, h,
3521 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3522 residual: Residual::done(residual, fctx),
3523 });
3524 return;
3525 }
3526 };
3527 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
3528 return;
3529 }
3530 push_op(fctx, ReconOp::Mc {
3531 plane, x, y, stride, w, h,
3532 // The whole window `reconstruct_mc_rect` reads at `stride`, not
3533 // `w * h`: the record keeps exactly what `src.to_vec()` carried.
3534 prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
3535 residual: Residual::done(residual, fctx),
3536 });
3537}
3538
3539/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
3540/// thread the transform runs here, exactly as before; on the wavefront it
3541/// travels with the op and runs on the worker (lane-wave3).
3542#[allow(clippy::too_many_arguments)]
3543fn push_intra_tx(
3544 plane: usize,
3545 x: usize,
3546 y: usize,
3547 bw: usize,
3548 bh: usize,
3549 rect: bool,
3550 mode: usize,
3551 angle_delta: i32,
3552 reach: Reach,
3553 tx: TxParams,
3554 grid: &[i32],
3555 cfl: Option<(i32, CflSrc)>,
3556 filter_intra: Option<usize>,
3557 smooth_neighbor: bool,
3558 fctx: &crate::decode::FrameCtx,
3559) {
3560 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3561 inline_intra(
3562 plane, x, y, bw, bh, rect, mode, angle_delta, reach, &tx.run(grid), cfl, filter_intra,
3563 smooth_neighbor, fctx,
3564 );
3565 return;
3566 }
3567 let pred = take_palette_pred(fctx);
3568 push_op(fctx, ReconOp::Intra {
3569 plane, x, y, bw, bh, rect, mode, angle_delta, reach,
3570 residual: Residual::coeffs(tx, grid, fctx), cfl, filter_intra, smooth_neighbor, pred,
3571 });
3572}
3573
3574/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
3575#[allow(clippy::too_many_arguments)]
3576fn push_mc_rect_tx(
3577 plane: usize,
3578 x: usize,
3579 y: usize,
3580 stride: usize,
3581 w: usize,
3582 h: usize,
3583 prediction: Pred<'_>,
3584 tx: TxParams,
3585 grid: &[i32],
3586 fctx: &crate::decode::FrameCtx,
3587) {
3588 // lane-wave4: a deferred prediction is not there to be windowed -- the
3589 // op carries its offset into the block's prediction instead, and the
3590 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
3591 // both buffers at one stride).
3592 let (prediction, stride) = match prediction.inline(stride) {
3593 Some(v) => v,
3594 None => {
3595 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3596 let mut tx = tx;
3597 tx.stride = 0;
3598 push_op(fctx, ReconOp::Mc {
3599 plane, x, y, stride: w, w, h,
3600 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3601 residual: Residual::coeffs(tx, grid, fctx),
3602 });
3603 return;
3604 }
3605 };
3606 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3607 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
3608 // stride, so a prediction handed over at the block's stride (a var-tx
3609 // unit's window, lane-wave4) has to be densified for a dense residual
3610 // -- which is exactly what the recorded path below does.
3611 let residual = tx.run(grid);
3612 let res_stride = if tx.stride == 0 { w } else { tx.stride };
3613 let window;
3614 let prediction = if stride == res_stride {
3615 prediction
3616 } else {
3617 debug_assert_eq!(res_stride, w);
3618 let mut win = Vec::with_capacity(w * h);
3619 for row in 0..h {
3620 win.extend_from_slice(&prediction[row * stride..][..w]);
3621 }
3622 window = win;
3623 &window[..]
3624 };
3625 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
3626 return;
3627 }
3628 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
3629 // two buffers at `stride`, so the record carries that window densely
3630 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
3631 // copied 64*64 samples on the PARSING thread before. The residual is then
3632 // produced dense too (`TxParams::stride = 0`), which is the same numbers
3633 // in the same places at stride `w`.
3634 let off = fctx.pred_arena.with(|a| {
3635 let mut a = a.borrow_mut();
3636 let off = a.len();
3637 for row in 0..h {
3638 a.extend_from_slice(&prediction[row * stride..][..w]);
3639 }
3640 off as u32
3641 });
3642 let mut tx = tx;
3643 tx.stride = 0;
3644 push_op(fctx, ReconOp::Mc {
3645 plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(off, (w * h) as u32),
3646 residual: Residual::coeffs(tx, grid, fctx),
3647 });
3648}
3649
3650/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
3651/// and empties the queue (lane-wave1 step (i)).
3652///
3653/// Called at the top of each superblock visit and at the end of each tile, so
3654/// a whole superblock's parsing runs with no plane access at all; the two
3655/// parse-time pixel READS that survive -- the intrabc source fetch and the
3656/// interintra intra predictor -- flush ahead of themselves instead, which
3657/// keeps them byte-exact and names exactly what step (ii) still has to move.
3658fn flush_recon(
3659 fctx: &crate::decode::FrameCtx,
3660 y: &mut PlaneBuf<'static>,
3661 u: &mut PlaneBuf<'static>,
3662 v: &mut PlaneBuf<'static>,
3663) {
3664 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
3665 // writes in place, not just this superblock's queue.
3666 wave_barrier(fctx);
3667 let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3668 fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
3669 let mut coeffs = fctx.coeff_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3670 fctx.coeff_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
3671 let mut preds = fctx.pred_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3672 fctx.pred_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
3673 let mut cur: [Vec<u16>; 3] = Default::default();
3674 for op in ops.drain(..) {
3675 exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
3676 }
3677 coeffs.clear();
3678 preds.clear();
3679 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
3680 fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
3681 fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
3682}
3683
3684/// Performs one recorded write: the body [`flush_recon`] replays, and the
3685/// body [`push_op`] runs immediately when reconstruction is inline.
3686fn exec_op(
3687 op: ReconOp,
3688 y: &mut PlaneBuf<'static>,
3689 u: &mut PlaneBuf<'static>,
3690 v: &mut PlaneBuf<'static>,
3691 cur: &mut [Vec<u16>; 3],
3692 coeffs: &[i32],
3693 preds: &[u16],
3694 fctx: &crate::decode::FrameCtx,
3695) {
3696 // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel
3697 // write, leaving the entropy parse and the per-mi neighbour bookkeeping
3698 // alone. It makes the encoder's own streams garbage, so it is a
3699 // MEASUREMENT rung only -- what it measures is how much of the encoder's
3700 // first decode of its own tiles (`par::S_FIRST`) is reconstruction and
3701 // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile
3702 // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that
3703 // stage and the parse plus the neighbour grids are the other 94%. That
3704 // is why handing the decoder the encoder's own reconstruction cannot
3705 // shrink the stage: only publishing the per-mi neighbour state the
3706 // filters read (and so never parsing at all) can.
3707 if crate::envflags::env_flag!("EC_AV1_NORECON") {
3708 return;
3709 }
3710 let mut scratch = Vec::new();
3711 match op {
3712 ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur),
3713 ReconOp::Intra {
3714 plane, x, y: oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl,
3715 filter_intra, smooth_neighbor, pred,
3716 } => exec_intra(
3717 y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3718 residual.resolve(coeffs, &mut scratch),
3719 cfl, filter_intra, smooth_neighbor, pred, fctx,
3720 ),
3721 ReconOp::Mc { plane, x, y: oy, stride, w, h, prediction, residual } => {
3722 let residual = residual.resolve(coeffs, &mut scratch);
3723 match prediction {
3724 PredSrc::Owned(off, len) => {
3725 let p = &preds[off as usize..][..len as usize];
3726 exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
3727 }
3728 PredSrc::Cur { plane: sp, off, src } => {
3729 let block = std::mem::take(&mut cur[sp]);
3730 if src == stride {
3731 exec_mc(y, u, v, plane, x, oy, stride, w, h, &block[off..], residual, fctx);
3732 } else {
3733 // A transform unit's residual is dense, so its window
3734 // of the block prediction is taken out dense too --
3735 // the copy the parsing thread used to make, made here.
3736 let mut window = Vec::with_capacity(w * h);
3737 for row in 0..h {
3738 window.extend_from_slice(&block[off + row * src..][..w]);
3739 }
3740 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
3741 }
3742 cur[sp] = block;
3743 }
3744 }
3745 }
3746 }
3747}
3748
3749/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
3750/// path ([`push_op`]'s registered planes) reaches it without ever building
3751/// the record -- which is what keeps one reconstruction thread at the cost of
3752/// the pre-lane-wave1 decoder.
3753#[allow(clippy::too_many_arguments)]
3754fn exec_intra(
3755 y: &mut PlaneBuf<'static>,
3756 u: &mut PlaneBuf<'static>,
3757 v: &mut PlaneBuf<'static>,
3758 plane: usize,
3759 x: usize,
3760 oy: usize,
3761 bw: usize,
3762 bh: usize,
3763 rect: bool,
3764 mode: usize,
3765 angle_delta: i32,
3766 reach: Reach,
3767 residual: &[i32],
3768 cfl: Option<(i32, CflSrc)>,
3769 filter_intra: Option<usize>,
3770 smooth_neighbor: bool,
3771 pred: Option<Vec<u16>>,
3772 fctx: &crate::decode::FrameCtx,
3773) {
3774 // The CfL AC signal is read HERE, off the luma that has already been
3775 // written for this block -- at parse time it would have been the previous
3776 // frame's samples.
3777 let ac = cfl.map(|(alpha, src)| {
3778 let sig = cfl_ac_ss(&*y, src.px, src.py, src.bw, src.bh, ss_x(fctx), ss_y(fctx));
3779 (alpha, sig)
3780 });
3781 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
3782 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3783 if rect {
3784 target.reconstruct_rect(
3785 x, oy, bw, bh, mode, angle_delta, reach, residual, cfl, filter_intra,
3786 smooth_neighbor, pred, fctx,
3787 );
3788 } else {
3789 target.reconstruct(
3790 x, oy, bw, mode, angle_delta, reach, residual, cfl, filter_intra,
3791 smooth_neighbor, pred, fctx,
3792 );
3793 }
3794}
3795
3796/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
3797#[allow(clippy::too_many_arguments)]
3798fn exec_mc(
3799 y: &mut PlaneBuf<'static>,
3800 u: &mut PlaneBuf<'static>,
3801 v: &mut PlaneBuf<'static>,
3802 plane: usize,
3803 x: usize,
3804 oy: usize,
3805 stride: usize,
3806 w: usize,
3807 h: usize,
3808 prediction: &[u16],
3809 residual: &[i32],
3810 fctx: &crate::decode::FrameCtx,
3811) {
3812 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3813 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
3814}
3815
3816thread_local! {
3817 /// The current frame's `mi` grid, kept only while a frame header set
3818 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
3819 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
3820 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
3821 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
3822 /// does not allow intrabc (so nothing is paid for it).
3823 ///
3824 /// corner-cut: only [`decode_block`] (the square path) records into it,
3825 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
3826 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
3827 /// be wrong there; upgrade = record from the rect/leaf paths too.
3828 /// The block vector [`read_intra_mode`] just decoded, handed to
3829 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
3830 /// which the alternative -- a tenth tuple member through every caller --
3831 /// already avoids). Always `.take()`n by the block that reads it.
3832 /// How many blocks read `use_intrabc == 1` and took the DV path -- the
3833 /// gate's hit counter. Bumped on the READ, before the rect-strip refusal
3834 /// returns too, so it counts reads, not reconstructions (a refused block
3835 /// is never reconstructed).
3836 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3837}
3838 // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
3839 // an intrabc block's chroma reads can inherit it (see
3840 // [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
3841 // through that one arming site.
3842 // libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
3843 // branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
3844 // satisfies (`blockd.h:373`) -- and takes the *colocated luma
3845 // transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
3846 // `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
3847 // intrabc block's two chroma [`read_plane`] calls; the type decides the
3848 // `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
3849 // -- getting it wrong desyncs the chroma coefficients, it is not a
3850 // reconstruction-only detail.
3851
3852/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
3853/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
3854/// needs no separate plumbing to reach the rect-strip mode reader.
3855fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
3856 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
3857}
3858
3859thread_local! {
3860 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
3861 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
3862 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
3863 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3864}
3865
3866/// Current value of [`RECT_INTRABC_READS`].
3867pub(crate) fn rect_intrabc_reads() -> usize {
3868 RECT_INTRABC_READS.with(|c| c.get())
3869}
3870
3871/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
3872#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3873pub(crate) fn reset_rect_intrabc_reads() {
3874 RECT_INTRABC_READS.with(|c| c.set(0));
3875}
3876
3877thread_local! {
3878 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
3879 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
3880 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3881}
3882
3883thread_local! {
3884 /// Chroma reads of an intrabc TX4-split leaf that consulted an ARMED
3885 /// [`INTRABC_CHROMA_TX`] slot -- proof that the arm's frame-copy +
3886 /// inherited-type route actually ran (lane-av1intrapred r2's non-vacuity
3887 /// counter: zero means the gate's fixture no longer reaches the route).
3888 static INTRABC_TX4_CHROMA_COPY_HITS: std::cell::Cell<usize> =
3889 const { std::cell::Cell::new(0) };
3890}
3891
3892/// Current value of [`INTRABC_TX4_CHROMA_COPY_HITS`].
3893#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3894pub(crate) fn intrabc_tx4_chroma_copy_hits() -> usize {
3895 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.get())
3896}
3897
3898/// Zeroes [`INTRABC_TX4_CHROMA_COPY_HITS`] (gate tests call this before a decode).
3899#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3900pub(crate) fn reset_intrabc_tx4_chroma_copy_hits() {
3901 INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.set(0));
3902}
3903
3904/// Current value of [`LEAF8_INTRABC_HITS`].
3905pub(crate) fn leaf8_intrabc_hits() -> usize {
3906 LEAF8_INTRABC_HITS.with(|c| c.get())
3907}
3908
3909/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
3910#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3911pub(crate) fn reset_leaf8_intrabc_hits() {
3912 LEAF8_INTRABC_HITS.with(|c| c.set(0));
3913}
3914
3915/// Current value of [`INTRABC_HITS`].
3916#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3917pub(crate) fn intrabc_hits() -> usize {
3918 INTRABC_HITS.with(|c| c.get())
3919}
3920
3921thread_local! {
3922 /// An intrabc block that IS a sub-8x8 group's CHROMA REFERENCE and is
3923 /// SKIPPED: the route that arms [`INTRABC_CHROMA_TX`] and then reads no
3924 /// chroma coefficient at all, so the slot used to stay armed into the NEXT
3925 /// block's chroma read. Both group shapes (4x4 split, 4x8/8x4 rect) count
3926 /// here. A non-zero value is what makes the disarm below load-bearing.
3927 static SKIPPED_INTRABC_CHROMA_ARM_HITS: std::cell::Cell<usize> =
3928 const { std::cell::Cell::new(0) };
3929}
3930
3931/// Current value of [`SKIPPED_INTRABC_CHROMA_ARM_HITS`].
3932#[allow(dead_code)] // read only from the `#[cfg(test)]` gates and the probe
3933pub(crate) fn skipped_intrabc_chroma_arm_hits() -> usize {
3934 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.get())
3935}
3936
3937/// Zeroes [`SKIPPED_INTRABC_CHROMA_ARM_HITS`] (gate tests call this before a
3938/// decode).
3939#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3940pub(crate) fn reset_skipped_intrabc_chroma_arm_hits() {
3941 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.set(0));
3942}
3943
3944/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
3945#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3946pub(crate) fn reset_intrabc_hits() {
3947 INTRABC_HITS.with(|c| c.set(0));
3948}
3949
3950thread_local! {
3951 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
3952 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
3953 /// that replaced the refusal "an intrabc block under TxMode::Select".
3954 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3955 /// lane-av1-ibcvtx: intrabc var-tx trees that resolved to MIXED leaf
3956 /// sizes (not one square size across every leaf) -- the engagement
3957 /// counter proving a witness actually exercises the per-leaf reconstruct.
3958 static INTRABC_VARTX_MIXED_LEAVES_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3959 /// lane-av1txr: as above for a `BLOCK_4X8`/`BLOCK_8X4` intrabc leaf --
3960 /// libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`, so these leaves
3961 /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no
3962 /// symbol here desynced `warped.obu` at the very next block.
3963 static RECT_INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3964 /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction
3965 /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip
3966 /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never
3967 /// this one).
3968 static INTRABC_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3969 /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT).
3970 static INTRABC_RECT_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3971 /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction
3972 /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read),
3973 /// split by the strip's orientation -- `bw > bh` is a HORZ strip,
3974 /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED
3975 /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS`
3976 /// counts neither orientation nor the skip flag, so an arm that flipped
3977 /// to an all-skip stream (no residual reader at all) would stay green.
3978 static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> =
3979 const { std::cell::Cell::new([0, 0]) };
3980 /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`]
3981 /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split
3982 /// by orientation. The r5 panic (residual stride `bw * bh` underrunning
3983 /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was
3984 /// invisible to every gate because they only counted CODED strips.
3985 static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> =
3986 const { std::cell::Cell::new([0, 0]) };
3987}
3988
3989/// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed,
3990/// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`].
3991#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3992pub fn intrabc_rect_coded_hits() -> [usize; 2] {
3993 INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get)
3994}
3995
3996/// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks
3997/// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`].
3998#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3999pub fn intrabc_rect_skipped_hits() -> [usize; 2] {
4000 INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get)
4001}
4002
4003/// Current value of [`INTRABC_RECT_HITS`].
4004#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4005pub fn intrabc_rect_hits() -> usize {
4006 INTRABC_RECT_HITS.with(|c| c.get())
4007}
4008
4009/// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`].
4010#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4011pub(crate) fn reset_intrabc_rect_hits() {
4012 INTRABC_RECT_HITS.with(|c| c.set(0));
4013 INTRABC_RECT_VARTX_HITS.with(|c| c.set(0));
4014 INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0]));
4015 INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0]));
4016}
4017
4018/// Current value of [`INTRABC_RECT_VARTX_HITS`].
4019#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4020pub fn intrabc_rect_vartx_hits() -> usize {
4021 INTRABC_RECT_VARTX_HITS.with(|c| c.get())
4022}
4023
4024thread_local! {
4025 /// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip
4026 /// (BLOCK_128X64 / BLOCK_64X128) whose reconstruction
4027 /// [`decode_intrabc_128rect`] ran -- the shape the named refusal used to
4028 /// guard (`decode_block_128rect`). A refused block bumps
4029 /// [`INTRABC_HITS`] but never this one.
4030 static INTRABC_128RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4031}
4032
4033/// Current value of [`INTRABC_128RECT_HITS`].
4034#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4035pub fn intrabc_128rect_hits() -> usize {
4036 INTRABC_128RECT_HITS.with(|c| c.get())
4037}
4038
4039/// Zeroes [`INTRABC_128RECT_HITS`].
4040#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4041pub(crate) fn reset_intrabc_128rect_hits() {
4042 INTRABC_128RECT_HITS.with(|c| c.set(0));
4043}
4044
4045/// Current value of [`INTRABC_VARTX_HITS`].
4046pub fn intrabc_vartx_hits() -> usize {
4047 INTRABC_VARTX_HITS.with(|c| c.get())
4048}
4049
4050/// Current value of [`INTRABC_VARTX_MIXED_LEAVES_HITS`].
4051pub fn intrabc_vartx_mixed_leaves_hits() -> usize {
4052 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.get())
4053}
4054
4055/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
4056#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4057pub(crate) fn reset_intrabc_vartx_hits() {
4058 INTRABC_VARTX_HITS.with(|c| c.set(0));
4059}
4060
4061/// Zeroes [`INTRABC_VARTX_MIXED_LEAVES_HITS`] (gate tests call this before a
4062/// decode).
4063#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4064pub(crate) fn reset_intrabc_vartx_mixed_leaves_hits() {
4065 INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.set(0));
4066}
4067
4068/// Current value of [`RECT_INTRABC_VARTX_HITS`].
4069#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4070pub fn rect_intrabc_vartx_hits() -> usize {
4071 RECT_INTRABC_VARTX_HITS.with(|c| c.get())
4072}
4073
4074/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
4075/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
4076/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
4077/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
4078fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>, n: &mut Neighbours, fctx: &crate::decode::FrameCtx) {
4079 record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx);
4080}
4081
4082/// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs`
4083/// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4`
4084/// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr).
4085///
4086/// Also stamps libaom's `is_inter_block` verdict for this block into the
4087/// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override
4088/// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] >
4089/// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and
4090/// `get_tx_size_context` reads its BLOCK size rather than its transform band.
4091/// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which
4092/// every block runs; this runs after it (class leaked-band otherwise).
4093fn record_intrabc_mi_rect(
4094 mi_r: usize,
4095 mi_c: usize,
4096 n4_w: usize,
4097 n4_h: usize,
4098 dv: Option<(i32, i32)>,
4099 n: &mut Neighbours,
4100 fctx: &crate::decode::FrameCtx,
4101) {
4102 if dv.is_some() {
4103 for i in 0..n4_w {
4104 if let Some(cell) = n.above_inter.get_mut(mi_c + i) {
4105 *cell = true;
4106 }
4107 }
4108 for i in 0..n4_h {
4109 if let Some(cell) = n.left_inter.get_mut(mi_r + i) {
4110 *cell = true;
4111 }
4112 }
4113 }
4114 fctx.intrabc_mi_grid.with(|g| {
4115 let mut g = g.borrow_mut();
4116 let Some((grid, _, _)) = g.as_mut() else {
4117 return;
4118 };
4119 let info = crate::mvstack::MiInfo {
4120 is_inter: dv.is_some(),
4121 ref_frame: 0,
4122 ref_frame1: NO_REF1,
4123 mv: mv16(dv.unwrap_or((0, 0))),
4124 mv1: (0, 0),
4125 is_new_mv: dv.is_some(),
4126 is_global_mv0: false,
4127 is_global_mv1: false,
4128 size: n4_w as u8,
4129 size_h: n4_h as u8,
4130 };
4131 for r in mi_r..mi_r + n4_h {
4132 for c in mi_c..mi_c + n4_w {
4133 grid.set(r, c, info);
4134 }
4135 }
4136 });
4137}
4138
4139// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
4140// proves a real `skip_mode_present` stream actually reached a block that
4141// picked it, not just that the frame header bit was set.
4142thread_local! {
4143 static SKIP_MODE_HITS: std::cell::Cell<usize> =
4144 const { std::cell::Cell::new(0) };
4145}
4146
4147/// Current value of [`SKIP_MODE_HITS`].
4148#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4149pub(crate) fn skip_mode_hits() -> usize {
4150 SKIP_MODE_HITS.with(|c| c.get())
4151}
4152
4153// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
4154// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
4155// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
4156// reached [`obmc_blend`], not just the header bit.
4157thread_local! {
4158 static OBMC_HITS: std::cell::Cell<usize> =
4159 const { std::cell::Cell::new(0) };
4160}
4161
4162// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
4163// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
4164// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
4165// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
4166// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
4167// decoder used to read with the wrong alphabet, so a gate that asserts this
4168// counter advanced proves the fixed path fired (class
4169// `gate-blind-to-feature`).
4170thread_local! {
4171 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4172}
4173
4174/// Current value of [`FIMV_ALPHABET_HITS`].
4175pub fn fimv_alphabet_hits() -> usize {
4176 FIMV_ALPHABET_HITS.with(|c| c.get())
4177}
4178
4179// lane-fimv r1: how many frame headers this decoder has decoded with
4180// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
4181// prove the encoder really produced the header state under test rather than
4182// assume it.
4183thread_local! {
4184 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4185}
4186
4187/// Current value of [`FIMV_FRAME_HITS`].
4188pub fn fimv_frame_hits() -> usize {
4189 FIMV_FRAME_HITS.with(|c| c.get())
4190}
4191
4192/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
4193/// `force_integer_mv` bit is set.
4194pub fn note_force_integer_mv_frame() {
4195 hit!(FIMV_FRAME_HITS);
4196}
4197
4198/// Current value of [`OBMC_HITS`].
4199#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4200pub(crate) fn obmc_hits() -> usize {
4201 OBMC_HITS.with(|c| c.get())
4202}
4203
4204// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
4205// off the neighbour band -- the positive half of the proof for "an OBMC
4206// neighbour whose switchable interp filter was never recorded". A
4207// fixed-filter frame returns before this point (its neighbours legitimately
4208// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
4209// `interp_filter` symbols were published by `record_inter_rect_mi`.
4210thread_local! {
4211 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4212}
4213
4214/// Current value of [`OBMC_FILTER_BAND_READS`].
4215#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4216pub(crate) fn obmc_filter_band_reads() -> usize {
4217 OBMC_FILTER_BAND_READS.with(|c| c.get())
4218}
4219
4220// lane-scaledref r1: per-case firing counts for the scaled-reference gate
4221// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
4222// reference would pass just as well and prove nothing, so the gate
4223// hard-asserts each combination this round lifts actually occurred:
4224// a compound block with a scaled tap, a warp block whose warp libaom
4225// suppresses because the reference is scaled, an OBMC block, an interintra
4226// block, and an 8x8 leaf.
4227thread_local! {
4228 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4229 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4230 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4231 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4232 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4233 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4234 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4235}
4236
4237/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
4238/// scaled and one unscaled tap.
4239#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4240pub(crate) fn mixed_scale_compound_hits() -> usize {
4241 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
4242}
4243
4244/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
4245/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
4246/// instead because their reference is scaled (libaom `motion_mode_allowed`,
4247/// `blockd.h:1484`).
4248#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4249pub(crate) fn scaled_warp_suppressed_hits() -> usize {
4250 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
4251}
4252
4253/// Current value of [`SCALED_COMPOUND_HITS`].
4254#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4255pub(crate) fn scaled_compound_hits() -> usize {
4256 SCALED_COMPOUND_HITS.with(|c| c.get())
4257}
4258
4259/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
4260pub fn scaled_warp_fallback_hits() -> usize {
4261 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
4262}
4263
4264/// Current value of [`SCALED_OBMC_HITS`].
4265#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4266pub(crate) fn scaled_obmc_hits() -> usize {
4267 SCALED_OBMC_HITS.with(|c| c.get())
4268}
4269
4270/// Current value of [`SCALED_INTERINTRA_HITS`].
4271#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4272pub(crate) fn scaled_interintra_hits() -> usize {
4273 SCALED_INTERINTRA_HITS.with(|c| c.get())
4274}
4275
4276/// Current value of [`SCALED_BLOCK8_HITS`].
4277#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4278pub(crate) fn scaled_block8_hits() -> usize {
4279 SCALED_BLOCK8_HITS.with(|c| c.get())
4280}
4281
4282// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
4283// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
4284// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
4285// 8x8-leaf OBMC block apart from a 16x16+ one.
4286thread_local! {
4287 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4288}
4289
4290// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
4291// pair whose two directions differ (`enable_dual_filter` only -- with dual
4292// filter off both directions take the single symbol, so this can never fire).
4293// A gate asserting it proves the stream really carries dual-filter blocks.
4294thread_local! {
4295 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4296}
4297
4298// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
4299// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
4300// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
4301// no-filter sentinel that made a neighbouring OBMC block panic).
4302thread_local! {
4303 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4304}
4305
4306/// Current value of [`DUAL_FILTER_DIFF_HITS`].
4307#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4308pub(crate) fn dual_filter_diff_hits() -> usize {
4309 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
4310}
4311
4312/// Current value of [`COMPOUND8_FILTER_HITS`].
4313#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4314pub(crate) fn compound8_filter_hits() -> usize {
4315 COMPOUND8_FILTER_HITS.with(|c| c.get())
4316}
4317
4318// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
4319// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
4320// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
4321// -- the gate's proof that a fixture really exercises the alphabet this
4322// round changed, even though the block itself still refuses (warp
4323// estimation/filter not ported).
4324thread_local! {
4325 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
4326 const { std::cell::Cell::new(0) };
4327}
4328
4329/// Current value of [`WARP_SELECTED_HITS`].
4330#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4331pub(crate) fn warp_selected_hits() -> usize {
4332 WARP_SELECTED_HITS.with(|c| c.get())
4333}
4334
4335// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
4336// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
4337// into the compound intermediate) rather than translationally -- the
4338// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
4339// really reached [`crate::warp::warp_affine_compound`].
4340thread_local! {
4341 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
4342 const { std::cell::Cell::new(0) };
4343}
4344
4345/// Current value of [`COMPOUND_WARP_HITS`].
4346#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4347pub(crate) fn compound_warp_hits() -> usize {
4348 COMPOUND_WARP_HITS.with(|c| c.get())
4349}
4350
4351// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
4352// arm ([`decode_inter_block8`]) -- that arm predicted both taps
4353// translationally until r3, so a gate needs to tell a warped 8x8 compound
4354// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
4355thread_local! {
4356 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
4357 const { std::cell::Cell::new(0) };
4358}
4359
4360/// Current value of [`COMPOUND_WARP_HITS_8`].
4361#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4362pub(crate) fn compound_warp_hits_8() -> usize {
4363 COMPOUND_WARP_HITS_8.with(|c| c.get())
4364}
4365
4366// lane-gmaffine r1: how many blocks built their prediction from a
4367// SIX-parameter (`AFFINE`) global-motion model through
4368// `crate::warp::global_warp_params` -- the gate's proof that a stream really
4369// carried an AFFINE `global_motion_params` AND that a block was predicted
4370// with it, not merely that the header parsed one.
4371thread_local! {
4372 static AFFINE_GM_HITS: std::cell::Cell<usize> =
4373 const { std::cell::Cell::new(0) };
4374}
4375
4376/// Current value of [`AFFINE_GM_HITS`].
4377#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4378pub(crate) fn affine_gm_hits() -> usize {
4379 AFFINE_GM_HITS.with(|c| c.get())
4380}
4381
4382// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
4383// differently at the block's WIDTH than at libaom's
4384// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
4385// pick the wrong motion_mode alphabet.
4386thread_local! {
4387 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4388}
4389
4390/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
4391pub fn tr_reach_longer_side_hits() -> usize {
4392 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
4393}
4394
4395// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
4396// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
4397// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
4398// reads its interp-filter symbol. Counts the blocks where that guard flips
4399// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
4400// and a 4-px side, which we used to suppress the interp read on (a pre-mode
4401// entropy desync one symbol wide).
4402thread_local! {
4403 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4404}
4405
4406/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
4407pub fn gm_nontrans_small_side_hits() -> usize {
4408 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
4409}
4410
4411// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
4412// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
4413// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
4414// only once `find_projection` returned a usable model, unlike
4415// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
4416// proof that the leaf path itself fired, not the 16x16+ one.
4417thread_local! {
4418 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4419 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4420}
4421
4422/// Current value of [`GLOBALMV_HITS_8`].
4423#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4424pub(crate) fn globalmv_hits_8() -> usize {
4425 GLOBALMV_HITS_8.with(|c| c.get())
4426}
4427
4428/// Current value of [`WARP_HITS_8`].
4429#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4430pub(crate) fn warp_hits_8() -> usize {
4431 WARP_HITS_8.with(|c| c.get())
4432}
4433
4434// How many blocks decoded `interintra == 1` with the non-wedge blended
4435// prediction applied (lane-interintra r1) -- the gate's proof that a
4436// stream actually exercised interintra.
4437thread_local! {
4438 static INTERINTRA_HITS: std::cell::Cell<usize> =
4439 const { std::cell::Cell::new(0) };
4440}
4441
4442/// Current value of [`INTERINTRA_HITS`].
4443#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4444pub(crate) fn interintra_hits() -> usize {
4445 INTERINTRA_HITS.with(|c| c.get())
4446}
4447
4448// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
4449// -- the shape `interintra_blend` used to build a square `side x side` intra
4450// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
4451// pre-existing interintra gate passed with that bug, so the rect arm needs
4452// its own counter to stop being vacuous.
4453thread_local! {
4454 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4455}
4456
4457/// Current value of [`INTERINTRA_RECT_HITS`].
4458pub fn interintra_rect_hits() -> usize {
4459 INTERINTRA_RECT_HITS.with(|c| c.get())
4460}
4461
4462// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
4463// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
4464// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
4465// gate fixture actually exercises this alphabet, even though the block
4466// still refuses (the mask blend itself is unported).
4467thread_local! {
4468 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
4469 const { std::cell::Cell::new(0) };
4470}
4471
4472/// Current value of [`MASKED_COMPOUND_HITS`].
4473#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4474pub(crate) fn masked_compound_hits() -> usize {
4475 MASKED_COMPOUND_HITS.with(|c| c.get())
4476}
4477
4478// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
4479// masked-compound block whose true footprint is rectangular, i.e. the case
4480// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
4481// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
4482// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
4483thread_local! {
4484 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
4485 const { std::cell::Cell::new(0) };
4486}
4487
4488/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
4489#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4490pub(crate) fn rect_masked_compound_hits() -> usize {
4491 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
4492}
4493
4494// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
4495// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
4496// actually exercised the wedge blend, not just the DIFFWTD half of
4497// `MASKED_COMPOUND_HITS`.
4498thread_local! {
4499 static WEDGE_HITS: std::cell::Cell<usize> =
4500 const { std::cell::Cell::new(0) };
4501}
4502
4503/// Current value of [`WEDGE_HITS`].
4504#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4505pub(crate) fn wedge_hits() -> usize {
4506 WEDGE_HITS.with(|c| c.get())
4507}
4508
4509// How many blocks decoded a real wedge-INTERINTRA block
4510// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
4511// a gate fixture exercised the wedge blend (fixed sign 0), not just the
4512// smooth arm counted by `INTERINTRA_HITS`.
4513thread_local! {
4514 static WII_HITS: std::cell::Cell<usize> =
4515 const { std::cell::Cell::new(0) };
4516}
4517
4518/// Current value of [`WII_HITS`].
4519#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4520pub(crate) fn wii_hits() -> usize {
4521 WII_HITS.with(|c| c.get())
4522}
4523
4524// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
4525// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
4526// wide <= 32 && high <= 32). The witness that a gate stream really carries a
4527// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
4528// frame carrying one.
4529thread_local! {
4530 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4531}
4532
4533/// Current value of [`NOCFL_UV_MODE_HITS`].
4534#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4535pub(crate) fn nocfl_uv_mode_hits() -> usize {
4536 NOCFL_UV_MODE_HITS.with(|c| c.get())
4537}
4538
4539/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
4540/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
4541pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
4542 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
4543
4544fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
4545 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
4546}
4547
4548// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
4549// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
4550// the rect wedge masks lifted this round actually fired, not just the square
4551// ones already counted by `WEDGE_HITS`/`WII_HITS`.
4552thread_local! {
4553 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
4554 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
4555}
4556
4557/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
4558pub(crate) fn rect_wedge_hits() -> [usize; 6] {
4559 RECT_WEDGE_HITS.with(|c| c.get())
4560}
4561
4562/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
4563pub(crate) fn rect_wii_hits() -> [usize; 6] {
4564 RECT_WII_HITS.with(|c| c.get())
4565}
4566
4567// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
4568// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
4569// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
4570// aomdec, neighbour list included).
4571thread_local! {
4572 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4573}
4574
4575/// Current value of [`OBMC_RECT_LEAF_HITS`].
4576pub(crate) fn obmc_rect_leaf_hits() -> usize {
4577 OBMC_RECT_LEAF_HITS.with(|c| c.get())
4578}
4579
4580// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
4581// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
4582// to be read from the pair's FIRST mi, which is a different block and, when
4583// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
4584// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
4585thread_local! {
4586 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4587}
4588
4589/// Current value of [`OBMC_PAIR_FILTER_HITS`].
4590pub(crate) fn obmc_pair_filter_hits() -> usize {
4591 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
4592}
4593
4594// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
4595// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
4596// own side, so a block overhanging the bottom/right still predicts the full
4597// neighbour strip (the destination write is what clips). We used to shrink the
4598// prediction to the visible part, which at 4 chroma rows/cols also swaps the
4599// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
4600thread_local! {
4601 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4602}
4603
4604/// Current value of [`OBMC_EDGE_SPAN_HITS`].
4605#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4606pub(crate) fn obmc_edge_span_hits() -> usize {
4607 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
4608}
4609
4610/// Current value of [`OBMC_HITS_8`].
4611#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4612pub(crate) fn obmc_hits_8() -> usize {
4613 OBMC_HITS_8.with(|c| c.get())
4614}
4615
4616// lane-rectgate r1: how many 32x32 quadrants actually decoded a
4617// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
4618// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
4619// `VERT_B` all still fall into the generic "a partition type this encoder
4620// never writes" refusal below) -- the gate's proof that a free-partition
4621// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
4622// coincidentally never selecting one.
4623thread_local! {
4624 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
4625 const { std::cell::Cell::new(0) };
4626}
4627
4628/// Current value of [`EXTENDED_PARTITION_HITS`].
4629#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4630pub(crate) fn extended_partition_hits() -> usize {
4631 EXTENDED_PARTITION_HITS.with(|c| c.get())
4632}
4633
4634// lane-partitions r1: how many 32x32 quadrants decoded a real
4635// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
4636// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
4637// gate's proof this round's arms actually fired.
4638thread_local! {
4639 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
4640 const { std::cell::Cell::new(0) };
4641}
4642
4643/// Current value of [`RECT_PARTITION_HITS`].
4644#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4645pub(crate) fn rect_partition_hits() -> usize {
4646 RECT_PARTITION_HITS.with(|c| c.get())
4647}
4648
4649// lane-inter8 r1: how many superblocks an inter tile coded as a single
4650// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
4651// static content, previously a named refusal).
4652thread_local! {
4653 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
4654 /// path decoded as one whole block (its gate's own witness).
4655 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4656 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
4657 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4658 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4659}
4660
4661/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
4662pub(crate) fn inter_sb128_horz_hits() -> usize {
4663 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
4664}
4665
4666/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
4667pub(crate) fn inter_sb128_vert_hits() -> usize {
4668 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
4669}
4670
4671/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
4672pub fn inter_sb128_none_hits() -> usize {
4673 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
4674}
4675
4676thread_local! {
4677 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
4678 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
4679 /// units) -- the gate's witness that the lifted refusal's case fired.
4680 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4681}
4682
4683/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
4684pub fn intra_128_in_inter_hits() -> usize {
4685 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
4686}
4687
4688thread_local! {
4689 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
4690 const { std::cell::Cell::new(0) };
4691}
4692
4693/// Current value of [`INTER_SB_NONE_HITS`].
4694#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4695pub(crate) fn inter_sb_none_hits() -> usize {
4696 INTER_SB_NONE_HITS.with(|c| c.get())
4697}
4698
4699// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
4700// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
4701// path has always run that loop, so only this counter proves the newly-lifted
4702// alphabet value fired.
4703thread_local! {
4704 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
4705 const { std::cell::Cell::new(0) };
4706}
4707
4708/// Current value of [`INTER_SUB16_SPLIT_HITS`].
4709#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4710pub(crate) fn inter_sub16_split_hits() -> usize {
4711 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
4712}
4713
4714// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
4715// while at least one reference picture was SCALED (superres) -- the counter
4716// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
4717thread_local! {
4718 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
4719 const { std::cell::Cell::new(0) };
4720}
4721
4722/// Current value of [`SCALED_LEAF8_HITS`].
4723pub fn scaled_leaf8_hits() -> usize {
4724 SCALED_LEAF8_HITS.with(|c| c.get())
4725}
4726
4727// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
4728// rect pair) were predicted from a SCALED reference -- the counter behind the
4729// lifted "sub-8x8 inter block under a scaled reference" refusal.
4730thread_local! {
4731 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
4732 const { std::cell::Cell::new(0) };
4733}
4734
4735/// Current value of [`SCALED_SUB8_HITS`].
4736pub fn scaled_sub8_hits() -> usize {
4737 SCALED_SUB8_HITS.with(|c| c.get())
4738}
4739
4740// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
4741// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
4742// rect coefficient reader itself fired, not just the strip-level partition
4743// symbol [`RECT_PARTITION_HITS`] already counts.
4744thread_local! {
4745 static RECT_COEFF_HITS: std::cell::Cell<usize> =
4746 const { std::cell::Cell::new(0) };
4747}
4748
4749/// Current value of [`RECT_COEFF_HITS`].
4750#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4751pub(crate) fn rect_coeff_hits() -> usize {
4752 RECT_COEFF_HITS.with(|c| c.get())
4753}
4754
4755// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
4756// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
4757// charter's real-aomenc gate hard-asserts.
4758thread_local! {
4759 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
4760 const { std::cell::Cell::new(0) };
4761}
4762
4763/// Current value of [`RECT_LEAF_COEFF_HITS`].
4764#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4765pub(crate) fn rect_leaf_coeff_hits() -> usize {
4766 RECT_LEAF_COEFF_HITS.with(|c| c.get())
4767}
4768
4769// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
4770// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
4771// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
4772// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
4773// needs rectangular intra prediction" before this round.
4774thread_local! {
4775 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
4776 const { std::cell::Cell::new([0; 3]) };
4777}
4778
4779/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
4780/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
4781#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4782pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
4783 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
4784}
4785
4786// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
4787// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
4788// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
4789// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
4790// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
4791// a single counter cannot tell an axis swap from a working arm
4792// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
4793thread_local! {
4794 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
4795 const { std::cell::Cell::new([0; 2]) };
4796}
4797
4798/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
4799/// (0 = 64x32, 1 = 32x64).
4800pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
4801 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
4802}
4803
4804// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
4805// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
4806// is never incremented) -- the gate's proof that the lifted path ran per depth.
4807thread_local! {
4808 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
4809 const { std::cell::Cell::new([0; 3]) };
4810}
4811
4812// lane-t900 r21: rect intra strips inside an inter frame that read the
4813// screen-content palette syntax (`allow_screen_content_tools` set and the
4814// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
4815// refusal used to guard, so this counter is what keeps its witness gate
4816// non-vacuous.
4817thread_local! {
4818 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4819}
4820
4821/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
4822#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4823pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
4824 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
4825}
4826
4827/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
4828#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4829pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
4830 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
4831}
4832
4833/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
4834#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4835pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
4836 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
4837}
4838
4839// lane-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid
4840// approximation would have resolved off a DIFFERENT CDF row than the real
4841// `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY
4842// frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block"
4843// tally is green on the old code too (class gate-blind-to-feature).
4844thread_local! {
4845 static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell<usize> =
4846 const { std::cell::Cell::new(0) };
4847}
4848
4849/// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`].
4850#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
4851pub(crate) fn txctx_deblock_divergence_hits() -> usize {
4852 TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get)
4853}
4854
4855// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
4856// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
4857// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
4858// rect strip on the inter block path" before this round.
4859thread_local! {
4860 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
4861 const { std::cell::Cell::new([0; 4]) };
4862}
4863
4864/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
4865/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
4866pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
4867 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
4868}
4869
4870// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
4871// through one of the key-frame rect readers ([`decode_block_rect4`],
4872// [`decode_block_rect64`]). `Some((size_group, skip))` tells
4873// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
4874// already read by [`decode_inter_block`] and (b) the luma mode comes off
4875// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
4876// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
4877
4878// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
4879// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
4880// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
4881// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
4882thread_local! {
4883 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4884 const { std::cell::Cell::new(0) };
4885}
4886
4887/// Current value of [`MODE_MI_OVERRIDE_HITS`].
4888#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4889pub(crate) fn mode_mi_override_hits() -> usize {
4890 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4891}
4892
4893// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
4894// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
4895// mode from the previous tile, where libaom's `up_available`/`left_available`
4896// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
4897// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
4898// per superblock row in `start_row`, so the luma fallback cannot leak the way
4899// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
4900// the invariant that makes the coarse fallback safe.
4901thread_local! {
4902 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
4903 const { std::cell::Cell::new(0) };
4904}
4905
4906/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
4907#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4908pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
4909 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
4910}
4911
4912// lane-cfl r1: how many times a chroma intra-edge filter-type read
4913// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
4914// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
4915// r1 defect would have filtered a chroma edge with the wrong strength.
4916thread_local! {
4917 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4918 const { std::cell::Cell::new(0) };
4919}
4920
4921/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
4922#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4923pub(crate) fn uv_mode_mi_override_hits() -> usize {
4924 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4925}
4926
4927// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
4928// `uv_mode` from the mi GRID where the one-slot-per-column map would have
4929// answered differently -- the sub-8x8 pair case where the pair's own first
4930// half had already overwritten the column slot the chroma-ref half reads.
4931thread_local! {
4932 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
4933 const { std::cell::Cell::new(0) };
4934}
4935
4936/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
4937pub fn uv_mode_grid_override_hits() -> usize {
4938 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
4939}
4940
4941// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
4942// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
4943// from an earlier block in that pixel row/column while the mi-exact map --
4944// which an inter block only started writing this round -- correctly says the
4945// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
4946// an INTER mode, and its `uv_mode` "is not set for inter blocks").
4947thread_local! {
4948 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
4949 const { std::cell::Cell::new(0) };
4950}
4951
4952/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
4953#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4954pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
4955 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
4956}
4957
4958// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
4959// suppressed at a TILE edge that is not a frame edge -- the above/left
4960// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
4961// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
4962// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
4963// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
4964// above would decide this tile's chroma edge filter strength.
4965thread_local! {
4966 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
4967 const { std::cell::Cell::new(0) };
4968}
4969
4970/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
4971#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4972pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
4973 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
4974}
4975
4976// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
4977// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
4978// shapes the r1 chroma defect showed up on.
4979thread_local! {
4980 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4981 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4982}
4983
4984/// Current value of [`CFL_BLOCK_HITS`].
4985#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4986pub(crate) fn cfl_block_hits() -> usize {
4987 CFL_BLOCK_HITS.with(|c| c.get())
4988}
4989
4990/// Current value of [`UV_ANGLE_DELTA_HITS`].
4991#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4992pub(crate) fn uv_angle_delta_hits() -> usize {
4993 UV_ANGLE_DELTA_HITS.with(|c| c.get())
4994}
4995
4996// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
4997// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
4998// gate's proof this round's arms actually reached a real block, not just
4999// that `partition_w64` read one of those two symbol values.
5000thread_local! {
5001 static SB_RECT_HITS: std::cell::Cell<usize> =
5002 const { std::cell::Cell::new(0) };
5003}
5004
5005// Current value of [`SB_RECT_HITS`].
5006// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
5007// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
5008// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
5009// non-SPLIT edge arm actually decoded (before this round the bit was read and
5010// thrown away, so that arm was unreachable).
5011thread_local! {
5012 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
5013}
5014
5015/// Current value of [`EDGE_PART_HITS`].
5016#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5017pub(crate) fn edge_part_hits() -> [usize; 4] {
5018 EDGE_PART_HITS.with(|c| c.get())
5019}
5020
5021/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
5022#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5023pub(crate) fn reset_edge_part_hits() {
5024 EDGE_PART_HITS.with(|c| c.set([0; 4]));
5025}
5026
5027fn bump_edge_part(slot: usize) {
5028 hit_do! {
5029 EDGE_PART_HITS.with(|c| {
5030 let mut h = c.get();
5031 h[slot] += 1;
5032 c.set(h);
5033 });
5034 }
5035}
5036
5037#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5038pub(crate) fn sb_rect_hits() -> usize {
5039 SB_RECT_HITS.with(|c| c.get())
5040}
5041
5042// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
5043// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
5044// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
5045// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
5046// paths (intra and inter) feed the same counter.
5047//
5048// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
5049// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
5050// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
5051// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
5052// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
5053// every SB of the last row), so the 32-level slots stay 0 on that content and
5054// only these prove the arm fired.
5055thread_local! {
5056 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
5057 const { std::cell::Cell::new([0; 8]) };
5058}
5059
5060/// Current value of [`EDGE32_HITS`].
5061#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5062pub(crate) fn edge32_hits() -> [usize; 8] {
5063 EDGE32_HITS.with(|c| c.get())
5064}
5065
5066/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
5067/// reads are `if`-conditions, so the counter has to ride the expression.
5068fn bump_edge32_bit(base: usize, bit: usize) -> usize {
5069 bump_edge32(base + bit.min(1));
5070 bit
5071}
5072
5073fn bump_edge32(slot: usize) {
5074 hit_do! {
5075 EDGE32_HITS.with(|c| {
5076 let mut h = c.get();
5077 h[slot] += 1;
5078 c.set(h)
5079 });
5080 }
5081}
5082
5083// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
5084// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
5085// strip) fired. Real aomenc picks these at 64 even with
5086// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
5087// the counter the gate hard-asserts.
5088thread_local! {
5089 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
5090 const { std::cell::Cell::new([0; 4]) };
5091}
5092
5093/// Current value of [`SB_AB_HITS`], summed over the four arms.
5094#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5095pub(crate) fn sb_ab_hits() -> usize {
5096 SB_AB_HITS.with(|c| c.get().iter().sum())
5097}
5098
5099/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
5100/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
5101/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
5102/// proof of all four.
5103#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5104pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
5105 SB_AB_HITS.with(std::cell::Cell::get)
5106}
5107
5108// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
5109// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
5110// strips). Two counters, not one, because a gate that only proved "some 1:4
5111// strip fired" would pass on a stream that never coded the other axis, and
5112// every scan/context table this round added comes in a transposed pair.
5113thread_local! {
5114 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5115 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5116}
5117
5118/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
5119#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5120pub(crate) fn sb_rect4_horz_hits() -> usize {
5121 SB_RECT4_HORZ_HITS.with(|c| c.get())
5122}
5123
5124/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
5125#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5126pub(crate) fn sb_rect4_vert_hits() -> usize {
5127 SB_RECT4_VERT_HITS.with(|c| c.get())
5128}
5129
5130// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
5131// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
5132// strips), the arms the ReelB mid-film extract stops at.
5133thread_local! {
5134 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5135 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5136 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
5137 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
5138 /// `PARTITION_VERT_4`.
5139 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5140 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5141 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
5142 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
5143 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5144 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5145 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5146 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5147}
5148
5149// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
5150// a gate that only counted strips would pass on an all-skip stream, which
5151// exercises none of the new scan/context tables.
5152thread_local! {
5153 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5154}
5155
5156// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
5157// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
5158// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
5159// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
5160// counts the same for a 16x8/8x16 strip below 16x16.
5161thread_local! {
5162 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5163 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5164 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5165}
5166
5167/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
5168#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5169pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
5170 (
5171 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
5172 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
5173 )
5174}
5175
5176/// Current value of `SUB16_SPLIT_HITS`.
5177#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5178pub(crate) fn sub16_split_hits() -> usize {
5179 SUB16_SPLIT_HITS.with(|c| c.get())
5180}
5181
5182// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
5183// luma transform is SPLIT and which therefore leave through that fn's early
5184// return -- the arm that published no `TXFM_CONTEXT` band until this round.
5185thread_local! {
5186 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5187}
5188
5189/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
5190#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5191pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
5192 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
5193}
5194
5195/// Current value of `RECT4_COEFF_HITS`.
5196pub(crate) fn rect4_coeff_hits() -> usize {
5197 RECT4_COEFF_HITS.with(|c| c.get())
5198}
5199
5200// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
5201// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
5202// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
5203// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
5204// asserts the arms it proves separately so a run whose RD only picked one
5205// cannot pass as proof of the others.
5206thread_local! {
5207 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
5208}
5209
5210/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
5211/// inter frame).
5212pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
5213 SB_AB_INTER_HITS.with(std::cell::Cell::get)
5214}
5215
5216// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
5217// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
5218// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
5219// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
5220// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
5221// arm separately so a run whose RD only picked one cannot pass as proof of
5222// four.
5223thread_local! {
5224 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
5225}
5226
5227/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
5228/// inter frame).
5229pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
5230 AB16_INTER_HITS.with(std::cell::Cell::get)
5231}
5232
5233// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
5234// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
5235// counts the odd strips that close a 4:2:0 chroma pair
5236// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
5237// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
5238// the PREVIOUS strip's own mv/ref/filters -- libaom
5239// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
5240// through `is_sub8x8_inter` (same file, :54).
5241thread_local! {
5242 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5243 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5244 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5245 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5246}
5247
5248// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
5249// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
5250// pair's single 8x4 (4x8) chroma unit for BOTH strips.
5251thread_local! {
5252 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
5253 const { std::cell::Cell::new([0; 3]) };
5254}
5255
5256/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
5257/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
5258pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
5259 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
5260 (v[0], v[1], v[2])
5261}
5262
5263/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
5264/// strips, chroma pairs closed, chroma pairs built from two different
5265/// strips' motion vectors)`.
5266pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
5267 (
5268 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
5269 INTER16_VERT4_HITS.with(std::cell::Cell::get),
5270 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
5271 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
5272 )
5273}
5274
5275/// One 16x4 / 4x16 inter strip's chroma situation, handed to
5276/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
5277/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
5278/// that all mean "an ordinary block, chroma of its own".
5279#[derive(Clone, Copy)]
5280pub(crate) struct InterStripChroma {
5281 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
5282 /// read and reconstruct NO chroma at all.
5283 has_chroma: bool,
5284 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
5285 horz: bool,
5286 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
5287 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
5288 /// i.e. the origin of the 8x4 (4x8) chroma transform.
5289 pair_mi: (usize, usize),
5290 /// The previous (even) strip's single-reference MC parameters, `None`
5291 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
5292 /// and the whole chroma block is predicted from THIS strip's mv.
5293 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
5294}
5295
5296 /// The single-reference MC parameters of the inter block that decoded
5297 /// last -- read by the next 1:4 strip to build its pair's chroma.
5298
5299fn bump_ab16_inter(arm: usize) {
5300 hit_do! {
5301 AB16_INTER_HITS.with(|c| {
5302 let mut v = c.get();
5303 v[arm] += 1;
5304 c.set(v);
5305 });
5306 }
5307}
5308
5309// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
5310// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
5311// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
5312thread_local! {
5313 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5314 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5315 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5316 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5317 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5318 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
5319 /// base mi differs from what the strip's own (odd) mi would have said --
5320 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
5321 /// key frame miss by 1. Zero here means a gate never exercised the fix.
5322 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5323 /// lane-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s.
5324 static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5325 /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip.
5326 static RECT4_16_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5327 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
5328 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
5329 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5330 /// lane-av1-loss64: chroma transform units the frame-edge clip skipped
5331 /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in
5332 /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless
5333 /// block overhanging the frame does NOT code.
5334 static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5335 /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma
5336 /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`,
5337 /// decodeframe.c:1262) instead of leaking the previous occupant's.
5338 static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5339 /// lane-av1-llband: 4x4 chroma transform units a lossless HORZ/VERT strip
5340 /// walked at subsampling 0/0 (one unit per mi cell -- the geometry the
5341 /// hardcoded 4:2:0 span mis-stepped).
5342 static RECT_SPLIT_LOSSLESS_CHROMA444_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5343}
5344
5345/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
5346/// that reconstructed as flat DC before lane-kf1200 r2).
5347pub fn skip_cfl_hits() -> usize {
5348 SKIP_CFL_HITS.with(|c| c.get())
5349}
5350
5351/// How many chroma transform units the frame-edge clip skipped in
5352/// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a
5353/// stream whose lossless blocks never overhang the frame -- a gate asserting
5354/// the clip fired must see this nonzero.
5355pub fn chroma_edge_tu_clip_hits() -> usize {
5356 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get())
5357}
5358
5359/// How many skipped lossless intrabc rect strips had their luma entropy
5360/// bands zeroed per unit (lane-av1-loss64).
5361pub fn skip_lossless_band_reset_hits() -> usize {
5362 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get())
5363}
5364
5365/// How many 4x4 chroma transform units a lossless HORZ/VERT strip walked at
5366/// subsampling 0/0 (lane-av1-llband). Zero means a stream never decoded the
5367/// 4:4:4 lossless unit walk this counter proves -- a gate asserting the fix
5368/// must see this nonzero.
5369pub fn rect_split_lossless_chroma444_hits() -> usize {
5370 RECT_SPLIT_LOSSLESS_CHROMA444_HITS.with(|c| c.get())
5371}
5372
5373/// Gate-side reset for the two lane-av1-loss64 counters above.
5374pub fn reset_loss64_hits() {
5375 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0));
5376 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0));
5377}
5378
5379/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
5380/// from the pair's base mi than the strip's own mi would have given.
5381pub fn rect4_16_uv_pair_filt_hits() -> usize {
5382 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
5383}
5384
5385/// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane.
5386pub fn rect4_16_lossless_chroma_hits() -> usize {
5387 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get())
5388}
5389
5390/// How many 16x4/4x16 strips reconstructed as intra block copy.
5391pub fn rect4_16_intrabc_hits() -> usize {
5392 RECT4_16_INTRABC_HITS.with(|c| c.get())
5393}
5394
5395/// Zero the lane-av1-rect14 pair counters so a gate measures one stream.
5396pub fn reset_rect4_16_pair_hits() {
5397 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
5398 RECT4_16_INTRABC_HITS.with(|c| c.set(0));
5399}
5400
5401// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
5402// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
5403// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
5404// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
5405// intra-edge filter type must come from the chroma-reference position).
5406thread_local! {
5407 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5408 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5409}
5410
5411/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
5412pub fn reelc_chroma_counters() -> (usize, usize) {
5413 (
5414 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
5415 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
5416 )
5417}
5418
5419/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
5420/// strips, chroma-reference strips, strips with a coded residual, strips
5421/// whose luma transform is split)`.
5422pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
5423 (
5424 RECT4_16_HORZ_HITS.with(|c| c.get()),
5425 RECT4_16_VERT_HITS.with(|c| c.get()),
5426 RECT4_16_CHROMA_HITS.with(|c| c.get()),
5427 RECT4_16_COEFF_HITS.with(|c| c.get()),
5428 RECT4_16_SPLIT_HITS.with(|c| c.get()),
5429 )
5430}
5431
5432/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
5433pub(crate) fn rect4_32_horz_hits() -> usize {
5434 RECT4_32_HORZ_HITS.with(|c| c.get())
5435}
5436
5437/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
5438pub(crate) fn rect4_32_vert_hits() -> usize {
5439 RECT4_32_VERT_HITS.with(|c| c.get())
5440}
5441
5442/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
5443pub(crate) fn rect4_32_horz_inter_hits() -> usize {
5444 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
5445}
5446
5447/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
5448pub(crate) fn rect4_32_vert_inter_hits() -> usize {
5449 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
5450}
5451
5452/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
5453pub(crate) fn inter_sb_horz_hits() -> usize {
5454 INTER_SB_HORZ_HITS.with(|c| c.get())
5455}
5456
5457/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
5458pub(crate) fn inter_sb_vert_hits() -> usize {
5459 INTER_SB_VERT_HITS.with(|c| c.get())
5460}
5461
5462/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
5463pub(crate) fn inter_sb_horz4_hits() -> usize {
5464 INTER_SB_HORZ4_HITS.with(|c| c.get())
5465}
5466
5467/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
5468pub(crate) fn inter_sb_vert4_hits() -> usize {
5469 INTER_SB_VERT4_HITS.with(|c| c.get())
5470}
5471
5472// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
5473// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
5474// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
5475// just inert-compiled. Zero forever on a passing gate means that gate's
5476// stream never carries `delta_q_present=1` through a rect64 block.
5477thread_local! {
5478 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
5479 const { std::cell::Cell::new(0) };
5480}
5481
5482/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
5483#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5484pub(crate) fn rect64_qidx_drift_hits() -> usize {
5485 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
5486}
5487
5488// lane-partab r1: how many 32x32 quadrants decoded an AB partition
5489// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
5490// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
5491// free-partition gate's proof this round's arms actually fired.
5492thread_local! {
5493 static PARTAB_HITS: std::cell::Cell<usize> =
5494 const { std::cell::Cell::new(0) };
5495}
5496
5497/// Current value of [`PARTAB_HITS`].
5498#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5499pub(crate) fn partab_hits() -> usize {
5500 PARTAB_HITS.with(|c| c.get())
5501}
5502
5503// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
5504// one counter per arm rather than one shared total -- the gate hard-asserts
5505// each of these individually nonzero so a recipe that only ever fires
5506// HORZ_A can't silently stand in for the whole set.
5507thread_local! {
5508 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
5509 const { std::cell::Cell::new(0) };
5510 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
5511 const { std::cell::Cell::new(0) };
5512 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
5513 const { std::cell::Cell::new(0) };
5514 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
5515 const { std::cell::Cell::new(0) };
5516}
5517
5518/// Current value of [`INTRA_HORZ_A_HITS`].
5519#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5520pub(crate) fn intra_horz_a_hits() -> usize {
5521 INTRA_HORZ_A_HITS.with(|c| c.get())
5522}
5523/// Current value of [`INTRA_HORZ_B_HITS`].
5524#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5525pub(crate) fn intra_horz_b_hits() -> usize {
5526 INTRA_HORZ_B_HITS.with(|c| c.get())
5527}
5528/// Current value of [`INTRA_VERT_A_HITS`].
5529#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5530pub(crate) fn intra_vert_a_hits() -> usize {
5531 INTRA_VERT_A_HITS.with(|c| c.get())
5532}
5533/// Current value of [`INTRA_VERT_B_HITS`].
5534#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5535pub(crate) fn intra_vert_b_hits() -> usize {
5536 INTRA_VERT_B_HITS.with(|c| c.get())
5537}
5538
5539// How many [`read_inter_compound_mode`] reads actually happened
5540// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
5541// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
5542// mvstack build), not just that `comp_mode` fired. Still refused right
5543// after (no MV assignment or MC wired), so this only counts attempted
5544// reads.
5545thread_local! {
5546 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
5547 const { std::cell::Cell::new(0) };
5548}
5549
5550/// Current value of [`COMPOUND_MODE_HITS`].
5551#[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds
5552pub(crate) fn compound_mode_hits() -> usize {
5553 COMPOUND_MODE_HITS.with(|c| c.get())
5554}
5555
5556/// How many query blocks folded in at least one temporal MV candidate
5557/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
5558/// temporal-MV gate's own firing counter (lane-av1tmvp).
5559///
5560/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
5561/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
5562/// this file (`decode_inter_block`) still passes `tpl: None` -- this
5563/// counter compiles and the projection math it counts is unit-tested
5564/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
5565/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
5566/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
5567/// against any real stream today. See the module doc on
5568/// `crate::motion_field` and this crate's ledger for the remaining wiring.
5569#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5570pub(crate) fn tmv_hits() -> usize {
5571 crate::mvstack::tmv_hits()
5572}
5573
5574/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
5575/// produced on this thread, the 10-bit inter gate's firing proof.
5576#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5577pub(crate) fn inter_pred_hits() -> usize {
5578 crate::mc::inter_pred_hits()
5579}
5580
5581/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
5582/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
5583/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
5584/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
5585/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
5586/// needs to turn a query block's own resolved `ref_frame` into
5587/// `TplArgs::cur_offset_0` (spec 7.9.3).
5588pub(crate) struct TplFrameArgs<'a> {
5589 pub field: &'a crate::motion_field::TplField,
5590 pub order_hint_bits: u32,
5591 pub order_hint: u32,
5592 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
5593 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
5594 /// frame's own `ref_frame_idx` names for each single reference.
5595 pub ref_order_hints: [u32; 7],
5596}
5597
5598/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
5599/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
5600/// decoded `grid`: every 4x4 unit an inter block covers reads the same
5601/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
5602/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
5603/// exact — every block this crate ever codes is at least 8x8, so no 8x8
5604/// cell straddles two different blocks' values.
5605#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
5606pub(crate) fn build_motion_field(
5607 grid: &MiGrid,
5608 mi_cols: usize,
5609 mi_rows: usize,
5610 order_hint: u32,
5611 order_hint_bits: u32,
5612 ref_order_hints: [u32; 7],
5613 fctx: &FrameCtx,
5614) -> crate::motion_field::MotionField {
5615 let mut field =
5616 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
5617 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
5618 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
5619 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
5620 // referencing one stores only its OTHER side's mv. With
5621 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
5622 // nothing is skipped.
5623 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
5624 // only on the reference frame, so it is 7 table lookups per frame instead
5625 // of two per inter unit.
5626 let other_side: [bool; 8] = std::array::from_fn(|rf| {
5627 let i = rf.wrapping_sub(LAST_FRAME as usize);
5628 order_hint_bits != 0
5629 && i < 7
5630 && (crate::motion_field::get_relative_dist(order_hint_bits, ref_order_hints[i], order_hint) > 0
5631 || ref_order_hints[i] == order_hint)
5632 });
5633 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
5634 // capped at 12 bits per component; a longer one is not stored at all.
5635 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
5636 let (cols, rows, cells) = field.cells_mut();
5637 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
5638 // never touch each other (an 8x8 cell lives in one cell row, and mi row
5639 // `row` writes cell row `row / 2`).
5640 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
5641 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
5642 let out = &mut out[(row / 2 - r0) * cols..][..cols];
5643 for col in 0..mi_cols {
5644 let Some(info) = grid.get_frame(row, col) else {
5645 continue;
5646 };
5647 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
5648 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
5649 // so an intra block -- or an inter block whose every slot is on the
5650 // other side / over the limit -- wipes what an earlier block wrote
5651 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
5652 // share a cell).
5653 if !info.is_inter {
5654 out[col / 2] = None;
5655 continue;
5656 }
5657 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
5658 // qualifying one wins -- a compound block stores its second
5659 // reference's mv, never its first (unless the second is on the
5660 // other side or over the limit). Storing slot 0 unconditionally
5661 // put the wrong (mv, ref_frame_offset) pair in every compound
5662 // block's cell, which a later frame's temporal candidate then
5663 // projected with the wrong reference distance.
5664 let mut saved: Option<crate::motion_field::SavedMv> = None;
5665 for (rf, mv) in [
5666 (info.ref_frame, Some(mv32(info.mv))),
5667 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
5668 ] {
5669 let (Some(mv), true) = (mv, rf > 0) else {
5670 continue;
5671 };
5672 if other_side[rf as usize] {
5673 continue;
5674 }
5675 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
5676 continue;
5677 }
5678 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
5679 }
5680 out[col / 2] = saved;
5681 }
5682 }
5683 };
5684 // lane-mf: the whole-frame pass split over the filter pool in cell-row
5685 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
5686 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
5687 let bands = crate::par::bands(rows, crate::par::filter_threads());
5688 if bands.len() <= 1 {
5689 fill(0, rows, cells);
5690 } else {
5691 let shared = crate::par::Shared::new(cells);
5692 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
5693 // SAFETY: cell rows `r0..r1` are this band's alone.
5694 let cells = unsafe { shared.get() };
5695 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
5696 });
5697 }
5698 if crate::envflags::env_flag!("EC_TRACE_TPL") {
5699 eprintln!("EC_TPL_SAVED oh={order_hint}");
5700 for (r, row) in field.occupancy().iter().enumerate() {
5701 eprintln!("EC_TPL_SAVED r{r} {row}");
5702 }
5703 }
5704 field
5705}
5706
5707/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
5708/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
5709#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5710pub(crate) fn ref_hits(ref_frame: i8) -> usize {
5711 let c = match ref_frame {
5712 LAST2_FRAME => &LAST2_HITS,
5713 LAST3_FRAME => &LAST3_HITS,
5714 GOLDEN_FRAME => &GOLDEN_HITS,
5715 BWDREF_FRAME => &BWDREF_HITS,
5716 ALTREF2_FRAME => &ALTREF2_HITS,
5717 ALTREF_FRAME => &ALTREF_HITS,
5718 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
5719 };
5720 c.with(|v| v.get())
5721}
5722
5723 /// The sequence header's `enable_intra_edge_filter`, set once per
5724 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
5725 /// own read of it, kept off the call stack (see that function's own doc
5726 /// comment for why) rather than threaded through every `read_plane`/
5727 /// `decode_block`/`decode_leaf8` call between here and there.
5728
5729/// Set [`ENABLE_EDGE_FILTER`] for this thread.
5730///
5731/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
5732/// never did -- so an inter frame's intra blocks read whatever value the last
5733/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
5734/// harmless (its own key frame sets it first), but a caller that decodes an
5735/// inter frame directly, or a test harness running several streams on one
5736/// thread, inherits a foreign sequence's bit: decode stops being a pure
5737/// function of the bitstream. `decode_stream` now calls this once per stream
5738/// from the sequence header, which covers every frame including inter ones.
5739pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
5740 fctx.enable_edge_filter.with(|f| f.set(value));
5741}
5742
5743/// Current value of [`ANGLE_DELTA_HITS`].
5744#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5745pub(crate) fn angle_delta_hits() -> usize {
5746 ANGLE_DELTA_HITS.with(|c| c.get())
5747}
5748
5749/// Current value of [`TX_CLASS1_HITS`].
5750#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5751pub(crate) fn tx_class1_hits() -> usize {
5752 TX_CLASS1_HITS.with(|c| c.get())
5753}
5754
5755// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
5756// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
5757// bottom) this thread's decode actually reconstructed -- the same
5758// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
5759// genuinely exercised the sub-8x8 leaf path rather than every attempt
5760// coincidentally landing on `PARTITION_NONE`.
5761thread_local! {
5762 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5763 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
5764 /// sub-blocks (lane-intersub8).
5765 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5766 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
5767 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
5768 /// `[1] = VERT` (two BLOCK_4X8).
5769 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
5770 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
5771 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
5772 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
5773 /// MIXED groups whose chroma reference is INTER while its sibling is
5774 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
5775 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
5776 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
5777 /// so only this cell separates the split arm from the HORZ/VERT one).
5778 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
5779}
5780
5781/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
5782/// mixed groups, split 4x4 leaves)`.
5783pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
5784 SUB8_INTRA_RECT_HITS.with(|c| {
5785 let h = c.get();
5786 (h[0], h[1], h[2], h[3], h[4])
5787 })
5788}
5789
5790/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
5791pub fn sub8_inter_rect_hits() -> (usize, usize) {
5792 SUB8_INTER_RECT_HITS.with(|c| {
5793 let h = c.get();
5794 (h[0], h[1])
5795 })
5796}
5797
5798// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
5799// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
5800// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
5801// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
5802// (b) was 0 for every stream before this round -- the leaf path never touched
5803// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
5804// filtered where libaom skips it. A gate asserts both are non-zero.
5805thread_local! {
5806 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5807 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5808 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
5809 // crosses the cropped frame edge -- the only units for which "clamp at
5810 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
5811 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
5812 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
5813 // whose width or height is not a multiple of 8 is the only shape that
5814 // produces one; the straddling-band gate arms assert it grew.
5815 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5816 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
5817 // (see `Neighbours::skip_written`).
5818 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5819 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
5820 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
5821 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
5822 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
5823 // 8-tall strip pair where only one half is skip must still be FILTERED.
5824 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5825 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5826}
5827
5828/// Current value of `RECT_SKIP_BAND_HITS`.
5829pub fn rect_skip_band_hits() -> usize {
5830 RECT_SKIP_BAND_HITS.with(|c| c.get())
5831}
5832
5833/// Current value of `CDEF_MIXED_SKIP_UNITS`.
5834pub fn cdef_mixed_skip_units() -> usize {
5835 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
5836}
5837
5838/// Current value of `CDEF_SKIPPED_UNITS`.
5839#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5840pub(crate) fn cdef_skipped_units() -> usize {
5841 CDEF_SKIPPED_UNITS.with(|c| c.get())
5842}
5843
5844/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
5845/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
5846pub fn cdef_unwritten_skip_units() -> usize {
5847 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
5848}
5849
5850/// Current value of `INTER8_SKIP_BAND_HITS`.
5851#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5852pub(crate) fn inter8_skip_band_hits() -> usize {
5853 INTER8_SKIP_BAND_HITS.with(|c| c.get())
5854}
5855
5856/// Current value of `CDEF_STRADDLE_UNITS`.
5857#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5858pub(crate) fn cdef_straddle_units() -> usize {
5859 CDEF_STRADDLE_UNITS.with(|c| c.get())
5860}
5861
5862/// Current value of [`SUB8_SPLIT_HITS`].
5863#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5864pub(crate) fn sub8_split_hits() -> usize {
5865 SUB8_SPLIT_HITS.with(|c| c.get())
5866}
5867
5868/// Current value of [`SUB8_INTER_SPLIT_HITS`].
5869pub fn sub8_inter_split_hits() -> usize {
5870 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
5871}
5872
5873// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
5874// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
5875// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
5876// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
5877// first sub-block's type is never the one). Reading it off sub-block 0
5878// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
5879// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
5880// see this rule through this counter.
5881thread_local! {
5882 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5883}
5884
5885/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
5886pub fn sub8_chroma_tx_from_ref_hits() -> usize {
5887 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
5888}
5889
5890fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
5891 if coeffs && first_sub != chroma_ref {
5892 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
5893 }
5894}
5895
5896// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
5897// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
5898// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
5899// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
5900// asserts on these two rather than a plain leaf count.
5901thread_local! {
5902 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5903 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5904 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
5905 /// two 4x4 transform units, predicted one after the other. A separate
5906 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
5907 /// the gate can prove THIS path fired.
5908 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5909 /// 16x8/8x16 intra strips whose prediction actually read past the block's
5910 /// own width (above-right) or height (below-left) -- the samples
5911 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
5912 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
5913 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5914 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
5915 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
5916 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5917}
5918
5919/// Current value of [`RECT8_SPLIT_TX_HITS`].
5920#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5921pub(crate) fn rect8_split_tx_hits() -> usize {
5922 RECT8_SPLIT_TX_HITS.with(|c| c.get())
5923}
5924
5925/// Current value of [`RECT_STRIP_PRED_HITS`].
5926#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5927pub(crate) fn rect_strip_pred_hits() -> usize {
5928 RECT_STRIP_PRED_HITS.with(|c| c.get())
5929}
5930
5931/// Current value of [`RECT_STRIP_REACH_HITS`].
5932#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5933pub(crate) fn rect_strip_reach_hits() -> usize {
5934 RECT_STRIP_REACH_HITS.with(|c| c.get())
5935}
5936
5937/// Current value of [`TX4X8_CODED_HITS`].
5938#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5939pub(crate) fn tx4x8_coded_hits() -> usize {
5940 TX4X8_CODED_HITS.with(|c| c.get())
5941}
5942
5943/// Current value of [`TX8X4_CODED_HITS`].
5944#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5945pub(crate) fn tx8x4_coded_hits() -> usize {
5946 TX8X4_CODED_HITS.with(|c| c.get())
5947}
5948
5949// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
5950// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
5951// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
5952// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
5953// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
5954// (`eob_pt_{16,64,128,256}_chroma_class1`).
5955thread_local! {
5956 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
5957 const { std::cell::Cell::new(0) };
5958}
5959
5960/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
5961#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5962pub(crate) fn chroma_eob_class1_hits() -> usize {
5963 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
5964}
5965
5966/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
5967/// `tx_type` put this block's `eob_pt` on the class-1 row.
5968fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
5969 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
5970 hit!(CHROMA_EOB_CLASS1_HITS);
5971 }
5972}
5973
5974const SUB_MI: u32 = 4;
5975const MI: usize = 4;
5976const SB: usize = 64;
5977/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
5978/// (tile start, superblock-row start).
5979///
5980/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
5981/// `av1_get_partition_plane_context` reads its own zero-initialised
5982/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
5983/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
5984/// (64), which reads identically at every level up to 64x64 but sets the bit
5985/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
5986/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
5987/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
5988const NO_NEIGHBOUR_SIDE: usize = 128;
5989const BLOCK: usize = 32;
5990const SUB: usize = 16;
5991const TX32: usize = 32;
5992const TX16: usize = 16;
5993const TX8: usize = 8;
5994const TX4: usize = 4;
5995const DC_PRED: usize = 0;
5996/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
5997/// carries an angle delta — [`crate::tile`]'s own private copy of the same
5998/// constant.
5999const V_PRED: usize = 1;
6000const H_PRED: usize = 2;
6001/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
6002/// `Fimode_To_Intradir`, libaom `blockd.h`).
6003const D157_PRED: usize = 6;
6004/// The last directional mode, `D67_PRED`.
6005const D67_PRED: usize = 8;
6006/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
6007/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
6008/// codes anything else, so this decoder never reads anything else either.
6009const ANGLE_DELTA_ZERO: usize = 3;
6010const NUM_BASE_LEVELS: i32 = 2;
6011const COEFF_BASE_RANGE: i32 = 12;
6012const BR_STEP: i32 = 3;
6013const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
6014
6015/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
6016/// whose probability mass a superblock or block half outside the frame
6017/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
6018/// duplicated here (that module is another lane's territory this round) and
6019/// kept in step with it by the byte-exact round-trip tests below rather than
6020/// by sharing code.
6021const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
6022const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
6023
6024fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
6025 if crate::envflags::env_flag!("EC_AV1_TRACE") {
6026 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
6027 }
6028}
6029
6030fn element_prob(cdf: &[u16], element: usize) -> u16 {
6031 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
6032}
6033
6034/// The two-symbol CDF a partial superblock/block's forced-split flag is read
6035/// with: the mass of `elements` becomes the probability of the one partition
6036/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
6037/// (the encoder's non-adapting counterpart to this read).
6038fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
6039 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
6040 [32768 - split, 32768, 0]
6041}
6042
6043fn unsupported(what: impl Into<String>) -> Error {
6044 Error::unsupported("AV1 tile", what.into())
6045}
6046
6047/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
6048/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
6049/// same rule.
6050pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
6051 match base_q_idx {
6052 0..=20 => 0,
6053 21..=60 => 1,
6054 61..=120 => 2,
6055 _ => 3,
6056 }
6057}
6058
6059/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
6060/// [`crate::tile`]'s writer generates its scan tables with.
6061fn default_scan(side: usize) -> &'static [u16] {
6062 // One table per transform side (4/8/16/32), built once: this used to be a
6063 // fresh heap allocation plus the whole anti-diagonal walk on every
6064 // transform block read.
6065 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
6066 [
6067 default_scan_gen(4),
6068 default_scan_gen(8),
6069 default_scan_gen(16),
6070 default_scan_gen(32),
6071 ]
6072 });
6073 assert!(
6074 matches!(side, 4 | 8 | 16 | 32),
6075 "no default scan for a {side}-point transform"
6076 );
6077 &SCANS[side.trailing_zeros() as usize - 2]
6078}
6079
6080fn default_scan_gen(side: usize) -> Vec<u16> {
6081 let mut scan = Vec::with_capacity(side * side);
6082 for d in 0..(2 * side - 1) {
6083 let lo = d.saturating_sub(side - 1);
6084 let hi = d.min(side - 1);
6085 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
6086 if d % 2 == 0 {
6087 scan.extend(diagonal.rev());
6088 } else {
6089 scan.extend(diagonal);
6090 }
6091 }
6092 scan
6093}
6094
6095/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
6096/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
6097/// in, instead of the default zigzag. libaom's own tables are keyed by a
6098/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
6099/// physically column-major level buffer, but they decompose to the exact
6100/// same (row, col) walk as a flat row-major traversal of *our* row-major
6101/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
6102/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
6103/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
6104/// transposed (column 0 down every row, then column 1, ...).
6105pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
6106 class_scan_table_wh(side, side, class)
6107}
6108
6109/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
6110/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
6111/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
6112/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
6113/// transcribed with -- `mrow` is the plain row-major raster in our indexing
6114/// and `mcol` its transpose, at rect sizes exactly as at square ones.
6115fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
6116 match class {
6117 TxClass::Vert => (0..(w * h) as u16).collect(),
6118 TxClass::Horiz => (0..w)
6119 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
6120 .collect(),
6121 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
6122 }
6123}
6124
6125fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
6126 match scan_idx {
6127 0 => 0,
6128 i if i <= area / 8 => 1,
6129 i if i <= area / 4 => 2,
6130 _ => 3,
6131 }
6132}
6133
6134/// One cell of [`read_coeffs`]'s level buffer.
6135///
6136/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
6137/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
6138/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
6139/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
6140/// zero cells instead of needing the `row >= side || col >= side` edge test
6141/// this used to run five times per coefficient. Nothing writes a padding
6142/// cell, so the values are the same zeros the test returned.
6143#[inline]
6144fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
6145 grid[row * stride + col] as i32
6146}
6147
6148/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
6149/// `txb_common.h`): everything but the two lone-axis-identity types this
6150/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
6151#[derive(Clone, Copy, PartialEq, Eq)]
6152pub(crate) enum TxClass {
6153 TwoD,
6154 Horiz,
6155 Vert,
6156}
6157
6158impl TxClass {
6159 pub(crate) fn of(tx_type: TxType) -> Self {
6160 match tx_type {
6161 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
6162 // key on axis alone -- FLIPADST is still ADST for this purpose.
6163 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
6164 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
6165 _ => Self::TwoD,
6166 }
6167 }
6168}
6169
6170/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
6171/// table (indexed by the position along the transform's *coded* axis --
6172/// `col` for horiz, `row` for vert) that places their contexts past the 2D
6173/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
6174/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
6175pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
6176 match i {
6177 0 => 26,
6178 1 => 31,
6179 _ => 36,
6180 }
6181}
6182
6183fn base_ctx(
6184 grid: &[u8],
6185 stride: usize,
6186 row: usize,
6187 col: usize,
6188 class: TxClass,
6189 rect_shape: Option<(usize, usize)>,
6190) -> usize {
6191 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
6192 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
6193 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
6194 // position through the full 1D neighbour sum and offset table. Skipping
6195 // that for every class desynced the last (DC) coefficient of a
6196 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
6197 // 0, which then read one extra `BR` symbol at the max and forced a
6198 // spurious third Golomb call).
6199 if class == TxClass::TwoD && row == 0 && col == 0 {
6200 return 0;
6201 }
6202 let offsets: [(usize, usize); 5] = match class {
6203 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
6204 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
6205 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
6206 };
6207 let mag: i32 = offsets
6208 .iter()
6209 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
6210 .sum();
6211 let ctx = ((mag + 1) >> 1).min(4) as usize;
6212 match class {
6213 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
6214 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
6215 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
6216 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
6217 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
6218 // strip, which own a genuinely different table from the square one
6219 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
6220 // square table vs the real ctx 13 the rect table gives).
6221 TxClass::TwoD => {
6222 // lane-rectsplit r4: apply libaom's GENERATING RULE
6223 // (`txb_common.h:199-209`) directly instead of indexing the
6224 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
6225 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
6226 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
6227 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
6228 // so 32 consecutive entries are one COLUMN: the [`cdf`]
6229 // transcriptions are `[col][row]` and this read had them as
6230 // `[row][col]` -- the transpose, i.e. the other shape's rule with
6231 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
6232 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
6233 // pins the rule against the tables over their whole 5x5 domain.
6234 if let Some((w, h)) = rect_shape {
6235 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
6236 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
6237 }
6238 if w < h && row < 2 {
6239 return ctx + 11;
6240 }
6241 if w > h && col < 2 {
6242 return ctx + 16;
6243 }
6244 }
6245 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6246 }
6247 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
6248 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
6249 }
6250}
6251
6252/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
6253/// offsets into the padded level frame (lane-coefread): the tap pattern is a
6254/// function of the tx class alone, which is fixed for a whole transform unit,
6255/// so resolving it once per unit takes the class match and the `(dr, dc)`
6256/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
6257/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
6258/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
6259/// original `(dr, dc)` form.
6260fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
6261 match class {
6262 TxClass::TwoD => (
6263 [stride, 1, stride + 1, 2 * stride, 2],
6264 [stride, 1, stride + 1],
6265 ),
6266 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
6267 TxClass::Vert => (
6268 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
6269 [stride, 1, 2 * stride],
6270 ),
6271 }
6272}
6273
6274/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
6275/// neighbours) + 1) >> 1`, clamped to 4.
6276#[inline(always)]
6277fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
6278 let mut mag = 0u32;
6279 for &t in taps {
6280 mag += u32::from(grid[idx + t]).min(3);
6281 }
6282 (((mag + 1) >> 1) as usize).min(4)
6283}
6284
6285/// [`br_ctx`]'s neighbour sum, off flat taps.
6286#[inline(always)]
6287fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
6288 let mut mag = 0u32;
6289 for &t in taps {
6290 mag += u32::from(grid[idx + t]);
6291 }
6292 (((mag + 1) >> 1) as usize).min(6)
6293}
6294
6295/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
6296/// origin-offset tail the two coefficient readers state inline; kept as the
6297/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
6298/// flat one against.
6299#[cfg(test)]
6300fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
6301 let extra = match class {
6302 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
6303 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
6304 TxClass::Vert => neighbour(grid, stride, row + 2, col),
6305 };
6306 let mag = neighbour(grid, stride, row + 1, col)
6307 + neighbour(grid, stride, row, col + 1)
6308 + extra;
6309 let mag = (((mag + 1) >> 1).min(6)) as usize;
6310 if row == 0 && col == 0 {
6311 return mag;
6312 }
6313 let near_origin = match class {
6314 TxClass::TwoD => row < 2 && col < 2,
6315 TxClass::Horiz => col == 0,
6316 TxClass::Vert => row == 0,
6317 };
6318 if near_origin { mag + 7 } else { mag + 14 }
6319}
6320
6321/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
6322/// transposed from libaom's column-major buffer into this decoder's row-major
6323/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
6324/// against the real table). Not the square zigzag formula generalized to
6325/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
6326const SCAN_32X16: [u16; 512] = [
6327 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
6328 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
6329 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
6330 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
6331 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
6332 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
6333 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
6334 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
6335 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
6336 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
6337 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
6338 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
6339 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
6340 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
6341 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
6342 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
6343 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
6344 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
6345 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
6346 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
6347 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
6348 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
6349 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
6350 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
6351 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
6352 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
6353 509, 478, 447, 510, 479, 511,
6354];
6355
6356/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
6357/// [`SCAN_32X16`]'s doc comment).
6358const SCAN_16X32: [u16; 512] = [
6359 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,
6360 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
6361 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
6362 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
6363 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
6364 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
6365 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
6366 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
6367 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
6368 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
6369 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
6370 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
6371 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
6372 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
6373 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
6374 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
6375 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
6376 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
6377 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
6378 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
6379 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
6380 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
6381 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
6382 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
6383 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
6384 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
6385];
6386
6387/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
6388/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
6389/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
6390/// the same source).
6391const SCAN_4X8: [u16; 32] = [
6392 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,
6393 23, 26, 29, 27, 30, 31,
6394];
6395
6396/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
6397const SCAN_8X4: [u16; 32] = [
6398 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,
6399 29, 22, 15, 30, 23, 31,
6400];
6401
6402/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
6403/// [`SCAN_32X16`]'s doc comment).
6404const SCAN_16X8: [u16; 128] = [
6405 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,
6406 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
6407 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
6408 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
6409 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
6410 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
6411];
6412
6413/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
6414/// [`SCAN_32X16`]'s doc comment).
6415const SCAN_8X16: [u16; 128] = [
6416 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,
6417 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
6418 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
6419 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
6420 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
6421 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
6422];
6423
6424/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
6425/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
6426/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
6427/// scans column-major (`p = col * height + row`), so a naive copy of
6428/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
6429/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
6430/// are byte-identical to this decoder's [`SCAN_8X16`].
6431const SCAN_32X8: [u16; 256] = [
6432 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
6433 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
6434 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
6435 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
6436 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
6437 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
6438 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
6439 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
6440 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
6441 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
6442 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
6443 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
6444 222, 191, 254, 223, 255,
6445];
6446/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
6447/// 16x64 `PARTITION_VERT_4` strip).
6448const SCAN_8X32: [u16; 256] = [
6449 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,
6450 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
6451 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
6452 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
6453 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
6454 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
6455 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
6456 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
6457 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
6458 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
6459 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
6460 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
6461 239, 246, 253, 247, 254, 255,
6462];
6463/// `Default_Scan_16x4`, this decoder's own row-major transcription of
6464/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
6465/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
6466/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
6467/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
6468/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
6469/// were emitted -- a naive copy installs the transpose (class
6470/// reference-layout-not-spec).
6471const SCAN_16X4: [u16; 64] = [
6472 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,
6473 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
6474 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
6475];
6476/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
6477/// 8x32 `PARTITION_VERT_4` strip).
6478const SCAN_4X16: [u16; 64] = [
6479 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,
6480 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
6481 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
6482];
6483
6484/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
6485/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
6486/// padding already holds.
6487#[inline]
6488fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
6489 grid[row * stride + col] as i32
6490}
6491
6492/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
6493/// the rect generalization is libaom's own comment in
6494/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
6495/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
6496/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
6497/// [`decode_block_rect`] codes (see that function's own doc comment).
6498fn base_ctx_rect(
6499 grid: &[u8],
6500 stride: usize,
6501 w: usize,
6502 h: usize,
6503 row: usize,
6504 col: usize,
6505 class: TxClass,
6506) -> usize {
6507 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
6508 // the 2D class short-circuits the DC position.
6509 if class == TxClass::TwoD && row == 0 && col == 0 {
6510 return 0;
6511 }
6512 let offsets: [(usize, usize); 5] = match class {
6513 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
6514 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
6515 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
6516 };
6517 let mag: i32 = offsets
6518 .iter()
6519 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
6520 .sum();
6521 let ctx = ((mag + 1) >> 1).min(4) as usize;
6522 match class {
6523 TxClass::TwoD => {
6524 if w < h && row < 2 {
6525 return ctx + 11;
6526 }
6527 if w > h && col < 2 {
6528 return ctx + 16;
6529 }
6530 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6531 }
6532 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
6533 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
6534 // position along one axis only).
6535 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
6536 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
6537 }
6538}
6539
6540/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
6541/// neighbour-offset math itself is shape-independent, only the boundary
6542/// clamp needs the real bound in each axis.
6543/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
6544/// its body was character-for-character [`br_ctx`]'s, which
6545/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
6546#[cfg(test)]
6547fn br_ctx_rect(
6548 grid: &[u8],
6549 stride: usize,
6550 row: usize,
6551 col: usize,
6552 class: TxClass,
6553) -> usize {
6554 let extra = match class {
6555 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
6556 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
6557 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
6558 };
6559 let mag = neighbour_rect(grid, stride, row + 1, col)
6560 + neighbour_rect(grid, stride, row, col + 1)
6561 + extra;
6562 let mag = (((mag + 1) >> 1).min(6)) as usize;
6563 if row == 0 && col == 0 {
6564 return mag;
6565 }
6566 let near_origin = match class {
6567 TxClass::TwoD => row < 2 && col < 2,
6568 TxClass::Horiz => col == 0,
6569 TxClass::Vert => row == 0,
6570 };
6571 if near_origin { mag + 7 } else { mag + 14 }
6572}
6573
6574fn dc_vote(dc: Option<bool>) -> i32 {
6575 match dc {
6576 None => 0,
6577 Some(true) => -1,
6578 Some(false) => 1,
6579 }
6580}
6581
6582fn dc_sign_ctx(vote: i32) -> usize {
6583 match vote.signum() {
6584 0 => 0,
6585 -1 => 1,
6586 _ => 2,
6587 }
6588}
6589
6590/// The `tx_type` a CDF symbol names, given the width of the row it was read
6591/// from.
6592///
6593/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
6594/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
6595/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
6596/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
6597/// members are a prefix of the five.
6598///
6599/// One function rather than a `match` at each reader, so
6600/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
6601/// tests the mapping the readers actually use.
6602pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
6603 match cdf_len {
6604 17 => TxType::from_symbol_all16(t),
6605 13 => TxType::from_symbol_set2_12(t),
6606 8 => TxType::from_symbol_set1(t),
6607 _ => TxType::from_symbol(t),
6608 }
6609}
6610
6611/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
6612/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
6613/// (class `table-and-reader-move-together` -- the writer picks its symbol
6614/// through the reader's own map, so the two cannot drift).
6615pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
6616 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
6617}
6618
6619/// The remainder of a level the base and base-range syntax could not reach
6620/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
6621/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
6622pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
6623 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
6624 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
6625 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
6626 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
6627 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
6628 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
6629 // stream_can_carry` enumerates that whole value domain.
6630 //
6631 // So this refusal never names a reader gap: it is always the SYMPTOM of an
6632 // earlier desync (class `refusal-hides-a-defect`), and every historical
6633 // instance was closed by fixing that desync -- lane-dgolomb's
6634 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
6635 // Raising the cap only trades a clean refusal for silent corruption:
6636 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
6637 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
6638 // from a refusal into a frame-0 LUMA MISMATCH.
6639 let mut length = 1u32;
6640 while dec.literal(1) == 0 {
6641 length += 1;
6642 if length > 20 {
6643 return Err(unsupported("a Golomb tail longer than this decoder reads"));
6644 }
6645 }
6646 let mut x = 1u32;
6647 for _ in 1..length {
6648 x = (x << 1) | dec.literal(1);
6649 }
6650 Ok(x - 1)
6651}
6652
6653/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
6654/// [`crate::tile`]'s `write_eob`.
6655fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
6656 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
6657 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
6658
6659 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6660 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
6661 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
6662 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
6663 // `eob_multi_ctx`). Missing that split desynced the very first
6664 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
6665 // against a real aomdec trace).
6666 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
6667 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
6668 (_, Some(class1)) => class1,
6669 };
6670 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6671 let (range, value) = dec.debug_state();
6672 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
6673 }
6674 let group = dec.symbol(eob_pt) + 1;
6675 if trace {
6676 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
6677 }
6678 let bits = OFFSET_BITS[group];
6679 let mut offset = 0u32;
6680 if bits > 0 {
6681 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
6682 if trace {
6683 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
6684 }
6685 offset = top << (bits - 1);
6686 if bits > 1 {
6687 offset |= dec.literal(bits - 1);
6688 }
6689 }
6690 GROUP_START[group] + offset as usize
6691}
6692
6693/// One transform block's levels, the inverse of [`crate::tile`]'s
6694/// `write_coeffs`, returned as a `side * side` grid in raster order, along
6695/// with the transform type that grid was coded under (`DCT_DCT` when the
6696/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
6697/// 64-point transforms, which never code anything else).
6698///
6699/// # Errors
6700/// Returns an error if the `tx_type` symbol decodes to a value outside its
6701/// CDF's own set (a corrupt or unsupported bitstream) — every value the
6702/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
6703/// produce dispatches to a real inverse transform.
6704/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
6705/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
6706/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
6707/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
6708/// the plane's own predicted mode instead. Every entry this table can
6709/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
6710/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
6711/// table ever names), so unlike the CDF-coded luma path there is no
6712/// ext-tx-set membership check to fall back from here.
6713pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
6714 use crate::intra::{
6715 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
6716 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
6717 };
6718 match mode {
6719 DC_PRED | D45_PRED => TxType::DctDct,
6720 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
6721 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
6722 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
6723 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
6724 }
6725}
6726
6727/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
6728/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
6729/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
6730fn is_smooth_mode(mode: usize) -> bool {
6731 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
6732}
6733
6734/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
6735/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
6736/// nine of them inside the base/sign loops pinned nine sets of values in the
6737/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
6738/// traffic). Out of line, the loop keeps its values in registers and the
6739/// trace output is character-for-character what it was.
6740#[cold]
6741#[inline(never)]
6742fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6743 eprintln!("TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6744}
6745
6746#[cold]
6747#[inline(never)]
6748fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6749 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6750}
6751
6752#[cold]
6753#[inline(never)]
6754fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
6755 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
6756}
6757
6758#[cold]
6759#[inline(never)]
6760fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
6761 let (rng, _) = dec.debug_state();
6762 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
6763}
6764
6765#[cold]
6766#[inline(never)]
6767fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
6768 let (rng, _) = dec.debug_state();
6769 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
6770}
6771
6772#[cold]
6773#[inline(never)]
6774fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
6775 let (rng, _) = dec.debug_state();
6776 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
6777}
6778
6779#[cold]
6780#[inline(never)]
6781fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
6782 let (rng, _) = dec.debug_state();
6783 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
6784}
6785
6786#[cold]
6787#[inline(never)]
6788fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
6789 let (rng, _) = dec.debug_state();
6790 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
6791}
6792
6793fn read_coeffs(
6794 dec: &mut SymbolDecoder,
6795 coding: &mut TxbTables,
6796 scan: &[u16],
6797 skip_ctx: usize,
6798 sign_ctx: usize,
6799 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
6800 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
6801 // nothing at all; `DctDct` for every luma call and every chroma call at
6802 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
6803 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
6804 default_tx_type: TxType,
6805 // `Some((w, h))` with `w != h` when this read is a superblock-level
6806 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
6807 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
6808 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
6809 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
6810 // caller's block genuinely is `side` x `side`.
6811 rect_shape: Option<(usize, usize)>,
6812) -> Result<(Grid, TxType)> {
6813 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6814 let side = coding.side;
6815 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6816 let (range, value) = dec.debug_state();
6817 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
6818 }
6819 if crate::envflags::env_flag!("EC_ECDUMP_IN") {
6820 let (range, value) = dec.debug_state();
6821 let bit = dec.debug_bitpos();
6822 eprintln!(
6823 "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})"
6824 );
6825 }
6826 let dbg_txbskip = if coeff_trace_on() {
6827 coding.txb_skip[skip_ctx]
6828 } else {
6829 [0; 3]
6830 };
6831 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
6832 if coeff_trace_on() {
6833 let (rng, _) = dec.debug_state();
6834 eprintln!(
6835 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
6836 coding.side,
6837 all_zero as i32
6838 );
6839 }
6840 if crate::envflags::env_flag!("EC_AV1_TELL") {
6841 eprintln!(
6842 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
6843 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
6844 );
6845 }
6846 if trace {
6847 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
6848 }
6849 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6850 let (range, value) = dec.debug_state();
6851 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
6852 }
6853 if all_zero {
6854 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
6855 // shared zero grid instead of allocating and zeroing its own.
6856 return Ok((Grid::Zero(side * side), TxType::DctDct));
6857 }
6858 let mut grid = vec![0i32; side * side];
6859 let mut tx_type = default_tx_type;
6860 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
6861 // The CDF row's own width names its set (lane-cdffwd2: extended
6862 // past the original two-way intra split once wider `reduced_tx_set
6863 // == 0` inter sets joined the table): 17 slots (16 symbols) is
6864 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
6865 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
6866 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
6867 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
6868 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
6869 let len = tx_type_cdf.len();
6870 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
6871 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
6872 }
6873 let t = dec.symbol(tx_type_cdf);
6874 crate::census::tx_type(len, t);
6875 if coeff_trace_on() {
6876 let (rng, _) = dec.debug_state();
6877 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
6878 }
6879 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6880 let (range, value) = dec.debug_state();
6881 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
6882 }
6883 if trace {
6884 eprintln!("TRACE tx_type value={t} len={len}");
6885 }
6886 tx_type = tx_type_from_symbol(len, t)
6887 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
6888 }
6889
6890 let class = TxClass::of(tx_type);
6891 if class != TxClass::TwoD {
6892 hit!(TX_CLASS1_HITS);
6893 hit!(RECT_CLASS1_HITS);
6894 }
6895 let eob = read_eob(dec, coding, class);
6896 if trace {
6897 eprintln!("TRACE eob value={eob}");
6898 }
6899 let ec_trace_coeff = coeff_trace_on();
6900 if ec_trace_coeff {
6901 let (rng, _) = dec.debug_state();
6902 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
6903 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
6904 }
6905 let class_scan;
6906 let scan: &[u16] = if class == TxClass::TwoD {
6907 scan
6908 } else {
6909 class_scan = class_scan_table(side, class);
6910 &class_scan
6911 };
6912 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
6913 // coefficient `pos / side`, `pos % side` was a hardware divide where a
6914 // shift and a mask say the same thing, and the level buffer fits a fixed
6915 // 32x32 frame of stack instead of a heap allocation per transform block.
6916 debug_assert!(side.is_power_of_two() && side <= 32);
6917 let sh = side.trailing_zeros();
6918 let col_mask = side - 1;
6919 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
6920 // `stride = side + 4` columns and four spare rows, so the widest read
6921 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
6922 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
6923 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
6924 let stride = side + 4;
6925 let mut levels_buf = [0u8; 36 * 36];
6926 let levels = &mut levels_buf[..stride * stride];
6927 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
6928 // `pos >> sh` / `& mask` decomposition and load the level back out of the
6929 // padded frame just to skip the zeros. The base pass already knows both,
6930 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
6931 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
6932 // pass walks that list in reverse (the base pass runs in reverse scan
6933 // order, so reversing it is forward scan order: the same coefficients, in
6934 // the same order, with the same `c` the trace prints).
6935 let mut nz_buf = [0u16; 1024];
6936 let mut nz_n = 0usize;
6937 let (base_taps, br_taps) = flat_taps(stride, class);
6938 for scan_idx in (0..eob).rev() {
6939 let pos = scan[scan_idx] as usize;
6940 let (row, col) = (pos >> sh, pos & col_mask);
6941 let idx = row * stride + col;
6942 let level = if scan_idx == eob - 1 {
6943 let ctx = eob_coeff_ctx(scan_idx, side * side);
6944 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
6945 if trace {
6946 trace_base_eob(scan_idx, pos, row, col, ctx, v);
6947 }
6948 v
6949 } else {
6950 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
6951 if row == 0 && col == 0 {
6952 0
6953 } else {
6954 base_mag(levels, idx, &base_taps)
6955 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6956 }
6957 } else {
6958 base_ctx(levels, stride, row, col, class, rect_shape)
6959 };
6960 let v = dec.symbol(&mut coding.base[ctx]) as i32;
6961 if ec_trace_coeff {
6962 // `pos` in libaom's column-major `coeff_idx` convention, so
6963 // the ladder lines up with instrumented `aomdec`.
6964 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
6965 }
6966 if trace {
6967 trace_base(scan_idx, pos, row, col, ctx, v);
6968 }
6969 v
6970 };
6971 let level = if level > NUM_BASE_LEVELS {
6972 let ctx = {
6973 let mag = br_mag(levels, idx, &br_taps);
6974 if row == 0 && col == 0 {
6975 mag
6976 } else {
6977 let near_origin = match class {
6978 TxClass::TwoD => row < 2 && col < 2,
6979 TxClass::Horiz => col == 0,
6980 TxClass::Vert => row == 0,
6981 };
6982 if near_origin { mag + 7 } else { mag + 14 }
6983 }
6984 };
6985 let mut level = level;
6986 let mut sent = 0;
6987 loop {
6988 let k = dec.symbol(&mut coding.br[ctx]) as i32;
6989 if ec_trace_coeff {
6990 // lane-leaf8tx r3: the `br` rung was missing from THIS
6991 // path's trace, so the cross-decoder range ladder was
6992 // blind to every base-range symbol and mis-reported the
6993 // first divergence (class [[gate-blind-to-feature]]).
6994 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
6995 }
6996 if trace {
6997 trace_br(scan_idx, pos, row, col, ctx, k);
6998 }
6999 level += k;
7000 sent += BR_STEP;
7001 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
7002 break;
7003 }
7004 }
7005 level
7006 } else {
7007 level
7008 };
7009 if ec_trace_coeff && scan_idx == eob - 1 {
7010 coeff_step_base_eob_level(dec, level);
7011 }
7012 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
7013 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
7014 // added in the sign pass below, straight into `grid`), so the context
7015 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
7016 // byte gather (lane-coefbuf).
7017 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
7018 levels[idx] = level as u8;
7019 if level != 0 {
7020 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
7021 nz_n += 1;
7022 }
7023 }
7024 if ec_trace_coeff {
7025 let (rng, _) = dec.debug_state();
7026 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
7027 }
7028
7029 for &packed in nz_buf[..nz_n].iter().rev() {
7030 let c = (packed >> 4) as usize;
7031 let pos = scan[c] as usize;
7032 let level = (packed & 15) as i32;
7033 let negative = if pos == 0 {
7034 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
7035 if trace {
7036 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
7037 }
7038 v
7039 } else {
7040 dec.literal(1) == 1
7041 };
7042 if ec_trace_coeff {
7043 coeff_step_sign(dec, c, negative);
7044 }
7045 let level = if level > MAX_BR_LEVEL {
7046 let g = read_golomb(dec)?;
7047 if trace {
7048 eprintln!("TRACE golomb pos={pos} value={g}");
7049 }
7050 level + g as i32
7051 } else {
7052 level
7053 };
7054 if ec_trace_coeff {
7055 coeff_step_post_golomb(dec, c, level);
7056 }
7057 grid[pos] = if negative { -level } else { level };
7058 }
7059 Ok((Grid::Own(grid), tx_type))
7060}
7061
7062/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
7063/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
7064/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
7065/// can ever produce, since every `tx_type` this decoder's rect sets can read
7066/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
7067/// rather than guess-decode if a non-2D class ever shows up here, since
7068/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
7069/// form for those.
7070
7071fn read_coeffs_rect(
7072 dec: &mut SymbolDecoder,
7073 coding: &mut TxbTables,
7074 scan: &[u16],
7075 w: usize,
7076 h: usize,
7077 skip_ctx: usize,
7078 sign_ctx: usize,
7079 default_tx_type: TxType,
7080) -> Result<(Grid, TxType)> {
7081 let rect_trace = coeff_trace_on();
7082 let entry_rng = dec.debug_state().0;
7083 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
7084 if rect_trace {
7085 eprintln!(
7086 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
7087 all_zero as i32,
7088 dec.debug_state().0
7089 );
7090 }
7091 if all_zero {
7092 return Ok((Grid::Zero(w * h), TxType::DctDct));
7093 }
7094 let mut grid = vec![0i32; w * h];
7095 hit!(RECT_COEFF_TU_HITS);
7096 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
7097 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
7098 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
7099 // context offsets -- both of which now have rect forms
7100 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
7101 // The rect sets that carry no symbol at all still pass `None` here.
7102 let mut tx_type = default_tx_type;
7103 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
7104 let len = tx_type_cdf.len();
7105 let t = dec.symbol(tx_type_cdf);
7106 crate::census::tx_type(len, t);
7107 tx_type = tx_type_from_symbol(len, t)
7108 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
7109 if rect_trace {
7110 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
7111 }
7112 }
7113 let class = TxClass::of(tx_type);
7114 if class != TxClass::TwoD {
7115 hit!(TX_CLASS1_HITS);
7116 }
7117 let eob = read_eob(dec, coding, class);
7118 if rect_trace {
7119 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
7120 }
7121 let class_scan;
7122 let scan: &[u16] = if class == TxClass::TwoD {
7123 scan
7124 } else {
7125 class_scan = class_scan_table_wh(w, h, class);
7126 &class_scan
7127 };
7128 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
7129 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
7130 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
7131 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
7132 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
7133 // mask rather than a hardware divide.
7134 let stride = w + 4;
7135 let n = stride * (h + 4);
7136 if !(w.is_power_of_two() && n <= 36 * 36) {
7137 panic!("rect coeff scratch w={w} h={h} n={n}");
7138 }
7139 let (mut b96, mut b256, mut b768);
7140 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
7141 let levels: &mut [u8] = if n <= 96 {
7142 b96 = [0u8; 96];
7143 &mut b96[..n]
7144 } else if n <= 256 {
7145 b256 = [0u8; 256];
7146 &mut b256[..n]
7147 } else {
7148 b768 = [0u8; 768];
7149 &mut b768[..n]
7150 };
7151 let wsh = w.trailing_zeros();
7152 let wmask = w - 1;
7153 // lane-coefread: the non-zero list [`read_coeffs`] documents.
7154 let mut nz_buf = [0u16; 1024];
7155 let mut nz_n = 0usize;
7156 let (base_taps, br_taps) = flat_taps(stride, class);
7157 let (wlt, wgt) = (w < h, w > h);
7158 for scan_idx in (0..eob).rev() {
7159 let pos = scan[scan_idx] as usize;
7160 let (row, col) = (pos >> wsh, pos & wmask);
7161 let idx = row * stride + col;
7162 // libaom's column-major `coeff_idx`, for ladder comparison.
7163 let _apos = col * h + row;
7164 let level = if scan_idx == eob - 1 {
7165 let ctx = eob_coeff_ctx(scan_idx, w * h);
7166 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
7167 if rect_trace {
7168 eprintln!(
7169 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
7170 dec.debug_state().0
7171 );
7172 }
7173 v
7174 } else {
7175 let ctx = if class == TxClass::TwoD {
7176 if row == 0 && col == 0 {
7177 0
7178 } else {
7179 let m = base_mag(levels, idx, &base_taps);
7180 if wlt && row < 2 {
7181 m + 11
7182 } else if wgt && col < 2 {
7183 m + 16
7184 } else {
7185 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
7186 }
7187 }
7188 } else {
7189 base_ctx_rect(levels, stride, w, h, row, col, class)
7190 };
7191 let v = dec.symbol(&mut coding.base[ctx]) as i32;
7192 if rect_trace {
7193 eprintln!(
7194 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
7195 dec.debug_state().0
7196 );
7197 }
7198 v
7199 };
7200 let level = if level > NUM_BASE_LEVELS {
7201 let ctx = {
7202 let mag = br_mag(levels, idx, &br_taps);
7203 if row == 0 && col == 0 {
7204 mag
7205 } else {
7206 let near_origin = match class {
7207 TxClass::TwoD => row < 2 && col < 2,
7208 TxClass::Horiz => col == 0,
7209 TxClass::Vert => row == 0,
7210 };
7211 if near_origin { mag + 7 } else { mag + 14 }
7212 }
7213 };
7214 let mut level = level;
7215 let mut sent = 0;
7216 loop {
7217 let k = dec.symbol(&mut coding.br[ctx]) as i32;
7218 if rect_trace {
7219 eprintln!(
7220 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
7221 dec.debug_state().0
7222 );
7223 }
7224 level += k;
7225 sent += BR_STEP;
7226 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
7227 break;
7228 }
7229 }
7230 level
7231 } else {
7232 level
7233 };
7234 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
7235 levels[idx] = level as u8;
7236 if level != 0 {
7237 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
7238 nz_n += 1;
7239 }
7240 if rect_trace {
7241 let (rng, _) = dec.debug_state();
7242 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
7243 }
7244 }
7245 if rect_trace {
7246 let (rng, _) = dec.debug_state();
7247 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
7248 }
7249 for &packed in nz_buf[..nz_n].iter().rev() {
7250 let pos = scan[(packed >> 4) as usize] as usize;
7251 let level = (packed & 15) as i32;
7252 let negative = if pos == 0 {
7253 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
7254 } else {
7255 dec.literal(1) == 1
7256 };
7257 if rect_trace {
7258 let (rng, _) = dec.debug_state();
7259 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative));
7260 }
7261 let level = if level > MAX_BR_LEVEL {
7262 let g = read_golomb(dec)?;
7263 level + g as i32
7264 } else {
7265 level
7266 };
7267 grid[pos] = if negative { -level } else { level };
7268 }
7269 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
7270 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
7271 // grids differ is a reader defect, one whose grids agree is a transform
7272 // defect.
7273 if crate::envflags::env_flag!("EC_DQCOEFF") {
7274 let nz: Vec<String> = grid
7275 .iter()
7276 .enumerate()
7277 .filter(|&(_, &v)| v != 0)
7278 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
7279 .collect();
7280 eprintln!("OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}", nz.join(","));
7281 }
7282 Ok((Grid::Own(grid), tx_type))
7283}
7284
7285/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
7286/// [`read_plane`] family already has.
7287///
7288/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
7289/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
7290/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
7291/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
7292/// enforces that for every strip that reads its chroma through it, but the rect
7293/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
7294/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
7295/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
7296/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
7297/// chroma read desyncs at the FIRST rect leaf of the frame and every later
7298/// symbol -- and therefore every later pixel -- is decoded from the wrong
7299/// place, without ever tripping a refusal (the desynced values stay inside
7300/// every coded alphabet).
7301fn read_chroma_coeffs_rect(
7302 dec: &mut SymbolDecoder,
7303 coding: &mut TxbTables,
7304 scan: &[u16],
7305 w: usize,
7306 h: usize,
7307 skip_ctx: usize,
7308 sign_ctx: usize,
7309 default_tx_type: TxType,
7310 fctx: &crate::decode::FrameCtx,
7311) -> Result<(Grid, TxType)> {
7312 if mono(fctx) {
7313 return Ok((Grid::Zero(w * h), TxType::DctDct));
7314 }
7315 read_coeffs_rect(dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type)
7316}
7317
7318/// What one coded block leaves behind for the blocks that read it as a
7319/// neighbour: whether it coded anything at all, and the sign of its DC —
7320/// [`crate::tile`]'s own private `Neighbour`.
7321#[derive(Clone, Copy, Default)]
7322struct Neighbour {
7323 /// The transform unit's cumulative coefficient level (spec `cul_level`,
7324 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
7325 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
7326 /// boolean (`level != 0`) is enough for every context this decoder read
7327 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
7328 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
7329 /// needs the actual magnitude tier of its above/left neighbours, not
7330 /// just whether they coded anything.
7331 level: u8,
7332 dc: Option<bool>,
7333}
7334
7335/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
7336/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
7337/// grid is dropped, never a panic. One `memset` per grid row instead of a
7338/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
7339/// is contiguous, so this writes exactly the cells the cell loop did,
7340/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
7341/// next row.
7342#[inline]
7343fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
7344 let end = (start + n).min(dst.len());
7345 if start < end {
7346 dst[start..end].fill(v);
7347 }
7348}
7349
7350fn neighbour_state(grid: &[i32]) -> Neighbour {
7351 // lane-coefgrid: the shared zero grid sums to zero by construction; this
7352 // sum has no early exit, so the 60% of units that code nothing used to
7353 // walk their whole grid here.
7354 if is_zero_grid(grid) {
7355 return Neighbour::default();
7356 }
7357 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
7358 Neighbour {
7359 level: cul.min(7) as u8,
7360 dc: (grid[0] != 0).then_some(grid[0] < 0),
7361 }
7362}
7363
7364/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
7365/// transform unit smaller than the block it sits in): `top`/`left` are the
7366/// above/left neighbours' magnitude tiers, each already clamped to 4.
7367pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
7368 [1, 2, 2, 2, 3],
7369 [2, 4, 4, 4, 5],
7370 [2, 4, 4, 4, 5],
7371 [2, 4, 4, 4, 5],
7372 [3, 5, 5, 5, 6],
7373];
7374
7375/// The `skip` flag, its written-instrument bit, and the covering coded
7376/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
7377/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
7378/// nothing else, so a block's row is one fill instead of four, and the
7379/// deblocker's `pu_edge` reads origin and dims off one cache line.
7380#[derive(Clone, Copy)]
7381struct BlkCell {
7382 skip: bool,
7383 written: bool,
7384 org: [u16; 2],
7385 dim: [u8; 2],
7386}
7387
7388/// The neighbour state a block's contexts are read from — a duplicate of
7389/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
7390/// territory this round), kept at the same two granularities the real writer
7391/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
7392/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
7393/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
7394/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
7395/// chroma transform straddling the true, odd-sized frame edge see its
7396/// neighbour's state clamped at its own subsampled edge rather than luma's.
7397#[derive(Clone)]
7398struct Neighbours {
7399 above: Vec<[Neighbour; 3]>,
7400 left: Vec<[Neighbour; 3]>,
7401 above_mode: Vec<usize>,
7402 left_mode: Vec<usize>,
7403 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
7404 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
7405 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
7406 /// luma one -- the same block can (and often does) code a different
7407 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
7408 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
7409 /// within-block neighbour finer than this grid) is luma-only -- a known,
7410 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
7411 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
7412 above_uv_mode: Vec<usize>,
7413 left_uv_mode: Vec<usize>,
7414 above_side: Vec<usize>,
7415 left_side: Vec<usize>,
7416 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
7417 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
7418 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
7419 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
7420 /// array cannot tell the second leaf's partition symbol that the first
7421 /// one was coded at 8x8.
7422 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
7423 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
7424 above_side_mi: Vec<u8>,
7425 left_side_mi: Vec<u8>,
7426 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
7427 /// / row, with the mi position it was written at
7428 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
7429 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
7430 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
7431 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
7432 /// leaf whose neighbour is another split group needs that group's leaf 3
7433 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
7434 /// and read only by [`decode_leaf_split4`]; the position guard makes it
7435 /// fall back to the coarse slot whenever the real neighbour was a block
7436 /// of 8x8 or larger (whose one mode is correct for every row it spans).
7437 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
7438 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
7439 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
7440 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
7441 /// frame is 65536 px = 16384 mi).
7442 sub8_mode_col: Vec<(u16, u8)>,
7443 sub8_mode_row: Vec<(u16, u8)>,
7444 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
7445 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
7446 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
7447 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
7448 /// the leaf above writes the same row slot the block to the left owns.
7449 uv_mode_col: Vec<(u16, u8)>,
7450 uv_mode_row: Vec<(u16, u8)>,
7451 /// Every mi cell's own `uv_mode`, the mi grid libaom's
7452 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
7453 /// blockd.h). lane-t900 r12: the one-slot-per-column
7454 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
7455 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
7456 /// overwrote the row the pair's chroma-ref half then wanted to read --
7457 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
7458 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
7459 uv_mode_grid: Vec<u8>,
7460 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
7461 /// every other band here).
7462 uv_grid_cols: usize,
7463 /// Whether the block above/left of this column/row was coded `skip` --
7464 /// an inter frame's own `skip` context (spec `SkipContext`), which the
7465 /// key-frame writer never tracks (its skip context is always zero); a
7466 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
7467 /// `left_skip`.
7468 above_skip: Vec<bool>,
7469 left_skip: Vec<bool>,
7470 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
7471 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
7472 /// pixels last written over each unit by `set_txfm_ctxs`/
7473 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
7474 /// symbol reads its context from (lane-txselect, spec 5.11.17).
7475 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
7476 /// array is exactly libaom's per-superblock-row reset, since each mi row
7477 /// is only ever visited inside one superblock row.
7478 above_txfm: Vec<u8>,
7479 left_txfm: Vec<u8>,
7480 /// Whether the block above/left of this column/row coded `skip_mode`
7481 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
7482 /// lane-av1comp round 14.
7483 above_skip_mode: Vec<bool>,
7484 left_skip_mode: Vec<bool>,
7485 /// Whether the block above/left was coded inter -- the `is_inter`
7486 /// context (spec `av1_get_intra_inter_context`), a duplicate of
7487 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
7488 above_inter: Vec<bool>,
7489 left_inter: Vec<bool>,
7490 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
7491 /// alphabet) the block above/left of this column/row coded, or `-1` for
7492 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
7493 /// functions (`mvstack::ref_ctx` family) need the real reference, not
7494 /// just "was it inter" (lane-av1refs: every inter block used to be
7495 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
7496 /// enough).
7497 above_ref: Vec<i8>,
7498 left_ref: Vec<i8>,
7499 /// The block above/left's *second* reference frame when it was coded
7500 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
7501 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
7502 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
7503 /// `i8`, once a compound `read_ref_frames` lands.
7504 /// lane-publish2 audit: the "always `None` today" note this doc used to
7505 /// carry is long stale -- compound blocks do occur, and
7506 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
7507 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
7508 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
7509 /// [`crate::mvstack::NeighbourRef`] construction (class
7510 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
7511 above_ref1: Vec<Option<i8>>,
7512 left_ref1: Vec<Option<i8>>,
7513 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
7514 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
7515 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
7516 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
7517 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
7518 above_comp_group_idx: Vec<u8>,
7519 left_comp_group_idx: Vec<u8>,
7520 above_compound_idx: Vec<u8>,
7521 left_compound_idx: Vec<u8>,
7522 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
7523 /// `3` = "no info": an intra neighbour or the frame's own border) of the
7524 /// block above/left of this column/row -- spec
7525 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
7526 above_filter: Vec<[u8; 2]>,
7527 left_filter: Vec<[u8; 2]>,
7528 mi_cols: usize,
7529 mi_rows: usize,
7530 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
7531 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
7532 /// 7.15) never filters an 8x8 luma block whose covering coded block read
7533 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
7534 /// grain [`Self::record_mi`] already writes at), read back at 8x8
7535 /// granularity by [`apply_cdef`] since `skip` is constant across every
7536 /// mi cell one coded block covers.
7537 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
7538 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
7539 /// the `skip` bit at this mi cell during this frame. A fresh
7540 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
7541 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
7542 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
7543 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
7544 /// unobservable from the pixels alone. Counted by
7545 /// [`cdef_unwritten_skip_units`].
7546 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
7547 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
7548 /// which re-enables the loop filter at a prediction boundary between two
7549 /// skipped inter blocks (lane-mergefix r4). Written by
7550 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
7551 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
7552 /// that cell -- the other half of `pu_edge`: libaom tests the edge
7553 /// coordinate against the block's size in the FILTERED plane's own
7554 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
7555 blk_grid: Vec<BlkCell>,
7556 skip_grid_cols_mi: usize,
7557 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
7558 /// never splits a coded block's transform below its own size (round 2:
7559 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
7560 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
7561 /// edge-length lookup (`apply_deblock`).
7562 tx_grid: Vec<u8>,
7563 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
7564 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
7565 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
7566 tx_h_grid: Vec<u8>,
7567 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
7568 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
7569 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
7570 /// does NOT follow luma's `tx_depth` split, so deriving it as
7571 /// `tx_grid / 2` invented chroma transform edges the deblocker then
7572 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
7573 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
7574 /// every caller routes through.
7575 uv_tx_grid: Vec<u8>,
7576 uv_tx_h_grid: Vec<u8>,
7577 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
7578 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
7579 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
7580 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
7581 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
7582 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
7583 /// reference onto `LAST_FRAME`'s own delta).
7584 ref_grid: Vec<i8>,
7585 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
7586 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
7587 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
7588 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
7589 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
7590 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
7591 /// to know which mode produced the value.
7592 delta_lf_grid: Vec<[i8; 4]>,
7593 /// The block above/left's own palette-Y size (0 = not a palette block)
7594 /// and its base colours -- `av1_get_palette_mode_ctx`/
7595 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
7596 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
7597 above_palette_size: Vec<u8>,
7598 left_palette_size: Vec<u8>,
7599 above_palette_colors: Vec<[u16; 8]>,
7600 left_palette_colors: Vec<[u16; 8]>,
7601 /// As the four fields above, for the neighbour's own chroma (U-channel
7602 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
7603 /// palette size/colours (lane-palette2 r1).
7604 above_palette_uv_size: Vec<u8>,
7605 left_palette_uv_size: Vec<u8>,
7606 above_palette_uv_colors: Vec<[u16; 8]>,
7607 left_palette_uv_colors: Vec<[u16; 8]>,
7608 /// This tile's own top-left corner, in 4x4 mode-info units (spec
7609 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
7610 /// neighbour" check compares against this instead of literal `0`, since a
7611 /// block at the tile's own top/left edge has no usable neighbour even
7612 /// though a decoded block sits there in the picture (spec `decode_tile`'s
7613 /// per-tile `clear_above_context`/`left_available`/`up_available`).
7614 /// `0` for a single-tile frame, matching every existing caller exactly.
7615 tile_row0_mi: usize,
7616 tile_col0_mi: usize,
7617}
7618
7619#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7620impl Neighbours {
7621 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
7622 /// true (unpadded) size in 4x4 mode-info units.
7623 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize, fctx: &crate::decode::FrameCtx) -> Self {
7624 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
7625 // neighbour state over the whole 64-row extent, past the frame's last
7626 // mi row (mi_rows 198, block rows 192..208). libaom's own context
7627 // buffers are superblock-aligned for exactly that reason
7628 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
7629 // side arrays to a superblock multiple and leave those cells unread --
7630 // every availability check uses the true `mi_rows`/`mi_cols` below.
7631 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
7632 let (cols, rows) = (
7633 cols.next_multiple_of(sb_sub),
7634 rows.next_multiple_of(sb_sub),
7635 );
7636 Self {
7637 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
7638 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
7639 above_mode: vec![DC_PRED; cols],
7640 left_mode: vec![DC_PRED; rows],
7641 above_uv_mode: vec![DC_PRED; cols],
7642 left_uv_mode: vec![DC_PRED; rows],
7643 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
7644 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
7645 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
7646 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
7647 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
7648 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
7649 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
7650 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
7651 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
7652 uv_grid_cols: cols * (SUB / MI),
7653 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
7654 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
7655 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
7656 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
7657 // 16x16 block beside it, which a SUB-grid slot cannot name
7658 // (class context-read-from-one-cell).
7659 above_skip: vec![false; cols * (SUB / MI)],
7660 left_skip: vec![false; rows * (SUB / MI)],
7661 above_skip_mode: vec![false; cols * (SUB / MI)],
7662 left_skip_mode: vec![false; rows * (SUB / MI)],
7663 above_inter: vec![false; cols * (SUB / MI)],
7664 left_inter: vec![false; rows * (SUB / MI)],
7665 above_ref: vec![-1; cols * (SUB / MI)],
7666 left_ref: vec![-1; rows * (SUB / MI)],
7667 above_ref1: vec![None; cols * (SUB / MI)],
7668 left_ref1: vec![None; rows * (SUB / MI)],
7669 above_comp_group_idx: vec![0; cols * (SUB / MI)],
7670 left_comp_group_idx: vec![0; rows * (SUB / MI)],
7671 above_compound_idx: vec![0; cols * (SUB / MI)],
7672 left_compound_idx: vec![0; rows * (SUB / MI)],
7673 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
7674 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
7675 mi_cols,
7676 mi_rows,
7677 blk_grid: vec![
7678 BlkCell { skip: false, written: false, org: [0; 2], dim: [1; 2] };
7679 cols * (SUB / MI) * rows * (SUB / MI)
7680 ],
7681 skip_grid_cols_mi: cols * (SUB / MI),
7682 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7683 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7684 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7685 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7686 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
7687 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
7688 above_palette_size: vec![0; cols * (SUB / MI)],
7689 left_palette_size: vec![0; rows * (SUB / MI)],
7690 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
7691 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
7692 above_palette_uv_size: vec![0; cols * (SUB / MI)],
7693 left_palette_uv_size: vec![0; rows * (SUB / MI)],
7694 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
7695 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
7696 tile_row0_mi: 0,
7697 tile_col0_mi: 0,
7698 }
7699 }
7700
7701 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
7702 /// tile's own column span (`col1_mi` exclusive), plus recording
7703 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
7704 /// availability check below. Left context resets every superblock row
7705 /// regardless of tile ([`Self::start_row`], already called once per SB
7706 /// row by every caller) so it needs no tile-specific reset here.
7707 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize, fctx: &crate::decode::FrameCtx) {
7708 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
7709 // are tile-relative, same as every other neighbour lookup here.
7710 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
7711 self.tile_row0_mi = row0_mi;
7712 self.tile_col0_mi = col0_mi;
7713 let end = col1_mi.min(self.above.len());
7714 for i in col0_mi.min(end)..end {
7715 self.above[i] = Default::default();
7716 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
7717 }
7718 let (sc0, sc1) = (
7719 col0_mi / (SUB / MI),
7720 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
7721 );
7722 for i in sc0.min(sc1)..sc1 {
7723 self.above_mode[i] = DC_PRED;
7724 self.above_side[i] = NO_NEIGHBOUR_SIDE;
7725 }
7726 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
7727 // the tile's own mi column span directly.
7728 let mend = col1_mi.min(self.above_skip.len());
7729 for i in col0_mi.min(mend)..mend {
7730 self.above_skip[i] = false;
7731 self.above_skip_mode[i] = false;
7732 self.above_inter[i] = false;
7733 self.above_ref[i] = -1;
7734 self.above_ref1[i] = None;
7735 self.above_comp_group_idx[i] = 0;
7736 self.above_compound_idx[i] = 0;
7737 self.above_filter[i] = [3u8; 2];
7738 }
7739 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
7740 // stale `(row, mode)` from the tile to the LEFT names an mi row this
7741 // tile's first block would read as its own above neighbour.
7742 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
7743 for i in col0_mi.min(mcol_end)..mcol_end {
7744 self.sub8_mode_col[i] = (u16::MAX, 0);
7745 self.uv_mode_col[i] = (u16::MAX, 0);
7746 }
7747 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
7748 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
7749 // not zero) -- without it a second tile column reads the first one's
7750 // resolved transform sizes as its own above context.
7751 let tend = col1_mi.min(self.above_txfm.len());
7752 for i in col0_mi.min(tend)..tend {
7753 self.above_txfm[i] = TXFM_CTX_INIT;
7754 }
7755 }
7756
7757 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
7758 /// for a non-palette block, clearing any stale neighbour state) into every
7759 /// [`SUB`]-grid cell it covers on both the above and left edges --
7760 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
7761 /// call sites are all square blocks).
7762 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
7763 self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors);
7764 }
7765
7766 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
7767 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
7768 /// [`Self::record`]): a true rect strip's above/left neighbour spans
7769 /// differ.
7770 fn record_palette_y_rect(
7771 &mut self,
7772 mi: (usize, usize),
7773 w: usize,
7774 h: usize,
7775 size: usize,
7776 colors: [u16; 8],
7777 ) {
7778 let (r, c) = mi;
7779 if crate::envflags::env_flag!("EC_PALPUB") {
7780 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
7781 }
7782 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
7783 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
7784 // cell immediately left of the block, not its 16px [`SUB`] cell. The
7785 // old SUB grid let a 16x8 strip pair share one slot, so the second
7786 // strip of mi(0,8) read the FIRST strip's palette size and the colour
7787 // cache came out one entry short (class [[context-read-from-one-cell]]).
7788 for cell in 0..(w / MI).max(1) {
7789 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
7790 *e = size as u8;
7791 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
7792 // neighbour's colours only where its palette size > 0, so a
7793 // non-palette block need not stamp 16 bytes of zeroes here.
7794 if size > 0 {
7795 self.above_palette_colors[c + cell] = colors;
7796 }
7797 }
7798 }
7799 for cell in 0..(h / MI).max(1) {
7800 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
7801 *e = size as u8;
7802 if size > 0 {
7803 self.left_palette_colors[r + cell] = colors;
7804 }
7805 }
7806 }
7807 }
7808
7809 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
7810 /// neighbours that are themselves a palette-Y block, plus
7811 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
7812 /// cache (pred_common.c:73).
7813 ///
7814 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
7815 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
7816 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
7817 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
7818 /// the ctx too made every superblock in the frame's second SB row read
7819 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
7820 /// palette block decoded as "no palette" and the tile desynced from
7821 /// there (class [[cdf-row-held-constant]]).
7822 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
7823 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7824 }
7825
7826 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
7827 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
7828 /// drops the above neighbour on a 64-px superblock boundary
7829 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
7830 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
7831 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
7832 /// every strip in an SB's top cell row, which libaom does not do.
7833 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
7834 let (r, c) = mi;
7835 let above_ok = r % 16 != 0;
7836 // `xd->above_mbmi` exists for every row but the tile's own first.
7837 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
7838 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
7839 (usize::from(self.above_palette_size[c]), self.above_palette_colors[c])
7840 } else {
7841 (0, [0u16; 8])
7842 };
7843 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
7844 // is NULL whenever the block sits at its TILE's own left column
7845 // (`left_available`), not the frame's -- without this guard a second
7846 // tile column reads the previous tile's palette colours into its cache
7847 // and its `palette_y_mode` ctx.
7848 let left_ok = c > self.tile_col0_mi;
7849 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
7850 (usize::from(self.left_palette_size[r]), self.left_palette_colors[r])
7851 } else {
7852 (0, [0u16; 8])
7853 };
7854 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
7855 let mut cache = Vec::with_capacity(16);
7856 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7857 if cache.last() != Some(&v) {
7858 cache.push(v);
7859 }
7860 };
7861 let (mut ai, mut li) = (0usize, 0usize);
7862 while ai < above_n && li < left_n {
7863 let (va, vl) = (above_colors[ai], left_colors[li]);
7864 if vl < va {
7865 push_dedup(&mut cache, vl);
7866 li += 1;
7867 } else {
7868 push_dedup(&mut cache, va);
7869 ai += 1;
7870 if vl == va {
7871 li += 1;
7872 }
7873 }
7874 }
7875 while ai < above_n {
7876 push_dedup(&mut cache, above_colors[ai]);
7877 ai += 1;
7878 }
7879 while li < left_n {
7880 push_dedup(&mut cache, left_colors[li]);
7881 li += 1;
7882 }
7883 (ctx, cache)
7884 }
7885
7886 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
7887 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
7888 /// same way (lane-palette2 r1).
7889 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
7890 self.record_palette_uv_rect(
7891 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
7892 side,
7893 side,
7894 size,
7895 colors,
7896 );
7897 }
7898
7899 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
7900 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
7901 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
7902 /// luma resolution regardless of which plane the recorded state is for).
7903 fn record_palette_uv_rect(
7904 &mut self,
7905 mi: (usize, usize),
7906 w: usize,
7907 h: usize,
7908 size: usize,
7909 colors: [u16; 8],
7910 ) {
7911 let (r, c) = mi;
7912 // mi granularity, see [`Self::record_palette_y_rect`].
7913 for cell in 0..(w / MI).max(1) {
7914 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
7915 *e = size as u8;
7916 if size > 0 {
7917 self.above_palette_uv_colors[c + cell] = colors;
7918 }
7919 }
7920 }
7921 for cell in 0..(h / MI).max(1) {
7922 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
7923 *e = size as u8;
7924 if size > 0 {
7925 self.left_palette_uv_colors[r + cell] = colors;
7926 }
7927 }
7928 }
7929 }
7930
7931 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
7932 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
7933 /// no neighbour lookup at all (it is this block's own just-decided Y
7934 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
7935 /// so only the cache is wanted here.
7936 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
7937 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7938 }
7939
7940 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
7941 /// [`Self::palette_ctx_and_cache_mi`].
7942 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
7943 let (r, c) = mi;
7944 let above_ok = r % 16 != 0;
7945 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
7946 (usize::from(self.above_palette_uv_size[c]), self.above_palette_uv_colors[c])
7947 } else {
7948 (0, [0u16; 8])
7949 };
7950 // Same tile-relative left availability as the luma cache above.
7951 let left_ok = c > self.tile_col0_mi;
7952 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
7953 (usize::from(self.left_palette_uv_size[r]), self.left_palette_uv_colors[r])
7954 } else {
7955 (0, [0u16; 8])
7956 };
7957 let mut cache = Vec::with_capacity(16);
7958 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7959 if cache.last() != Some(&v) {
7960 cache.push(v);
7961 }
7962 };
7963 let (mut ai, mut li) = (0usize, 0usize);
7964 while ai < above_n && li < left_n {
7965 let (va, vl) = (above_colors[ai], left_colors[li]);
7966 if vl < va {
7967 push_dedup(&mut cache, vl);
7968 li += 1;
7969 } else {
7970 push_dedup(&mut cache, va);
7971 ai += 1;
7972 if vl == va {
7973 li += 1;
7974 }
7975 }
7976 }
7977 while ai < above_n {
7978 push_dedup(&mut cache, above_colors[ai]);
7979 ai += 1;
7980 }
7981 while li < left_n {
7982 push_dedup(&mut cache, left_colors[li]);
7983 li += 1;
7984 }
7985 cache
7986 }
7987
7988 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
7989 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
7990 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
7991 /// units as [`Self::fill_skip_grid`].
7992 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx) {
7993 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
7994 }
7995
7996 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
7997 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
7998 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
7999 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
8000 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
8001 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
8002 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
8003 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
8004 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
8005 /// block's published transform extent to its own size is exactly that
8006 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
8007 /// that needs it is the 128 root, whose chroma extent (64) is the one
8008 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
8009 /// never suppressed (libaom's `is_inter_block` term), so this is called
8010 /// only from the skipped-inter branch.
8011 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
8012 let (mi_r, mi_c) = at_mi;
8013 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
8014 for rr in 0..h_mi {
8015 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
8016 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
8017 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
8018 }
8019 }
8020
8021 fn fill_lf_grid_rect(
8022 &mut self,
8023 at_mi: (usize, usize),
8024 w_mi: usize,
8025 h_mi: usize,
8026 tx_px: u8,
8027 tx_h_px: u8,
8028 ref_frame: i8, fctx: &crate::decode::FrameCtx,
8029 ) {
8030 let (mi_r, mi_c) = at_mi;
8031 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
8032 // half its luma one (min 4 px, the smallest transform), capped at
8033 // TX_32X32 -- independent of this block's luma `tx_depth`.
8034 let uv_tx_w = (((w_mi * MI) >> ss_x(fctx)).max(4).min(32)) as u8;
8035 let uv_tx_h = (((h_mi * MI) >> ss_y(fctx)).max(4).min(32)) as u8;
8036 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
8037 eprintln!("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}");
8038 }
8039 crate::census::tx(tx_px, tx_h_px);
8040 let cur = fctx.current_delta_lf.with(|c| c.get());
8041 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
8042 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
8043 } else {
8044 [cur[0].clamp(-63, 63) as i8; 4]
8045 };
8046 for rr in 0..h_mi {
8047 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
8048 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
8049 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
8050 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
8051 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
8052 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
8053 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
8054 }
8055 if fctx.intra_only.with(std::cell::Cell::get) {
8056 // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size,
8057 // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi),
8058 // xd)` for EVERY block, an intra-only frame's included, and
8059 // `get_tx_size_context` / `txfm_partition_context` read those two
8060 // `TXFM_CONTEXT` bands. This grid carries the same transform size
8061 // over the same footprint, so the publish is this write: the
8062 // `skip && is_inter` term is 0 for every intra-only block that is
8063 // not an intrabc one, and the bodies that can code an intrabc
8064 // block publish their own (the term is then the BLOCK size, a value
8065 // this grid cannot express -- see `decode_block`/`decode_leaf8`).
8066 // Inter frames publish at their own sites and are excluded here
8067 // because their skipped-block term needs the block size too.
8068 txfm_partition_update_rect(
8069 self,
8070 at_mi,
8071 (tx_px as usize, tx_h_px as usize),
8072 (w_mi * MI, h_mi * MI),
8073 );
8074 // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`),
8075 // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size
8076 // instead of its transform band. Every block stamps its own cells
8077 // here; the intrabc bodies re-stamp theirs `true` afterwards
8078 // (`record_intrabc_inter_bands`).
8079 for i in 0..w_mi {
8080 if let Some(cell) = self.above_inter.get_mut(mi_c + i) {
8081 *cell = false;
8082 }
8083 }
8084 for i in 0..h_mi {
8085 if let Some(cell) = self.left_inter.get_mut(mi_r + i) {
8086 *cell = false;
8087 }
8088 }
8089 }
8090 // lane-av1-intrabc r4: publish this coded block's own mi footprint
8091 // into the intrabc MV grid's block-COVERAGE map -- every coded block,
8092 // not just the intrabc ones. A later intrabc block's DV predictor is
8093 // built by libaom's own row/col scans over `xd->mi[]`, which holds an
8094 // `MB_MODE_INFO` for EVERY block and steps by
8095 // `mi_size_wide/height[candidate->bsize]`; without this footprint a
8096 // non-intrabc neighbour reads as uncovered and the scan advances it
8097 // by one cell instead of by its real width.
8098 fctx.intrabc_mi_grid.with(|g| {
8099 if let Some((grid, _, _)) = g.borrow_mut().as_mut() {
8100 grid.cover_rect(mi_r, mi_c, w_mi, h_mi);
8101 }
8102 });
8103 }
8104
8105 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
8106 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
8107 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
8108 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
8109 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
8110 /// dims from the LEAF span and so invented chroma transform edges the
8111 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
8112 /// are already correct from the block's own fill over the same span.
8113 fn fill_lf_grid_leaf_luma(
8114 &mut self,
8115 at_mi: (usize, usize),
8116 w_mi: usize,
8117 h_mi: usize,
8118 tx_px: u8,
8119 tx_h_px: u8,
8120 ) {
8121 let (mi_r, mi_c) = at_mi;
8122 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
8123 eprintln!("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}");
8124 }
8125 for rr in 0..h_mi {
8126 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
8127 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
8128 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
8129 }
8130 }
8131
8132 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
8133 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
8134 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
8135 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
8136 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
8137 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
8138 }
8139
8140 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
8141 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
8142 let (mi_r, mi_c) = at_mi;
8143 if skip && w_mi != h_mi {
8144 hit!(RECT_SKIP_BAND_HITS);
8145 }
8146 // lane-census: an INTRA frame's blocks never reach the inter
8147 // publisher, and this one is what every coded block writes.
8148 crate::census::block_intra_frame(w_mi, h_mi, skip);
8149 for rr in 0..h_mi {
8150 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
8151 fill_span(
8152 &mut self.blk_grid,
8153 start,
8154 w_mi,
8155 BlkCell {
8156 skip,
8157 written: true,
8158 org: [mi_r as u16, mi_c as u16],
8159 dim: [w_mi as u8, h_mi as u8],
8160 },
8161 );
8162 }
8163 }
8164
8165 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
8166 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
8167 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
8168 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
8169 /// straddle the region with a mix of skip/non-skip blocks).
8170 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
8171 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
8172 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
8173 /// filtered edge's two sides are each exactly one coded block wide.
8174 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
8175 self.blk_grid
8176 .get(mi_r * self.skip_grid_cols_mi + mi_c)
8177 .is_some_and(|c| c.skip)
8178 }
8179
8180 /// The `skip_txfm` context of a block whose top-left mi cell is
8181 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
8182 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
8183 /// with an absent neighbour contributing 0. The mi grid is per tile, so
8184 /// row/column 0 is a tile edge and has no neighbour on that axis.
8185 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
8186 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
8187 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
8188 }
8189
8190 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
8191 (0..2).all(|rr| {
8192 (0..2).all(|cc| {
8193 self.blk_grid
8194 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
8195 .is_some_and(|c| c.skip)
8196 })
8197 })
8198 }
8199
8200 fn start_row(&mut self) {
8201 self.left.iter_mut().for_each(|l| *l = Default::default());
8202 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
8203 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
8204 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
8205 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
8206 self.left_skip.iter_mut().for_each(|s| *s = false);
8207 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
8208 self.left_inter.iter_mut().for_each(|i| *i = false);
8209 self.left_ref.iter_mut().for_each(|r| *r = -1);
8210 self.left_ref1.iter_mut().for_each(|r| *r = None);
8211 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
8212 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
8213 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
8214 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
8215 // context (a tile/SB-row boundary has no left neighbour).
8216 self.sub8_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
8217 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
8218 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
8219 // are per-mi maps like every other one here, so they reset with the
8220 // row too -- the left guard above is what actually stops a cross-tile
8221 // read, this keeps a stale colour out of the arrays at all.
8222 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
8223 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
8224 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
8225 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
8226 // lane-mergefix r2: `av1_zero_left_context` memsets
8227 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
8228 // every superblock row of every tile -- the var-tx left context does
8229 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
8230 // previous tile column's last block otherwise).
8231 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
8232 }
8233
8234 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
8235 /// block that reads it as a neighbour -- [`crate::tile`]'s
8236 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
8237 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
8238 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
8239 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
8240 /// the real value, not just `is_inter`).
8241 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8242 fn record_inter(
8243 &mut self,
8244 at: (usize, usize),
8245 side: usize,
8246 skip: bool,
8247 is_inter: bool,
8248 ref_frame: i8,
8249 filter: [u8; 2],
8250 skip_mode: bool,
8251 ) {
8252 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
8253 }
8254
8255 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
8256 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
8257 /// r1: a true rectangular strip's above-context span (its own width) and
8258 /// left-context span (its own height) differ, unlike every caller before
8259 /// this round (class neighbour-votes-all-its-fields).
8260 #[allow(clippy::too_many_arguments)]
8261 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8262 fn record_inter_rect(
8263 &mut self,
8264 at: (usize, usize),
8265 w_sub: usize,
8266 h_sub: usize,
8267 skip: bool,
8268 is_inter: bool,
8269 ref_frame: i8,
8270 filter: [u8; 2],
8271 skip_mode: bool,
8272 ) {
8273 let (r, c) = at;
8274 self.record_inter_rect_mi(
8275 (r * (SUB / MI), c * (SUB / MI)),
8276 w_sub / MI,
8277 h_sub / MI,
8278 skip,
8279 is_inter,
8280 ref_frame,
8281 filter,
8282 skip_mode,
8283 );
8284 }
8285
8286 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
8287 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
8288 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
8289 /// routes through the wrapper above.
8290 #[allow(clippy::too_many_arguments)]
8291 fn record_inter_rect_mi(
8292 &mut self,
8293 at_mi: (usize, usize),
8294 w_mi: usize,
8295 h_mi: usize,
8296 skip: bool,
8297 is_inter: bool,
8298 ref_frame: i8,
8299 filter: [u8; 2],
8300 skip_mode: bool,
8301 ) {
8302 let (r, c) = at_mi;
8303 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
8304 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
8305 // writes for a whole block class): an INTER block left the luma mode
8306 // map untouched, so a later intra block's `get_intra_edge_filter_type`
8307 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
8308 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
8309 // block in that pixel row -- the directional edge filter then ran at
8310 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
8311 // which for an inter block is an INTER mode (>= NEARESTMV) and is
8312 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
8313 // already stamped it).
8314 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
8315 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
8316 // uv map must read DC_PRED over an inter block's cells too.
8317 if is_inter {
8318 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
8319 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
8320 }
8321 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
8322 self.above_skip[c..c + w_mi].fill(skip);
8323 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
8324 self.above_inter[c..c + w_mi].fill(is_inter);
8325 self.above_ref[c..c + w_mi].fill(ref_frame);
8326 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
8327 // this with the block's real second reference for a compound block,
8328 // called right after this one (lane-publish2 audit).
8329 self.above_ref1[c..c + w_mi].fill(None);
8330 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
8331 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
8332 // as `3`/`1` even though this block has no second reference.
8333 // `record_compound_ctx` overwrites this with the real bit for an
8334 // actual compound block's cells, called right after this one.
8335 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
8336 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
8337 self.above_filter[c..c + w_mi].fill(filter);
8338 self.left_skip[r..r + h_mi].fill(skip);
8339 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
8340 self.left_inter[r..r + h_mi].fill(is_inter);
8341 self.left_ref[r..r + h_mi].fill(ref_frame);
8342 self.left_ref1[r..r + h_mi].fill(None);
8343 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
8344 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
8345 self.left_filter[r..r + h_mi].fill(filter);
8346 }
8347
8348 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
8349 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
8350 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
8351 /// `get_comp_index_context`) -- called right after `record_inter` for
8352 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
8353 /// stamps `above_ref1`/`left_ref1` with the block's real second
8354 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
8355 /// this is the one caller that actually knows it) -- so the next block's
8356 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
8357 /// neighbour instead of `record_inter`'s single-ref default.
8358 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8359 fn record_compound_ctx(
8360 &mut self,
8361 at: (usize, usize),
8362 side: usize,
8363 ref1: i8,
8364 comp_group_idx: u8,
8365 compound_idx: u8,
8366 ) {
8367 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
8368 }
8369
8370 /// [`Self::record_compound_ctx`] with independent above/left extents,
8371 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
8372 #[allow(clippy::too_many_arguments)]
8373 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8374 fn record_compound_ctx_rect(
8375 &mut self,
8376 at: (usize, usize),
8377 w_sub: usize,
8378 h_sub: usize,
8379 ref1: i8,
8380 comp_group_idx: u8,
8381 compound_idx: u8,
8382 ) {
8383 let (r, c) = at;
8384 self.record_compound_ctx_rect_mi(
8385 (r * (SUB / MI), c * (SUB / MI)),
8386 w_sub / MI,
8387 h_sub / MI,
8388 ref1,
8389 comp_group_idx,
8390 compound_idx,
8391 );
8392 }
8393
8394 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
8395 /// [`Self::record_inter_rect_mi`]).
8396 fn record_compound_ctx_rect_mi(
8397 &mut self,
8398 at_mi: (usize, usize),
8399 w_mi: usize,
8400 h_mi: usize,
8401 ref1: i8,
8402 comp_group_idx: u8,
8403 compound_idx: u8,
8404 ) {
8405 let (r, c) = at_mi;
8406 crate::census::compound();
8407 for cell in 0..w_mi {
8408 self.above_ref1[c + cell] = Some(ref1);
8409 self.above_comp_group_idx[c + cell] = comp_group_idx;
8410 self.above_compound_idx[c + cell] = compound_idx;
8411 }
8412 for cell in 0..h_mi {
8413 self.left_ref1[r + cell] = Some(ref1);
8414 self.left_comp_group_idx[r + cell] = comp_group_idx;
8415 self.left_compound_idx[r + cell] = compound_idx;
8416 }
8417 }
8418
8419 /// The context of a block's partition symbol: delegates to the mi-precise
8420 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
8421 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
8422 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
8423 /// only touches the finer mi arrays -- leaves them stale for the *next*
8424 /// sibling's own partition symbol.
8425 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
8426 let (r, c) = at;
8427 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
8428 }
8429
8430 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
8431 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
8432 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
8433 /// than the enclosing 16x16 slot's stale, shared state.
8434 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
8435 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
8436 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
8437 }
8438
8439 /// The gathered coded/DC-sign state of the blocks above and to the left
8440 /// of a block `side` samples across, per plane.
8441 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
8442 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
8443 }
8444
8445 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
8446 /// units, for the same reason [`Self::record_mi`] does.
8447 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
8448 let side_mi = side / MI;
8449 // One pass over the cells accumulating all three planes, not one pass
8450 // per plane: the three planes of a cell live in the same
8451 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
8452 // cache lines three times (lane-publish). Clamp each edge to the true
8453 // frame extent: a block at the right/bottom edge may be padded beyond
8454 // `mi_cols`/`mi_rows`, and libaom's unavailable context is zero there.
8455 let above_mi = side_mi.min(self.mi_cols.saturating_sub(mi_c));
8456 let left_mi = side_mi.min(self.mi_rows.saturating_sub(mi_r));
8457 let mut out = [(false, false, 0i32); 3];
8458 for cell in 0..above_mi {
8459 let above = &self.above[mi_c + cell];
8460 for (plane, o) in out.iter_mut().enumerate() {
8461 o.0 |= above[plane].level != 0;
8462 o.2 += dc_vote(above[plane].dc);
8463 }
8464 }
8465 for cell in 0..left_mi {
8466 let left = &self.left[mi_r + cell];
8467 for (plane, o) in out.iter_mut().enumerate() {
8468 o.1 |= left[plane].level != 0;
8469 o.2 += dc_vote(left[plane].dc);
8470 }
8471 }
8472 out
8473 }
8474
8475 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
8476 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
8477 /// extent pattern for a true rectangular strip's own coefficient context.
8478 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
8479 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
8480 }
8481
8482 /// [`Self::around_rect`] taking the block's position directly in 4x4
8483 /// mode-info units, mirroring [`Self::around_mi`].
8484 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
8485 let (w_mi, h_mi) = (w / MI, h / MI);
8486 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
8487 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
8488 // [`Self::around_mi`]'s single pass, with the two extents split.
8489 let mut out = [(false, false, 0i32); 3];
8490 for cell in 0..above_mi {
8491 let above = &self.above[mi_c + cell];
8492 for (plane, o) in out.iter_mut().enumerate() {
8493 o.0 |= above[plane].level != 0;
8494 o.2 += dc_vote(above[plane].dc);
8495 }
8496 }
8497 for cell in 0..left_mi {
8498 let left = &self.left[mi_r + cell];
8499 for (plane, o) in out.iter_mut().enumerate() {
8500 o.1 |= left[plane].level != 0;
8501 o.2 += dc_vote(left[plane].dc);
8502 }
8503 }
8504 if crate::envflags::env_flag!("EC_DCDUMP") {
8505 for (plane, o) in out.iter().enumerate() {
8506 let vote = o.2;
8507 let ab: Vec<String> = (0..above_mi)
8508 .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level))
8509 .collect();
8510 let lf: Vec<String> = (0..left_mi)
8511 .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level))
8512 .collect();
8513 eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(","));
8514 }
8515 }
8516 out
8517 }
8518
8519 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
8520 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
8521 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
8522 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
8523 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
8524 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
8525 /// is always 0, spec's `plane_bsize == tx_size` branch).
8526 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
8527 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
8528 }
8529
8530 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
8531 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
8532 /// context over `tx_size_wide` and the left one over `tx_size_high`.
8533 fn luma_skip_ctx_rect(
8534 &self,
8535 (mi_r, mi_c): (usize, usize),
8536 w_mi: usize,
8537 h_mi: usize,
8538 ) -> usize {
8539 let side_mi = w_mi;
8540 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
8541 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
8542 let mut top = 0u8;
8543 let mut left = 0u8;
8544 for cell in 0..above_mi {
8545 top |= self.above[mi_c + cell][0].level;
8546 }
8547 for cell in 0..left_mi {
8548 left |= self.left[mi_r + cell][0].level;
8549 }
8550 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
8551 if crate::envflags::env_flag!("EC_ECDUMP") {
8552 let ab: Vec<String> =
8553 (0..above_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect();
8554 let lf: Vec<String> =
8555 (0..left_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect();
8556 // lane-av1mix: the last few msac register states, so the
8557 // byte-position of the `all_zero` read can be matched against
8558 // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a
8559 // second run.
8560 let recent = crate::msac::symtrace::ecdump_recent(4)
8561 .iter()
8562 .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})"))
8563 .collect::<Vec<_>>()
8564 .join(" ");
8565 eprintln!(
8566 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]",
8567 ab.join(","), lf.join(","), recent
8568 );
8569 }
8570 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8571 eprintln!(
8572 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
8573 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
8574 );
8575 }
8576 ctx
8577 }
8578
8579 /// Writes one coded block into every cell it covers, on both grids: the
8580 /// mode/side arrays up to `side`'s own width, and the coefficient-context
8581 /// arrays up to the true frame edge — the units past it are left at their
8582 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
8583 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
8584 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
8585 /// not from this block's own side).
8586 fn record(
8587 &mut self,
8588 at: (usize, usize),
8589 side: usize,
8590 mode: usize,
8591 uv_mode: usize,
8592 grids: &[&[i32]; 3],
8593 ) {
8594 self.record_rect(at, side, side, mode, uv_mode, grids);
8595 }
8596
8597 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
8598 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
8599 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
8600 /// spec's per-edge partition-context rule, so a true rectangular block
8601 /// naturally wants two different values here rather than one.
8602 /// Writes this block's luma `mode` into the mi-granular
8603 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
8604 /// position a *later* neighbour would read it from: the block's LAST mi
8605 /// row for every column it spans (what the block below reads via
8606 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
8607 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
8608 /// read these back, and only when the recorded position is exactly their
8609 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
8610 fn record_mode_mi(
8611 &mut self,
8612 mi_r: usize,
8613 mi_c: usize,
8614 mi_w: usize,
8615 mi_h: usize,
8616 mode: usize,
8617 ) {
8618 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
8619 let mode = mode as u8;
8620 for cell in 0..mi_w {
8621 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
8622 *slot = (last_r, mode);
8623 }
8624 }
8625 for cell in 0..mi_h {
8626 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
8627 *slot = (last_c, mode);
8628 }
8629 }
8630 }
8631
8632 /// The mi-exact above/left neighbour luma mode for a block whose top-left
8633 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
8634 /// mi position (then the coarse [`SUB`]-grid slot is right by
8635 /// construction). See [`Self::record_mode_mi`].
8636 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
8637 match self.sub8_mode_col.get(mi_c) {
8638 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => Some(usize::from(m)),
8639 _ => None,
8640 }
8641 }
8642
8643 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
8644 match self.sub8_mode_row.get(mi_r) {
8645 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => Some(usize::from(m)),
8646 _ => None,
8647 }
8648 }
8649
8650 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
8651 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
8652 fn record_uv_mode_mi(
8653 &mut self,
8654 mi_r: usize,
8655 mi_c: usize,
8656 mi_w: usize,
8657 mi_h: usize,
8658 uv_mode: usize,
8659 ) {
8660 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
8661 fill_span(&mut self.uv_mode_col, mi_c, mi_w, (last_r as u16, uv_mode as u8));
8662 fill_span(&mut self.uv_mode_row, mi_r, mi_h, (last_c as u16, uv_mode as u8));
8663 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
8664 // covers, so the chroma neighbour read below is a plain grid read.
8665 let stride = self.uv_grid_cols;
8666 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
8667 for row in mi_r..=last_r {
8668 fill_span(&mut self.uv_mode_grid, row * stride + mi_c, n, uv_mode as u8);
8669 }
8670 }
8671
8672 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
8673 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
8674 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
8675 /// block has recorded the exact neighbouring mi.
8676 fn smooth_uv_neighbour(
8677 &self,
8678 mi_r: usize,
8679 mi_c: usize,
8680 r: usize,
8681 c: usize,
8682 fctx: &crate::decode::FrameCtx,
8683 ) -> bool {
8684 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
8685 // REFERENCE block, not off the mi that carries the chroma syntax.
8686 // `set_mi_row_col` (`blockd.h`) takes
8687 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
8688 // only then `chroma_above_mbmi = base_mi[-stride]` /
8689 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
8690 // the ODD mi, so without the snap we looked one mi row/column too far
8691 // down/right -- the mi-exact slot never matched and the coarse
8692 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
8693 // 8x4 at (688, 100) = mi (51, 344): libaom's
8694 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
8695 // `UV_SMOOTH_PRED`), ours was 0, which flips
8696 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
8697 // false for type 1, TRUE for type 0) and upsampled an edge libaom
8698 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
8699 // predicting from it (class `context-read-from-one-cell`).
8700 // lane-av1-444: the snap is the SEQUENCE's subsampling, hardcoded
8701 // `& !1` before -- at subsampling 0/0 libaom's `mi_row & 0` snaps
8702 // nothing, and the hardcoded snap read a 4x4 leaf's smooth
8703 // neighbour two mi away (frame 0 of `av1-profile1-444.ivf`, leaf
8704 // mi(5,15): left neighbour SMOOTH_V at mi(5,14), read at mi(4,13)).
8705 let snap_y = (1usize << ss_y(fctx)) - 1;
8706 let snap_x = (1usize << ss_x(fctx)) - 1;
8707 self.smooth_uv_neighbour_unsnapped(mi_r & !snap_y, mi_c & !snap_x, r, c)
8708 }
8709
8710 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
8711 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
8712 /// counter wants this: it measures how often the snap CHANGES the answer,
8713 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
8714 /// decode path uses the snapping form.
8715 fn smooth_uv_neighbour_unsnapped(
8716 &self,
8717 mi_r: usize,
8718 mi_c: usize,
8719 r: usize,
8720 c: usize,
8721 ) -> bool {
8722 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
8723 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
8724 // array that `start_tile` does not clear, so a block on a tile's first
8725 // mi row used to read the uv_mode of the block above it in the tile
8726 // ABOVE and filter its chroma edge at that neighbour's strength
8727 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
8728 // at chroma (120, 32), the top-right tile's first block).
8729 let have_above = mi_r > self.tile_row0_mi;
8730 let have_left = mi_c > self.tile_col0_mi;
8731 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
8732 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
8733 {
8734 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
8735 }
8736 // The mi grid is libaom's own read; the two maps below stay as the
8737 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
8738 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
8739 (col < self.uv_grid_cols)
8740 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
8741 .flatten()
8742 .filter(|&m| m != u8::MAX)
8743 .map(usize::from)
8744 };
8745 let above = match self.uv_mode_col.get(mi_c) {
8746 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, mi_r - 1, mi_c) => m,
8747 Some(&(row, m)) if have_above && usize::from(row) == mi_r - 1 => usize::from(m),
8748 _ if have_above => self.above_uv_mode[c],
8749 _ => DC_PRED,
8750 };
8751 let left = match self.uv_mode_row.get(mi_r) {
8752 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, mi_r, mi_c - 1) => m,
8753 Some(&(col, m)) if have_left && usize::from(col) == mi_c - 1 => usize::from(m),
8754 _ if have_left => self.left_uv_mode[r],
8755 _ => DC_PRED,
8756 };
8757 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
8758 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
8759 }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| {
8760 !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if usize::from(col) == mi_c - 1 && usize::from(cm) == m)
8761 }) {
8762 hit!(UV_MODE_GRID_OVERRIDE_HITS);
8763 }
8764 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
8765 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
8766 // have been filtered at the wrong strength by the coarse map alone.
8767 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
8768 hit!(UV_MODE_MI_OVERRIDE_HITS);
8769 }
8770 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
8771 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
8772 {
8773 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
8774 }
8775 is_smooth_mode(above) || is_smooth_mode(left)
8776 }
8777
8778 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
8779 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
8780 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
8781 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
8782 /// holding an OLDER, larger block's mode -- it only ever recorded into the
8783 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
8784 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
8785 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
8786 /// a different CDF for the same mode value).
8787 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
8788 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
8789 /// only when `up_available` and `left_mbmi` only when `left_available`;
8790 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
8791 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
8792 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
8793 /// strip's mode as its "left neighbour" (measured on the band fixture at
8794 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
8795 fn modes_above_left_mi(
8796 &self,
8797 mi_r: usize,
8798 mi_c: usize,
8799 fallback: (usize, usize),
8800 ) -> (usize, usize) {
8801 let above = if mi_r > self.tile_row0_mi {
8802 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
8803 } else {
8804 DC_PRED
8805 };
8806 let left = if mi_c > self.tile_col0_mi {
8807 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
8808 } else {
8809 DC_PRED
8810 };
8811 (above, left)
8812 }
8813
8814 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
8815 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
8816 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
8817 /// per superblock row and never per tile, so the first block column of
8818 /// tile 2..N read the previous tile's mode as its left neighbour, and the
8819 /// above band survives across a tile ROW boundary the same way lane-mtfix's
8820 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
8821 /// `up_available`/`left_available` and uses DC_PRED otherwise
8822 /// ([`Self::modes_above_left_mi`]).
8823 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
8824 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8825 let (above, left) =
8826 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
8827 if above != self.above_mode[c] || left != self.left_mode[r] {
8828 hit!(MODE_MI_OVERRIDE_HITS);
8829 }
8830 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
8831 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
8832 {
8833 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
8834 }
8835 // A neighbour the coarse band offered where the tile edge makes it
8836 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
8837 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
8838 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
8839 {
8840 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
8841 }
8842 (above, left)
8843 }
8844
8845 fn record_rect(
8846 &mut self,
8847 at: (usize, usize),
8848 w: usize,
8849 h: usize,
8850 mode: usize,
8851 uv_mode: usize,
8852 grids: &[&[i32]; 3],
8853 ) {
8854 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
8855 }
8856
8857 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
8858 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
8859 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
8860 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
8861 /// the [`SUB`]-unit path does).
8862 fn record_rect_mi(
8863 &mut self,
8864 at_mi: (usize, usize),
8865 w: usize,
8866 h: usize,
8867 mode: usize,
8868 uv_mode: usize,
8869 grids: &[&[i32]; 3],
8870 ) {
8871 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
8872 // lane-inter4 r2: a strip whose own footprint runs past the frame's
8873 // last 16-px column/row stamps only the cells that exist (libaom's
8874 // arrays are padded past the frame and those cells are never read).
8875 for cell in 0..w / SUB {
8876 if c + cell >= self.above_mode.len() {
8877 break;
8878 }
8879 self.above_mode[c + cell] = mode;
8880 self.above_uv_mode[c + cell] = uv_mode;
8881 self.above_side[c + cell] = w;
8882 }
8883 for cell in 0..h / SUB {
8884 if r + cell >= self.left_mode.len() {
8885 break;
8886 }
8887 self.left_mode[r + cell] = mode;
8888 self.left_uv_mode[r + cell] = uv_mode;
8889 self.left_side[r + cell] = h;
8890 }
8891 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
8892 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
8893 self.record_mi_rect(at_mi, w, h, grids);
8894 }
8895
8896 /// The coefficient-context half of [`Self::record`], taking the block's
8897 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
8898 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
8899 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
8900 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
8901 self.record_mi_rect(at_mi, side, side, grids);
8902 }
8903
8904 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
8905 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
8906 fn record_mi_rect(
8907 &mut self,
8908 at_mi: (usize, usize),
8909 w: usize,
8910 h: usize,
8911 grids: &[&[i32]; 3],
8912 ) {
8913 let (mi_r, mi_c) = at_mi;
8914 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
8915 let (w_mi, h_mi) = (w / MI, h / MI);
8916 if crate::envflags::env_flag!("EC_ECPUB") {
8917 eprintln!("EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", states[0].level);
8918 }
8919 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
8920 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
8921 // A chroma 4x4 unit straddling the true luma edge is still whole in
8922 // chroma's own halved grid, so libaom rounds the luma bound up to the
8923 // plane's own 4x4 unit before clamping a subsampled plane
8924 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
8925 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8926 let bound_h = [
8927 self.mi_rows,
8928 round_up_even(self.mi_rows),
8929 round_up_even(self.mi_rows),
8930 ];
8931 let bound_w = [
8932 self.mi_cols,
8933 round_up_even(self.mi_cols),
8934 round_up_even(self.mi_cols),
8935 ];
8936 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
8937 // past the padded side arrays (mi_rows 198, block rows 192..208);
8938 // libaom's own arrays are superblock-sized, so those cells simply
8939 // have no reader -- [`fill_span`] drops them, as the `break` did.
8940 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
8941 // predicate is three contiguous runs: all planes, chroma only, none
8942 // (lane-mi).
8943 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
8944 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
8945 let uv_only = [Neighbour::default(), states[1], states[2]];
8946 fill_span(&mut self.left, mi_r, luma_h, states);
8947 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
8948 fill_span(
8949 &mut self.left,
8950 mi_r + chroma_h,
8951 h_mi - chroma_h,
8952 [Neighbour::default(); 3],
8953 );
8954 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
8955 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
8956 let uv_only_w = [Neighbour::default(), states[1], states[2]];
8957 fill_span(&mut self.above, mi_c, luma_w, states);
8958 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
8959 fill_span(
8960 &mut self.above,
8961 mi_c + chroma_w,
8962 w_mi - chroma_w,
8963 [Neighbour::default(); 3],
8964 );
8965 }
8966
8967 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
8968 /// inside a coded block whose luma transform is smaller than its own
8969 /// side (`TxMode::Select`): the real per-transform-unit coefficient
8970 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
8971 /// coarse per-block `tx_grid`/`fill_lf_grid` state
8972 /// [`Self::record_split_luma`] still writes once for the whole block.
8973 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
8974 /// the caller's own [`Self::record_split_luma`] call sets those once,
8975 /// at the block's own true side, not this TU's.
8976 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
8977 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
8978 }
8979
8980 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
8981 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
8982 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
8983 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
8984 /// coefficient-context arrays are indexed by luma mi, the convention
8985 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
8986 /// clamp included.
8987 fn record_mi_chroma(
8988 &mut self,
8989 (mi_r, mi_c): (usize, usize),
8990 w_px: usize,
8991 h_px: usize,
8992 plane: usize,
8993 grid: &[i32],
8994 ) {
8995 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8996 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
8997 let state = neighbour_state(grid);
8998 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
8999 self.left[mi_r + cell][plane] = state;
9000 }
9001 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
9002 self.above[mi_c + cell][plane] = state;
9003 }
9004 }
9005
9006 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
9007 /// r1): the above context spans the unit's width, the left context its
9008 /// height, which for a square unit is the same loop it always was.
9009 fn record_mi_luma_rect(
9010 &mut self,
9011 (mi_r, mi_c): (usize, usize),
9012 w_px: usize,
9013 h_px: usize,
9014 grid: &[i32],
9015 ) {
9016 let state = neighbour_state(grid);
9017 if crate::envflags::env_flag!("EC_ECPUB") {
9018 eprintln!("EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", state.level);
9019 }
9020 for cell in 0..h_px / MI {
9021 if mi_r + cell < self.mi_rows {
9022 self.left[mi_r + cell][0] = state;
9023 }
9024 }
9025 for cell in 0..w_px / MI {
9026 if mi_c + cell < self.mi_cols {
9027 self.above[mi_c + cell][0] = state;
9028 }
9029 }
9030 }
9031
9032 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
9033 /// block whose luma was decoded as several transform units through
9034 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
9035 /// whole-block luma write -- everything [`Self::record`] does except
9036 /// plane 0, which is already correct per-TU by the time this runs.
9037 fn record_split_luma(
9038 &mut self,
9039 at: (usize, usize),
9040 side: usize,
9041 mode: usize,
9042 uv_mode: usize,
9043 chroma_grids: [&[i32]; 2],
9044 ) {
9045 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
9046 }
9047
9048 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
9049 /// extents in pixels (lane-rectsplit r1), the same relationship
9050 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
9051 /// luma transform split into several square units needs exactly this
9052 /// bookkeeping, at its own true rectangular extents.
9053 fn record_split_luma_rect(
9054 &mut self,
9055 at: (usize, usize),
9056 w: usize,
9057 h: usize,
9058 mode: usize,
9059 uv_mode: usize,
9060 chroma_grids: [&[i32]; 2],
9061 ) {
9062 let (r, c) = at;
9063 self.record_split_luma_rect_mi(
9064 (r * (SUB / MI), c * (SUB / MI)),
9065 w,
9066 h,
9067 mode,
9068 uv_mode,
9069 chroma_grids,
9070 );
9071 }
9072
9073 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
9074 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
9075 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
9076 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
9077 /// convention [`decode_block_rect4`] already established for 1:4 strips.
9078 fn record_split_luma_rect_mi(
9079 &mut self,
9080 at_mi: (usize, usize),
9081 w: usize,
9082 h: usize,
9083 mode: usize,
9084 uv_mode: usize,
9085 chroma_grids: [&[i32]; 2],
9086 ) {
9087 let (mi_r, mi_c) = at_mi;
9088 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
9089 for cell in 0..w.div_ceil(SUB) {
9090 if c + cell >= self.above_mode.len() {
9091 break;
9092 }
9093 self.above_mode[c + cell] = mode;
9094 self.above_uv_mode[c + cell] = uv_mode;
9095 self.above_side[c + cell] = w;
9096 }
9097 for cell in 0..h.div_ceil(SUB) {
9098 if r + cell >= self.left_mode.len() {
9099 break;
9100 }
9101 self.left_mode[r + cell] = mode;
9102 self.left_uv_mode[r + cell] = uv_mode;
9103 self.left_side[r + cell] = h;
9104 }
9105
9106 let (w_mi, h_mi) = (w / MI, h / MI);
9107 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
9108 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
9109 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
9110 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
9111 let round_up_even = |n: usize| n.div_ceil(2) * 2;
9112 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
9113 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
9114 let plane = plane_idx + 1;
9115 let state = neighbour_state(grid);
9116 for cell in 0..h_mi {
9117 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
9118 self.left[mi_r + cell][plane] = state;
9119 }
9120 }
9121 for cell in 0..w_mi {
9122 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
9123 self.above[mi_c + cell][plane] = state;
9124 }
9125 }
9126 }
9127 }
9128}
9129
9130/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
9131/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
9132/// exactly — including its skip context, which the real key-frame writer
9133/// always writes at a fixed context of zero (it never tracks a neighbour-based
9134/// one for intra blocks; that is the inter-frame writer's rule instead).
9135/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
9136/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
9137/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
9138/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
9139/// plain DC chroma.
9140/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
9141/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
9142/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
9143/// instead (the defect commit 1a89ed9 fixed at the square sites).
9144pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
9145 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
9146 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
9147}
9148
9149/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
9150/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
9151/// bound (spec `filter_intra_mode_info` never reads a symbol there).
9152pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
9153 match side {
9154 4 => Some(0),
9155 8 => Some(1),
9156 16 => Some(2),
9157 32 => Some(3),
9158 _ => None,
9159 }
9160}
9161
9162/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
9163/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
9164/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
9165/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
9166fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
9167 match (bw, bh) {
9168 (32, 16) => Some(4),
9169 (16, 32) => Some(5),
9170 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
9171 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
9172 // here dropped that symbol on every DC_PRED strip of that size and
9173 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
9174 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
9175 (16, 8) => Some(6),
9176 (8, 16) => Some(7),
9177 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
9178 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
9179 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
9180 (4, 8) => Some(8),
9181 (8, 4) => Some(9),
9182 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
9183 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
9184 // `use_filter_intra` symbol on those strips although aomenc writes
9185 // one for every DC_PRED block of that shape with
9186 // `--enable-filter-intra=1` (its default), silently desyncing the
9187 // tile (class symbol-consumption-gap).
9188 (32, 8) => Some(10),
9189 (8, 32) => Some(11),
9190 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
9191 // strips), rows 17/16 of `default_filter_intra_cdfs`.
9192 (16, 4) => Some(12),
9193 (4, 16) => Some(13),
9194 _ if bw == bh => filter_intra_size_class(bw),
9195 _ => None,
9196 }
9197}
9198
9199/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
9200/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
9201/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
9202/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
9203/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
9204pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
9205 palette_bsize_ctx_wh(side, side)
9206}
9207
9208/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
9209/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
9210/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
9211/// for ANY bsize, not just the square ones a hand-picked table happened to
9212/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
9213/// row breaks the moment its indexing field moves off the diagonal, and a
9214/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
9215/// block dimension is a power of two, so `bw*bh` always is too and
9216/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
9217/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
9218fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
9219 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
9220 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
9221 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
9222 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
9223 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
9224 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
9225 if bw > 64 || bh > 64 || bw * bh < 64 {
9226 return None;
9227 }
9228 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
9229}
9230
9231/// A just-decoded palette-Y block's own size, base colours (only the first
9232/// `size` entries are real), and per-pixel colour-index map (`side*side`,
9233/// row-major, each entry `< size`).
9234struct PaletteY {
9235 size: usize,
9236 colors: [u16; 8],
9237 map: Vec<u8>,
9238}
9239
9240/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
9241/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
9242/// shared between U and V, both co-located after 4:2:0 subsampling) plus
9243/// each plane's own base colours.
9244struct PaletteUv {
9245 size: usize,
9246 u_colors: [u16; 8],
9247 v_colors: [u16; 8],
9248 map: Vec<u8>,
9249}
9250
9251/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
9252/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
9253/// `get_unsigned_bits`, which is the same formula): smallest `n` with
9254/// `2^n >= x`, `0` for `x <= 1`.
9255pub(crate) fn ceil_log2(x: u32) -> u32 {
9256 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
9257}
9258
9259/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
9260/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
9261fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
9262 let l = ceil_log2(n as u32);
9263 let m = (1usize << l) - n;
9264 let v = dec.literal(l - 1) as usize;
9265 if v < m {
9266 v
9267 } else {
9268 (v << 1) - m + dec.literal(1) as usize
9269 }
9270}
9271
9272/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
9273/// colours (already-known, from the above/left neighbours) with the
9274/// ascending `transmitted` ones (delta-coded off the wire) back into one
9275/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
9276/// value picks the cached copy first, matching the C `<=`.
9277fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
9278 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
9279 let (mut ci, mut ti) = (0, 0);
9280 while ci < cached.len() && ti < transmitted.len() {
9281 if cached[ci] <= transmitted[ti] {
9282 out.push(cached[ci]);
9283 ci += 1;
9284 } else {
9285 out.push(transmitted[ti]);
9286 ti += 1;
9287 }
9288 }
9289 out.extend_from_slice(&cached[ci..]);
9290 out.extend_from_slice(&transmitted[ti..]);
9291 out
9292}
9293
9294/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
9295/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
9296/// each delta's width, the `range` bound and the clamp) is sized by
9297/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
9298/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
9299/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
9300/// the msac range, so a cross-decoder range ladder stays bit-identical
9301/// through the whole miscount -- only the decoded VALUE differs (class
9302/// `compare-range-not-tell`'s blind spot). (this
9303/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
9304/// (one flag bit each, in cache order), then delta-codes the remainder
9305/// (first value raw, each following delta `>= 1` off a shrinking bit width),
9306/// and merges the two ascending lists back together.
9307fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> [u16; 8] {
9308 let mut cached = Vec::with_capacity(n);
9309 for &c in cache {
9310 if cached.len() >= n {
9311 break;
9312 }
9313 if dec.literal(1) == 1 {
9314 cached.push(c);
9315 }
9316 }
9317 let bd = u32::from(bit_depth(fctx));
9318 let max_val = (1i32 << bd) - 1;
9319 let mut colors = [0u16; 8];
9320 let n_cached = cached.len();
9321 if n_cached < n {
9322 let mut transmitted = Vec::with_capacity(n - n_cached);
9323 let first = dec.literal(bd) as u16;
9324 transmitted.push(first);
9325 if n_cached + 1 < n {
9326 let min_bits = bd - 3;
9327 let mut bits = min_bits + dec.literal(2);
9328 let mut range = (1i32 << bd) - i32::from(first) - 1;
9329 for _ in (n_cached + 1)..n {
9330 let delta = dec.literal(bits) as i32 + 1;
9331 let prev = *transmitted.last().unwrap();
9332 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
9333 range -= i32::from(val) - i32::from(prev);
9334 bits = bits.min(ceil_log2(range.max(0) as u32));
9335 transmitted.push(val);
9336 }
9337 }
9338 let merged = merge_colors(&transmitted, &cached);
9339 colors[..n].copy_from_slice(&merged);
9340 } else {
9341 colors[..n].copy_from_slice(&cached[..n]);
9342 }
9343 colors
9344}
9345
9346/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
9347/// `bit_depth` (see [`read_palette_colors_y`]): U reads
9348/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
9349/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
9350/// unbiased by `+1` -- both differences from Y's own reader, matching the C
9351/// side by side). V never uses a cache: a leading bit picks either `n` raw
9352/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
9353/// rather than clamp.
9354fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> ([u16; 8], [u16; 8]) {
9355 let mut cached = Vec::with_capacity(n);
9356 for &c in cache {
9357 if cached.len() >= n {
9358 break;
9359 }
9360 if dec.literal(1) == 1 {
9361 cached.push(c);
9362 }
9363 }
9364 let bd = u32::from(bit_depth(fctx));
9365 let max_val = 1i32 << bd;
9366 let mut u_colors = [0u16; 8];
9367 let n_cached = cached.len();
9368 if n_cached < n {
9369 let mut transmitted = Vec::with_capacity(n - n_cached);
9370 let first = dec.literal(bd) as u16;
9371 transmitted.push(first);
9372 if n_cached + 1 < n {
9373 let min_bits = bd - 3;
9374 let mut bits = min_bits + dec.literal(2);
9375 let mut range = max_val - i32::from(first);
9376 for _ in (n_cached + 1)..n {
9377 let delta = dec.literal(bits) as i32;
9378 let prev = *transmitted.last().unwrap();
9379 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
9380 range -= i32::from(val) - i32::from(prev);
9381 bits = bits.min(ceil_log2(range.max(0) as u32));
9382 transmitted.push(val);
9383 }
9384 }
9385 let merged = merge_colors(&transmitted, &cached);
9386 u_colors[..n].copy_from_slice(&merged);
9387 } else {
9388 u_colors[..n].copy_from_slice(&cached[..n]);
9389 }
9390 let mut v_colors = [0u16; 8];
9391 if dec.literal(1) == 1 {
9392 let min_bits_v = bd - 4;
9393 let bits = min_bits_v + dec.literal(2);
9394 v_colors[0] = dec.literal(bd) as u16;
9395 for i in 1..n {
9396 let mut delta = dec.literal(bits) as i32;
9397 if delta != 0 && dec.literal(1) == 1 {
9398 delta = -delta;
9399 }
9400 let mut val = i32::from(v_colors[i - 1]) + delta;
9401 if val < 0 {
9402 val += max_val;
9403 }
9404 if val >= max_val {
9405 val -= max_val;
9406 }
9407 v_colors[i] = val as u16;
9408 }
9409 } else {
9410 for i in 0..n {
9411 v_colors[i] = dec.literal(bd) as u16;
9412 }
9413 }
9414 (u_colors, v_colors)
9415}
9416
9417/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
9418/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
9419/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
9420const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
9421
9422/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
9423/// map's own per-pixel context and colour-order permutation, from the
9424/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
9425/// selection sort). `map`'s stride is `side` (this decoder never crops a
9426/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
9427/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
9428/// actual colour index to store.
9429pub(crate) fn palette_color_index_context(
9430 map: &[u8],
9431 side: usize,
9432 row: usize,
9433 col: usize,
9434 n: usize,
9435) -> (usize, [u8; 8]) {
9436 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
9437 let up_left = if col >= 1 && row >= 1 {
9438 Some(map[(row - 1) * side + col - 1])
9439 } else {
9440 None
9441 };
9442 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
9443 let mut scores = [0i32; 8];
9444 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
9445 if let Some(v) = neighbour {
9446 scores[v as usize] += weight;
9447 }
9448 }
9449 let mut color_order = [0u8; 8];
9450 for i in 0..8 {
9451 color_order[i] = i as u8;
9452 }
9453 for i in 0..3 {
9454 let mut max = scores[i];
9455 let mut max_idx = i;
9456 for j in (i + 1)..n {
9457 if scores[j] > max {
9458 max = scores[j];
9459 max_idx = j;
9460 }
9461 }
9462 if max_idx != i {
9463 let max_score = scores[max_idx];
9464 let max_color = color_order[max_idx];
9465 for k in (i + 1..=max_idx).rev() {
9466 scores[k] = scores[k - 1];
9467 color_order[k] = color_order[k - 1];
9468 }
9469 scores[i] = max_score;
9470 color_order[i] = max_color;
9471 }
9472 }
9473 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
9474 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
9475 (ctx as usize, color_order)
9476}
9477
9478/// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512):
9479/// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block
9480/// cut by the frame's bottom or right mi edge codes its colour-index map only
9481/// over this part and replicates it outward -- reading the full `bw x bh` grid
9482/// consumed symbols libaom never wrote and desynced the rest of the tile
9483/// (lane-svtinter; class map-read-past-frame-edge).
9484fn palette_onscreen(
9485 mi_r: usize,
9486 mi_c: usize,
9487 bw: usize,
9488 bh: usize,
9489 fctx: &crate::decode::FrameCtx,
9490) -> (usize, usize) {
9491 // lane-palw: the ENCODER's own in-process reconstruct runs on a
9492 // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
9493 // frame encoders publish the header's mi dims onto it themselves
9494 // (`encode.rs`, beside their `true_width`/`true_height`) so that this
9495 // clamp and `tile::write_color_index_map`'s now agree there too.
9496 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
9497 palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
9498}
9499
9500/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
9501/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
9502/// compute the same on-screen extent or the decoder reads a different number
9503/// of symbols than the encoder wrote.
9504pub(crate) fn palette_onscreen_dims(
9505 mi_r: usize,
9506 mi_c: usize,
9507 bw: usize,
9508 bh: usize,
9509 (mi_rows, mi_cols): (usize, usize),
9510) -> (usize, usize) {
9511 (
9512 bw.min(mi_cols.saturating_sub(mi_c) * MI),
9513 bh.min(mi_rows.saturating_sub(mi_r) * MI),
9514 )
9515}
9516
9517/// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus
9518/// the SAME sub-8 bump the caller's own `(bw >> ss).max(4)` applies to the
9519/// block dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move
9520/// together or a cut 8-wide block reads its chroma map at the wrong width.
9521/// lane-av1-444: the shifts are the sequence's own subsampling (a 4:4:4
9522/// intra-in-inter palette read its chroma map at the 4:2:0 extent and
9523/// panicked feeding the 4:2:0-sized prediction to a full-size reconstruct).
9524pub(crate) fn palette_onscreen_uv(
9525 luma: (usize, usize),
9526 on: (usize, usize),
9527 chroma: (usize, usize),
9528 ss: (usize, usize),
9529) -> (usize, usize) {
9530 (
9531 (on.0 >> ss.0) + (chroma.0 - (luma.0 >> ss.0)),
9532 (on.1 >> ss.1) + (chroma.1 - (luma.1 >> ss.1)),
9533 )
9534}
9535
9536/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
9537/// map's wavefront decode over a `side x side` grid, read over the on-screen
9538/// `on_side x on_side` corner (see [`palette_onscreen`]).
9539fn decode_color_index_map(
9540 dec: &mut SymbolDecoder,
9541 cdfs: &mut Cdfs,
9542 n: usize,
9543 side: usize,
9544 on: (usize, usize),
9545 uv: bool,
9546) -> Vec<u8> {
9547 decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv)
9548}
9549
9550/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
9551/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
9552/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
9553/// independently rather than one shared `side` -- the square call above is
9554/// just `bw == bh`.
9555fn decode_color_index_map_wh(
9556 dec: &mut SymbolDecoder,
9557 cdfs: &mut Cdfs,
9558 n: usize,
9559 bw: usize,
9560 bh: usize,
9561 // `(onscreenWidth, onscreenHeight)` in this plane's own units.
9562 on: (usize, usize),
9563 uv: bool,
9564) -> Vec<u8> {
9565 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
9566 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
9567 if on_bw < bw || on_bh < bh {
9568 hit!(PALETTE_ONSCREEN_CUT_HITS);
9569 }
9570 let mut map = vec![0u8; bw * bh];
9571 if trace {
9572 let (rng, _) = dec.debug_state();
9573 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
9574 }
9575 map[0] = read_uniform(dec, n) as u8;
9576 if trace {
9577 let (rng, _) = dec.debug_state();
9578 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
9579 }
9580 for i in 1..(on_bw + on_bh - 1) {
9581 let j_hi = i.min(on_bw - 1);
9582 let j_lo = i.saturating_sub(on_bh - 1);
9583 for j in (j_lo..=j_hi).rev() {
9584 let row = i - j;
9585 let col = j;
9586 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
9587 if trace {
9588 let (rng, _) = dec.debug_state();
9589 let row_cdf = if uv {
9590 &cdfs.palette_uv_color_index[n - 2][ctx]
9591 } else {
9592 &cdfs.palette_y_color_index[n - 2][ctx]
9593 };
9594 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", row_cdf[0], row_cdf[n]);
9595 }
9596 let symbol = if uv {
9597 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
9598 } else {
9599 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
9600 };
9601 map[row * bw + col] = color_order[symbol];
9602 if trace {
9603 let (rng, _) = dec.debug_state();
9604 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
9605 }
9606 }
9607 }
9608 palette_replicate(&mut map, bw, bh, on);
9609 map
9610}
9611
9612/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
9613/// last on-screen column then the last on-screen row are replicated over the
9614/// off-screen remainder, so the prediction still covers the whole block. The
9615/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
9616/// so the pixels it prices and reconstructs are the ones the on-screen
9617/// symbols it writes really decode to.
9618pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
9619 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
9620 for row in 0..on_bh {
9621 let last = map[row * bw + on_bw - 1];
9622 map[row * bw + on_bw..row * bw + bw].fill(last);
9623 }
9624 for row in on_bh..bh {
9625 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
9626 }
9627}
9628
9629/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
9630/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
9631/// size class comes from [`filter_intra_size_class_rect`] instead of the
9632/// square-only [`filter_intra_size_class`], and the palette read (when
9633/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
9634/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
9635/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
9636/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
9637#[allow(clippy::too_many_arguments)]
9638fn read_intra_mode_rect(
9639 dec: &mut SymbolDecoder,
9640 cdfs: &mut Cdfs,
9641 above_mode: usize,
9642 left_mode: usize,
9643 cfl: bool,
9644 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
9645 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
9646 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
9647 // chroma is coded once, on the closing strip). Every other caller is a
9648 // block big enough to own its chroma and passes `true`.
9649 has_chroma: bool,
9650 bw: usize,
9651 bh: usize,
9652 enable_filter_intra: bool,
9653 skip_ctx: usize,
9654 allow_screen_content_tools: bool,
9655 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
9656 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
9657 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
9658 palette: Option<(usize, &[u16])>,
9659 palette_uv_cache: &[u16],
9660 mi_r: usize,
9661 mi_c: usize, fctx: &crate::decode::FrameCtx,
9662) -> Result<(
9663 bool,
9664 usize,
9665 i32,
9666 usize,
9667 i32,
9668 Option<(i32, i32)>,
9669 Option<usize>,
9670 Option<PaletteY>,
9671 Option<PaletteUv>,
9672 // lane-av1-intrabc: the block vector, `Some` exactly when this block's
9673 // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns
9674 // straight out of `read_intra_frame_mode_info` then, so every later field
9675 // of the tuple is at its default (mode/uv_mode DC, no angle, no palette,
9676 // no filter intra). A caller that can reconstruct intrabc at its shape
9677 // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by
9678 // name with the same string it always did.
9679 Option<(i32, i32)>,
9680)> {
9681 // lane-av1mono: libaom guards every chroma symbol read with
9682 // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
9683 // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
9684 // `palette_uv` even on a chroma-reference strip. Fold the plane count
9685 // into the same `has_chroma` this reader already gates on.
9686 let has_chroma = has_chroma && !mono(fctx);
9687 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
9688 if ec_istep {
9689 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
9690 // (decodemv.c:818), printed at the same point: before the first
9691 // mode-info symbol of the block, so a cross-decoder range ladder can
9692 // be keyed on the BLOCK, not just on the symbol sequence.
9693 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}", enable_filter_intra as i32, filter_intra_size_class_rect(bw, bh), dec.debug_state().0);
9694 }
9695 macro_rules! istep {
9696 ($name:literal, $val:expr) => {
9697 if ec_istep {
9698 let (rng, _) = dec.debug_state();
9699 eprintln!(
9700 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
9701 $name, $val
9702 );
9703 }
9704 };
9705 }
9706 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
9707 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
9708 // the one point every rect caller routes through, so no call site can
9709 // offer the 14-symbol CFL alphabet on a 64-axis block (class
9710 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
9711 let cfl = if cfl && bw.max(bh) > 32 {
9712 hit!(NOCFL_UV_MODE_HITS);
9713 false
9714 } else {
9715 cfl
9716 };
9717 // lane-intra14 r1: on the INTER block path everything up to and including
9718 // `is_inter` was already read by [`decode_inter_block`], so this reader
9719 // starts at the mode syntax with the `skip` that caller read.
9720 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
9721 let skip = if let Some((_, skip)) = inter {
9722 skip
9723 } else {
9724 // Same `intra_segment_id` placement as the square reader above.
9725 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
9726 if seg_id_pre_skip(fctx) {
9727 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
9728 }
9729 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
9730 istep!("skip", skip as i32);
9731 if !seg_id_pre_skip(fctx) {
9732 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
9733 }
9734 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
9735 istep!("cdef", 0);
9736 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
9737 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
9738 // `false`.
9739 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
9740 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
9741 istep!("dq", 0);
9742 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
9743 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
9744 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
9745 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
9746 // rect strips read it exactly like square leaves ([`read_intra_mode`],
9747 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
9748 // decoder at the FIRST symbol of the first rect block of every
9749 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
9750 // block at this shape is out of scope, so the flag is consumed and
9751 // refused by name when it fires.
9752 if allow_intrabc_frame(fctx) {
9753 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
9754 hit!(RECT_INTRABC_READS);
9755 istep!("intrabc", use_intrabc as i32);
9756 if use_intrabc {
9757 hit!(INTRABC_HITS);
9758 // libaom `read_intrabc_info`: the DV read, then an immediate
9759 // return out of the mode-info read -- no `y_mode`, no `uv_mode`,
9760 // no angle deltas, no palette, no filter intra. The caller owns
9761 // the reconstruction at its own shape.
9762 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx);
9763 return Ok((
9764 skip,
9765 DC_PRED,
9766 0,
9767 DC_PRED,
9768 0,
9769 None,
9770 None,
9771 None,
9772 None,
9773 Some(dv),
9774 ));
9775 }
9776 }
9777 skip
9778 };
9779 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
9780 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
9781 // off `kf_y_mode_cdf[above][left]`).
9782 let mode = if let Some((size_group, _)) = inter {
9783 dec.symbol(&mut cdfs.y_mode[size_group])
9784 } else {
9785 let above_ctx = INTRA_MODE_CTX[above_mode];
9786 let left_ctx = INTRA_MODE_CTX[left_mode];
9787 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
9788 };
9789 istep!("mode", mode as i32);
9790 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
9791 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
9792 } else {
9793 0
9794 };
9795 istep!("angle_y", angle_delta_y);
9796 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
9797 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
9798 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
9799 // here, from the block's own size, is the single point every caller routes
9800 // through -- a caller passing `true` for a >32 strip used to pick the
9801 // 14-symbol CFL CDF, same value but a different range (class
9802 // wrong-alphabet-same-value).
9803 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
9804 let uv_mode = if !has_chroma {
9805 DC_PRED
9806 } else if cfl {
9807 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
9808 } else {
9809 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
9810 };
9811 istep!("uv_mode", uv_mode as i32);
9812 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
9813 Some(read_cfl_alphas(dec, cdfs))
9814 } else {
9815 None
9816 };
9817 if has_chroma && (9..=12).contains(&uv_mode) {
9818 hit!(SMOOTH_UV_HITS);
9819 }
9820 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
9821 hit!(DIRECTIONAL_UV_HITS);
9822 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
9823 } else {
9824 0
9825 };
9826 istep!("angle_uv", angle_delta_uv);
9827 if angle_delta_uv != 0 {
9828 hit!(UV_ANGLE_DELTA_HITS);
9829 }
9830 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
9831 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
9832 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
9833 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
9834 // colours only here, the colour-index maps deferred past `filter_intra`
9835 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
9836 // runs from the caller, after the whole mode-info read).
9837 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
9838 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
9839 if allow_screen_content_tools
9840 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
9841 {
9842 // r6: this is the exact site the removed blanket refusal used to
9843 // guard -- reached for EVERY rect strip in a screen-content frame,
9844 // independent of whether the block ends up using a palette.
9845 hit!(RECT_SCREEN_CONTENT_HITS);
9846 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
9847 let use_palette_y =
9848 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
9849 if use_palette_y {
9850 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
9851 let colors = read_palette_colors_y(dec, n, cache, fctx);
9852 palette_y_pending = Some((n, colors));
9853 }
9854 let palette_uv_mode_ctx = usize::from(use_palette_y);
9855 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
9856 if has_chroma
9857 && uv_mode == DC_PRED
9858 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
9859 {
9860 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
9861 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
9862 palette_uv_pending = Some((n, u_colors, v_colors));
9863 }
9864 }
9865 let mut filter_intra = None;
9866 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9867 let (rng, _) = dec.debug_state();
9868 eprintln!(
9869 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
9870 class={:?} rng={rng}",
9871 enable_filter_intra as i32,
9872 filter_intra_size_class_rect(bw, bh)
9873 );
9874 }
9875 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
9876 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
9877 if mode == DC_PRED
9878 && enable_filter_intra
9879 && palette_y_pending.is_none()
9880 && let Some(class) = filter_intra_size_class_rect(bw, bh)
9881 {
9882 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
9883 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9884 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
9885 }
9886 istep!("use_filter_intra", use_filter_intra as i32);
9887 if use_filter_intra {
9888 hit!(FILTER_INTRA_HITS);
9889 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
9890 istep!("filter_intra_mode", fi_mode as i32);
9891 filter_intra = Some(fi_mode);
9892 }
9893 }
9894 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
9895 // same order as [`read_intra_mode`]'s own square path.
9896 let palette_y = palette_y_pending.map(|(n, colors)| {
9897 let map =
9898 decode_color_index_map_wh(dec, cdfs, n, bw, bh, palette_onscreen(mi_r, mi_c, bw, bh, fctx), false);
9899 hit!(PALETTE_HITS);
9900 hit!(PALETTE_RECT_HITS);
9901 PaletteY { size: n, colors, map }
9902 });
9903 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
9904 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
9905 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
9906 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
9907 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
9908 // chroma palette and desynced the tile from there.
9909 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
9910 let on = palette_onscreen_uv((bw, bh), palette_onscreen(mi_r, mi_c, bw, bh, fctx), (cw, ch), (ss_x(fctx), ss_y(fctx)));
9911 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
9912 hit!(PALETTE_UV_HITS);
9913 PaletteUv { size: n, u_colors, v_colors, map }
9914 });
9915 Ok((
9916 skip,
9917 mode,
9918 angle_delta_y,
9919 uv_mode,
9920 angle_delta_uv,
9921 alpha,
9922 filter_intra,
9923 palette_y,
9924 palette_uv,
9925 None,
9926 ))
9927}
9928
9929/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
9930/// at the strip's REAL mi position. `av1_get_palette_cache` reads
9931/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
9932/// block, so each strip owns its own rows and columns and no aliasing rule
9933/// is needed (lane-kf900 r6).
9934#[allow(clippy::too_many_arguments)]
9935fn record_strip_palette(
9936 n: &mut Neighbours,
9937 mi: (usize, usize),
9938 bw: usize,
9939 bh: usize,
9940 y_size: usize,
9941 y_colors: [u16; 8],
9942 uv_size: usize,
9943 uv_colors: [u16; 8],
9944) {
9945 let (r, c) = mi;
9946 // lane-t900 r23 rung: every publication of a block's palette state into
9947 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
9948 // path left a stale `left_palette_size` behind when
9949 // `av1_get_palette_mode_ctx` disagrees with libaom's.
9950 if crate::envflags::env_flag!("EC_PALPUB") {
9951 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
9952 }
9953 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
9954 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
9955 // existed because the 16px [`SUB`] cell held one slot for all the strips
9956 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
9957 // real neighbour leaf 1 reads.
9958 {
9959 for cell in 0..(bw / MI).max(1) {
9960 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
9961 *e = y_size as u8;
9962 n.above_palette_uv_size[c + cell] = uv_size as u8;
9963 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
9964 // colours of a size-0 neighbour are never read.
9965 if y_size > 0 {
9966 n.above_palette_colors[c + cell] = y_colors;
9967 }
9968 if uv_size > 0 {
9969 n.above_palette_uv_colors[c + cell] = uv_colors;
9970 }
9971 }
9972 }
9973 }
9974 {
9975 for cell in 0..(bh / MI).max(1) {
9976 if n.left_palette_size.get(r + cell).is_none() {
9977 break;
9978 }
9979 n.left_palette_size[r + cell] = y_size as u8;
9980 n.left_palette_uv_size[r + cell] = uv_size as u8;
9981 if y_size > 0 {
9982 n.left_palette_colors[r + cell] = y_colors;
9983 }
9984 if uv_size > 0 {
9985 n.left_palette_uv_colors[r + cell] = uv_colors;
9986 }
9987 }
9988 }
9989}
9990
9991/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
9992fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
9993 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| i32::from(y.data[ly * y.width + lx]))
9994}
9995
9996/// Everything a rect strip already read out of the stream before its luma
9997/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
9998/// (nine values that would otherwise be nine more parameters).
9999struct RectStripModes {
10000 skip: bool,
10001 mode: usize,
10002 angle_delta_y: i32,
10003 uv_predict_mode: usize,
10004 angle_delta_uv: i32,
10005 alpha: Option<(i32, i32)>,
10006 filter_intra: Option<usize>,
10007 smooth_neighbor: bool,
10008 smooth_neighbor_uv: bool,
10009 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
10010 /// mapped through the colour table), sliced per transform unit below --
10011 /// palette prediction reads no edge pixels, so a unit's slice of the
10012 /// whole-block map IS its prediction. Without this a palette strip whose
10013 /// transform splits predicted DC and came out flat grey while the entropy
10014 /// stream stayed in sync (the coefficients are read either way).
10015 palette_y: Option<Vec<u16>>,
10016 /// As `palette_y`, for the un-split chroma transform (U, V).
10017 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
10018}
10019
10020/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
10021/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
10022/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
10023/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
10024/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
10025/// TX_32X16`) and only the second reaches a square -- the reason
10026/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
10027/// already square) mis-tiled 1:4 strips.
10028fn depth_to_tx_wh(
10029 bw: usize,
10030 bh: usize,
10031 depth: usize,
10032 fctx: &crate::decode::FrameCtx,
10033) -> (usize, usize) {
10034 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
10035 // `read_tx_size`: the lossless early return comes before
10036 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
10037 if lossless(fctx) {
10038 return (4, 4);
10039 }
10040 let (mut w, mut h) = (bw.min(64), bh.min(64));
10041 for _ in 0..depth {
10042 match w.cmp(&h) {
10043 std::cmp::Ordering::Greater => w /= 2,
10044 std::cmp::Ordering::Less => h /= 2,
10045 std::cmp::Ordering::Equal => {
10046 w /= 2;
10047 h /= 2;
10048 }
10049 }
10050 }
10051 (w, h)
10052}
10053
10054/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
10055/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
10056/// rect path here refused by name until now ("per-unit rect prediction is not
10057/// ported").
10058///
10059/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
10060/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
10061/// strip the very first step already lands on a SQUARE transform
10062/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
10063/// every further step halves a square) -- so each unit is square and reads
10064/// through the ordinary square [`read_plane`]. What is genuinely rectangular
10065/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
10066/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
10067/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
10068/// split by luma's depth.
10069///
10070/// Each unit predicts off whatever the earlier units of this same block
10071/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
10072/// inside `av1_foreach_transformed_block`, raster order), which is exactly
10073/// what predicting the whole strip in one shot got wrong.
10074#[allow(clippy::too_many_arguments)]
10075fn decode_rect_split(
10076 dec: &mut SymbolDecoder,
10077 cdfs: &mut Cdfs,
10078 neighbours: &mut Neighbours,
10079 at_mi: (usize, usize),
10080 bw: usize,
10081 bh: usize,
10082 // The transform unit's own width and height in pixels. Square for every
10083 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
10084 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
10085 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
10086 tx_w: usize,
10087 tx_h: usize,
10088 m: &RectStripModes,
10089 y: &mut PlaneBuf<'static>,
10090 u: &mut PlaneBuf<'static>,
10091 v: &mut PlaneBuf<'static>,
10092 base_q_idx: u8,
10093 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
10094) -> Result<()> {
10095 let (mi_r, mi_c) = at_mi;
10096 let (px, py) = (mi_c * MI, mi_r * MI);
10097 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
10098 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
10099 // The chroma transform is picked before any symbol is read, so an
10100 // unsupported chroma shape refuses before this strip desyncs the tile.
10101 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
10102 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
10103 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
10104 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
10105 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
10106 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
10107 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
10108 // squares a rect transform down to a CDF set by
10109 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
10110 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
10111 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
10112 // paths already prove for these same shapes.
10113 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
10114 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
10115 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
10116 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
10117 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
10118 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
10119 _ => None,
10120 };
10121 // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted
10122 // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled
10123 // below; everything else still needs a single-unit table.
10124 let chroma_tiled = matches!((chroma_w, chroma_h), (64, 32) | (32, 64) | (64, 16) | (16, 64));
10125 if !m.skip {
10126 if let Some(i) = match (chroma_w, chroma_h) {
10127 (32, 8) => Some(0),
10128 (8, 32) => Some(1),
10129 (8, 4) => Some(2),
10130 (4, 8) => Some(3),
10131 _ => None,
10132 } {
10133 hit_do! {
10134 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
10135 let mut hits = c.get();
10136 hits[i] += 1;
10137 c.set(hits);
10138 });
10139 }
10140 }
10141 if chroma.is_none() && !chroma_tiled {
10142 // Diagnostic for the next caller that lands here (class
10143 // refusal-names-a-correlate: the message names the tool, not the
10144 // shape); the refusal below keeps its inventory-pinned wording.
10145 // The condition is the refusal's exact precondition, so the
10146 // print can never fire without the refusal (or vice versa): the
10147 // four 64-axis chroma shapes are tiled below and at LOSSLESS the
10148 // 4x4 walk never consults `chroma` at all -- libaom has no such
10149 // transform to name a row for (`av1_get_tx_size` returns TX_4X4
10150 // for every plane at lossless, blockd.h:1383; outside it
10151 // `av1_get_adjusted_tx_size` collapses TX_64X32/32X64 to TX_32X32
10152 // for chroma, blockd.h:1361-1367). lane-av1-ll64: the old
10153 // ungated print fired on those working routes and mislabelled
10154 // them a gap (one lane report cited it as a decode stop).
10155 eprintln!(
10156 "EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} \
10157 chroma={chroma_w}x{chroma_h} libaom_lossless_tx=none"
10158 );
10159 }
10160 }
10161 // lane-rectsplit r2 (verifier finding): with both callers wired
10162 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
10163 // 64x32/32x64) every shape that reaches here has a table above, so this
10164 // arm is UNREACHABLE today. It stays as the shape guard for the next
10165 // caller -- a new strip size would otherwise hit the `expect` below and
10166 // panic instead of refusing by name -- and so stays in
10167 // `refusal_inventory::REFUSALS`.
10168 if !m.skip && chroma.is_none() && !chroma_tiled {
10169 return Err(unsupported(
10170 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
10171 ));
10172 }
10173 hit!(RECT_SPLIT_TX_HITS);
10174 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
10175 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
10176 }
10177 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
10178 // A square unit reads through the ordinary square [`read_plane`]; a rect
10179 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
10180 // the very tables the unsplit 16x8/32x16 paths use.
10181 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
10182 (w, h) if w == h => None,
10183 (16, 8) | (8, 16) => Some((
10184 if reduced_tx_set {
10185 TxbSet::LumaRect16x8
10186 } else {
10187 TxbSet::LumaRect16x8Set1
10188 },
10189 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
10190 )),
10191 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
10192 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
10193 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
10194 // strip, read through the `luma_64corner` arm below instead of a rect
10195 // table -- a 64-length axis codes only its low 32 coefficients
10196 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
10197 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
10198 // depth-0 arm already reads on the key-frame path.
10199 //
10200 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
10201 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
10202 // sub-8x8 intra leaves still refused: with those lifted (r2) the
10203 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
10204 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
10205 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
10206 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
10207 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
10208 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
10209 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
10210 (64, 32) | (32, 64) => None,
10211 _ => {
10212 return Err(unsupported(format!(
10213 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
10214 coefficient tables for that shape here)"
10215 )))
10216 }
10217 };
10218 // The `None` above that is NOT the square arm.
10219 let luma_64corner = tx_w != tx_h;
10220 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
10221 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
10222 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
10223 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
10224 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
10225 // per-unit rect walk stay wired above/below; the round that finds that
10226 // defect deletes this refusal and nothing else.
10227 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
10228 let luma_scan = default_scan(tx_w.min(tx_h));
10229 let zero_tu = vec![0i32; tx_w * tx_h];
10230 // The strip's OWN edge availability, the fallback for a transform unit
10231 // whose top-right/bottom-left pixels fall outside the strip.
10232 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
10233 for tu_row in 0..bh / tx_h {
10234 for tu_col in 0..bw / tx_w {
10235 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
10236 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
10237 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
10238 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
10239 // libaom clips `av1_foreach_transformed_block_in_plane` to
10240 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
10241 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
10242 // TOP-LEFT sample falls outside the frame is never coded. We read
10243 // coefficients for those phantom units and desynced the stream at
10244 // the very next symbol.
10245 if tu_px >= y.true_width || tu_py >= y.true_height {
10246 continue;
10247 }
10248 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
10249 // transform unit INSIDE a block, which is a different rule from
10250 // the standalone-block table [`Reach::of`] applies -- and the
10251 // reason a depth-2 superblock strip came out one sample off
10252 // before this: `Reach::of(tx, ..)` answered as if the unit were
10253 // its own block at that superblock position.
10254 // * top-right: if the unit's right neighbour is still inside the
10255 // strip the pixels are already reconstructed (`col_off +
10256 // tx_wide < plane_bw`); otherwise only the strip's own top row
10257 // of units can reach past it, through the block-level answer.
10258 // * bottom-left: a unit that is not in the strip's left column
10259 // has none (`col_off > 0` returns 0); inside the strip
10260 // (`row_off + tx_high < plane_bh`) they are the left
10261 // neighbour's, already reconstructed; the last row falls back
10262 // to the block-level answer.
10263 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
10264 // The unit's own window on the block's palette prediction.
10265 if let Some(buf) = &m.palette_y {
10266 let tu_buf: Vec<u16> = (0..tx_h)
10267 .flat_map(|i| {
10268 let base = (row_off + i) * bw + col_off;
10269 buf[base..base + tx_w].iter().copied()
10270 })
10271 .collect();
10272 set_palette_pred(tu_buf, fctx);
10273 }
10274 if m.skip {
10275 push_intra_rect(0,
10276 tu_px,
10277 tu_py,
10278 tx_w,
10279 tx_h,
10280 m.mode,
10281 m.angle_delta_y,
10282 tu_reach,
10283 &zero_tu,
10284 None,
10285 m.filter_intra,
10286 m.smooth_neighbor, fctx,
10287 );
10288 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
10289 } else if luma_64corner && luma_rect.is_none() {
10290 // The un-split 64-level luma transform: `read_coeffs` on the
10291 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
10292 // and the real rect shape passed through for
10293 // `av1_nz_map_ctx_offset` -- byte for byte
10294 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
10295 // 64-level strip gate already proves. `tx_type` is not coded
10296 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
10297 // the square-up size is TX_64X64), and this unit covers its
10298 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
10299 if crate::envflags::env_flag!("EC_RECT64TU") {
10300 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
10301 }
10302 hit_do! {
10303 RECT64_CORNER_TU_HITS.with(|c| {
10304 let mut v = c.get();
10305 v[usize::from(tx_h > tx_w)] += 1;
10306 c.set(v);
10307 });
10308 }
10309 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
10310 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
10311 let (corner, tu_tx_type) = read_coeffs(
10312 dec,
10313 &mut coding,
10314 default_scan(TX32),
10315 0,
10316 dc_sign_ctx(tu_around.2),
10317 TxType::DctDct,
10318 Some((tx_w, tx_h)),
10319 )?;
10320 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
10321 let mut tu_grid = vec![0i32; tx_w * tx_h];
10322 for row in 0..ch {
10323 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
10324 }
10325 let residual = dequant_and_inverse_typed_wh(
10326 &tu_grid,
10327 tx_w,
10328 tx_h,
10329 crate::decode::bit_depth(fctx),
10330 block_q_idx(fctx),
10331 plane_q_delta(0, fctx).0,
10332 plane_q_delta(0, fctx).1,
10333 tu_tx_type,
10334 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
10335 );
10336 push_intra_rect(0,
10337 tu_px,
10338 tu_py,
10339 tx_w,
10340 tx_h,
10341 m.mode,
10342 m.angle_delta_y,
10343 tu_reach,
10344 &residual,
10345 None,
10346 m.filter_intra,
10347 m.smooth_neighbor, fctx,
10348 );
10349 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
10350 } else if let Some((rect_set, rect_scan)) = luma_rect {
10351 // The rect-unit twin of the square arm below: same contexts,
10352 // same order, through the rect coefficient reader. The
10353 // `tx_type` CDF row of a filter-intra block is
10354 // `fimode_to_intradir[filter_intra_mode]`, never the block's
10355 // own (always DC_PRED) mode -- [`read_plane`] applies that
10356 // for the square arm, so this one must too.
10357 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
10358 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
10359 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
10360 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
10361 // neighbour-magnitude table is for a unit SMALLER than its
10362 // block. [`decode_block_rect`]'s own unsplit read passes a
10363 // literal 0 for the same reason; this arm applied the table
10364 // unconditionally and desynced every depth-0 rect strip that
10365 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
10366 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
10367 0
10368 } else {
10369 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
10370 };
10371 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
10372 let (tu_grid, tu_tx_type) = read_coeffs_rect(
10373 dec,
10374 &mut coding,
10375 rect_scan,
10376 tx_w,
10377 tx_h,
10378 tu_skip_ctx,
10379 dc_sign_ctx(tu_around.2),
10380 TxType::DctDct,
10381 )?;
10382 let residual = dequant_and_inverse_typed_wh(
10383 &tu_grid,
10384 tx_w,
10385 tx_h,
10386 crate::decode::bit_depth(fctx),
10387 block_q_idx(fctx),
10388 plane_q_delta(0, fctx).0,
10389 plane_q_delta(0, fctx).1,
10390 tu_tx_type,
10391 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
10392 );
10393 push_intra_rect(0,
10394 tu_px,
10395 tu_py,
10396 tx_w,
10397 tx_h,
10398 m.mode,
10399 m.angle_delta_y,
10400 tu_reach,
10401 &residual,
10402 None,
10403 m.filter_intra,
10404 m.smooth_neighbor, fctx,
10405 );
10406 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
10407 } else {
10408 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
10409 // This unit is smaller than the block it sits in, so
10410 // `txb_skip_ctx` is the neighbour-magnitude table, not the
10411 // lone-TU 0 (spec `get_txb_ctx_general`).
10412 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
10413 let tu_grid = read_plane(
10414 dec,
10415 cdfs,
10416 luma_set,
10417 &luma_scan,
10418 0,
10419 tu_around,
10420 m.mode,
10421 m.mode,
10422 m.angle_delta_y,
10423 tu_reach,
10424 y,
10425 tu_px,
10426 tu_py,
10427 tx_w,
10428 tx_w,
10429 base_q_idx,
10430 None,
10431 m.filter_intra,
10432 Some(tu_skip_ctx),
10433 m.smooth_neighbor, fctx,
10434 )?;
10435 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
10436 }
10437 }
10438 }
10439 // CHROMA: one un-split rect transform for the whole strip.
10440 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
10441 // units -- each stamps its own neighbour context as it is read, and the
10442 // whole-block `record_split_luma_rect_mi` below would overwrite all of
10443 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
10444 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
10445 // collected here and replayed after that record.
10446 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
10447 // The chroma_tiled arm below stamps each unit's coefficient context
10448 // immediately (so the NEXT unit reads it), then the whole-strip
10449 // `record_split_luma_rect_mi` rewrites every chroma cell with ONE
10450 // whole-strip state and the per-unit DC signs and levels are lost
10451 // (class `override-slot-on-one-arm`). The units are collected here and
10452 // replayed after that record, the way the lossless arm's
10453 // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail
10454 // already do.
10455 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
10456 let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10457 let reach = block_reach;
10458 let (u_grid, v_grid) = if mono(fctx) {
10459 // lane-av1mono: a monochrome frame codes no chroma coefficients on
10460 // any block (`plane < av1_num_planes == 1`), so the whole chroma
10461 // section -- the skipped-strip pushes, the lossless raster and the
10462 // un-split `read_coeffs_rect` below -- is bypassed.
10463 let zero = Grid::Zero(chroma_w * chroma_h);
10464 (zero.clone(), zero)
10465 } else if m.skip {
10466 let zero = Grid::Zero(chroma_w * chroma_h);
10467 if let Some((ub, _)) = &m.palette_uv {
10468 set_palette_pred(ub.clone(), fctx);
10469 }
10470 push_intra_rect(1,
10471 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
10472 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx,
10473 );
10474 if let Some((_, vb)) = &m.palette_uv {
10475 set_palette_pred(vb.clone(), fctx);
10476 }
10477 push_intra_rect(2,
10478 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
10479 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx,
10480 );
10481 (zero.clone(), zero)
10482 } else if lossless(fctx) {
10483 // lane-lossless: the strip's chroma plane block is coded as 4x4
10484 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
10485 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
10486 // (`decode_token_recon_block`'s mu-chunk loop, measured against
10487 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
10488 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
10489 // offset (our `+3` row base) whenever the plane block is bigger than
10490 // the transform.
10491 let scan4 = default_scan(4);
10492 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
10493 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
10494 // lane-av1-llband: one 4x4 chroma unit's extent in LUMA pixels -- 4
10495 // chroma px scaled by the plane's own subsampling. The hardcoded 8
10496 // was the 4:2:0 unit's span; at 4:4:4 a unit is 4x4 LUMA px (one mi
10497 // cell), and the 8-px step made every unit past the first column/row
10498 // read its `txb_skip` context at the WRONG mi (two cells over) and
10499 // stamp a 2-cell span with one unit's state -- the polluted above-band
10500 // cell behind a 16x8 leaf's U bc=2 unit of the 444 lossless key frame
10501 // (measured: oracle `EC_DBGCTX` reads 1-cell spans at 1-mi steps;
10502 // ours read `above[28..29]` where the oracle read `above[26]`).
10503 let span_x = 4 << ss_x(fctx);
10504 let span_y = 4 << ss_y(fctx);
10505 let mut last = [Grid::Zero(16), Grid::Zero(16)];
10506 for plane_idx in 1..=2 {
10507 for cu_row in 0..ch_n {
10508 for cu_col in 0..cw_n {
10509 let cu_mi = (
10510 mi_r + cu_row * (span_y / MI),
10511 mi_c + cu_col * (span_x / MI),
10512 );
10513 let cu_around = neighbours.around_mi_rect(cu_mi, span_x, span_y);
10514 let cu_reach = tu_reach(
10515 bw, bh,
10516 cu_col * span_x, cu_row * span_y, span_x,
10517 block_reach, px, py, y.width, y.height, fctx,
10518 );
10519 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
10520 if let Some((ub, vb)) = &m.palette_uv {
10521 let pbuf = if plane_idx == 1 { ub } else { vb };
10522 set_palette_pred(
10523 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
10524 fctx,
10525 );
10526 }
10527 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
10528 let grid = read_plane(
10529 dec, cdfs, TxbSet::Chroma4, &scan4, plane_idx,
10530 cu_around[plane_idx], m.mode, m.uv_predict_mode,
10531 m.angle_delta_uv, cu_reach, plane, cu_x, cu_y, 4, 4,
10532 base_q_idx,
10533 m.alpha.zip(ac).map(|((au, av), ac)| {
10534 (if plane_idx == 1 { au } else { av }, ac)
10535 }),
10536 None, offset, m.smooth_neighbor_uv, fctx,
10537 )?;
10538 if span_x == 4 && span_y == 4 {
10539 hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS);
10540 }
10541 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid);
10542 ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y));
10543 last[plane_idx - 1] = grid;
10544 }
10545 }
10546 }
10547 let [ug, vg] = last;
10548 (ug, vg)
10549 } else if chroma_tiled {
10550 let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) = match (chroma_w, chroma_h) {
10551 (64, 32) | (32, 64) => (32, 32, TxbSet::Chroma32, default_scan(32)),
10552 (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16),
10553 (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32),
10554 _ => unreachable!("chroma_tiled"),
10555 };
10556 let (nw, nh) = (chroma_w / uw, chroma_h / uh);
10557 let bigger = chroma_w * chroma_h > uw * uh;
10558 let default_tx = TxType::DctDct;
10559 let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)];
10560 for plane_idx in 1..=2 {
10561 for cu_row in 0..nh {
10562 for cu_col in 0..nw {
10563 let luma_span_x = uw << ss_x(fctx);
10564 let luma_span_y = uh << ss_y(fctx);
10565 let cu_mi = (
10566 mi_r + cu_row * (luma_span_y / MI),
10567 mi_c + cu_col * (luma_span_x / MI),
10568 );
10569 let cu_around = neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y);
10570 let (cu_x, cu_y) = (cpx + cu_col * uw, cpy + cu_row * uh);
10571 let cfl = m.alpha.map(|(au, av)| {
10572 let alpha = if plane_idx == 1 { au } else { av };
10573 (
10574 alpha,
10575 cfl_src_rect(
10576 px + cu_col * luma_span_x,
10577 py + cu_row * luma_span_y,
10578 luma_span_x,
10579 luma_span_y,
10580 ),
10581 )
10582 });
10583 // 32x32 does not fit read_coeffs_rect's scratch (768). The
10584 // square reader is the path every other 32x32 chroma unit uses.
10585 let levels = if uw == uh {
10586 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
10587 read_plane(
10588 dec, cdfs, set, scan, plane_idx, cu_around[plane_idx],
10589 m.mode, m.uv_predict_mode, m.angle_delta_uv, reach,
10590 plane, cu_x, cu_y, uw, uw, base_q_idx, cfl, None,
10591 bigger.then_some(3), m.smooth_neighbor_uv, fctx,
10592 )?
10593 } else {
10594 let skip_ctx = usize::from(cu_around[plane_idx].0)
10595 + usize::from(cu_around[plane_idx].1)
10596 + usize::from(bigger) * 3;
10597 let mut coding = cdfs.txb(set, m.uv_predict_mode);
10598 let (levels, tx_type) = read_coeffs_rect(
10599 dec, &mut coding, scan, uw, uh, skip_ctx,
10600 dc_sign_ctx(cu_around[plane_idx].2), default_tx,
10601 )?;
10602 let residual = dequant_and_inverse_typed_wh(
10603 &levels, uw, uh, crate::decode::bit_depth(fctx),
10604 block_q_idx(fctx),
10605 plane_q_delta(plane_idx, fctx).0,
10606 plane_q_delta(plane_idx, fctx).1,
10607 tx_type,
10608 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
10609 );
10610 push_intra_rect(
10611 plane_idx, cu_x, cu_y, uw, uh,
10612 m.uv_predict_mode, m.angle_delta_uv, reach, &residual,
10613 cfl, None, m.smooth_neighbor_uv, fctx,
10614 );
10615 levels
10616 };
10617 neighbours.record_mi_chroma(cu_mi, luma_span_x, luma_span_y, plane_idx, &levels);
10618 tiled_chroma_units.push((
10619 cu_mi,
10620 plane_idx,
10621 levels.clone(),
10622 luma_span_x,
10623 luma_span_y,
10624 ));
10625 last[plane_idx - 1] = levels;
10626 }
10627 }
10628 }
10629 (last[0].clone(), last[1].clone())
10630 } else {
10631 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
10632 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
10633 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
10634 // so only the 16x8/8x16 pair takes the mode-indexed default.
10635 let default_tx = if chroma_w.max(chroma_h) >= 32 {
10636 TxType::DctDct
10637 } else {
10638 default_intra_tx_type(m.uv_predict_mode as u8)
10639 };
10640 let around = neighbours.around_mi_rect(at_mi, bw, bh);
10641 let mut grids: Vec<Grid> = Vec::with_capacity(2);
10642 for plane_idx in 1..=2 {
10643 let skip_ctx =
10644 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
10645 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
10646 let (levels, tx_type) = read_coeffs_rect(
10647 dec,
10648 &mut coding,
10649 chroma_scan,
10650 chroma_w,
10651 chroma_h,
10652 skip_ctx,
10653 dc_sign_ctx(around[plane_idx].2),
10654 default_tx,
10655 )?;
10656 // The same delta_q proof the unsplit rect64 path records
10657 // (lane-rectsplit r4: lifting the split-transform refusal moved
10658 // superblock strips onto this path, so only counting there would
10659 // leave the delta_q gate's counter silent for them).
10660 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
10661 hit!(RECT64_QIDX_DRIFT_HITS);
10662 }
10663 let residual = dequant_and_inverse_typed_wh(
10664 &levels,
10665 chroma_w,
10666 chroma_h,
10667 crate::decode::bit_depth(fctx),
10668 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
10669 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
10670 // reading `current_q_idx` here dropped the segment feature
10671 // that every other dequant site applies (class
10672 // `parsed-then-discarded`).
10673 block_q_idx(fctx),
10674 plane_q_delta(plane_idx, fctx).0,
10675 plane_q_delta(plane_idx, fctx).1,
10676 tx_type,
10677 block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, tx_type),
10678 );
10679 let cfl = m
10680 .alpha
10681 .zip(ac)
10682 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
10683 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
10684 if let Some((ub, vb)) = &m.palette_uv {
10685 let buf = if plane_idx == 1 { ub } else { vb };
10686 set_palette_pred(buf.clone(), fctx);
10687 }
10688 push_intra_rect(plane_idx,
10689 cpx,
10690 cpy,
10691 chroma_w,
10692 chroma_h,
10693 m.uv_predict_mode,
10694 m.angle_delta_uv,
10695 reach,
10696 &residual,
10697 cfl,
10698 None,
10699 m.smooth_neighbor_uv, fctx,
10700 );
10701 grids.push(levels);
10702 }
10703 let mut it = grids.into_iter();
10704 (it.next().unwrap(), it.next().unwrap())
10705 };
10706 neighbours.record_split_luma_rect_mi(
10707 at_mi,
10708 bw,
10709 bh,
10710 m.mode,
10711 m.uv_predict_mode,
10712 [&u_grid, &v_grid],
10713 );
10714 for (cu_mi, plane, unit, span_w, span_h) in &ll_chroma_units {
10715 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
10716 }
10717 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
10718 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
10719 }
10720 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
10721 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
10722 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10723 let (rng, _) = dec.debug_state();
10724 eprintln!(
10725 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
10726 tx={tx_w}x{tx_h} rng={rng}"
10727 );
10728 }
10729 Ok(())
10730}
10731
10732/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
10733/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
10734/// because it predicts squares only. Every pixel here goes through the rect
10735/// machinery the key-frame paths already prove: [`decode_rect_split`], which
10736/// at `depth == 0` is the unsplit strip as a single transform unit and
10737/// beyond it the per-unit walk of [`depth_to_tx_wh`].
10738///
10739/// What is genuinely different from [`decode_block_rect`] is the mode
10740/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
10741/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
10742/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
10743/// intra-in-inter arm's own reads at the rect footprint, including its
10744/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
10745/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
10746/// square and this arm) and a nonzero luma angle delta refused by name.
10747///
10748/// The strip's own neighbour records (luma per transform unit, chroma, skip
10749/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
10750/// inter-side bands and the mi map.
10751#[allow(clippy::too_many_arguments)]
10752/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
10753/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
10754/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
10755/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
10756/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
10757/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
10758/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
10759/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
10760/// table here rather than a shift of `bw.min(bh)`.
10761fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
10762 Some(match (bw.min(bh), bw.max(bh)) {
10763 (8, 16) => (1usize, 1usize),
10764 (16, 32) => (2, 2),
10765 (32, 64) => (3, 3),
10766 (8, 32) => (1, 2),
10767 (16, 64) => (2, 3),
10768 _ => return None,
10769 })
10770}
10771
10772/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
10773/// block path"): the shapes that can reach that arm, enumerated against the
10774/// MEASURED domain of the inter block path
10775/// ([`INTER_BLOCK_SHAPES`], the census the gate
10776/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
10777/// fills from three real streams).
10778///
10779/// [`decode_intra_rect_in_inter`] is called from one site, under
10780/// `write_w != side || write_h != side`, and only after two earlier arms have
10781/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
10782/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
10783/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
10784/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
10785/// and each of those has a row, so the refusal names a shape no measured
10786/// stream can present.
10787#[test]
10788fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
10789 let mut checked = 0;
10790 for &(side, w, h) in &INTER_BLOCK_SHAPES {
10791 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
10792 continue;
10793 }
10794 assert!(
10795 intra_in_inter_size_row(w, h).is_some(),
10796 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
10797 the \"no size-group/tx-category row\" refusal"
10798 );
10799 checked += 1;
10800 }
10801 assert_eq!(
10802 checked, 10,
10803 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
10804 lookup, not the 10 this claim was measured over"
10805 );
10806}
10807
10808/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
10809/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
10810/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
10811/// matched before the square arm's `log2` shortcut).
10812///
10813/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
10814/// row here"; the enumeration below is what proves no conformant block can
10815/// reach it.
10816pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
10817 Some(match (write_w, write_h) {
10818 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
10819 // below maps 128 to row 4 (BLOCK_16X32).
10820 (64, 128) => 14,
10821 (128, 64) => 15,
10822 (128, 128) => 16,
10823 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
10824 (16, 32) => 4,
10825 (32, 16) => 5,
10826 (32, 64) => 6,
10827 (64, 32) => 7,
10828 (8, 32) => 8,
10829 (32, 8) => 9,
10830 (16, 64) => 10,
10831 (64, 16) => 11,
10832 // lane-inter4 r3: the 16x16-level rect inter leaves.
10833 (8, 16) => 12,
10834 (16, 8) => 13,
10835 _ => return None,
10836 })
10837}
10838
10839/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
10840/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
10841/// `block_size_wide`/`block_size_high`).
10842#[cfg(test)]
10843const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
10844 (4, 4),
10845 (4, 8),
10846 (8, 4),
10847 (8, 8),
10848 (8, 16),
10849 (16, 8),
10850 (16, 16),
10851 (16, 32),
10852 (32, 16),
10853 (32, 32),
10854 (32, 64),
10855 (64, 32),
10856 (64, 64),
10857 (64, 128),
10858 (128, 64),
10859 (128, 128),
10860 (4, 16),
10861 (16, 4),
10862 (8, 32),
10863 (32, 8),
10864 (16, 64),
10865 (64, 16),
10866];
10867
10868/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
10869/// shape with no CDF row here" names a shape no conformant stream can present.
10870///
10871/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
10872/// whose `write_w.min(write_h) >= 8` clause is libaom's
10873/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
10874/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
10875/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
10876/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
10877/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
10878/// clause rejects before the lookup.
10879#[test]
10880fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
10881 let mut rows = std::collections::BTreeSet::new();
10882 let mut excluded = 0;
10883 for (w, h) in BLOCK_SIZES_ALL_WH {
10884 if w.min(h) < 8 {
10885 excluded += 1;
10886 assert!(
10887 w == 4 || h == 4,
10888 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
10889 );
10890 continue;
10891 }
10892 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
10893 panic!(
10894 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
10895 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
10896 )
10897 });
10898 assert!(
10899 row < 17,
10900 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
10901 );
10902 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
10903 }
10904 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
10905 assert_eq!(
10906 rows.len(),
10907 17,
10908 "17 eligible footprints must fill all 17 rows of the motion_mode table"
10909 );
10910}
10911
10912fn decode_intra_rect_in_inter(
10913 dec: &mut SymbolDecoder,
10914 cdfs: &mut Cdfs,
10915 neighbours: &mut Neighbours,
10916 at: (usize, usize),
10917 bw: usize,
10918 bh: usize,
10919 skip: bool,
10920 allow_screen_content_tools: bool,
10921 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
10922 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
10923 strip16: Option<(bool, bool)>,
10924 y: &mut PlaneBuf<'static>,
10925 u: &mut PlaneBuf<'static>,
10926 v: &mut PlaneBuf<'static>,
10927 base_q_idx: u8, fctx: &crate::decode::FrameCtx,
10928) -> Result<()> {
10929 // `at` is in MI units (the inter path's own unit since lane-inter4);
10930 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
10931 // below are still keyed by.
10932 let (mi_r, mi_c) = at;
10933 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
10934 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
10935 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
10936 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
10937 // finding -- the category is NOT the same for every strip size).
10938 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
10939 // it is refused by name rather than read from the wrong CDF row.
10940 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
10941 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
10942 // tx-depth category is 1 -- but nothing here has to know either, because
10943 // the strip decodes through the very body the KEY FRAME path proves for
10944 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
10945 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
10946 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
10947 // inter-frame difference is the mode-info read, which
10948 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
10949 // `y_mode[0]` plus the `skip` this caller already read.
10950 if let Some((horz, has_chroma)) = strip16 {
10951 // lane-t900 r22: the screen-content refusal here was STALE (class
10952 // stale-premise): [`decode_rect4_16_strip`] takes
10953 // `allow_screen_content_tools` and reads the whole palette syntax
10954 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
10955 // pair) -- the key frame proves that body. Lifted with the 10-bit
10956 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
10957 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
10958 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
10959 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
10960 let res = decode_rect4_16_strip(
10961 dec,
10962 cdfs,
10963 neighbours,
10964 (mi_r, mi_c),
10965 horz,
10966 has_chroma,
10967 // The inter strips of the same partition publish their own
10968 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
10969 // has nothing to add here.
10970 None,
10971 y,
10972 u,
10973 v,
10974 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10975 allow_screen_content_tools,
10976 base_q_idx,
10977 fctx.tx_select_inter.with(std::cell::Cell::get),
10978 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10979 );
10980 fctx.intra_in_inter_mode.with(|c| c.set(None));
10981 let (mode, uv, (tx_w, tx_h)) = res?;
10982 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
10983 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
10984 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
10985 // block of an inter frame, intra ones included, and
10986 // `txfm_partition_update` for the var-tx context. The key-frame body
10987 // writes neither (a key frame has no var-tx tree and its own readers
10988 // use the deblock grid), so the block AFTER this strip read a stale
10989 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
10990 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
10991 // 16x16 row.
10992 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10993 for i in 0..bw / MI {
10994 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
10995 *cell = tx_w as u8;
10996 }
10997 }
10998 for i in 0..bh / MI {
10999 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
11000 *cell = tx_h as u8;
11001 }
11002 }
11003 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
11004 // coarse 16-px cell holds one entry for the whole 16x16 and the last
11005 // block to write it wins).
11006 neighbours.above_mode[c] = mode;
11007 neighbours.left_mode[r] = mode;
11008 if let Some(uvm) = uv {
11009 neighbours.above_uv_mode[c] = uvm;
11010 neighbours.left_uv_mode[r] = uvm;
11011 }
11012 neighbours.above_side[c] = bw;
11013 neighbours.left_side[r] = bh;
11014 if crate::envflags::env_flag!("EC_INTRA16X4") {
11015 eprintln!(
11016 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
11017 mi_c * MI,
11018 mi_r * MI
11019 );
11020 }
11021 hit_do! {
11022 INTRA16X4_IN_INTER_HITS.with(|h| {
11023 let mut v = h.get();
11024 v[usize::from(!horz)] += 1;
11025 v[2] += usize::from(has_chroma);
11026 h.set(v);
11027 });
11028 }
11029 return Ok(());
11030 }
11031 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
11032 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
11033 // puts BLOCK_128X64/64X128/128X128 in group 3 and
11034 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
11035 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
11036 // block decodes through the very body the KEY FRAME path proves for this
11037 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
11038 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
11039 // `Reach` rule and the frame-edge write clip). The only inter-frame
11040 // differences live inside that body: the mode-info read
11041 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
11042 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
11043 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
11044 // palette (>64) do not exist at this size and are refused by name there.
11045 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
11046 // `intra128_in_inter_witness2.obu` (gate
11047 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
11048 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
11049 // all 15 frames, so the hits are counted out of exact frames (class
11050 // `counter-from-refused-stream`). What r16/r17 could not find, and what
11051 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
11052 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
11053 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
11054 // where the frame EDGE forces it: a partial last superblock row has
11055 // `has_rows128 == false`, so the 128x64 top half is implied, and a
11056 // partial last column implies the 64x128 left half. Put content no
11057 // reference holds (a fresh smooth ramp) in exactly those two bands of an
11058 // inter frame and the encoder codes those forced halves INTRA.
11059 if bw.max(bh) == 128 {
11060 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
11061 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
11062 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
11063 // palette_syntax`), so a 128-root half consumes no palette syntax and
11064 // a screen-content frame's half is syntactically identical to the
11065 // non-screen one this arm already decodes byte-exact.
11066 if coeff_trace_on() {
11067 // lane-t900 r16: which decode-order frame this arm fires in --
11068 // interleaved with the `EC_COEFF_FRAME` markers, this is what
11069 // proves the hit is counted out of a frame that compares exact
11070 // (class `counter-from-refused-stream`).
11071 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
11072 }
11073 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
11074 let res = decode_block_128rect(
11075 dec,
11076 cdfs,
11077 neighbours,
11078 (r, c),
11079 bw,
11080 bh,
11081 y,
11082 u,
11083 v,
11084 base_q_idx,
11085 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
11086 allow_screen_content_tools,
11087 fctx.tx_select_inter.with(std::cell::Cell::get),
11088 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
11089 );
11090 fctx.intra_in_inter_mode.with(|c| c.set(None));
11091 return res;
11092 }
11093 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
11094 if crate::envflags::env_flag!("EC_OBMCREC") {
11095 eprintln!(
11096 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
11097 );
11098 }
11099 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
11100 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
11101 // can arrive here are enumerated against the measured block-shape
11102 // census ([`INTER_BLOCK_SHAPES`]) by
11103 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
11104 // -- every one of them has a row, so this arm names a shape no stream
11105 // has been able to present.
11106 return Err(unsupported(format!(
11107 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
11108 )));
11109 };
11110 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
11111 // screen-content frame ("palette syntax is consumed for square blocks
11112 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
11113 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
11114 // it, while the 2:1 reader inlined further down now codes the same syntax
11115 // itself. A real `--tune-content=screen` inter stream reached this refusal
11116 // on 8x16 / 16x8 strips (gate
11117 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
11118 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
11119 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
11120 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
11121 // luma/chroma transform tables, the per-unit split walk and the strip's
11122 // own neighbour records). The ONLY difference on an inter frame is the
11123 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
11124 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
11125 // this caller already read. `tx_cat` above is the same category those
11126 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
11127 // `decode_block_rect64`), asserted here so a future shape cannot drift.
11128 if bw.max(bh) == 4 * bw.min(bh) {
11129 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
11130 fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip))));
11131 let res = if bw.max(bh) == 64 {
11132 decode_block_rect64(
11133 dec,
11134 cdfs,
11135 neighbours,
11136 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
11137 bw,
11138 bh,
11139 y,
11140 u,
11141 v,
11142 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
11143 allow_screen_content_tools,
11144 base_q_idx,
11145 fctx.tx_select_inter.with(std::cell::Cell::get),
11146 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
11147 )
11148 } else {
11149 decode_block_rect4(
11150 dec,
11151 cdfs,
11152 neighbours,
11153 (mi_r, mi_c),
11154 bw,
11155 bh,
11156 None,
11157 y,
11158 u,
11159 v,
11160 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
11161 allow_screen_content_tools,
11162 base_q_idx,
11163 fctx.tx_select_inter.with(std::cell::Cell::get), fctx,
11164 )
11165 .map(|_| ())
11166 };
11167 fctx.intra_in_inter_mode.with(|c| c.set(None));
11168 res?;
11169 let shape = match (bw, bh) {
11170 (64, 16) => 0,
11171 (16, 64) => 1,
11172 (32, 8) => 2,
11173 _ => 3,
11174 };
11175 hit_do! {
11176 INTRA_RECT4_IN_INTER_HITS.with(|h| {
11177 let mut v = h.get();
11178 v[shape] += 1;
11179 h.set(v);
11180 });
11181 }
11182 return Ok(());
11183 }
11184 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
11185 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
11186 // own, so a cross-decoder bisection could only see the block's first
11187 // coefficient. Same names/format as [`read_tx_size`]'s rung.
11188 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
11189 if step_trace {
11190 eprintln!(
11191 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
11192 dec.debug_state().0
11193 );
11194 }
11195 if mode >= 13 {
11196 return Err(unsupported(
11197 "an intra mode this decoder does not code (round 2)",
11198 ));
11199 }
11200 // lane-angleinter (merged on main for the square intra-in-inter arm):
11201 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
11202 // directional predictor; this arm refused a nonzero one before the merge.
11203 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
11204 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
11205 } else {
11206 0
11207 };
11208 if angle_delta_y != 0 {
11209 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
11210 }
11211 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
11212 // superblock-level strip reads the no-CFL alphabet -- the same split
11213 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
11214 //
11215 // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
11216 // (libaom `decodemv.c:933`).
11217 let has_chroma = !mono(fctx);
11218 let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
11219 let uv_mode = if !has_chroma {
11220 DC_PRED
11221 } else if cfl_allowed {
11222 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
11223 } else {
11224 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
11225 };
11226 if step_trace {
11227 eprintln!(
11228 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
11229 u8::from(cfl_allowed),
11230 dec.debug_state().0
11231 );
11232 }
11233 if (9..=12).contains(&uv_mode) {
11234 hit!(SMOOTH_UV_HITS);
11235 }
11236 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
11237 Some(read_cfl_alphas(dec, cdfs))
11238 } else {
11239 None
11240 };
11241 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
11242 DC_PRED
11243 } else {
11244 uv_mode
11245 };
11246 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
11247 hit!(DIRECTIONAL_UV_HITS);
11248 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
11249 } else {
11250 0
11251 };
11252 if angle_delta_uv != 0 {
11253 hit!(UV_ANGLE_DELTA_HITS);
11254 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
11255 }
11256 // `read_palette_mode_info` (spec 5.11.13), in the position
11257 // `read_intra_block_mode_info` writes it: after the chroma mode and
11258 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
11259 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
11260 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
11261 // skipping the syntax here desynced the tile at the strip's own symbol.
11262 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
11263 // context and colour cache at its own mi position, and the two
11264 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
11265 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
11266 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
11267 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
11268 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
11269 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
11270 if allow_screen_content_tools
11271 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
11272 {
11273 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
11274 let use_palette_y =
11275 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
11276 if use_palette_y {
11277 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
11278 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
11279 }
11280 // A 2:1 strip of at least 8x8 is always a chroma reference, so
11281 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
11282 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
11283 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
11284 let use_palette_uv = has_chroma
11285 && uv_mode == DC_PRED
11286 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
11287 if crate::envflags::env_flag!("EC_PALSYN") {
11288 eprintln!("EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", use_palette_y as i32, use_palette_uv as i32, dec.debug_state().0);
11289 }
11290 if use_palette_uv {
11291 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
11292 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
11293 palette_uv_pending = Some((n, u_colors, v_colors));
11294 }
11295 }
11296 // lane-fiinter (merged on main for the square intra-in-inter arm):
11297 // `read_filter_intra_mode_info` is the tail of
11298 // `read_intra_block_mode_info`, after the palette syntax (refused whole
11299 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
11300 // 2:1 strips with both sides <= 32 -- their own CDF rows
11301 // ([`filter_intra_size_class_rect`]).
11302 let mut filter_intra = None;
11303 if mode == DC_PRED
11304 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
11305 // `av1_filter_intra_allowed` excludes a palette-Y block.
11306 && palette_y_pending.is_none()
11307 && let Some(class) = filter_intra_size_class_rect(bw, bh)
11308 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
11309 {
11310 hit!(FILTER_INTRA_HITS);
11311 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
11312 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
11313 }
11314 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
11315 let palette_y = palette_y_pending.map(|(n, colors)| {
11316 let map =
11317 decode_color_index_map_wh(dec, cdfs, n, bw, bh, palette_onscreen(mi_r, mi_c, bw, bh, fctx), false);
11318 hit!(PALETTE_HITS);
11319 hit!(PALETTE_RECT_HITS);
11320 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
11321 PaletteY { size: n, colors, map }
11322 });
11323 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
11324 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
11325 let on = palette_onscreen_uv((bw, bh), palette_onscreen(mi_r, mi_c, bw, bh, fctx), (cw, ch), (ss_x(fctx), ss_y(fctx)));
11326 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
11327 hit!(PALETTE_UV_HITS);
11328 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
11329 PaletteUv { size: n, u_colors, v_colors, map }
11330 });
11331 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
11332 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
11333 // chroma ones -- [`decode_block_rect`]'s own pair.
11334 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
11335 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
11336 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
11337 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
11338 // one exactly as [`decode_leaf8`] already does (class
11339 // context-read-from-one-cell).
11340 let coarse_pair = neighbours.modes_above_left(r, c);
11341 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
11342 if (nb_above_mode, nb_left_mode) != coarse_pair {
11343 hit!(EDGE_FILTER_MI_FIX_HITS);
11344 }
11345 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
11346 if smooth_neighbor {
11347 hit!(SMOOTH_LUMA_HITS);
11348 }
11349 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
11350 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
11351 // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside
11352 // an inter frame codes no depth symbol either (`xd->lossless` is per
11353 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
11354 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
11355 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
11356 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
11357 let d = match tx_cat {
11358 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
11359 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
11360 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
11361 };
11362 if step_trace {
11363 eprintln!(
11364 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
11365 dec.debug_state().0
11366 );
11367 }
11368 d
11369 } else {
11370 0
11371 };
11372 if depth != 0 || lossless(fctx) {
11373 hit!(TX_DEPTH_HITS);
11374 // lane-intrasplit r1: a split intra strip in an inter frame walks the
11375 // key frame's own per-TU path ([`decode_rect_split`] below); what was
11376 // wrong when this refusal was written was the depth SYMBOL, not the walk.
11377 hit_do! {
11378 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
11379 let mut v = h.get();
11380 v[depth.min(2)] += 1;
11381 h.set(v);
11382 });
11383 }
11384 }
11385 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
11386 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
11387 // the two are indistinguishable when the diagnostic fires on splits alone.
11388 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
11389 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
11390 }
11391 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
11392 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
11393 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
11394 // of an inter frame, intra ones included -- with the skip term 0 it
11395 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
11396 // and `left_txfm_context` to `tx_size_high` over its height. This strip
11397 // wrote neither, so the next block's var-tx `txfm_partition` context read
11398 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
11399 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
11400 // mi(16,0) and desyncing the tile at that symbol.
11401 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
11402 let modes = RectStripModes {
11403 skip,
11404 mode,
11405 angle_delta_y,
11406 uv_predict_mode,
11407 angle_delta_uv,
11408 alpha,
11409 filter_intra,
11410 smooth_neighbor,
11411 smooth_neighbor_uv,
11412 palette_y: palette_y
11413 .as_ref()
11414 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
11415 palette_uv: palette_uv.as_ref().map(|p| {
11416 (
11417 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11418 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11419 )
11420 }),
11421 };
11422 decode_rect_split(
11423 dec,
11424 cdfs,
11425 neighbours,
11426 (mi_r, mi_c),
11427 bw,
11428 bh,
11429 tx_w,
11430 tx_h,
11431 &modes,
11432 y,
11433 u,
11434 v,
11435 base_q_idx,
11436 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
11437 )?;
11438 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
11439 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
11440 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
11441 // left column over its height. This arm wrote neither before lane-intrasplit
11442 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
11443 // context across the strip's footprint.
11444 for i in 0..bw / MI {
11445 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
11446 *cell = tx_w as u8;
11447 }
11448 }
11449 for i in 0..bh / MI {
11450 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
11451 *cell = tx_h as u8;
11452 }
11453 }
11454 // The strip's own palette state into the mi-granular neighbour bands, so
11455 // the next block's colour cache and `palette_y_mode` context are libaom's.
11456 record_strip_palette(
11457 neighbours,
11458 (mi_r, mi_c),
11459 bw,
11460 bh,
11461 palette_y.as_ref().map_or(0, |p| p.size),
11462 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
11463 palette_uv.as_ref().map_or(0, |p| p.size),
11464 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
11465 );
11466 let class = match bw.max(bh) {
11467 64 => 0,
11468 32 => 1,
11469 _ => 2,
11470 };
11471 hit_do! {
11472 INTRA_RECT_IN_INTER_HITS.with(|h| {
11473 let mut v = h.get();
11474 v[class] += 1;
11475 h.set(v);
11476 });
11477 }
11478 Ok(())
11479}
11480
11481/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real
11482/// mi `(mi_r, mi_c)` (lane-av1-intrabc).
11483///
11484/// libaom treats an intrabc block as INTER for everything except the mode-info
11485/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA`
11486/// (`blockd.h:373`), so
11487///
11488/// * `parse_decode_block` reads the transform size through the INTER var-tx
11489/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose
11490/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and
11491/// whose leaves publish their own resolved size back;
11492/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT
11493/// frame's own pre-loop-filter reconstruction, at the coded block vector
11494/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`);
11495/// * `decode_token_recon_block`'s inter branch then reads one residual per
11496/// transform unit, through the INTER coefficient sets
11497/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane
11498/// inheriting the colocated luma unit's coded `tx_type`.
11499///
11500/// Text order is libaom's: transform tree, prediction, luma residual, chroma
11501/// residual, bookkeeping. A skipped block codes no residual at all -- the
11502/// prediction is the reconstruction.
11503#[allow(clippy::too_many_arguments)]
11504fn decode_intrabc_rect(
11505 dec: &mut SymbolDecoder,
11506 cdfs: &mut Cdfs,
11507 neighbours: &mut Neighbours,
11508 (mi_r, mi_c): (usize, usize),
11509 (bw, bh): (usize, usize),
11510 skip: bool,
11511 (dv_row, dv_col): (i32, i32),
11512 y: &mut PlaneBuf<'static>,
11513 u: &mut PlaneBuf<'static>,
11514 v: &mut PlaneBuf<'static>,
11515 base_q_idx: u8,
11516 fctx: &crate::decode::FrameCtx,
11517) -> Result<()> {
11518 hit!(INTRABC_RECT_HITS);
11519 // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
11520 let idx = usize::from(bh > bw);
11521 if skip {
11522 INTRABC_RECT_SKIPPED_HITS.with(|c| {
11523 let mut seen = c.get();
11524 seen[idx] += 1;
11525 c.set(seen);
11526 });
11527 } else {
11528 INTRABC_RECT_CODED_HITS.with(|c| {
11529 let mut seen = c.get();
11530 seen[idx] += 1;
11531 c.set(seen);
11532 });
11533 }
11534 let (px, py) = (mi_c * MI, mi_r * MI);
11535 let (cpx, cpy) = (px / 2, py / 2);
11536 // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the
11537 // halved shape's own `max_txsize_rect_lookup` entry IS that size for every
11538 // shape this helper is called at, so the uv plane block is ONE unit --
11539 // the same call `decode_token_recon_block`'s own chroma loop makes.
11540 let (cw, ch) = (bw / 2, bh / 2);
11541 // lane-av1-intrabc r2: the square stride the proven INTER path uses
11542 // (`side`). The residual grids, the prediction windows AND
11543 // `TxParams::stride` are all laid out at it -- the block's own width
11544 // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h`
11545 // exceeds the stride).
11546 let side = bw.max(bh);
11547 let cside = cw.max(ch);
11548 // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right
11549 // or bottom frame edge reads no transform-tree symbol for the units
11550 // outside it.
11551 let mi_cols = 2 * y.true_width.div_ceil(8);
11552 let mi_rows = 2 * y.true_height.div_ceil(8);
11553 let leaves = read_block_tx_size_rect(
11554 dec,
11555 cdfs,
11556 neighbours,
11557 (mi_r, mi_c),
11558 (bw, bh),
11559 (mi_cols, mi_rows),
11560 skip, fctx,
11561 )?;
11562 if leaves.is_some() {
11563 hit!(INTRABC_RECT_VARTX_HITS);
11564 }
11565 // The whole-block prediction: `predict_inter_block` runs once, before any
11566 // coefficient is read. `flush_recon` first -- the source is this frame's
11567 // own reconstruction, including the writes this superblock has queued.
11568 flush_recon(fctx, y, u, v);
11569 // `mc::predict_with_filter` writes a DENSE window; the residual machinery
11570 // reads it at the square stride, so re-lay it -- the same step the inter
11571 // path takes for its own square prediction buffer.
11572 let mut pred_y_dense = vec![0u16; bw * bh];
11573 mc::predict_with_filter(
11574 &y.data, y.width, y.true_width, y.true_height,
11575 mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0),
11576 bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx,
11577 );
11578 let mut pred_y = vec![0u16; side * side];
11579 for row in 0..bh {
11580 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
11581 }
11582 let mut pred_u_dense = vec![0u16; cw * ch];
11583 mc::predict_with_filter(
11584 &u.data, u.width, u.true_width, u.true_height,
11585 mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)),
11586 cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_u_dense, fctx,
11587 );
11588 let mut pred_u = vec![0u16; cside * cside];
11589 for row in 0..ch {
11590 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
11591 }
11592 let mut pred_v_dense = vec![0u16; cw * ch];
11593 mc::predict_with_filter(
11594 &v.data, v.width, v.true_width, v.true_height,
11595 mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)),
11596 cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_v_dense, fctx,
11597 );
11598 let mut pred_v = vec![0u16; cside * cside];
11599 for row in 0..ch {
11600 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
11601 }
11602 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
11603 let luma_tx_type: TxType;
11604 let (luma_grid, u_grid, v_grid);
11605 if skip {
11606 // No residual syntax at all: the prediction IS the block.
11607 // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes
11608 // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip
11609 // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm.
11610 push_mc_rect(0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * side], fctx);
11611 push_mc_rect(1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * cside], fctx);
11612 push_mc_rect(2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * cside], fctx);
11613 if let Some(ls) = leaves.as_ref() {
11614 // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s
11615 // skip arm performs -- libaom `av1_reset_entropy_context`
11616 // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a
11617 // SKIPPED block zeroes its whole entropy-band footprint. This
11618 // helper serves `decode_block_rect4`'s 1:4 strips on this tree,
11619 // so a skipped lossless strip whose `leaves` resolved (every
11620 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
11621 // returns the 4x4 grid before it looks at `skip`) left the
11622 // PREVIOUS occupant's luma bands standing and the NEXT block's
11623 // partition parse diverged from libaom's: the 320x242 lossless
11624 // sb128 gate read a phantom unskipped 8x32 intrabc strip at
11625 // mi(56,66) right after the skipped 8x16 one at mi(48,66).
11626 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
11627 for &(row, col, tw, th) in ls {
11628 neighbours.record_mi_luma_rect(
11629 (mi_r + row, mi_c + col),
11630 tw,
11631 th,
11632 &ZERO_RESIDUAL[..tw * th],
11633 );
11634 }
11635 }
11636 luma_tx_type = TxType::DctDct;
11637 luma_grid = Grid::Zero(side * side);
11638 u_grid = Grid::Zero(cside * cside);
11639 v_grid = Grid::Zero(cside * cside);
11640 } else {
11641 match leaves.as_ref() {
11642 None => {
11643 // One whole-block rectangular transform unit.
11644 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
11645 let (grid, tx_type) = read_inter_plane_rect(
11646 dec,
11647 cdfs,
11648 rect_inter_luma_set(bw, bh, fctx)?,
11649 (bw, bh),
11650 side,
11651 0,
11652 around[0],
11653 0,
11654 y,
11655 px,
11656 py,
11657 Pred::Inline(&pred_y, side),
11658 None,
11659 None, fctx,
11660 )?;
11661 luma_tx_type = tx_type;
11662 luma_grid = embed_grid_stride(&grid, bw, bh, side);
11663 let (ug, _) = read_inter_plane_rect(
11664 dec,
11665 cdfs,
11666 rect_inter_chroma_set(cw, ch)?,
11667 (cw, ch),
11668 cside,
11669 1,
11670 around[1],
11671 0,
11672 u,
11673 cpx,
11674 cpy,
11675 Pred::Inline(&pred_u, cside),
11676 Some(luma_tx_type),
11677 None, fctx,
11678 )?;
11679 u_grid = embed_grid_stride(&ug, cw, ch, cside);
11680 let (vg, _) = read_inter_plane_rect(
11681 dec,
11682 cdfs,
11683 rect_inter_chroma_set(cw, ch)?,
11684 (cw, ch),
11685 cside,
11686 2,
11687 around[2],
11688 0,
11689 v,
11690 cpx,
11691 cpy,
11692 Pred::Inline(&pred_v, cside),
11693 Some(luma_tx_type),
11694 None, fctx,
11695 )?;
11696 v_grid = embed_grid_stride(&vg, cw, ch, cside);
11697 }
11698 Some(leaves) => {
11699 // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies
11700 // the split override to LUMA only, per leaf -- the step the
11701 // proven inter var-tx path applies right after its own residual
11702 // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the
11703 // leaf's own transform edges are never filtered.
11704 for &(row, col, tw, th) in leaves.iter() {
11705 neighbours.fill_lf_grid_leaf_luma(
11706 (mi_r + row, mi_c + col),
11707 tw / MI,
11708 th / MI,
11709 tw as u8,
11710 th as u8,
11711 );
11712 }
11713 // One residual per transform unit, in the order the tree coded
11714 // them; each unit reads its own neighbour-magnitude context off
11715 // the units already decoded before it, and every unit adds onto
11716 // its own window of the block's single prediction.
11717 let mut first_tx_type = TxType::DctDct;
11718 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
11719 let tu_mi = (mi_r + row, mi_c + col);
11720 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
11721 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
11722 let (tu_grid, tu_tx_type) = if tw == th {
11723 let scan = default_scan(tw.min(32));
11724 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
11725 read_inter_plane(
11726 dec,
11727 cdfs,
11728 inter_txbset_for(tw, reduced),
11729 scan,
11730 0,
11731 neighbours.around_mi(tu_mi, tw)[0],
11732 0,
11733 y,
11734 tu_px,
11735 tu_py,
11736 tw,
11737 base_q_idx,
11738 tu_pred,
11739 None,
11740 Some(tu_skip_ctx), fctx,
11741 )?
11742 } else {
11743 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
11744 read_inter_plane_rect(
11745 dec,
11746 cdfs,
11747 rect_inter_luma_set(tw, th, fctx)?,
11748 (tw, th),
11749 side,
11750 0,
11751 neighbours.around_mi_rect(tu_mi, tw, th)[0],
11752 0,
11753 y,
11754 tu_px,
11755 tu_py,
11756 tu_pred,
11757 None,
11758 Some(tu_skip_ctx), fctx,
11759 )?
11760 };
11761 if idx == 0 {
11762 first_tx_type = tu_tx_type;
11763 }
11764 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
11765 }
11766 // `av1_get_tx_type`'s chroma lookup lands on the colocated
11767 // LUMA unit, which for a split block is the top-left one.
11768 luma_tx_type = first_tx_type;
11769 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
11770 let (ug, _) = read_inter_plane_rect(
11771 dec,
11772 cdfs,
11773 rect_inter_chroma_set(cw, ch)?,
11774 (cw, ch),
11775 cside,
11776 1,
11777 around[1],
11778 0,
11779 u,
11780 cpx,
11781 cpy,
11782 Pred::Inline(&pred_u, cside),
11783 Some(luma_tx_type),
11784 None, fctx,
11785 )?;
11786 u_grid = embed_grid_stride(&ug, cw, ch, cside);
11787 let (vg, _) = read_inter_plane_rect(
11788 dec,
11789 cdfs,
11790 rect_inter_chroma_set(cw, ch)?,
11791 (cw, ch),
11792 cside,
11793 2,
11794 around[2],
11795 0,
11796 v,
11797 cpx,
11798 cpy,
11799 Pred::Inline(&pred_v, cside),
11800 Some(luma_tx_type),
11801 None, fctx,
11802 )?;
11803 v_grid = embed_grid_stride(&vg, cw, ch, cside);
11804 luma_grid = Grid::Zero(side * side);
11805 }
11806 }
11807 }
11808 let _ = luma_tx_type;
11809 // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the
11810 // next block reads a neighbour mode, its own block size in both `TXFM`
11811 // bands (already done by `read_block_tx_size_rect`), a zeroed palette
11812 // state (a stale entry would feed the next block's colour cache), and its
11813 // DV into the intrabc mi grid the next block's DV predictor reads.
11814 if leaves.is_some() {
11815 neighbours.record_split_luma_rect_mi(
11816 (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid, &v_grid],
11817 );
11818 } else {
11819 neighbours.record_rect_mi(
11820 (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &[&luma_grid, &u_grid, &v_grid],
11821 );
11822 }
11823 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
11824 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
11825 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
11826 neighbours.fill_lf_grid_rect(
11827 (mi_r, mi_c),
11828 bw / MI,
11829 bh / MI,
11830 bw.min(64) as u8,
11831 bh.min(64) as u8,
11832 0, fctx,
11833 );
11834 record_intrabc_mi_rect(
11835 mi_r,
11836 mi_c,
11837 bw / MI,
11838 bh / MI,
11839 Some((dv_row, dv_col)),
11840 neighbours,
11841 fctx,
11842 );
11843 Ok(())
11844}
11845
11846/// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root
11847/// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape
11848/// `decode_block_128rect` refused by name before this port. libaom decodes
11849/// such a block through the INTER machinery (an intrabc block
11850/// `is_inter_block`): `predict_inter_block` copies the whole block from this
11851/// frame's own reconstruction at the integer block vector once, then
11852/// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks --
11853/// per chunk every plane, luma units at the block's own resolved transform
11854/// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at
11855/// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per
11856/// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits
11857/// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`,
11858/// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in
11859/// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here.
11860#[allow(clippy::too_many_arguments)]
11861fn decode_intrabc_128rect(
11862 dec: &mut SymbolDecoder,
11863 cdfs: &mut Cdfs,
11864 neighbours: &mut Neighbours,
11865 (mi_r, mi_c): (usize, usize),
11866 (bw, bh): (usize, usize),
11867 skip: bool,
11868 (dv_row, dv_col): (i32, i32),
11869 y: &mut PlaneBuf<'static>,
11870 u: &mut PlaneBuf<'static>,
11871 v: &mut PlaneBuf<'static>,
11872 base_q_idx: u8,
11873 fctx: &crate::decode::FrameCtx,
11874) -> Result<()> {
11875 hit!(INTRABC_128RECT_HITS);
11876 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11877 let (rng, _) = dec.debug_state();
11878 eprintln!(
11879 "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}"
11880 );
11881 }
11882 let (px, py) = (mi_c * MI, mi_r * MI);
11883 let (cpx, cpy) = (px / 2, py / 2);
11884 let (cw, ch) = (bw / 2, bh / 2);
11885 // The square strides the proven INTER path lays its residual grids,
11886 // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2
11887 // note): 128/64 here.
11888 let side = bw.max(bh);
11889 let cside = cw.max(ch);
11890 // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code
11891 // nothing (`decode_reconstruct_tx`'s max_blocks_* early return).
11892 let mi_cols = 2 * y.true_width.div_ceil(8);
11893 let mi_rows = 2 * y.true_height.div_ceil(8);
11894 // An intrabc block is is_inter_block: the tx tree is the INTER one, and
11895 // [`read_block_tx_size_rect`]'s 128-root branch already carries the
11896 // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree
11897 // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid)
11898 // arms (lane-sb128c r7).
11899 let leaves = read_block_tx_size_rect(
11900 dec,
11901 cdfs,
11902 neighbours,
11903 (mi_r, mi_c),
11904 (bw, bh),
11905 (mi_cols, mi_rows),
11906 skip, fctx,
11907 )?;
11908 // Whole-block prediction, once, before any coefficient is read
11909 // (`predict_inter_block`); the source is this frame's own
11910 // reconstruction, including the writes this superblock has queued.
11911 flush_recon(fctx, y, u, v);
11912 let mut pred_y_dense = vec![0u16; bw * bh];
11913 mc::predict_with_filter(
11914 &y.data, y.width, y.true_width, y.true_height,
11915 mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0),
11916 bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx,
11917 );
11918 let mut pred_y = vec![0u16; side * side];
11919 for row in 0..bh {
11920 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
11921 }
11922 let mut pred_u_dense = vec![0u16; cw * ch];
11923 mc::predict_with_filter(
11924 &u.data, u.width, u.true_width, u.true_height,
11925 mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)),
11926 cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_u_dense, fctx,
11927 );
11928 let mut pred_u = vec![0u16; cside * cside];
11929 for row in 0..ch {
11930 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
11931 }
11932 let mut pred_v_dense = vec![0u16; cw * ch];
11933 mc::predict_with_filter(
11934 &v.data, v.width, v.true_width, v.true_height,
11935 mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)),
11936 cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_v_dense, fctx,
11937 );
11938 let mut pred_v = vec![0u16; cside * cside];
11939 for row in 0..ch {
11940 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
11941 }
11942 let (luma_grid, u_grid, v_grid);
11943 // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour
11944 // contexts per transform unit -- the replay after this fn's end-of-block
11945 // record restores them (the record itself re-stamps both planes with ONE
11946 // composed state, class `override-slot-on-one-arm`).
11947 let mut mu_chroma = false;
11948 if skip {
11949 // No residual syntax at all: the prediction IS the block. Strides are
11950 // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes
11951 // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun).
11952 push_mc_rect(0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * side], fctx);
11953 push_mc_rect(1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * cside], fctx);
11954 push_mc_rect(2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * cside], fctx);
11955 if let Some(ls) = leaves.as_ref() {
11956 // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4
11957 // grid before it looks at `skip`; the skipped block still zeroes
11958 // its entropy-band footprint over every unit (libaom
11959 // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) --
11960 // the same arm [`decode_intrabc_rect`]'s loss64 merge added.
11961 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
11962 for &(row, col, tw, th) in ls {
11963 neighbours.record_mi_luma_rect(
11964 (mi_r + row, mi_c + col),
11965 tw,
11966 th,
11967 &ZERO_RESIDUAL[..tw * th],
11968 );
11969 }
11970 }
11971 luma_grid = Grid::Zero(side * side);
11972 u_grid = Grid::Zero(cside * cside);
11973 v_grid = Grid::Zero(cside * cside);
11974 } else {
11975 let leaves = leaves.expect(
11976 "read_block_tx_size_rect returns None only for skip below 128 at this shape",
11977 );
11978 // libaom `get_transform_size`'s split override applies to LUMA only,
11979 // per leaf -- each unit's own transform edges get filtered
11980 // ([`decode_intrabc_rect`]'s P2, the proven inter path's step).
11981 for &(row, col, tw, th) in leaves.iter() {
11982 neighbours.fill_lf_grid_leaf_luma(
11983 (mi_r + row, mi_c + col),
11984 tw / MI,
11985 th / MI,
11986 tw as u8,
11987 th as u8,
11988 );
11989 }
11990 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
11991 let mut u_units: Vec<i32> = Vec::new();
11992 let mut v_units: Vec<i32> = Vec::new();
11993 let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new();
11994 // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose
11995 // top-left sample is outside the frame codes nothing.
11996 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
11997 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
11998 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
11999 debug_assert_eq!(tw, th, "a square TX_64X64 tree root only yields square leaves");
12000 let tu_mi = (mi_r + row, mi_c + col);
12001 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
12002 if tu_px >= y.true_width || tu_py >= y.true_height {
12003 continue;
12004 }
12005 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
12006 let scan = default_scan(tw.min(32));
12007 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
12008 let (tu_grid, tu_tx_type) = read_inter_plane(
12009 dec,
12010 cdfs,
12011 inter_txbset_for(tw, reduced),
12012 &scan,
12013 0,
12014 neighbours.around_mi(tu_mi, tw)[0],
12015 0,
12016 y,
12017 tu_px,
12018 tu_py,
12019 tw,
12020 base_q_idx,
12021 tu_pred,
12022 None,
12023 Some(tu_skip_ctx), fctx,
12024 )?;
12025 leaf_tx_types.push((row, col, tw, th, tu_tx_type));
12026 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
12027 // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64
12028 // mu chunk before the next one starts: once this chunk's leaves
12029 // are done, its chroma is read immediately (the inter 128 path's
12030 // interleave).
12031 let chunk = (row / 16, col / 16);
12032 let done = idx + 1 == leaves.len()
12033 || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk;
12034 if done {
12035 let (cr, cc) = chunk;
12036 // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one
12037 // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster
12038 // within the chunk, plane-major inside the chunk.
12039 let cu_tx = 32usize;
12040 let chunk_chroma = cside * 64 / side;
12041 let unit_luma = cu_tx * (side / cside);
12042 let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16));
12043 let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16));
12044 let units_x = chunk_w_mi / (unit_luma / MI);
12045 let units_y = chunk_h_mi / (unit_luma / MI);
12046 if lossless(fctx) {
12047 // TX_4X4 chroma units over this chunk (lane-lossless2's
12048 // walk, shared with the inter 128 path).
12049 read_inter_chroma_lossless(
12050 dec, cdfs, neighbours, u, v,
12051 Pred::Inline(&pred_u, cside), Pred::Inline(&pred_v, cside),
12052 (mi_r, mi_c), (cpx, cpy),
12053 (cc * chunk_chroma, cr * chunk_chroma),
12054 (chunk_chroma, chunk_chroma),
12055 (cw, ch),
12056 cside, 0, base_q_idx,
12057 &mut u_units, &mut v_units, fctx,
12058 )?;
12059 // lane-av1-ibcrect: read_inter_chroma_lossless stamped
12060 // every TX_4X4 unit's own context (`record_mi_chroma`
12061 // inside the walk) -- the end-of-block record below must
12062 // not overwrite them with the composed grid (the inter
12063 // 128 path sets the same flag on this arm).
12064 mu_chroma = true;
12065 continue;
12066 }
12067 let cu_scan = default_scan(cu_tx);
12068 for plane_idx in 1..3 {
12069 let (src, buf) = if plane_idx == 1 {
12070 (Pred::Inline(&pred_u, cside), &mut *u)
12071 } else {
12072 (Pred::Inline(&pred_v, cside), &mut *v)
12073 };
12074 for ur in 0..units_y {
12075 for uc in 0..units_x {
12076 let unit_mi = (
12077 mi_r + cr * 16 + ur * (unit_luma / MI),
12078 mi_c + cc * 16 + uc * (unit_luma / MI),
12079 );
12080 // Per unit, AFTER the earlier units' stamps: this
12081 // unit's coefficient context must see them.
12082 let cu_around = neighbours.around_mi(unit_mi, unit_luma);
12083 if crate::envflags::env_flag!("EC_ECDUMP") {
12084 for p in 1..3 {
12085 let ab: Vec<String> = (0..unit_luma / MI)
12086 .map(|k| {
12087 format!(
12088 "{:?}/{}",
12089 neighbours.above[unit_mi.1 + k][p].dc,
12090 neighbours.above[unit_mi.1 + k][p].level
12091 )
12092 })
12093 .collect();
12094 let lf: Vec<String> = (0..unit_luma / MI)
12095 .map(|k| {
12096 format!(
12097 "{:?}/{}",
12098 neighbours.left[unit_mi.0 + k][p].dc,
12099 neighbours.left[unit_mi.0 + k][p].level
12100 )
12101 })
12102 .collect();
12103 eprintln!(
12104 "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]",
12105 cu_around[p].0, cu_around[p].1, cu_around[p].2, ab.join(","), lf.join(",")
12106 );
12107 }
12108 }
12109 let (cu_x, cu_y) = (
12110 cpx + cc * chunk_chroma + uc * cu_tx,
12111 cpy + cr * chunk_chroma + ur * cu_tx,
12112 );
12113 // `av1_get_tx_type` (blockd.h:1291): an inter
12114 // block's chroma unit never codes a tx_type; it
12115 // inherits the coded type of the luma leaf
12116 // covering its own quadrant (all of this chunk's
12117 // leaves are read by now).
12118 let unit_rel_mi = (
12119 unit_mi.0 - mi_r,
12120 unit_mi.1 - mi_c,
12121 );
12122 let covering = leaf_tx_types
12123 .iter()
12124 .copied()
12125 .find(|&(lr, lc, lw, lh, _)| {
12126 lr <= unit_rel_mi.0
12127 && unit_rel_mi.0 < lr + lh / MI
12128 && lc <= unit_rel_mi.1
12129 && unit_rel_mi.1 < lc + lw / MI
12130 })
12131 .map(|(_, _, _, _, t)| t);
12132 let cu_pred = src.offset(
12133 (cr * chunk_chroma + ur * cu_tx) * cside
12134 + cc * chunk_chroma
12135 + uc * cu_tx,
12136 );
12137 let cu_grid = read_inter_plane(
12138 dec,
12139 cdfs,
12140 TxbSet::Chroma32,
12141 &cu_scan,
12142 plane_idx,
12143 cu_around[plane_idx],
12144 0,
12145 buf,
12146 cu_x,
12147 cu_y,
12148 cu_tx,
12149 base_q_idx,
12150 cu_pred,
12151 Some(covering.unwrap_or(TxType::DctDct)),
12152 Some(3), fctx,
12153 )?
12154 .0;
12155 // Immediately, so the NEXT unit reads this one's
12156 // coefficient context.
12157 neighbours.record_mi_chroma(
12158 unit_mi,
12159 unit_luma,
12160 unit_luma,
12161 plane_idx,
12162 &cu_grid,
12163 );
12164 if crate::envflags::env_flag!("EC_ECDUMP") {
12165 let st = crate::decode::neighbour_state(&cu_grid);
12166 eprintln!(
12167 "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})",
12168 st.dc, st.level
12169 );
12170 }
12171 hit!(CHROMA_SPLIT_TX_HITS);
12172 // lane-av1-ibcrect: per-unit chroma context -- the
12173 // end-of-block record's composed-grid re-stamp
12174 // must not stand (replayed below).
12175 mu_chroma = true;
12176 let dst = mu_units(
12177 if plane_idx == 1 { &mut u_units } else { &mut v_units },
12178 cside * cside,
12179 );
12180 for rr in 0..cu_tx {
12181 let start = (cr * chunk_chroma + ur * cu_tx + rr)
12182 * cside
12183 + cc * chunk_chroma
12184 + uc * cu_tx;
12185 dst[start..start + cu_tx]
12186 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
12187 }
12188 }
12189 }
12190 }
12191 }
12192 }
12193 // The block-level luma bands were recorded per leaf above; the
12194 // composed chroma grids carry every unit in place.
12195 luma_grid = Grid::Zero(side * side);
12196 u_grid = if u_units.is_empty() {
12197 Grid::Zero(cside * cside)
12198 } else {
12199 Grid::Own(std::mem::take(&mut u_units))
12200 };
12201 v_grid = if v_units.is_empty() {
12202 Grid::Zero(cside * cside)
12203 } else {
12204 Grid::Own(std::mem::take(&mut v_units))
12205 };
12206 }
12207 // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a
12208 // neighbour reads a mode, zeroed palette state, the skip grid, the
12209 // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them),
12210 // and the DV into the intrabc mi grid.
12211 if skip {
12212 neighbours.record_rect_mi(
12213 (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED,
12214 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
12215 );
12216 } else {
12217 neighbours.record_split_luma_rect_mi(
12218 (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid[..], &v_grid[..]],
12219 );
12220 }
12221 // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER
12222 // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside
12223 // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps
12224 // both planes with ONE `neighbour_state(composed_grid)` over the whole
12225 // span -- level = the SUM of every unit's levels and dc = the top-left
12226 // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128
12227 // inter block: the next block read a stale `dc_sign_ctx` one row low).
12228 // Measured on this shape: the 128x64 block at mi(64,32) of the
12229 // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared
12230 // into chunk-0's cells and the block below read `txb_skip` off the sum.
12231 // Replay every coded unit's own state after the record, in mu-chunk order
12232 // so a later unit still wins over an earlier one on the shared seam cells
12233 // (the composed construction `mu_chroma_units` uses, transcribed here).
12234 if mu_chroma {
12235 let cu = if lossless(fctx) { 4usize } else { 32usize };
12236 // The unit's own footprint on the LUMA mi grid (the chroma context
12237 // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s
12238 // convention): 8 px x2 per TX_4X4 unit, 64 px per TX_32X32 one.
12239 let unit_luma = cu * 2;
12240 // Raster over the block's chroma plane, `chunk_chroma` per mu chunk
12241 // (the same extents the read loop above laid the composed grid out
12242 // at) -- a unit the frame edge clipped codes nothing and carries no
12243 // composed samples beyond the clip, so it replays as the zero state
12244 // exactly like libaom's uncoded unit.
12245 let chunk_chroma = cside * 64 / side;
12246 let (rows, cols) = ((ch / chunk_chroma).max(1), (cw / chunk_chroma).max(1));
12247 for cr in 0..rows {
12248 for cc in 0..cols {
12249 let unit_mi = (mi_r + cr * (unit_luma / MI), mi_c + cc * (unit_luma / MI));
12250 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
12251 let mut unit = Vec::with_capacity(cu * cu);
12252 for rr in 0..cu {
12253 let start =
12254 (cr * chunk_chroma + rr) * cside + cc * chunk_chroma;
12255 unit.extend_from_slice(&grid[start..start + cu]);
12256 }
12257 neighbours.record_mi_chroma(
12258 unit_mi, unit_luma, unit_luma, plane_idx, &unit,
12259 );
12260 }
12261 }
12262 }
12263 }
12264 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
12265 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
12266 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
12267 neighbours.fill_lf_grid_rect(
12268 (mi_r, mi_c),
12269 bw / MI,
12270 bh / MI,
12271 bw.min(64) as u8,
12272 bh.min(64) as u8,
12273 0, fctx,
12274 );
12275 record_intrabc_mi_rect(
12276 mi_r,
12277 mi_c,
12278 bw / MI,
12279 bh / MI,
12280 Some((dv_row, dv_col)),
12281 neighbours,
12282 fctx,
12283 );
12284 Ok(())
12285}
12286
12287/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
12288/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
12289/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
12290/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
12291/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
12292/// has no rectangular-transform coefficient reader, and a chroma plane here
12293/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
12294/// with no depth-based square-tiling escape the way luma's own resolved
12295/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
12296/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
12297#[allow(clippy::too_many_arguments)]
12298fn decode_block_rect(
12299 dec: &mut SymbolDecoder,
12300 cdfs: &mut Cdfs,
12301 neighbours: &mut Neighbours,
12302 at: (usize, usize),
12303 bw: usize,
12304 bh: usize,
12305 y: &mut PlaneBuf<'static>,
12306 u: &mut PlaneBuf<'static>,
12307 v: &mut PlaneBuf<'static>,
12308 enable_filter_intra: bool,
12309 allow_screen_content_tools: bool,
12310 base_q_idx: u8,
12311 tx_select: bool,
12312 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
12313) -> Result<()> {
12314 let (r, c) = at;
12315 let (px, py) = (c * SUB, r * SUB);
12316 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
12317 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
12318 let palette_uv_cache = neighbours.palette_uv_cache(at);
12319 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) =
12320 read_intra_mode_rect(
12321 dec,
12322 cdfs,
12323 nb_above_mode,
12324 nb_left_mode,
12325 true,
12326 true,
12327 bw,
12328 bh,
12329 enable_filter_intra,
12330 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
12331 allow_screen_content_tools,
12332 Some((palette_ctx, &palette_cache)),
12333 &palette_uv_cache,
12334 r * (SUB / MI),
12335 c * (SUB / MI), fctx,
12336 )?;
12337
12338 if let Some((dv_row, dv_col)) = intrabc {
12339 return decode_intrabc_rect(
12340 dec,
12341 cdfs,
12342 neighbours,
12343 (r * (SUB / MI), c * (SUB / MI)),
12344 (bw, bh),
12345 skip,
12346 (dv_row, dv_col),
12347 y,
12348 u,
12349 v,
12350 base_q_idx, fctx,
12351 );
12352 }
12353 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
12354 if smooth_neighbor {
12355 hit!(SMOOTH_LUMA_HITS);
12356 }
12357 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
12358 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
12359 // `uv_mode`, not the luma one.
12360 let smooth_neighbor_uv =
12361 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
12362 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
12363 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
12364 // rectangle just as happily), so a `use_filter_intra` strip at this level
12365 // predicts instead of refusing. The below-16x16 leaf arm
12366 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
12367 if filter_intra.is_some() {
12368 hit!(FILTER_INTRA_RECT_HITS);
12369 }
12370 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
12371 DC_PRED
12372 } else {
12373 uv_mode
12374 };
12375 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
12376 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
12377 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
12378 // one did not, so with `--enable-tx-size-search=0` -- which several gate
12379 // recipes use -- the decoder consumed a symbol the encoder never wrote and
12380 // desynced the tile from that point on. That is why both strips of the
12381 // pinned HORZ quadrant were wrong from their very first pixel, and why our
12382 // range after the read equalled the oracle's range for the whole block.
12383 // lane-av1mixloss: the lossless-segment early return
12384 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment
12385 // rect block codes no depth symbol here either (class sweep of the sub8
12386 // leaf's fix).
12387 let depth = if tx_select && !lossless(fctx) {
12388 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
12389 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
12390 // intra-only frame publishes them from every block too
12391 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
12392 // 1920x792 128-superblock stream,
12393 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
12394 // `tx_size_cat2` row 1 where libaom reads row 2.
12395 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
12396 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
12397 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
12398 eprintln!(
12399 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
12400 dec.debug_state().0
12401 );
12402 }
12403 d
12404 } else {
12405 0
12406 };
12407 // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame
12408 // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
12409 publish_txfm_bands_if_in_inter(
12410 neighbours,
12411 (mi_r, mi_c),
12412 depth_to_tx_wh(bw, bh, depth, fctx),
12413 (bw, bh), fctx,
12414 );
12415 if depth != 0 || lossless(fctx) {
12416 hit!(TX_DEPTH_HITS);
12417 // lane-rectsplit r1: a split transform is predicted and reconstructed
12418 // per transform unit, each unit taking its edges from the previous
12419 // unit's reconstruction inside this same strip (spec 5.11.36) --
12420 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
12421 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
12422 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
12423 eprintln!(
12424 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
12425 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
12426 angle_y={angle_delta_y}"
12427 );
12428 }
12429 let modes = RectStripModes {
12430 skip,
12431 mode,
12432 angle_delta_y,
12433 uv_predict_mode,
12434 angle_delta_uv,
12435 alpha,
12436 filter_intra,
12437 smooth_neighbor,
12438 smooth_neighbor_uv,
12439 palette_y: palette_y
12440 .as_ref()
12441 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
12442 palette_uv: palette_uv.as_ref().map(|p| {
12443 (
12444 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12445 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12446 )
12447 }),
12448 };
12449 if palette_y.is_some() || palette_uv.is_some() {
12450 hit!(PALETTE_SPLIT_TX_HITS);
12451 }
12452 decode_rect_split(
12453 dec,
12454 cdfs,
12455 neighbours,
12456 (mi_r, mi_c),
12457 bw,
12458 bh,
12459 tx_w,
12460 tx_h,
12461 &modes,
12462 y,
12463 u,
12464 v,
12465 base_q_idx,
12466 reduced_tx_set, fctx,
12467 )?;
12468 // This early return skips this fn's own tail, so the palette
12469 // neighbour state has to be stamped HERE too: without it a split-tx
12470 // strip left the above/left palette arrays holding a DEAD block's
12471 // colours, and the next block's colour cache
12472 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
12473 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
12474 // and only those pixels were wrong (lane-palette2 r10).
12475 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12476 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12477 let (puv_size, puv_colors) =
12478 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12479 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12480 hit!(RECT_PARTITION_HITS);
12481 return Ok(());
12482 }
12483 let (tx_w, tx_h) = (bw, bh);
12484 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
12485 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
12486 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12487 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12488 let (rng, _) = dec.debug_state();
12489 eprintln!(
12490 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
12491 skip={} tx={depth} rng={rng}",
12492 skip as i32
12493 );
12494 }
12495 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
12496 // block's prediction is the reconstructed colour-index map, set fresh
12497 // right before each `reconstruct_rect` call below (lane-palette2 r4).
12498 if let Some(ref pyv) = palette_y {
12499 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
12500 set_palette_pred(buf, fctx);
12501 }
12502 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
12503 (
12504 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
12505 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
12506 )
12507 });
12508 if skip {
12509 push_intra_rect(0,
12510 px,
12511 py,
12512 bw,
12513 bh,
12514 mode,
12515 angle_delta_y,
12516 reach,
12517 &ZERO_RESIDUAL[..bw * bh],
12518 None,
12519 filter_intra,
12520 smooth_neighbor, fctx,
12521 );
12522 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12523 if let Some((ub, _)) = &palette_uv_bufs {
12524 set_palette_pred(ub.clone(), fctx);
12525 }
12526 push_intra_rect(1,
12527 cpx,
12528 cpy,
12529 chroma_w,
12530 chroma_h,
12531 uv_predict_mode,
12532 angle_delta_uv,
12533 reach,
12534 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12535 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12536 None,
12537 smooth_neighbor_uv, fctx,
12538 );
12539 if let Some((_, vb)) = &palette_uv_bufs {
12540 set_palette_pred(vb.clone(), fctx);
12541 }
12542 push_intra_rect(2,
12543 cpx,
12544 cpy,
12545 chroma_w,
12546 chroma_h,
12547 uv_predict_mode,
12548 angle_delta_uv,
12549 reach,
12550 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12551 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12552 None,
12553 smooth_neighbor_uv, fctx,
12554 );
12555 neighbours.record_rect(
12556 at,
12557 bw,
12558 bh,
12559 mode,
12560 uv_predict_mode,
12561 &[
12562 &ZERO_RESIDUAL[..bw * bh],
12563 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12564 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12565 ],
12566 );
12567 } else {
12568 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
12569 // reduces both size pairs to their square-up CDF sets
12570 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
12571 // doc comments); the scan order and 2D context tables are the real
12572 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
12573 let luma_scan: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 };
12574 // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a
12575 // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16
12576 // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis).
12577 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
12578 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
12579 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
12580 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8),
12581 (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16),
12582 _ => {
12583 return Err(unsupported(
12584 "a rectangular chroma transform whose size has no coefficient table",
12585 ))
12586 }
12587 };
12588 let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 {
12589 TxType::DctDct
12590 } else {
12591 default_intra_tx_type(uv_predict_mode as u8)
12592 };
12593 // lane-rectwire r3: real coefficients desync a pixel-exact gate
12594 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
12595 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
12596 // pixel (not a subtle context-table off-by-one), while the sibling
12597 // non-rect quadrants of the same frame match. Range-ladder bisection
12598 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
12599 // but the intra key-frame path has no traced symbol between the
12600 // partition read and the first coefficient block (mode/skip/tx_depth
12601 // reads are all untraced in libaom's decodeframe.c intra path, unlike
12602 // the inter EC_TRACE_MODE this round added), so a same-length range
12603 // comparison wasn't reachable within budget -- see
12604 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
12605 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
12606 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
12607 // libaom and match). lane-rectwire r4: range-ladder against the
12608 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
12609 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
12610 // both confirmed in sync -- rng=58692 on both sides right after
12611 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
12612 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
12613 // immediately after: ours moves rng 58692 -> 43570, which cannot be
12614 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
12615 // its own tx_size read) unless oracle's tx symbol is a near-certainty
12616 // CDF that barely narrows the range -- i.e. this decoder's
12617 // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for
12618 // a 32x16/16x32 strip is the first diverging symbol, not the
12619 // coefficient-context math r3 already cleared. Not confirmed byte-
12620 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
12621 // `read_tx_size`'s own rng, not attempted this round -- budget), so
12622 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
12623 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
12624 // it unconditionally where both square paths gate on `tx_select`. With
12625 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
12626 // decoder consumed one that was never there.
12627 {
12628 let around = neighbours.around_rect(at, bw, bh);
12629 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
12630 let (luma_levels, luma_tx_type) = read_coeffs_rect(
12631 dec,
12632 &mut luma_coding,
12633 luma_scan,
12634 bw,
12635 bh,
12636 0,
12637 dc_sign_ctx(around[0].2),
12638 TxType::DctDct,
12639 )?;
12640 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12641 let (rng, _) = dec.debug_state();
12642 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
12643 }
12644 let luma_residual = dequant_and_inverse_typed_wh(
12645 &luma_levels,
12646 bw,
12647 bh,
12648 crate::decode::bit_depth(fctx),
12649 block_q_idx(fctx),
12650 plane_q_delta(0, fctx).0,
12651 plane_q_delta(0, fctx).1,
12652 luma_tx_type,
12653 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
12654 );
12655 push_intra_rect(0,
12656 px,
12657 py,
12658 bw,
12659 bh,
12660 mode,
12661 angle_delta_y,
12662 reach,
12663 &luma_residual,
12664 None,
12665 filter_intra,
12666 smooth_neighbor, fctx,
12667 );
12668 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12669 if let Some((ub, _)) = &palette_uv_bufs {
12670 set_palette_pred(ub.clone(), fctx);
12671 }
12672 let u_default_tx = chroma_default_tx;
12673 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
12674 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
12675 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
12676 dec,
12677 &mut u_coding,
12678 chroma_scan,
12679 chroma_w,
12680 chroma_h,
12681 u_skip_ctx,
12682 dc_sign_ctx(around[1].2),
12683 u_default_tx,
12684 fctx,
12685 )?;
12686 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12687 let (rng, _) = dec.debug_state();
12688 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
12689 }
12690 let u_residual = dequant_and_inverse_typed_wh(
12691 &u_levels,
12692 chroma_w,
12693 chroma_h,
12694 crate::decode::bit_depth(fctx),
12695 block_q_idx(fctx),
12696 plane_q_delta(1, fctx).0,
12697 plane_q_delta(1, fctx).1,
12698 u_tx_type,
12699 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
12700 );
12701 push_intra_rect(1,
12702 cpx,
12703 cpy,
12704 chroma_w,
12705 chroma_h,
12706 uv_predict_mode,
12707 angle_delta_uv,
12708 reach,
12709 &u_residual,
12710 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12711 None,
12712 smooth_neighbor_uv, fctx,
12713 );
12714 if let Some((_, vb)) = &palette_uv_bufs {
12715 set_palette_pred(vb.clone(), fctx);
12716 }
12717 let v_default_tx = chroma_default_tx;
12718 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
12719 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
12720 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
12721 dec,
12722 &mut v_coding,
12723 chroma_scan,
12724 chroma_w,
12725 chroma_h,
12726 v_skip_ctx,
12727 dc_sign_ctx(around[2].2),
12728 v_default_tx,
12729 fctx,
12730 )?;
12731 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12732 let (rng, _) = dec.debug_state();
12733 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
12734 }
12735 let v_residual = dequant_and_inverse_typed_wh(
12736 &v_levels,
12737 chroma_w,
12738 chroma_h,
12739 crate::decode::bit_depth(fctx),
12740 block_q_idx(fctx),
12741 plane_q_delta(2, fctx).0,
12742 plane_q_delta(2, fctx).1,
12743 v_tx_type,
12744 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
12745 );
12746 push_intra_rect(2,
12747 cpx,
12748 cpy,
12749 chroma_w,
12750 chroma_h,
12751 uv_predict_mode,
12752 angle_delta_uv,
12753 reach,
12754 &v_residual,
12755 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12756 None,
12757 smooth_neighbor_uv, fctx,
12758 );
12759 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
12760 hit!(RECT_COEFF_HITS);
12761 }
12762 }
12763 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12764 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12765 let (puv_size, puv_colors) =
12766 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12767 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12768 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
12769 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
12770 hit!(RECT_PARTITION_HITS);
12771 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12772 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
12773 }
12774 Ok(())
12775}
12776
12777/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
12778/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
12779/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
12780/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
12781/// the second strip of a HORZ/VERT split sits offset by half the 16x16
12782/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
12783/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
12784/// previous strip is directly above (same column, `mi_h` rows up) or
12785/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
12786/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
12787/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
12788/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
12789/// this strip's real position, never the coarse `record_rect` (which the
12790/// caller uses once, after both strips, exactly like the `VERT_B` arm next
12791/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
12792/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
12793/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
12794/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
12795#[allow(clippy::too_many_arguments)]
12796fn decode_leaf_rect(
12797 dec: &mut SymbolDecoder,
12798 cdfs: &mut Cdfs,
12799 neighbours: &mut Neighbours,
12800 outer_at: (usize, usize),
12801 leaf_mi: (usize, usize),
12802 bw: usize,
12803 bh: usize,
12804 prev_leaf: Option<((usize, usize), usize)>,
12805 y: &mut PlaneBuf<'static>,
12806 u: &mut PlaneBuf<'static>,
12807 v: &mut PlaneBuf<'static>,
12808 enable_filter_intra: bool,
12809 allow_screen_content_tools: bool,
12810 base_q_idx: u8,
12811 tx_select: bool,
12812 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
12813) -> Result<usize> {
12814 let _ = base_q_idx;
12815 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
12816 eprintln!(
12817 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
12818 dec.debug_state().0
12819 );
12820 }
12821 let (r, c) = outer_at;
12822 let mut above_mode = neighbours.above_mode[c];
12823 let mut left_mode = neighbours.left_mode[r];
12824 let (mi_w, mi_h) = (bw / MI, bh / MI);
12825 if let Some(((pr, pc), pmode)) = prev_leaf {
12826 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
12827 above_mode = pmode;
12828 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
12829 left_mode = pmode;
12830 }
12831 }
12832 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
12833 // cannot hold the modes a split (or a pair of strips) leaves behind, so
12834 // when the map holds the block at exactly this strip's above/left mi it
12835 // is the neighbour libaom's `above_mi`/`left_mi` reads.
12836 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
12837 // availability-correct -- four 16x8 strips share one coarse 16x16
12838 // `left_mode` cell too, so the fallback must not stand in for an absent
12839 // tile-edge neighbour.
12840 let (above_mode, left_mode) =
12841 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
12842 let smooth_neighbor =
12843 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
12844 if smooth_neighbor {
12845 hit!(SMOOTH_LUMA_HITS);
12846 }
12847 // The palette-Y mode CDF row is picked by the neighbours' palette use
12848 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
12849 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
12850 // a palette narrows the wrong interval and desyncs the tile even when the
12851 // decoded bit is the same. The cell is the 16px-SUB cell containing the
12852 // leaf (the palette neighbour arrays have no finer granularity).
12853 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
12854 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
12855 // exclusion and the neighbour palette lookup itself are mi-granular
12856 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
12857 let pal_at = leaf_mi;
12858 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
12859 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
12860 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) =
12861 read_intra_mode_rect(
12862 dec,
12863 cdfs,
12864 above_mode,
12865 left_mode,
12866 true,
12867 true,
12868 bw,
12869 bh,
12870 enable_filter_intra,
12871 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
12872 allow_screen_content_tools,
12873 Some((palette_ctx, &palette_cache)),
12874 &palette_uv_cache,
12875 leaf_mi.0,
12876 leaf_mi.1, fctx,
12877 )?;
12878
12879 if let Some((dv_row, dv_col)) = intrabc {
12880 decode_intrabc_rect(
12881 dec, cdfs, neighbours, leaf_mi, (bw, bh), skip, (dv_row, dv_col),
12882 y, u, v, base_q_idx, fctx,
12883 )?;
12884 return Ok(DC_PRED);
12885 }
12886 // lane-kf900 r4: palette prediction on this shape, the same colour-index
12887 // map -> base colours buffer [`decode_block_rect`] hands each
12888 // `reconstruct_rect` through [`set_palette_pred`].
12889 if palette_y.is_some() || palette_uv.is_some() {
12890 hit!(RECT4_PALETTE_HITS);
12891 }
12892 let palette_y_buf: Option<Vec<u16>> = palette_y
12893 .as_ref()
12894 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
12895 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
12896 (
12897 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12898 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12899 )
12900 });
12901 let (pal_y_size, pal_y_colors) =
12902 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12903 let (pal_uv_size, pal_uv_colors) =
12904 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12905 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
12906 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
12907 }
12908 if filter_intra.is_some() {
12909 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
12910 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
12911 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
12912 // below already makes; this refusal was square-only prose.
12913 hit!(FILTER_INTRA_RECT_HITS);
12914 hit!(FILTER_INTRA_RECT_SUB16_HITS);
12915 }
12916 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
12917 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
12918 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
12919 // a constant `false`.
12920 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
12921 let depth = if tx_select && !lossless(fctx) {
12922 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
12923 // every other rect reader now does -- a no-op on a key frame.
12924 // lane-av1mixloss: libaom `read_tx_size`'s first line
12925 // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return
12926 // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment
12927 // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4).
12928 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
12929 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
12930 // read was the leaf's own txb_skip.
12931 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
12932 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
12933 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
12934 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
12935 // count (3), different CDF row: a wrong-table read of a real symbol,
12936 // the class that cost lane-rectsplit r1 its 64x32 depth.
12937 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
12938 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
12939 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
12940 // function also decodes) sit at depth 2, so they read
12941 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
12942 // while `tx_size_cat2` belongs to the 32-level shapes
12943 // ([`decode_block_rect`]). Both tables carry three symbols, so the
12944 // wrong one decodes a plausible depth from the wrong probabilities:
12945 // the range diverges silently at the first such leaf and every later
12946 // symbol in the tile is read from the wrong place (class
12947 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
12948 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
12949 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
12950 eprintln!("EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}", leaf_mi.0, leaf_mi.1, dec.debug_state().0);
12951 }
12952 d
12953 } else {
12954 0
12955 };
12956 // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads
12957 // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
12958 publish_txfm_bands_if_in_inter(
12959 neighbours,
12960 leaf_mi,
12961 depth_to_tx_wh(bw, bh, depth, fctx),
12962 (bw, bh), fctx,
12963 );
12964 if depth != 0 || lossless(fctx) {
12965 // The same per-transform-unit walk the bigger strips take
12966 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
12967 // depth 2), addressed at this leaf's own mi position.
12968 hit!(TX_DEPTH_HITS);
12969 hit!(SUB16_SPLIT_HITS);
12970 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
12971 let modes = RectStripModes {
12972 skip,
12973 mode,
12974 angle_delta_y,
12975 uv_predict_mode,
12976 angle_delta_uv,
12977 alpha,
12978 filter_intra,
12979 smooth_neighbor,
12980 // lane-rectsplitx r3: the split arm hard-coded `false` here while
12981 // the unsplit arm below passes the real neighbour answer -- chroma
12982 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
12983 smooth_neighbor_uv,
12984 palette_y: palette_y_buf.clone(),
12985 palette_uv: palette_uv_bufs.clone(),
12986 };
12987 if palette_y.is_some() || palette_uv.is_some() {
12988 hit!(PALETTE_SPLIT_TX_HITS);
12989 }
12990 decode_rect_split(
12991 dec,
12992 cdfs,
12993 neighbours,
12994 leaf_mi,
12995 bw,
12996 bh,
12997 tx_w,
12998 tx_h,
12999 &modes,
13000 y,
13001 u,
13002 v,
13003 base_q_idx,
13004 reduced_tx_set, fctx,
13005 )?;
13006 record_strip_palette(
13007 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
13008 );
13009 return Ok(mode);
13010 }
13011 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
13012 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
13013 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
13014 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
13015 let (luma_levels, u_levels, v_levels);
13016 if skip {
13017 luma_levels = Grid::Zero(bw * bh);
13018 u_levels = Grid::Zero(chroma_w * chroma_h);
13019 v_levels = Grid::Zero(chroma_w * chroma_h);
13020 if let Some(b) = &palette_y_buf {
13021 set_palette_pred(b.clone(), fctx);
13022 }
13023 push_intra_rect(0,
13024 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
13025 smooth_neighbor, fctx,
13026 );
13027 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
13028 if let Some((ub, _)) = &palette_uv_bufs {
13029 set_palette_pred(ub.clone(), fctx);
13030 }
13031 push_intra_rect(1,
13032 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
13033 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
13034 );
13035 if let Some((_, vb)) = &palette_uv_bufs {
13036 set_palette_pred(vb.clone(), fctx);
13037 }
13038 push_intra_rect(2,
13039 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
13040 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
13041 );
13042 } else {
13043 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
13044 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
13045 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
13046 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
13047 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
13048 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
13049 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 {
13050 if bw == 16 { (&SCAN_16X8, &SCAN_16X8) } else { (&SCAN_8X16, &SCAN_8X16) }
13051 } else if bw == 16 {
13052 (&SCAN_16X8, &SCAN_8X4)
13053 } else {
13054 (&SCAN_8X16, &SCAN_4X8)
13055 };
13056 let chroma_rect_set = if ss_x(fctx) == 0 { TxbSet::ChromaRect16x8 } else { TxbSet::ChromaRect8x4 };
13057 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
13058 let luma_set = if reduced_tx_set {
13059 TxbSet::LumaRect16x8
13060 } else {
13061 TxbSet::LumaRect16x8Set1
13062 };
13063 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
13064 let (l_levels, luma_tx_type) = read_coeffs_rect(
13065 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
13066 )?;
13067 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
13068 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
13069 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
13070 }
13071 luma_levels = l_levels;
13072 let luma_residual = dequant_and_inverse_typed_wh(
13073 &luma_levels, bw, bh, crate::decode::bit_depth(fctx),
13074 block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type,
13075 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
13076 );
13077 if let Some(b) = &palette_y_buf {
13078 set_palette_pred(b.clone(), fctx);
13079 }
13080 push_intra_rect(0,
13081 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
13082 smooth_neighbor, fctx,
13083 );
13084 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
13085 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
13086 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
13087 let mut u_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
13088 let (u_l, u_tx_type) = read_chroma_coeffs_rect(
13089 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
13090 dc_sign_ctx(around[1].2), u_default_tx, fctx,
13091 )?;
13092 u_levels = u_l;
13093 let u_residual = dequant_and_inverse_typed_wh(
13094 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
13095 block_q_idx(fctx), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type,
13096 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
13097 );
13098 if let Some((ub, _)) = &palette_uv_bufs {
13099 set_palette_pred(ub.clone(), fctx);
13100 }
13101 push_intra_rect(1,
13102 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
13103 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
13104 );
13105 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
13106 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
13107 let mut v_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
13108 let (v_l, v_tx_type) = read_chroma_coeffs_rect(
13109 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
13110 dc_sign_ctx(around[2].2), v_default_tx, fctx,
13111 )?;
13112 v_levels = v_l;
13113 let v_residual = dequant_and_inverse_typed_wh(
13114 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
13115 block_q_idx(fctx), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type,
13116 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
13117 );
13118 if let Some((_, vb)) = &palette_uv_bufs {
13119 set_palette_pred(vb.clone(), fctx);
13120 }
13121 push_intra_rect(2,
13122 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
13123 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
13124 );
13125 hit!(RECT_LEAF_COEFF_HITS);
13126 }
13127 neighbours.record_mi_rect(leaf_mi, bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
13128 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
13129 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
13130 // The leaf's own palette state (`0` clears, as this site always did
13131 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
13132 // AXIS only until the pair's closing leaf: the coarse cell holds one
13133 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
13134 // real left neighbour leaf 1 reads (lane-kf900 r4).
13135 record_strip_palette(
13136 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
13137 );
13138 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
13139 // rows -- record the whole span, not one cell.
13140 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
13141 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
13142 Ok(mode)
13143}
13144
13145/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
13146/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
13147/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
13148/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
13149/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
13150/// strip's mode so this one's mode context sees its true above/left
13151/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
13152///
13153/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
13154/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
13155/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
13156/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
13157/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
13158/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
13159/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
13160///
13161/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
13162/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
13163/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
13164/// unexamined.
13165#[allow(clippy::too_many_arguments)]
13166fn decode_block_rect4(
13167 dec: &mut SymbolDecoder,
13168 cdfs: &mut Cdfs,
13169 neighbours: &mut Neighbours,
13170 strip_mi: (usize, usize),
13171 bw: usize,
13172 bh: usize,
13173 prev_strip: Option<((usize, usize), usize)>,
13174 y: &mut PlaneBuf<'static>,
13175 u: &mut PlaneBuf<'static>,
13176 v: &mut PlaneBuf<'static>,
13177 enable_filter_intra: bool,
13178 allow_screen_content_tools: bool,
13179 base_q_idx: u8,
13180 tx_select: bool, fctx: &crate::decode::FrameCtx,
13181) -> Result<(usize, usize)> {
13182 let _ = base_q_idx;
13183 let (mi_r, mi_c) = strip_mi;
13184 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
13185 let (mi_w, mi_h) = (bw / MI, bh / MI);
13186 let mut above_mode = neighbours.above_mode[c];
13187 let mut left_mode = neighbours.left_mode[r];
13188 if let Some(((pr, pc), pmode)) = prev_strip {
13189 if pc == mi_c && mi_r == pr + mi_h {
13190 above_mode = pmode;
13191 } else if pr == mi_r && mi_c == pc + mi_w {
13192 left_mode = pmode;
13193 }
13194 }
13195 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
13196 // availability-correct neighbour modes (see
13197 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
13198 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
13199 let (above_mode, left_mode) =
13200 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
13201 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
13202 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
13203 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
13204 // wrong interval, so a screen-content tile desynced at the first strip
13205 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
13206 let pal_at = (mi_r, mi_c);
13207 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
13208 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
13209 let (
13210 skip,
13211 mode,
13212 angle_delta_y,
13213 uv_mode,
13214 angle_delta_uv,
13215 alpha,
13216 filter_intra,
13217 palette_y,
13218 palette_uv,
13219 intrabc,
13220 ) = read_intra_mode_rect(
13221 dec,
13222 cdfs,
13223 above_mode,
13224 left_mode,
13225 true,
13226 true,
13227 bw,
13228 bh,
13229 enable_filter_intra,
13230 neighbours.skip_txfm_ctx(mi_r, mi_c),
13231 allow_screen_content_tools,
13232 Some((palette_ctx, &palette_cache)),
13233 &palette_uv_cache,
13234 mi_r,
13235 mi_c, fctx,
13236 )?;
13237 if let Some((dv_row, dv_col)) = intrabc {
13238 decode_intrabc_rect(
13239 dec, cdfs, neighbours, strip_mi, (bw, bh), skip, (dv_row, dv_col),
13240 y, u, v, base_q_idx, fctx,
13241 )?;
13242 return Ok((DC_PRED, DC_PRED));
13243 }
13244 // lane-kf900 r4: palette prediction on this shape, exactly as
13245 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
13246 // mapped through the base colours IS the prediction (it reads no edge
13247 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
13248 if palette_y.is_some() || palette_uv.is_some() {
13249 hit!(RECT4_PALETTE_HITS);
13250 }
13251 let palette_y_buf: Option<Vec<u16>> = palette_y
13252 .as_ref()
13253 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
13254 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
13255 (
13256 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
13257 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
13258 )
13259 });
13260 let (pal_y_size, pal_y_colors) =
13261 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
13262 let (pal_uv_size, pal_uv_colors) =
13263 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
13264 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
13265 if smooth_neighbor {
13266 hit!(SMOOTH_LUMA_HITS);
13267 }
13268 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
13269 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
13270 // `r * (SUB / MI)` names a different mi column and the chroma
13271 // edge-filter strength was read from the wrong neighbour (measured:
13272 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
13273 // with luma bit-exact).
13274 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
13275 if filter_intra.is_some() {
13276 hit!(FILTER_INTRA_RECT_HITS);
13277 if bw > bh {
13278 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
13279 } else {
13280 hit!(FILTER_INTRA_RECT4_VERT_HITS);
13281 }
13282 }
13283 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
13284 DC_PRED
13285 } else {
13286 uv_mode
13287 };
13288 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
13289 // precedes `TX_MODE_SELECT`, so a lossless-segment rect4 block codes no
13290 // depth symbol here either (class sweep of the sub8 leaf's fix).
13291 let depth = if tx_select && !lossless(fctx) {
13292 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
13293 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
13294 // intra-only frame publishes them from every block too
13295 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
13296 // 1920x792 128-superblock stream,
13297 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
13298 // `tx_size_cat2` row 1 where libaom reads row 2.
13299 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
13300 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
13301 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
13302 eprintln!(
13303 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
13304 dec.debug_state().0
13305 );
13306 }
13307 d
13308 } else {
13309 0
13310 };
13311 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
13312 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
13313 publish_txfm_bands_if_in_inter(
13314 neighbours,
13315 (mi_r, mi_c),
13316 depth_to_tx_wh(bw, bh, depth, fctx),
13317 (bw, bh), fctx,
13318 );
13319 if depth != 0 || lossless(fctx) {
13320 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
13321 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
13322 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
13323 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
13324 // both interleave in every real stream.
13325 hit!(TX_DEPTH_HITS);
13326 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
13327 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
13328 // predicted -- depth 1 fires FIRST in every attempt that splits at
13329 // all, so a depth-2-only lift could never be gated. The r1 mismatch
13330 // was never the rect unit: it was the neighbour MODE the strip reads
13331 // (see `modes_above_left_mi`).
13332 let which = if depth == 1 {
13333 &RECT4_SPLIT_DEPTH1_HITS
13334 } else {
13335 &RECT4_SPLIT_DEPTH2_HITS
13336 };
13337 hit_do! { which.with(|c| c.set(c.get() + 1)); }
13338 let modes = RectStripModes {
13339 skip,
13340 mode,
13341 angle_delta_y,
13342 uv_predict_mode,
13343 angle_delta_uv,
13344 alpha,
13345 filter_intra,
13346 smooth_neighbor,
13347 smooth_neighbor_uv,
13348 palette_y: palette_y_buf.clone(),
13349 palette_uv: palette_uv_bufs.clone(),
13350 };
13351 if palette_y.is_some() || palette_uv.is_some() {
13352 hit!(PALETTE_SPLIT_TX_HITS);
13353 }
13354 decode_rect_split(
13355 dec,
13356 cdfs,
13357 neighbours,
13358 (mi_r, mi_c),
13359 bw,
13360 bh,
13361 tx_w,
13362 tx_h,
13363 &modes,
13364 y,
13365 u,
13366 v,
13367 base_q_idx,
13368 false, fctx,
13369 )?;
13370 record_strip_palette(
13371 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
13372 pal_uv_colors,
13373 );
13374 if bw > bh {
13375 hit!(RECT4_32_HORZ_HITS);
13376 } else {
13377 hit!(RECT4_32_VERT_HITS);
13378 }
13379 if !skip {
13380 hit!(RECT4_COEFF_HITS);
13381 }
13382 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
13383 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
13384 // frame, so this 1:4 strip -- which is also the INTER frame's reader
13385 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
13386 // transform size in both TXFM_CONTEXT bands. Without it the next block
13387 // reads the row's stale value.
13388 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
13389 return Ok((mode, uv_predict_mode));
13390 }
13391 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
13392 // that is 8 px tall, so each strip stamps every cell it touches and the
13393 // LAST strip wins -- which is the right answer for the block below/right
13394 // of the 32x32, the only reader outside it. Written after this strip's
13395 // own context read above, never before.
13396 for cell in 0..bw.div_ceil(SUB) {
13397 neighbours.above_mode[c + cell] = mode;
13398 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
13399 neighbours.above_side[c + cell] = bw;
13400 }
13401 for cell in 0..bh.div_ceil(SUB) {
13402 neighbours.left_mode[r + cell] = mode;
13403 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
13404 neighbours.left_side[r + cell] = bh;
13405 }
13406 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
13407 // [`decode_leaf_rect`] does (the split arm above records these through
13408 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
13409 // `sub8_mode_row` holding the previous block, and the next 32x32's
13410 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
13411 // fixture).
13412 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
13413 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
13414 let (px, py) = (mi_c * MI, mi_r * MI);
13415 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
13416 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
13417 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
13418 // lane-av1-444: the strip's chroma shape follows the subsampling.
13419 // 4:2:0 codes 16x4/4x16 (`TxbSet::Chroma8`); 4:4:4 codes the strip
13420 // itself, 32x8/8x32 (`get_txsize_entropy_ctx(TX_32X8)` =
13421 // `(wide_log2 + high_log2 + 1) >> 1` = the 16x16 set,
13422 // `TxbSet::Chroma16`). The caller set is closed -- this reader only
13423 // ever sees 32x8 / 8x32 luma and the sequence header admits ss 0/0
13424 // and 1/1 only -- so the table is exhaustive.
13425 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
13426 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
13427 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
13428 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8[..]),
13429 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32[..]),
13430 _ => unreachable!("decode_block_rect4 chroma shape set is closed"),
13431 };
13432 let luma_scan: &[u16] = if bw > bh { &SCAN_32X8 } else { &SCAN_8X32 };
13433 let (luma_levels, u_levels, v_levels) = if skip {
13434 (
13435 vec![0i32; bw * bh],
13436 vec![0i32; chroma_w * chroma_h],
13437 vec![0i32; chroma_w * chroma_h],
13438 )
13439 } else {
13440 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
13441 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
13442 let (luma_levels, luma_tx_type) = read_coeffs_rect(
13443 dec,
13444 &mut luma_coding,
13445 luma_scan,
13446 bw,
13447 bh,
13448 0,
13449 dc_sign_ctx(around[0].2),
13450 TxType::DctDct,
13451 )?;
13452 let mut planes = Vec::with_capacity(2);
13453 for plane in 1..3 {
13454 // `av1_get_tx_type` (`blockd.h:1278`): the mode-indexed type
13455 // stands only while it is a member of this tx size's set; a
13456 // 32x8/8x32 chroma transform (4:4:4) squares up to TX_32X32,
13457 // whose intra set is `EXT_TX_SET_DCTONLY` -- every ADST clamps
13458 // to DCT_DCT there, and ADST is undefined at widths above 16.
13459 let default_tx = if chroma_w.max(chroma_h) >= 32 {
13460 TxType::DctDct
13461 } else {
13462 default_intra_tx_type(uv_predict_mode as u8)
13463 };
13464 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
13465 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
13466 let (levels, tx_type) = read_chroma_coeffs_rect(
13467 dec,
13468 &mut coding,
13469 chroma_scan,
13470 chroma_w,
13471 chroma_h,
13472 skip_ctx,
13473 dc_sign_ctx(around[plane].2),
13474 default_tx,
13475 fctx,
13476 )?;
13477 planes.push((levels, tx_type));
13478 }
13479 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
13480 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
13481 hit!(RECT4_COEFF_HITS);
13482 let luma_residual = dequant_and_inverse_typed_wh(
13483 &luma_levels,
13484 bw,
13485 bh,
13486 crate::decode::bit_depth(fctx),
13487 block_q_idx(fctx),
13488 plane_q_delta(0, fctx).0,
13489 plane_q_delta(0, fctx).1,
13490 luma_tx_type,
13491 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
13492 );
13493 if let Some(b) = &palette_y_buf {
13494 set_palette_pred(b.clone(), fctx);
13495 }
13496 push_intra_rect(0,
13497 px,
13498 py,
13499 bw,
13500 bh,
13501 mode,
13502 angle_delta_y,
13503 reach,
13504 &luma_residual,
13505 None,
13506 filter_intra,
13507 smooth_neighbor, fctx,
13508 );
13509 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
13510 for (plane, _buf, levels, tx_type) in [
13511 (1usize, &mut *u, &u_levels, u_tx_type),
13512 (2, &mut *v, &v_levels, v_tx_type),
13513 ] {
13514 let residual = dequant_and_inverse_typed_wh(
13515 levels,
13516 chroma_w,
13517 chroma_h,
13518 crate::decode::bit_depth(fctx),
13519 block_q_idx(fctx),
13520 plane_q_delta(plane, fctx).0,
13521 plane_q_delta(plane, fctx).1,
13522 tx_type,
13523 block_iqmatrix(fctx, plane, chroma_w, chroma_h, tx_type),
13524 );
13525 if let Some((ub, vb)) = &palette_uv_bufs {
13526 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
13527 }
13528 push_intra_rect(plane,
13529 cpx,
13530 cpy,
13531 chroma_w,
13532 chroma_h,
13533 uv_predict_mode,
13534 angle_delta_uv,
13535 reach,
13536 &residual,
13537 alpha
13538 .zip(ac)
13539 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
13540 None,
13541 smooth_neighbor_uv, fctx,
13542 );
13543 }
13544 neighbours.record_mi_rect(
13545 (mi_r, mi_c),
13546 bw,
13547 bh,
13548 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
13549 );
13550 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
13551 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
13552 record_strip_palette(
13553 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
13554 pal_uv_colors,
13555 );
13556 if bw > bh {
13557 hit!(RECT4_32_HORZ_HITS);
13558 } else {
13559 hit!(RECT4_32_VERT_HITS);
13560 }
13561 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
13562 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
13563 // frame, so this 1:4 strip -- which is also the INTER frame's reader
13564 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
13565 // transform size in both TXFM_CONTEXT bands. Without it the next block
13566 // reads the row's stale value.
13567 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
13568 return Ok((mode, uv_predict_mode));
13569 };
13570 if let Some(b) = &palette_y_buf {
13571 set_palette_pred(b.clone(), fctx);
13572 }
13573 push_intra_rect(0,
13574 px,
13575 py,
13576 bw,
13577 bh,
13578 mode,
13579 angle_delta_y,
13580 reach,
13581 &luma_levels,
13582 None,
13583 filter_intra,
13584 smooth_neighbor, fctx,
13585 );
13586 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
13587 if let Some((ub, _)) = &palette_uv_bufs {
13588 set_palette_pred(ub.clone(), fctx);
13589 }
13590 push_intra_rect(1,
13591 cpx,
13592 cpy,
13593 chroma_w,
13594 chroma_h,
13595 uv_predict_mode,
13596 angle_delta_uv,
13597 reach,
13598 &u_levels,
13599 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
13600 None,
13601 smooth_neighbor_uv, fctx,
13602 );
13603 if let Some((_, vb)) = &palette_uv_bufs {
13604 set_palette_pred(vb.clone(), fctx);
13605 }
13606 push_intra_rect(2,
13607 cpx,
13608 cpy,
13609 chroma_w,
13610 chroma_h,
13611 uv_predict_mode,
13612 angle_delta_uv,
13613 reach,
13614 &v_levels,
13615 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
13616 None,
13617 smooth_neighbor_uv, fctx,
13618 );
13619 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
13620 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
13621 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
13622 record_strip_palette(
13623 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
13624 );
13625 if bw > bh {
13626 hit!(RECT4_32_HORZ_HITS);
13627 } else {
13628 hit!(RECT4_32_VERT_HITS);
13629 }
13630 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
13631 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
13632 // frame, so this 1:4 strip -- which is also the INTER frame's reader
13633 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
13634 // transform size in both TXFM_CONTEXT bands. Without it the next block
13635 // reads the row's stale value.
13636 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
13637 Ok((mode, uv_predict_mode))
13638}
13639
13640/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
13641/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
13642/// down, and the first shape here whose luma block is a single mi row (or
13643/// column).
13644///
13645/// What is new at this size is CHROMA. `is_chroma_reference`
13646/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
13647/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
13648/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
13649/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
13650/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
13651/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
13652/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
13653///
13654/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
13655/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
13656/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
13657/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
13658/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
13659/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
13660/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
13661/// shape's own CDF row.
13662///
13663/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
13664/// refuses by name rather than guess-decode.
13665#[allow(clippy::too_many_arguments)]
13666fn decode_rect4_16(
13667 dec: &mut SymbolDecoder,
13668 cdfs: &mut Cdfs,
13669 neighbours: &mut Neighbours,
13670 at16: (usize, usize),
13671 horz: bool,
13672 y: &mut PlaneBuf<'static>,
13673 u: &mut PlaneBuf<'static>,
13674 v: &mut PlaneBuf<'static>,
13675 enable_filter_intra: bool,
13676 allow_screen_content_tools: bool,
13677 base_q_idx: u8,
13678 tx_select: bool,
13679 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
13680) -> Result<()> {
13681 let (r, c) = at16;
13682 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
13683 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
13684 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
13685 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
13686 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
13687 let mut prev: Option<((usize, usize), usize)> = None;
13688 let mut last_mode = DC_PRED;
13689 let mut last_uv_mode = DC_PRED;
13690 for i in 0..4usize {
13691 let lmi = if horz {
13692 (mi_row0 + i, mi_col0)
13693 } else {
13694 (mi_row0, mi_col0 + i)
13695 };
13696 // lane-av1-444: at 4:4:4 every strip is its own chroma reference
13697 // (no mi-parity test at ss 0/0, and the strip's own chroma block is
13698 // already >= 4x4) -- there is no 4:2:0 pair to close.
13699 let has_chroma = i % 2 == 1 || (ss_x(fctx) == 0 && ss_y(fctx) == 0);
13700 let (mode, uv, _tx) = decode_rect4_16_strip(
13701 dec,
13702 cdfs,
13703 neighbours,
13704 lmi,
13705 horz,
13706 has_chroma,
13707 prev,
13708 y,
13709 u,
13710 v,
13711 enable_filter_intra,
13712 allow_screen_content_tools,
13713 base_q_idx,
13714 tx_select,
13715 reduced_tx_set, fctx,
13716 )?;
13717 if let Some(m) = uv {
13718 last_uv_mode = m;
13719 }
13720 last_mode = mode;
13721 prev = Some((lmi, mode));
13722 }
13723 // The coarse 16-px cell holds one entry for the whole 16x16: the last
13724 // strip is what a block below (right) sees through it, the mi-exact maps
13725 // above answering everything finer.
13726 neighbours.above_mode[c] = last_mode;
13727 neighbours.left_mode[r] = last_mode;
13728 neighbours.above_uv_mode[c] = last_uv_mode;
13729 neighbours.left_uv_mode[r] = last_uv_mode;
13730 neighbours.above_side[c] = bw;
13731 neighbours.left_side[r] = bh;
13732 Ok(())
13733}
13734
13735/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
13736/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
13737/// block path can decode a SINGLE intra strip of a partition whose other
13738/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
13739/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
13740/// every strip publishes its own mi-exact mode). Returns
13741/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
13742/// Intrabc reconstruction for a rect strip that OWNS its chroma
13743/// (`bw/2 x bh/2` at the strip origin). 16x4/4x16 is not this shape -- that
13744/// pair goes through [`decode_rect4_16_intrabc`].
13745///
13746/// This is the same control flow as the unmerged lane's `decode_intrabc_rect`
13747/// (predict once, then one residual per transform unit on the INTER sets,
13748/// chroma inherits luma's `tx_type`), written against the helpers that exist
13749/// on this tree so a 2:1 strip no longer hides the 16x4 pair witness. The
13750/// merge with lane-av1-intrabc should keep one of the two bodies; the call
13751/// shape is the same.
13752#[allow(clippy::too_many_arguments)]
13753fn decode_intrabc_owned_rect(
13754 dec: &mut SymbolDecoder,
13755 cdfs: &mut Cdfs,
13756 neighbours: &mut Neighbours,
13757 (mi_r, mi_c): (usize, usize),
13758 (bw, bh): (usize, usize),
13759 skip: bool,
13760 (dv_row, dv_col): (i32, i32),
13761 y: &mut PlaneBuf<'static>,
13762 u: &mut PlaneBuf<'static>,
13763 v: &mut PlaneBuf<'static>,
13764 base_q_idx: u8,
13765 tx_select: bool,
13766 reduced_tx_set: bool,
13767 fctx: &crate::decode::FrameCtx,
13768) -> Result<()> {
13769 let _ = base_q_idx;
13770 let (px, py) = (mi_c * MI, mi_r * MI);
13771 let (cw, ch) = (bw / 2, bh / 2);
13772 let side = bw.max(bh);
13773 let cside = cw.max(ch);
13774 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
13775 let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get);
13776 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
13777 // `read_block_tx_size_rect` keys on this cell. A key frame forces it
13778 // false; the real bit is the caller's `tx_select`. Restored before return.
13779 fctx.tx_select_inter.with(|c| c.set(tx_select));
13780 let restore = ReducedTxRestore { fctx, saved_reduced, saved_tx };
13781
13782 flush_recon(fctx, y, u, v);
13783 let pred_y = predict_intrabc_window(y, px, py, bw, bh, dv_col, dv_row, true, side, fctx);
13784 let pred_u = predict_intrabc_window(u, px / 2, py / 2, cw, ch, dv_col, dv_row, false, cside, fctx);
13785 let pred_v = predict_intrabc_window(v, px / 2, py / 2, cw, ch, dv_col, dv_row, false, cside, fctx);
13786
13787 let mi_cols = 2 * y.true_width.div_ceil(8);
13788 let mi_rows = 2 * y.true_height.div_ceil(8);
13789 let leaves = read_block_tx_size_rect(
13790 dec, cdfs, neighbours, (mi_r, mi_c), (bw, bh), (mi_cols, mi_rows), skip, fctx,
13791 )?;
13792 let mut luma_tx_type = TxType::DctDct;
13793 let luma_grid;
13794 let u_grid;
13795 let v_grid;
13796 if skip {
13797 // `reconstruct_mc_rect` indexes the residual at the square stride.
13798 // `bw * bh` underruns on a VERT strip (8x16: stride 16, 16 rows, index 136).
13799 push_mc_rect(0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * bh], fctx);
13800 push_mc_rect(1, px / 2, py / 2, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * ch], fctx);
13801 push_mc_rect(2, px / 2, py / 2, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * ch], fctx);
13802 if let Some(ls) = leaves.as_ref() {
13803 // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`,
13804 // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its
13805 // whole entropy-band footprint. The non-skip arm below writes
13806 // those bands per transform unit and the tail's
13807 // `record_split_luma_rect_mi` writes chroma only, so without
13808 // this walk a skipped strip whose `leaves` resolved (every
13809 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
13810 // returns the 4x4 grid before it looks at `skip`) leaked the
13811 // PREVIOUS occupant's luma bands into the next block's
13812 // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped
13813 // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128
13814 // stream left a stale 7 in left[48] and mi(48,68)'s first
13815 // transform unit read `txb_skip_ctx` 3 where aomdec reads 1).
13816 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
13817 for &(row, col, tw, th) in ls {
13818 neighbours.record_mi_luma_rect(
13819 (mi_r + row, mi_c + col),
13820 tw,
13821 th,
13822 &ZERO_RESIDUAL[..tw * th],
13823 );
13824 }
13825 }
13826 luma_grid = Grid::Zero(side * side);
13827 u_grid = Grid::Zero(cside * cside);
13828 v_grid = Grid::Zero(cside * cside);
13829 } else if let Some(ls) = leaves.as_ref() {
13830 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
13831 let tu_mi = (mi_r + row, mi_c + col);
13832 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
13833 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
13834 let (g, tt) = if tw == th {
13835 read_inter_plane(
13836 dec, cdfs, inter_txbset_for(tw, reduced_tx_set), &default_scan(tw.min(32)),
13837 0, neighbours.around_mi(tu_mi, tw)[0], 0, y, tu_px, tu_py, tw, base_q_idx,
13838 tu_pred, None, Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)), fctx,
13839 )?
13840 } else {
13841 read_inter_plane_rect(
13842 dec, cdfs, rect_inter_luma_set(tw, th, fctx)?, (tw, th), side, 0,
13843 neighbours.around_mi_rect(tu_mi, tw, th)[0], 0, y, tu_px, tu_py, tu_pred,
13844 None, Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)), fctx,
13845 )?
13846 };
13847 if idx == 0 {
13848 luma_tx_type = tt;
13849 }
13850 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
13851 if tw != th {
13852 neighbours.fill_lf_grid_leaf_luma((tu_mi.0, tu_mi.1), tw / MI, th / MI, tw as u8, th as u8);
13853 }
13854 }
13855 luma_grid = Grid::Zero(side * side);
13856 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
13857 let (ug, _) = read_inter_plane_rect(
13858 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0,
13859 u, px / 2, py / 2, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx,
13860 )?;
13861 let (vg, _) = read_inter_plane_rect(
13862 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0,
13863 v, px / 2, py / 2, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx,
13864 )?;
13865 u_grid = ug;
13866 v_grid = vg;
13867 } else {
13868 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
13869 let (g, tt) = read_inter_plane_rect(
13870 dec, cdfs, rect_inter_luma_set(bw, bh, fctx)?, (bw, bh), side, 0, around[0], 0,
13871 y, px, py, Pred::Inline(&pred_y, side), None, None, fctx,
13872 )?;
13873 luma_tx_type = tt;
13874 luma_grid = g;
13875 let (ug, _) = read_inter_plane_rect(
13876 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0,
13877 u, px / 2, py / 2, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx,
13878 )?;
13879 let (vg, _) = read_inter_plane_rect(
13880 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0,
13881 v, px / 2, py / 2, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx,
13882 )?;
13883 u_grid = ug;
13884 v_grid = vg;
13885 }
13886 drop(restore);
13887 if leaves.is_some() {
13888 neighbours.record_split_luma_rect_mi((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid, &v_grid]);
13889 } else {
13890 neighbours.record_rect_mi((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &[&luma_grid, &u_grid, &v_grid]);
13891 }
13892 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
13893 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
13894 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
13895 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, bw.min(64) as u8, bh.min(64) as u8, 0, fctx);
13896 record_intrabc_mi_rect(mi_r, mi_c, bw / MI, bh / MI, Some((dv_row, dv_col)), neighbours, fctx);
13897 let _ = luma_tx_type;
13898 Ok(())
13899}
13900
13901fn predict_intrabc_window(
13902 plane: &PlaneBuf<'_>,
13903 px: usize,
13904 py: usize,
13905 w: usize,
13906 h: usize,
13907 dv_col: i32,
13908 dv_row: i32,
13909 luma: bool,
13910 stride: usize,
13911 fctx: &crate::decode::FrameCtx,
13912) -> Vec<u16> {
13913 let mut dense = vec![0u16; w * h];
13914 mc::predict_with_filter(
13915 &plane.data, plane.width, plane.true_width, plane.true_height,
13916 mv_to_q4(px, dv_col, if luma { 0 } else { ss_x(fctx) }), mv_to_q4(py, dv_row, if luma { 0 } else { ss_y(fctx) }),
13917 w, h, mc::InterpFilterKind::Bilinear, &mut dense, fctx,
13918 );
13919 let mut laid = vec![0u16; stride * stride];
13920 for row in 0..h {
13921 laid[row * stride..][..w].copy_from_slice(&dense[row * w..][..w]);
13922 }
13923 laid
13924}
13925
13926struct ReducedTxRestore<'a> {
13927 fctx: &'a crate::decode::FrameCtx,
13928 saved_reduced: bool,
13929 saved_tx: bool,
13930}
13931impl Drop for ReducedTxRestore<'_> {
13932 fn drop(&mut self) {
13933 self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved_reduced));
13934 self.fctx.tx_select_inter.with(|c| c.set(self.saved_tx));
13935 }
13936}
13937
13938/// Reconstruction of one intrabc 16x4 / 4x16 strip (lane-av1-rect14).
13939///
13940/// A 1:4 strip is a PAIR. Both children share one chroma block, and only the
13941/// odd-mi member codes it (`is_chroma_reference`, `av1_common_int.h:1454`:
13942/// the bottom strip of a `HORZ_4`, the right strip of a `VERT_4`). The chroma
13943/// plane block is `ss_size_lookup[BLOCK_16X4][1][1] == BLOCK_8X4` (and
13944/// `BLOCK_4X8` for `VERT_4`) at the PAIR origin -- `setup_pred_plane`'s
13945/// `mi_row -= 1` when the block is one mi tall on an odd row. Luma is this
13946/// strip's own footprint, copied from this strip's DV. The block is
13947/// `is_inter_block`, so the residual uses the INTER sets and chroma inherits
13948/// the luma unit's coded `tx_type`.
13949///
13950/// Not [`decode_intrabc_rect`]: that helper (lane-av1-intrabc, not on this
13951/// tree) predicts chroma at `bw/2 x bh/2` of the strip itself. At 16x4 that
13952/// is an 8x2 half-pair at the odd strip -- wrong size, wrong origin, and it
13953/// would code chroma on every strip.
13954#[allow(clippy::too_many_arguments)]
13955fn decode_rect4_16_intrabc(
13956 dec: &mut SymbolDecoder,
13957 cdfs: &mut Cdfs,
13958 neighbours: &mut Neighbours,
13959 lmi: (usize, usize),
13960 horz: bool,
13961 has_chroma: bool,
13962 skip: bool,
13963 (dv_row, dv_col): (i32, i32),
13964 y: &mut PlaneBuf<'static>,
13965 u: &mut PlaneBuf<'static>,
13966 v: &mut PlaneBuf<'static>,
13967 base_q_idx: u8,
13968 tx_select: bool,
13969 reduced_tx_set: bool,
13970 fctx: &crate::decode::FrameCtx,
13971) -> Result<(usize, Option<usize>, (usize, usize))> {
13972 let _ = base_q_idx;
13973 hit!(RECT4_16_INTRABC_HITS);
13974 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
13975 let (mi_w, mi_h) = (bw / MI, bh / MI);
13976 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
13977 let side = bw.max(bh);
13978 // `rect_inter_luma_set` reads the frame cell. A key frame's tile decoder
13979 // publishes `reduced_tx_set` into it; set it here too so a caller that
13980 // passed the bit explicitly cannot disagree with the set we read.
13981 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
13982 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
13983 let restored = scopeguard_reduced(fctx, saved_reduced);
13984
13985 flush_recon(fctx, y, u, v);
13986 let mut pred_y_dense = vec![0u16; bw * bh];
13987 mc::predict_with_filter(
13988 &y.data, y.width, y.true_width, y.true_height,
13989 mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0),
13990 bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx,
13991 );
13992 let mut pred_y = vec![0u16; side * side];
13993 for row in 0..bh {
13994 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
13995 }
13996
13997 let (pw, ph) = if horz { (16usize, 8usize) } else { (8, 16) };
13998 let (cw, ch) = (pw / 2, ph / 2);
13999 let pair_mi = if has_chroma {
14000 if horz { (lmi.0 - 1, lmi.1) } else { (lmi.0, lmi.1 - 1) }
14001 } else {
14002 lmi
14003 };
14004 let (cpx, cpy) = if has_chroma {
14005 (pair_mi.1 * MI / 2, pair_mi.0 * MI / 2)
14006 } else {
14007 (0, 0)
14008 };
14009 let cside = cw.max(ch);
14010 let (pred_u, pred_v) = if has_chroma {
14011 let mut ud = vec![0u16; cw * ch];
14012 mc::predict_with_filter(
14013 &u.data, u.width, u.true_width, u.true_height,
14014 mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)),
14015 cw, ch, mc::InterpFilterKind::Bilinear, &mut ud, fctx,
14016 );
14017 let mut us = vec![0u16; cside * cside];
14018 for row in 0..ch {
14019 us[row * cside..][..cw].copy_from_slice(&ud[row * cw..][..cw]);
14020 }
14021 let mut vd = vec![0u16; cw * ch];
14022 mc::predict_with_filter(
14023 &v.data, v.width, v.true_width, v.true_height,
14024 mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_y(fctx)),
14025 cw, ch, mc::InterpFilterKind::Bilinear, &mut vd, fctx,
14026 );
14027 let mut vs = vec![0u16; cside * cside];
14028 for row in 0..ch {
14029 vs[row * cside..][..cw].copy_from_slice(&vd[row * cw..][..cw]);
14030 }
14031 (us, vs)
14032 } else {
14033 (Vec::new(), Vec::new())
14034 };
14035
14036 // Key-frame `tx_select` is the parameter. `tx_select_inter` is forced
14037 // false for a key frame, so `read_block_tx_size_rect` would skip the
14038 // symbol; read it here against the parameter the intra path already uses.
14039 // A skipped intrabc block predicts the whole footprint once and codes
14040 // no residual (`decode_token_recon_block`'s inter branch). Lossless
14041 // still forces TX_4X4 when the block is coded.
14042 let leaves = if skip || (!lossless(fctx) && !tx_select) {
14043 None
14044 } else if lossless(fctx) {
14045 let mut leaves = Vec::new();
14046 for row in 0..bh / MI {
14047 for col in 0..bw / MI {
14048 leaves.push((row, col, 4usize, 4usize));
14049 }
14050 }
14051 Some(leaves)
14052 } else {
14053 let ctx = txfm_partition_ctx_rect(
14054 neighbours.above_txfm[lmi.1],
14055 neighbours.left_txfm[lmi.0],
14056 side,
14057 bw,
14058 bh,
14059 );
14060 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
14061 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14062 let (rng, _) = dec.debug_state();
14063 eprintln!(
14064 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
14065 lmi.0, lmi.1, u8::from(split)
14066 );
14067 }
14068 if !split {
14069 None
14070 } else {
14071 let (sub_w, sub_h) = sub_tx_size_map(bw, bh);
14072 let mi_cols = 2 * y.true_width.div_ceil(8);
14073 let mi_rows = 2 * y.true_height.div_ceil(8);
14074 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(lmi.1));
14075 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(lmi.0));
14076 let mut out = Vec::new();
14077 for row in (0..bh / MI).step_by(sub_h / MI) {
14078 for col in (0..bw / MI).step_by(sub_w / MI) {
14079 read_var_tx_size(
14080 dec, cdfs, neighbours, lmi, side, (max_w_mi, max_h_mi),
14081 (sub_w, sub_h), 1, row, col, &mut out,
14082 );
14083 }
14084 }
14085 Some(out)
14086 }
14087 };
14088 let (tx_w, tx_h) = leaves.as_ref().and_then(|ls| ls.first()).map_or((bw, bh), |l| (l.2, l.3));
14089
14090 let mut luma_tx_type = TxType::DctDct;
14091 let luma_grid;
14092 let mut u_grid = Grid::Zero(cw * ch);
14093 let mut v_grid = Grid::Zero(cw * ch);
14094 let chroma_stamped_per_unit;
14095
14096 if skip {
14097 push_mc_rect(
14098 0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * bh], fctx,
14099 );
14100 luma_grid = Grid::Zero(bw * bh);
14101 if has_chroma {
14102 push_mc_rect(
14103 1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside),
14104 &ZERO_RESIDUAL[..cside * ch], fctx,
14105 );
14106 push_mc_rect(
14107 2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside),
14108 &ZERO_RESIDUAL[..cside * ch], fctx,
14109 );
14110 }
14111 chroma_stamped_per_unit = false;
14112 } else if let Some(ls) = leaves.as_ref() {
14113 if lossless(fctx) {
14114 for &(row, col, _tw, _th) in ls {
14115 let tu_mi = (lmi.0 + row, lmi.1 + col);
14116 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14117 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
14118 let (g, _) = read_inter_plane(
14119 dec, cdfs,
14120 if reduced_tx_set { TxbSet::Luma4Inter } else { TxbSet::Luma4InterSet1 },
14121 &default_scan(4), 0, neighbours.around_mi(tu_mi, 4)[0], 0,
14122 y, tu_px, tu_py, 4, base_q_idx, tu_pred, None,
14123 Some(neighbours.luma_skip_ctx(tu_mi, 1)), fctx,
14124 )?;
14125 neighbours.record_mi_luma_rect(tu_mi, 4, 4, &g);
14126 }
14127 } else {
14128 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
14129 let tu_mi = (lmi.0 + row, lmi.1 + col);
14130 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
14131 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
14132 let (g, tt) = if tw == th {
14133 read_inter_plane(
14134 dec, cdfs, inter_txbset_for(tw, reduced_tx_set),
14135 &default_scan(tw.min(32)), 0, neighbours.around_mi(tu_mi, tw)[0], 0,
14136 y, tu_px, tu_py, tw, base_q_idx, tu_pred, None,
14137 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)), fctx,
14138 )?
14139 } else {
14140 read_inter_plane_rect(
14141 dec, cdfs, rect_inter_luma_set(tw, th, fctx)?, (tw, th), side, 0,
14142 neighbours.around_mi_rect(tu_mi, tw, th)[0], 0, y, tu_px, tu_py, tu_pred,
14143 None, Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)), fctx,
14144 )?
14145 };
14146 if idx == 0 {
14147 luma_tx_type = tt;
14148 }
14149 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
14150 }
14151 }
14152 luma_grid = Grid::Zero(bw * bh);
14153 chroma_stamped_per_unit = has_chroma && lossless(fctx);
14154 if has_chroma && lossless(fctx) {
14155 let (mut uo, mut vo) = (Vec::new(), Vec::new());
14156 read_inter_chroma_lossless(
14157 dec, cdfs, neighbours, u, v,
14158 Pred::Inline(&pred_u, cside), Pred::Inline(&pred_v, cside),
14159 pair_mi, (cpx, cpy), (0, 0), (cw, ch), (cw, ch), cside, 0, base_q_idx,
14160 &mut uo, &mut vo, fctx,
14161 )?;
14162 u_grid = if uo.is_empty() { Grid::Zero(cw * ch) } else { Grid::Own(uo) };
14163 v_grid = if vo.is_empty() { Grid::Zero(cw * ch) } else { Grid::Own(vo) };
14164 } else if has_chroma {
14165 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
14166 let (ug, _) = read_inter_plane_rect(
14167 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0,
14168 u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx,
14169 )?;
14170 u_grid = ug;
14171 let (vg, _) = read_inter_plane_rect(
14172 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0,
14173 v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx,
14174 )?;
14175 v_grid = vg;
14176 }
14177 } else {
14178 let around = neighbours.around_mi_rect(lmi, bw, bh);
14179 let (g, tt) = read_inter_plane_rect(
14180 dec, cdfs, rect_inter_luma_set(bw, bh, fctx)?, (bw, bh), side, 0, around[0], 0,
14181 y, px, py, Pred::Inline(&pred_y, side), None, None, fctx,
14182 )?;
14183 luma_tx_type = tt;
14184 luma_grid = g;
14185 chroma_stamped_per_unit = false;
14186 if has_chroma {
14187 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
14188 let (ug, _) = read_inter_plane_rect(
14189 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0,
14190 u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx,
14191 )?;
14192 u_grid = ug;
14193 let (vg, _) = read_inter_plane_rect(
14194 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0,
14195 v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx,
14196 )?;
14197 v_grid = vg;
14198 }
14199 }
14200 drop(restored);
14201
14202 if leaves.is_none() {
14203 neighbours.record_mi_luma_rect(lmi, bw, bh, &luma_grid);
14204 }
14205 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, DC_PRED);
14206 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
14207 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
14208 for cell in 0..mi_w {
14209 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
14210 *slot = bw as u8;
14211 }
14212 }
14213 for cell in 0..mi_h {
14214 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
14215 *slot = bh as u8;
14216 }
14217 }
14218 let mut last_uv = None;
14219 if has_chroma {
14220 hit!(RECT4_16_CHROMA_HITS);
14221 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, DC_PRED);
14222 if !chroma_stamped_per_unit {
14223 let u_state = neighbour_state(&u_grid);
14224 let v_state = neighbour_state(&v_grid);
14225 let round_up_even = |n: usize| n.div_ceil(2) * 2;
14226 let bound_h = round_up_even(neighbours.mi_rows);
14227 let bound_w = round_up_even(neighbours.mi_cols);
14228 for cell in 0..(ph / MI) {
14229 if pair_mi.0 + cell < bound_h
14230 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
14231 {
14232 slot[1] = u_state;
14233 slot[2] = v_state;
14234 }
14235 }
14236 for cell in 0..(pw / MI) {
14237 if pair_mi.1 + cell < bound_w
14238 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
14239 {
14240 slot[1] = u_state;
14241 slot[2] = v_state;
14242 }
14243 }
14244 }
14245 last_uv = Some(DC_PRED);
14246 }
14247 if horz {
14248 hit!(RECT4_16_HORZ_HITS);
14249 } else {
14250 hit!(RECT4_16_VERT_HITS);
14251 }
14252 record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]);
14253 if leaves.is_none() {
14254 // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs`
14255 // with `skip && is_inter`, or the unsplit unit). A split tree already
14256 // published per leaf inside `read_var_tx_size`.
14257 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
14258 }
14259 record_intrabc_mi_rect(
14260 lmi.0, lmi.1, mi_w, mi_h, Some((dv_row, dv_col)), neighbours, fctx,
14261 );
14262 Ok((DC_PRED, last_uv, (tx_w, tx_h)))
14263}
14264
14265/// Restores `reduced_tx_set_inter` when the intrabc pair reader returns,
14266/// including through `?`.
14267struct ReducedRestore<'a> {
14268 fctx: &'a crate::decode::FrameCtx,
14269 saved: bool,
14270}
14271impl Drop for ReducedRestore<'_> {
14272 fn drop(&mut self) {
14273 self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved));
14274 }
14275}
14276fn scopeguard_reduced(fctx: &crate::decode::FrameCtx, saved: bool) -> ReducedRestore<'_> {
14277 ReducedRestore { fctx, saved }
14278}
14279
14280#[allow(clippy::too_many_arguments)]
14281fn decode_rect4_16_strip(
14282 dec: &mut SymbolDecoder,
14283 cdfs: &mut Cdfs,
14284 neighbours: &mut Neighbours,
14285 lmi: (usize, usize),
14286 horz: bool,
14287 has_chroma: bool,
14288 prev: Option<((usize, usize), usize)>,
14289 y: &mut PlaneBuf<'static>,
14290 u: &mut PlaneBuf<'static>,
14291 v: &mut PlaneBuf<'static>,
14292 enable_filter_intra: bool,
14293 allow_screen_content_tools: bool,
14294 base_q_idx: u8,
14295 tx_select: bool,
14296 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14297) -> Result<(usize, Option<usize>, (usize, usize))> {
14298 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
14299 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
14300 let (mi_w, mi_h) = (bw / MI, bh / MI);
14301 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
14302 let mut last_uv_mode: Option<usize> = None;
14303 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
14304 // aliases all four strips onto one entry, so the mi-exact map wins and
14305 // the previous strip stands in on the split axis.
14306 let mut above_mode = neighbours.above_mode[c];
14307 let mut left_mode = neighbours.left_mode[r];
14308 if let Some(((pr, pc), pmode)) = prev {
14309 if pc == lmi.1 && lmi.0 == pr + mi_h {
14310 above_mode = pmode;
14311 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
14312 left_mode = pmode;
14313 }
14314 }
14315 let (above_mode, left_mode) =
14316 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
14317 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
14318 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
14319 // off CDF row 0 and every cache hit off an empty cache.
14320 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
14321 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
14322 let (
14323 skip,
14324 mode,
14325 angle_delta_y,
14326 uv_mode,
14327 angle_delta_uv,
14328 alpha,
14329 filter_intra,
14330 palette_y,
14331 palette_uv,
14332 intrabc,
14333 ) = read_intra_mode_rect(
14334 dec,
14335 cdfs,
14336 above_mode,
14337 left_mode,
14338 true,
14339 has_chroma,
14340 bw,
14341 bh,
14342 enable_filter_intra,
14343 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
14344 allow_screen_content_tools,
14345 Some((palette_ctx, &palette_cache)),
14346 &palette_uv_cache,
14347 lmi.0,
14348 lmi.1, fctx,
14349 )?;
14350 if let Some(dv) = intrabc {
14351 return decode_rect4_16_intrabc(
14352 dec, cdfs, neighbours, lmi, horz, has_chroma, skip, dv, y, u, v,
14353 base_q_idx, tx_select, reduced_tx_set, fctx,
14354 );
14355 }
14356 if palette_y.is_some() || palette_uv.is_some() {
14357 hit!(RECT4_PALETTE_HITS);
14358 }
14359 // The colour-index map through the base colours IS the prediction.
14360 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
14361 // chroma transform this closing strip codes.
14362 let palette_y_buf: Option<Vec<u16>> = palette_y
14363 .as_ref()
14364 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
14365 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
14366 (
14367 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
14368 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
14369 )
14370 });
14371 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
14372 if smooth_neighbor {
14373 hit!(SMOOTH_LUMA_HITS);
14374 }
14375 if filter_intra.is_some() {
14376 hit!(FILTER_INTRA_RECT_HITS);
14377 }
14378 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
14379 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
14380 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
14381 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
14382 // lane-av1mixloss: the lossless-segment early return
14383 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a
14384 // lossless-segment strip codes no depth symbol here either (class
14385 // sweep of the sub8 leaf's fix).
14386 let depth = if tx_select && !lossless(fctx) {
14387 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
14388 // (`get_tx_size_context`, libaom `pred_common.h:342`).
14389 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
14390 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
14391 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14392 eprintln!(
14393 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
14394 lmi.0,
14395 lmi.1,
14396 dec.debug_state().0
14397 );
14398 }
14399 d
14400 } else {
14401 0
14402 };
14403 if depth != 0 {
14404 hit!(TX_DEPTH_HITS);
14405 hit!(RECT4_16_SPLIT_HITS);
14406 }
14407 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
14408 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
14409 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
14410 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
14411 if depth != 0 || lossless(fctx) {
14412 // [`decode_rect_split`]'s per-unit walk, inlined because the
14413 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
14414 // the strip (that function codes one chroma transform per block).
14415 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
14416 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
14417 // unit predicts off the units before it in raster order.
14418 let rect_unit = tx_w != tx_h;
14419 let zero_tu = vec![0i32; tx_w * tx_h];
14420 for tu_row in 0..bh / tx_h {
14421 for tu_col in 0..bw / tx_w {
14422 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
14423 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
14424 let tu_reach = Reach::of_tu(
14425 bw,
14426 bh,
14427 tu_col * tx_w,
14428 tu_row * tx_h,
14429 tx_w,
14430 tx_h,
14431 reach,
14432 );
14433 if let Some(b) = &palette_y_buf {
14434 let tu_buf: Vec<u16> = (0..tx_h)
14435 .flat_map(|i| {
14436 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
14437 b[base..base + tx_w].iter().copied()
14438 })
14439 .collect();
14440 set_palette_pred(tu_buf, fctx);
14441 }
14442 if skip {
14443 push_intra_rect(0,
14444 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
14445 None, filter_intra, smooth_neighbor, fctx,
14446 );
14447 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
14448 } else if rect_unit {
14449 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
14450 // 32 coded positions and the `TX_4X4` `tx_type` row:
14451 // exactly [`TxbSet::LumaRect4x8`].
14452 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
14453 let tu_skip_ctx =
14454 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
14455 let set = if reduced_tx_set {
14456 TxbSet::LumaRect4x8
14457 } else {
14458 TxbSet::LumaRect4x8Set1
14459 };
14460 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
14461 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
14462 let (tu_grid, tu_tx_type) = read_coeffs_rect(
14463 dec,
14464 &mut coding,
14465 tu_scan,
14466 tx_w,
14467 tx_h,
14468 tu_skip_ctx,
14469 dc_sign_ctx(tu_around.2),
14470 TxType::DctDct,
14471 )?;
14472 let residual = dequant_and_inverse_typed_wh(
14473 &tu_grid,
14474 tx_w,
14475 tx_h,
14476 crate::decode::bit_depth(fctx),
14477 block_q_idx(fctx),
14478 plane_q_delta(0, fctx).0,
14479 plane_q_delta(0, fctx).1,
14480 tu_tx_type,
14481 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
14482 );
14483 push_intra_rect(0,
14484 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
14485 None, filter_intra, smooth_neighbor, fctx,
14486 );
14487 if tu_grid.iter().any(|&l| l != 0) {
14488 hit!(RECT4_16_COEFF_HITS);
14489 }
14490 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
14491 } else {
14492 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
14493 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
14494 let tu_grid = read_plane(
14495 dec,
14496 cdfs,
14497 txbset_for(tx_w, reduced_tx_set),
14498 default_scan(tx_w),
14499 0,
14500 tu_around,
14501 mode,
14502 mode,
14503 angle_delta_y,
14504 tu_reach,
14505 y,
14506 tu_px,
14507 tu_py,
14508 tx_w,
14509 tx_w,
14510 base_q_idx,
14511 None,
14512 filter_intra,
14513 Some(tu_skip_ctx),
14514 smooth_neighbor, fctx,
14515 )?;
14516 if tu_grid.iter().any(|&l| l != 0) {
14517 hit!(RECT4_16_COEFF_HITS);
14518 }
14519 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
14520 }
14521 }
14522 }
14523 } else {
14524 let levels = if skip {
14525 let zeros = Grid::Zero(bw * bh);
14526 if let Some(b) = &palette_y_buf {
14527 set_palette_pred(b.clone(), fctx);
14528 }
14529 push_intra_rect(0,
14530 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
14531 smooth_neighbor, fctx,
14532 );
14533 zeros
14534 } else {
14535 // The strip's luma TU *is* the strip (`plane_bsize ==
14536 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
14537 // `txb_skip_ctx` at 0.
14538 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
14539 let set = if reduced_tx_set {
14540 TxbSet::LumaRect16x4
14541 } else {
14542 TxbSet::LumaRect16x4Set1
14543 };
14544 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
14545 let (levels, tx_type) = read_coeffs_rect(
14546 dec,
14547 &mut coding,
14548 scan,
14549 bw,
14550 bh,
14551 0,
14552 dc_sign_ctx(around.2),
14553 TxType::DctDct,
14554 )?;
14555 let residual = dequant_and_inverse_typed_wh(
14556 &levels,
14557 bw,
14558 bh,
14559 crate::decode::bit_depth(fctx),
14560 block_q_idx(fctx),
14561 plane_q_delta(0, fctx).0,
14562 plane_q_delta(0, fctx).1,
14563 tx_type,
14564 block_iqmatrix(fctx, 0, bw, bh, tx_type),
14565 );
14566 if let Some(b) = &palette_y_buf {
14567 set_palette_pred(b.clone(), fctx);
14568 }
14569 push_intra_rect(0,
14570 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
14571 smooth_neighbor, fctx,
14572 );
14573 hit!(RECT4_16_COEFF_HITS);
14574 levels
14575 };
14576 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
14577 }
14578 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
14579 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
14580 // `update_partition_context` writes `partition_context_lookup[
14581 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
14582 // the left (mirrored under VERT_4).
14583 for cell in 0..mi_w {
14584 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
14585 *slot = bw as u8;
14586 }
14587 }
14588 for cell in 0..mi_h {
14589 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
14590 *slot = bh as u8;
14591 }
14592 }
14593 if has_chroma {
14594 hit!(RECT4_16_CHROMA_HITS);
14595 // lane-av1-444: at 4:4:4 there is no pair -- every strip is its
14596 // own chroma reference and codes its own 16x4 / 4x16 chroma
14597 // block. (`set_mi_offsets`'s chroma snap is the zero offset at
14598 // ss 0/0, so the neighbour reads below anchor at the strip.)
14599 let (pair_mi, pw, ph) = if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
14600 (lmi, bw, bh)
14601 } else if horz {
14602 ((lmi.0 - 1, lmi.1), 16, 8)
14603 } else {
14604 ((lmi.0, lmi.1 - 1), 8, 16)
14605 };
14606 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
14607 let (cpx, cpy) = (ppx >> ss_x(fctx), ppy >> ss_y(fctx));
14608 let (cw, ch) = (pw >> ss_x(fctx), ph >> ss_y(fctx));
14609 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
14610 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
14611 hit!(RECT4_16_CHROMA_DIR_HITS);
14612 }
14613 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
14614 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
14615 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
14616 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
14617 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
14618 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
14619 // the pair's top-left luma mi, never this leaf's odd row/column.
14620 // Reading `lmi` here named the leaf directly above (a non-chroma
14621 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
14622 // SMOOTH neighbour: filt_type 0 instead of 1 turned
14623 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
14624 // directional chroma strip, moving 4 samples by 1.
14625 let smooth_neighbor_uv =
14626 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c, fctx);
14627 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
14628 {
14629 hit!(RECT4_16_UV_PAIR_FILT_HITS);
14630 }
14631 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane
14632 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is
14633 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major
14634 // (`decode_token_recon_block`), not one `ChromaRect8x4`. Reading
14635 // the rect here consumed one symbol block too few and desynced
14636 // the next strip's `skip` (measured: lossless sb128 320x240,
14637 // mi(1,20) uv_mode matched, the following skip did not).
14638 let lossless_pair = lossless(fctx);
14639 let (u_levels, v_levels) = if lossless_pair {
14640 hit!(RECT4_16_LOSSLESS_CHROMA_HITS);
14641 if skip {
14642 for plane in 1..3usize {
14643 for rr in 0..ch / 4 {
14644 for cc in 0..cw / 4 {
14645 let (ox, oy) = (cc * 4, rr * 4);
14646 let cu_reach = tu_reach(
14647 pw, ph, ox * 2, oy * 2, 8, pair_reach, ppx, ppy,
14648 y.width, y.height, fctx,
14649 );
14650 if let Some((ub, vb)) = &palette_uv_bufs {
14651 let buf = if plane == 1 { ub } else { vb };
14652 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
14653 }
14654 push_intra(
14655 plane, cpx + ox, cpy + oy, 4, uv_predict_mode,
14656 angle_delta_uv, cu_reach, &ZERO_RESIDUAL[..16], None, None,
14657 smooth_neighbor_uv, fctx,
14658 );
14659 let cu_mi = (
14660 pair_mi.0 + (oy << ss_y(fctx)) / MI,
14661 pair_mi.1 + (ox << ss_x(fctx)) / MI,
14662 );
14663 neighbours.record_mi_chroma(
14664 cu_mi,
14665 4 << ss_x(fctx),
14666 4 << ss_y(fctx),
14667 plane,
14668 &ZERO_RESIDUAL[..16],
14669 );
14670 }
14671 }
14672 }
14673 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
14674 } else {
14675 let scan4 = default_scan(4);
14676 // `get_txb_ctx`: offset 10 (our tables store it at +3)
14677 // when the plane block is larger than the transform.
14678 let offset = Some(3usize);
14679 let mut uo = vec![0i32; cw * ch];
14680 let mut vo = vec![0i32; cw * ch];
14681 for plane in 1..3usize {
14682 for rr in 0..ch / 4 {
14683 for cc in 0..cw / 4 {
14684 let (ox, oy) = (cc * 4, rr * 4);
14685 if cpx + ox >= u.true_width || cpy + oy >= u.true_height {
14686 continue;
14687 }
14688 // The unit's stamp is its own span: aom
14689 // `av1_set_entropy_contexts` (blockd.c:29)
14690 // memsets exactly `tx_size_wide_unit` x
14691 // `tx_size_high_unit` cells at the unit's own
14692 // `(aoff, loff)` -- for TX_4X4 ONE above cell
14693 // and ONE left cell. `(oy / 2, ox / 2)` +
14694 // `(8, 8)` is the 4:2:0 subsampled form (one
14695 // chroma cell = 8 luma px = 2 mi cells); at
14696 // 4:4:4 a unit is ONE mi cell, and the 2x2
14697 // smear let a 4-wide strip's later units
14698 // overwrite the NEXT COLUMN's above cell with
14699 // their own state -- a column aom never sees
14700 // this block write -- so the following block's
14701 // `all_zero` read the wrong `txb_skip` row
14702 // (frame-0 read #452, the llkf named gap).
14703 let cu_mi = (
14704 pair_mi.0 + (oy << ss_y(fctx)) / MI,
14705 pair_mi.1 + (ox << ss_x(fctx)) / MI,
14706 );
14707 // One luma-mi cell: the chroma entropy arrays
14708 // are subsampled, and our bands replicate that
14709 // one entry over the unit's two cells
14710 // (`read_intra_chroma_lossless`).
14711 let cu_around = neighbours.around_mi(cu_mi, MI);
14712 let cu_reach = tu_reach(
14713 pw, ph, ox * 2, oy * 2, 8, pair_reach, ppx, ppy,
14714 y.width, y.height, fctx,
14715 );
14716 if let Some((ub, vb)) = &palette_uv_bufs {
14717 let buf = if plane == 1 { ub } else { vb };
14718 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
14719 }
14720 let buf: &mut PlaneBuf<'static> =
14721 if plane == 1 { &mut *u } else { &mut *v };
14722 let cu_grid = read_plane(
14723 dec, cdfs, TxbSet::Chroma4, &scan4, plane,
14724 cu_around[plane], mode, uv_predict_mode, angle_delta_uv,
14725 cu_reach, buf, cpx + ox, cpy + oy, 4, 4, base_q_idx,
14726 None, None, offset, smooth_neighbor_uv, fctx,
14727 )?;
14728 neighbours.record_mi_chroma(
14729 cu_mi,
14730 4 << ss_x(fctx),
14731 4 << ss_y(fctx),
14732 plane,
14733 &cu_grid,
14734 );
14735 hit!(CHROMA_SPLIT_TX_HITS);
14736 let dst = if plane == 1 { &mut uo } else { &mut vo };
14737 for row in 0..4 {
14738 let start = (oy + row) * cw + ox;
14739 dst[start..start + 4]
14740 .copy_from_slice(&cu_grid[row * 4..][..4]);
14741 }
14742 }
14743 }
14744 }
14745 (Grid::Own(uo), Grid::Own(vo))
14746 }
14747 } else if skip {
14748 let zeros = Grid::Zero(cw * ch);
14749 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
14750 // ~1000) predicts EVERY plane and only guards the residual on
14751 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
14752 // DC + alpha * luma-AC. Dropping the CfL term here left a
14753 // chroma-only bounded box on ReelC's key frames.
14754 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
14755 if alpha.is_some() {
14756 hit!(CHROMA_SKIP_CFL_HITS);
14757 }
14758 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
14759 if let Some((ub, vb)) = &palette_uv_bufs {
14760 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
14761 }
14762 push_intra_rect(plane,
14763 cpx,
14764 cpy,
14765 cw,
14766 ch,
14767 uv_predict_mode,
14768 angle_delta_uv,
14769 pair_reach,
14770 &zeros,
14771 alpha
14772 .zip(ac)
14773 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
14774 None,
14775 smooth_neighbor_uv, fctx,
14776 );
14777 }
14778 (zeros.clone(), zeros)
14779 } else {
14780 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
14781 // lane-av1-444: the strip's own 16x4 / 4x16 chroma at ss 0/0
14782 // (`TxbSet::Chroma8`, `get_txsize_entropy_ctx(TX_16X4)` =
14783 // the 8x8 set); 4:2:0 keeps the pair's 8x4 / 4x8.
14784 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (cw, ch) {
14785 (8, 4) => (TxbSet::ChromaRect8x4, &SCAN_8X4[..]),
14786 (4, 8) => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
14787 (16, 4) => (TxbSet::Chroma8, &SCAN_16X4[..]),
14788 (4, 16) => (TxbSet::Chroma8, &SCAN_4X16[..]),
14789 _ => unreachable!("decode_rect4_16_strip chroma shape set is closed"),
14790 };
14791 let mut planes = Vec::with_capacity(2);
14792 for plane in 1..3 {
14793 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
14794 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
14795 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
14796 let (levels, tx_type) = read_chroma_coeffs_rect(
14797 dec,
14798 &mut coding,
14799 chroma_scan,
14800 cw,
14801 ch,
14802 skip_ctx,
14803 dc_sign_ctx(around[plane].2),
14804 default_tx,
14805 fctx,
14806 )?;
14807 planes.push((levels, tx_type));
14808 }
14809 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
14810 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
14811 // CfL averages the luma of the WHOLE pair, the region this one
14812 // chroma transform covers.
14813 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
14814 for (plane, _buf, levels, tx_type) in [
14815 (1usize, &mut *u, &u_levels, u_tx_type),
14816 (2, &mut *v, &v_levels, v_tx_type),
14817 ] {
14818 let residual = dequant_and_inverse_typed_wh(
14819 levels,
14820 cw,
14821 ch,
14822 crate::decode::bit_depth(fctx),
14823 block_q_idx(fctx),
14824 plane_q_delta(plane, fctx).0,
14825 plane_q_delta(plane, fctx).1,
14826 tx_type,
14827 block_iqmatrix(fctx, plane, cw, ch, tx_type),
14828 );
14829 if let Some((ub, vb)) = &palette_uv_bufs {
14830 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
14831 }
14832 push_intra_rect(plane,
14833 cpx,
14834 cpy,
14835 cw,
14836 ch,
14837 uv_predict_mode,
14838 angle_delta_uv,
14839 pair_reach,
14840 &residual,
14841 alpha
14842 .zip(ac)
14843 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
14844 None,
14845 smooth_neighbor_uv, fctx,
14846 );
14847 }
14848 (u_levels, v_levels)
14849 };
14850 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
14851 // A lossless pair already stamped each TX_4X4 (`record_mi_chroma`).
14852 // The single-state rewrite below is the non-lossless TX_8X4/TX_4X8.
14853 if !lossless_pair {
14854 // The chroma planes' coefficient context, over the PAIR's mi span
14855 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
14856 // the luma one rounded up to its 4x4 unit).
14857 let u_state = neighbour_state(&u_levels);
14858 let v_state = neighbour_state(&v_levels);
14859 let round_up_even = |n: usize| n.div_ceil(2) * 2;
14860 let bound_h = round_up_even(neighbours.mi_rows);
14861 let bound_w = round_up_even(neighbours.mi_cols);
14862 for cell in 0..(ph / MI) {
14863 if pair_mi.0 + cell < bound_h
14864 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
14865 {
14866 slot[1] = u_state;
14867 slot[2] = v_state;
14868 }
14869 }
14870 for cell in 0..(pw / MI) {
14871 if pair_mi.1 + cell < bound_w
14872 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
14873 {
14874 slot[1] = u_state;
14875 slot[2] = v_state;
14876 }
14877 }
14878 }
14879 last_uv_mode = Some(uv_predict_mode);
14880 }
14881 if horz {
14882 hit!(RECT4_16_HORZ_HITS);
14883 } else {
14884 hit!(RECT4_16_VERT_HITS);
14885 }
14886 let (pal_y_size, pal_y_colors) =
14887 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14888 let (pal_uv_size, pal_uv_colors) =
14889 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14890 record_strip_palette(
14891 neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
14892 );
14893 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
14894 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
14895 // frame): the above row records `tx_size_wide` over the block's width and
14896 // the left column `tx_size_high` over its height. This 1:4 strip reader is
14897 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
14898 // and it published neither band -- so the block after a 64x16 strip read
14899 // the row's init value 64 as its left transform height and took
14900 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
14901 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
14902 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
14903 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
14904 Ok((mode, last_uv_mode, (tx_w, tx_h)))
14905}
14906
14907
14908/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
14909/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
14910/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
14911/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
14912/// cap, so LUMA needs the same corner truncation [`decode_block`] already
14913/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
14914/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
14915/// this function's own charter/report), so both strips read a real 32x32
14916/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
14917/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
14918/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
14919/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
14920/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
14921/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
14922/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
14923/// that function, only the single-transform-unit (`tx_depth == 0`) case is
14924/// supported: a split transform refuses by name rather than guess-decode.
14925#[allow(clippy::too_many_arguments)]
14926fn decode_block_rect64(
14927 dec: &mut SymbolDecoder,
14928 cdfs: &mut Cdfs,
14929 neighbours: &mut Neighbours,
14930 at: (usize, usize),
14931 bw: usize,
14932 bh: usize,
14933 y: &mut PlaneBuf<'static>,
14934 u: &mut PlaneBuf<'static>,
14935 v: &mut PlaneBuf<'static>,
14936 enable_filter_intra: bool,
14937 allow_screen_content_tools: bool,
14938 base_q_idx: u8,
14939 tx_select: bool,
14940 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14941) -> Result<()> {
14942 let (r, c) = at;
14943 let (px, py) = (c * SUB, r * SUB);
14944 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14945 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14946 let palette_uv_cache = neighbours.palette_uv_cache(at);
14947 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) =
14948 read_intra_mode_rect(
14949 dec,
14950 cdfs,
14951 nb_above_mode,
14952 nb_left_mode,
14953 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
14954 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
14955 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
14956 // correct), CFL must never be offered here -- passing `true`
14957 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
14958 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
14959 // from this block's very first symbol (lane-sbpart r3 bisect).
14960 false,
14961 true,
14962 bw,
14963 bh,
14964 enable_filter_intra,
14965 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
14966 allow_screen_content_tools,
14967 Some((palette_ctx, &palette_cache)),
14968 &palette_uv_cache,
14969 r * (SUB / MI),
14970 c * (SUB / MI), fctx,
14971 )?;
14972 if let Some((dv_row, dv_col)) = intrabc {
14973 return decode_intrabc_owned_rect(
14974 dec, cdfs, neighbours, (r * (SUB / MI), c * (SUB / MI)), (bw, bh), skip,
14975 (dv_row, dv_col), y, u, v, base_q_idx, tx_select, reduced_tx_set, fctx,
14976 );
14977 }
14978 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
14979 // lane-t900 r34: a non-skip palette block on a superblock-level strip
14980 // -- counted so its gate cannot go vacuous (this was a refusal until
14981 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
14982 // decodes_pixel_exact`).
14983 hit!(PALETTE_SB_STRIP_HITS);
14984 }
14985 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14986 if smooth_neighbor {
14987 hit!(SMOOTH_LUMA_HITS);
14988 }
14989 let smooth_neighbor_uv =
14990 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
14991 if filter_intra.is_some() {
14992 // `filter_intra_size_class_rect` already returns `None` for both
14993 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
14994 // 32 on both axes), so this symbol is never read at this level --
14995 // kept only as the same defensive refusal [`decode_block_rect`] has.
14996 return Err(unsupported(
14997 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
14998 av1_filter_intra_allowed_bsize caps at 32x32)",
14999 ));
15000 }
15001 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15002 DC_PRED
15003 } else {
15004 uv_mode
15005 };
15006 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
15007 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
15008 // precedes `TX_MODE_SELECT`, so a lossless-segment 64-axis rect block codes
15009 // no depth symbol here either (class sweep of the sub8 leaf's fix).
15010 let depth = if tx_select && !lossless(fctx) {
15011 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
15012 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
15013 // intra-only frame publishes them from every block too
15014 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
15015 // 1920x792 128-superblock stream,
15016 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
15017 // `tx_size_cat2` row 1 where libaom reads row 2.
15018 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
15019 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
15020 // counts `sub_tx_size_map` steps from the block's own max rect
15021 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
15022 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
15023 // steps, so this level's category is 3 (the same one a 64x64 square
15024 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
15025 // here was a wrong-table read of a real symbol.
15026 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
15027 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15028 eprintln!(
15029 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
15030 dec.debug_state().0
15031 );
15032 }
15033 d
15034 } else {
15035 0
15036 };
15037 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
15038 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
15039 publish_txfm_bands_if_in_inter(
15040 neighbours,
15041 (mi_r, mi_c),
15042 depth_to_tx_wh(bw, bh, depth, fctx),
15043 (bw, bh), fctx,
15044 );
15045 if depth != 0 || lossless(fctx) {
15046 hit!(TX_DEPTH_HITS);
15047 // lane-rectsplit r1/r4: the superblock-level strip splits its
15048 // transform through the very same per-unit path as its 32x32-level
15049 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
15050 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
15051 // measured the old square formula mis-tiling exactly that strip).
15052 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
15053 if bw.max(bh) / bw.min(bh) == 4 {
15054 let which = if depth == 1 {
15055 &RECT4_SPLIT_DEPTH1_HITS
15056 } else {
15057 &RECT4_SPLIT_DEPTH2_HITS
15058 };
15059 hit_do! { which.with(|c| c.set(c.get() + 1)); }
15060 }
15061 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
15062 eprintln!(
15063 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
15064 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
15065 angle_y={angle_delta_y}"
15066 );
15067 }
15068 let modes = RectStripModes {
15069 skip,
15070 mode,
15071 angle_delta_y,
15072 uv_predict_mode,
15073 angle_delta_uv,
15074 alpha,
15075 filter_intra,
15076 smooth_neighbor,
15077 smooth_neighbor_uv,
15078 palette_y: palette_y
15079 .as_ref()
15080 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
15081 palette_uv: palette_uv.as_ref().map(|p| {
15082 (
15083 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15084 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15085 )
15086 }),
15087 };
15088 if palette_y.is_some() || palette_uv.is_some() {
15089 hit!(PALETTE_SPLIT_TX_HITS);
15090 }
15091 decode_rect_split(
15092 dec,
15093 cdfs,
15094 neighbours,
15095 (mi_r, mi_c),
15096 bw,
15097 bh,
15098 tx_w,
15099 tx_h,
15100 &modes,
15101 y,
15102 u,
15103 v,
15104 base_q_idx,
15105 reduced_tx_set, fctx,
15106 )?;
15107 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
15108 // (lane-palette2 r10): this return skips the fn's own tail, so a
15109 // split-tx superblock strip would otherwise leave the above/left
15110 // palette arrays holding a dead block's colours.
15111 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15112 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
15113 let (puv_size, puv_colors) =
15114 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15115 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
15116 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
15117 // return skips the fn's own tail, so a SPLIT superblock-level strip
15118 // published no TXFM_CONTEXT band and the next block read the row's init
15119 // value 64 as its left transform height. Measured on the 10-bit
15120 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
15121 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
15122 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
15123 // bands carry the SPLIT unit's size, not the block's.
15124 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
15125 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
15126 hit!(RECT_PARTITION_HITS);
15127 return Ok(());
15128 }
15129 let (tx_w, tx_h) = (bw, bh);
15130 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
15131 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
15132 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15133 if let Some(ref pyv) = palette_y {
15134 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
15135 set_palette_pred(buf, fctx);
15136 }
15137 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
15138 (
15139 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
15140 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
15141 )
15142 });
15143 if skip {
15144 push_intra_rect(0,
15145 px,
15146 py,
15147 bw,
15148 bh,
15149 mode,
15150 angle_delta_y,
15151 reach,
15152 &ZERO_RESIDUAL[..bw * bh],
15153 None,
15154 filter_intra,
15155 smooth_neighbor, fctx,
15156 );
15157 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15158 if let Some((ub, _)) = &palette_uv_bufs {
15159 set_palette_pred(ub.clone(), fctx);
15160 }
15161 push_intra_rect(1,
15162 cpx,
15163 cpy,
15164 chroma_w,
15165 chroma_h,
15166 uv_predict_mode,
15167 angle_delta_uv,
15168 reach,
15169 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15170 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15171 None,
15172 smooth_neighbor_uv, fctx,
15173 );
15174 if let Some((_, vb)) = &palette_uv_bufs {
15175 set_palette_pred(vb.clone(), fctx);
15176 }
15177 push_intra_rect(2,
15178 cpx,
15179 cpy,
15180 chroma_w,
15181 chroma_h,
15182 uv_predict_mode,
15183 angle_delta_uv,
15184 reach,
15185 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15186 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15187 None,
15188 smooth_neighbor_uv, fctx,
15189 );
15190 neighbours.record_rect(
15191 at,
15192 bw,
15193 bh,
15194 mode,
15195 uv_predict_mode,
15196 &[
15197 &ZERO_RESIDUAL[..bw * bh],
15198 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15199 &ZERO_RESIDUAL[..chroma_w * chroma_h],
15200 ],
15201 );
15202 } else {
15203 let around = neighbours.around_rect(at, bw, bh);
15204 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
15205 // (see this function's own doc comment). A 64-length axis codes only
15206 // its low 32 coefficients, so the corner is `min(bw, 32)` x
15207 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
15208 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
15209 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
15210 let scan32 = default_scan(TX32);
15211 if coeff_trace_on() {
15212 let (rng, _) = dec.debug_state();
15213 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
15214 }
15215 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
15216 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
15217 read_coeffs(
15218 dec,
15219 &mut luma_coding,
15220 &scan32,
15221 0,
15222 dc_sign_ctx(around[0].2),
15223 TxType::DctDct,
15224 Some((bw, bh)),
15225 )?
15226 } else {
15227 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
15228 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
15229 // (`scan.c`) gives both the very same `default_scan_32x16` /
15230 // `default_scan_16x32` the 2:1 sizes use ("Half of the
15231 // coefficients of tx64 at higher frequencies are set to zeros. So
15232 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
15233 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
15234 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
15235 // 512-position eob group) -- BOTH identical to TX_32X16, so the
15236 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
15237 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
15238 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
15239 // what `base_ctx_rect` computes at (32, 16).
15240 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
15241 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
15242 read_coeffs_rect(
15243 dec,
15244 &mut luma_coding,
15245 luma_scan,
15246 luma_cw,
15247 luma_ch,
15248 0,
15249 dc_sign_ctx(around[0].2),
15250 TxType::DctDct,
15251 )?
15252 };
15253 if coeff_trace_on() {
15254 let (rng, _) = dec.debug_state();
15255 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
15256 }
15257 let mut luma_levels = vec![0i32; bw * bh];
15258 for row in 0..luma_ch {
15259 luma_levels[row * bw..][..luma_cw]
15260 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
15261 }
15262 {
15263 let cur = block_q_idx(fctx);
15264 if cur != i32::from(base_q_idx) {
15265 hit!(RECT64_QIDX_DRIFT_HITS);
15266 }
15267 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15268 eprintln!(
15269 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
15270 );
15271 }
15272 }
15273 let luma_residual = dequant_and_inverse_typed_wh(
15274 &luma_levels,
15275 bw,
15276 bh,
15277 crate::decode::bit_depth(fctx),
15278 block_q_idx(fctx),
15279 plane_q_delta(0, fctx).0,
15280 plane_q_delta(0, fctx).1,
15281 luma_tx_type,
15282 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
15283 );
15284 push_intra_rect(0,
15285 px,
15286 py,
15287 bw,
15288 bh,
15289 mode,
15290 angle_delta_y,
15291 reach,
15292 &luma_residual,
15293 None,
15294 filter_intra,
15295 smooth_neighbor, fctx,
15296 );
15297 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
15298 let leftcol: Vec<u16> = if px > 0 {
15299 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
15300 } else {
15301 vec![]
15302 };
15303 eprintln!(
15304 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
15305 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
15306 luma_corner.iter().any(|&v| v != 0),
15307 &y.data[py * y.width + px..][..bw],
15308 leftcol,
15309 );
15310 }
15311 // CHROMA. At 4:2:0 the plane block is already one adjusted UV
15312 // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma
15313 // is larger than that, so it is tiled into 32-capped units.
15314 let _ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
15315 let (uw, uh) = (chroma_w.min(32), chroma_h.min(32));
15316 let (nw, nh) = (chroma_w / uw, chroma_h / uh);
15317 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (uw, uh) {
15318 (32, 32) => (TxbSet::Chroma32, default_scan(32)),
15319 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
15320 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
15321 (32, 8) => (TxbSet::Chroma16, &SCAN_32X8),
15322 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
15323 _ => {
15324 return Err(unsupported(
15325 "a 64-axis strip whose chroma unit has no coefficient table",
15326 ))
15327 }
15328 };
15329 let bigger = nw * nh > 1;
15330 let mut u_levels = vec![0i32; chroma_w * chroma_h];
15331 let mut v_levels = vec![0i32; chroma_w * chroma_h];
15332 // The tiled units below stamp their own coefficient context
15333 // immediately, then the whole-strip `record_rect` rewrite paints
15334 // every chroma cell with ONE whole-strip state and the per-unit DC
15335 // signs and levels are lost (class `override-slot-on-one-arm`, same
15336 // shape as `decode_rect_split`'s chroma_tiled clobber). Collected
15337 // here and replayed after that record, the c8 `mu_chroma_units` way.
15338 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
15339 for plane_idx in 1..=2 {
15340 for cu_row in 0..nh {
15341 for cu_col in 0..nw {
15342 let cu_around = if nw == 1 && nh == 1 {
15343 around
15344 } else {
15345 let lsx = uw << ss_x(fctx);
15346 let lsy = uh << ss_y(fctx);
15347 let cu_mi = (
15348 mi_r + cu_row * (lsy / MI),
15349 mi_c + cu_col * (lsx / MI),
15350 );
15351 neighbours.around_mi_rect(cu_mi, lsx, lsy)
15352 };
15353 let lsx = uw << ss_x(fctx);
15354 let lsy = uh << ss_y(fctx);
15355 let cfl = alpha.map(|(au, av)| {
15356 let a = if plane_idx == 1 { au } else { av };
15357 (a, cfl_src_rect(px + cu_col * lsx, py + cu_row * lsy, lsx, lsy))
15358 });
15359 let levels = if uw == uh {
15360 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
15361 if let Some((ub, vb)) = &palette_uv_bufs {
15362 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
15363 }
15364 read_plane(
15365 dec, cdfs, chroma_set, chroma_scan, plane_idx, cu_around[plane_idx],
15366 mode, uv_predict_mode, angle_delta_uv, reach, plane,
15367 cpx + cu_col * uw, cpy + cu_row * uh, uw, uw, base_q_idx,
15368 cfl, None, bigger.then_some(3), smooth_neighbor_uv, fctx,
15369 )?
15370 } else {
15371 let skip_ctx = usize::from(cu_around[plane_idx].0)
15372 + usize::from(cu_around[plane_idx].1)
15373 + usize::from(bigger) * 3;
15374 let mut coding = cdfs.txb(chroma_set, uv_predict_mode);
15375 let (levels, tx_type) = read_chroma_coeffs_rect(
15376 dec, &mut coding, chroma_scan, uw, uh, skip_ctx,
15377 dc_sign_ctx(cu_around[plane_idx].2), TxType::DctDct, fctx,
15378 )?;
15379 let residual = dequant_and_inverse_typed_wh(
15380 &levels, uw, uh, crate::decode::bit_depth(fctx),
15381 block_q_idx(fctx),
15382 plane_q_delta(plane_idx, fctx).0,
15383 plane_q_delta(plane_idx, fctx).1,
15384 tx_type,
15385 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
15386 );
15387 if let Some((ub, vb)) = &palette_uv_bufs {
15388 set_palette_pred((if plane_idx == 1 { ub } else { vb }).clone(), fctx);
15389 }
15390 push_intra_rect(
15391 plane_idx, cpx + cu_col * uw, cpy + cu_row * uh, uw, uh,
15392 uv_predict_mode, angle_delta_uv, reach, &residual,
15393 cfl, None, smooth_neighbor_uv, fctx,
15394 );
15395 levels
15396 };
15397 let dst = if plane_idx == 1 { &mut u_levels } else { &mut v_levels };
15398 for row in 0..uh {
15399 let d = (cu_row * uh + row) * chroma_w + cu_col * uw;
15400 dst[d..d + uw].copy_from_slice(&levels[row * uw..][..uw]);
15401 }
15402 if bigger {
15403 neighbours.record_mi_chroma(
15404 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
15405 lsx, lsy, plane_idx, &levels,
15406 );
15407 tiled_chroma_units.push((
15408 (mi_r + cu_row * (lsy / MI), mi_c + cu_col * (lsx / MI)),
15409 plane_idx,
15410 levels.clone(),
15411 lsx,
15412 lsy,
15413 ));
15414 }
15415 }
15416 }
15417 }
15418 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
15419 // The per-unit re-stamp: `record_rect` above wrote the whole strip's
15420 // chroma cells from the assembled grids' one whole-strip state,
15421 // overwriting exactly the stamps the tiled loop just made.
15422 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
15423 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
15424 }
15425 hit!(RECT_COEFF_HITS);
15426 }
15427 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15428 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
15429 let (puv_size, puv_colors) =
15430 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15431 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
15432 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
15433 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
15434 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
15435 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
15436 // frame): the above row records `tx_size_wide` over the block's width and
15437 // the left column `tx_size_high` over its height. This 1:4 strip reader is
15438 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
15439 // and it published neither band -- so the block after a 64x16 strip read
15440 // the row's init value 64 as its left transform height and took
15441 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
15442 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
15443 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
15444 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
15445 hit!(SB_RECT_HITS);
15446 match (bw, bh) {
15447 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
15448 (16, 64) => hit!(SB_RECT4_VERT_HITS),
15449 _ => {}
15450 }
15451 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15452 let (rng, _) = dec.debug_state();
15453 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
15454 }
15455 Ok(())
15456}
15457
15458/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
15459/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
15460/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
15461/// it lands away from zero, for gate tests to prove a real stream fired one.
15462fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
15463 let symbol = dec.symbol(cdf);
15464 if symbol != ANGLE_DELTA_ZERO {
15465 hit!(ANGLE_DELTA_HITS);
15466 }
15467 symbol as i32 - ANGLE_DELTA_ZERO as i32
15468}
15469
15470#[allow(clippy::too_many_arguments)]
15471fn read_intra_mode(
15472 dec: &mut SymbolDecoder,
15473 cdfs: &mut Cdfs,
15474 above_mode: usize,
15475 left_mode: usize,
15476 cfl: bool,
15477 side: usize,
15478 enable_filter_intra: bool,
15479 skip_ctx: usize,
15480 allow_screen_content_tools: bool,
15481 allow_intrabc: bool,
15482 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
15483 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
15484 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
15485 // `None` at the excluded call sites (the 8x8-leaf path), which still read
15486 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
15487 // decoder reads either way -- but refuse by name the moment it fires,
15488 // exactly the old behaviour.
15489 palette: Option<(usize, &[u16])>,
15490 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
15491 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
15492 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
15493 // `use_palette_y`, not a neighbour lookup).
15494 palette_uv_cache: &[u16],
15495 mi_r: usize,
15496 mi_c: usize, fctx: &crate::decode::FrameCtx,
15497) -> Result<(
15498 bool,
15499 usize,
15500 i32,
15501 usize,
15502 i32,
15503 Option<(i32, i32)>,
15504 Option<usize>,
15505 Option<PaletteY>,
15506 Option<PaletteUv>,
15507)> {
15508 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
15509 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
15510 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
15511 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
15512 // line against the instrumented aomdec, not just `tell()`.
15513 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
15514 if ec_istep {
15515 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
15516 // (decodemv.c:818), printed at the same point: before the first
15517 // mode-info symbol of the block, so a cross-decoder range ladder can
15518 // be keyed on the BLOCK, not just on the symbol sequence.
15519 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
15520 }
15521 macro_rules! istep {
15522 ($name:literal, $val:expr) => {
15523 if ec_istep {
15524 let (rng, _) = dec.debug_state();
15525 eprintln!(
15526 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
15527 $name, $val
15528 );
15529 }
15530 };
15531 }
15532 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
15533 // point every square caller routes through (see `read_intra_mode_rect`).
15534 let cfl = if cfl && side > 32 {
15535 hit!(NOCFL_UV_MODE_HITS);
15536 false
15537 } else {
15538 cfl
15539 };
15540 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
15541 // `skip` when `SegIdPreSkip`, and after it otherwise.
15542 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
15543 if seg_id_pre_skip(fctx) {
15544 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
15545 }
15546 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
15547 if trace {
15548 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
15549 }
15550 istep!("skip", skip as i32);
15551 if !seg_id_pre_skip(fctx) {
15552 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
15553 }
15554 // spec order (see the comment below on `read_intrabc_info`): `skip`,
15555 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
15556 maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
15557 istep!("cdef", 0);
15558 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
15559 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
15560 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
15561 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
15562 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
15563 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
15564 istep!("dq", 0);
15565 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
15566 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
15567 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
15568 // intra frame whose header set `allow_intrabc`. Actual intra block copy
15569 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
15570 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
15571 // draws the line at consuming this one flag symbol and refusing by name
15572 // when it fires, so the arithmetic decoder still resyncs for a stream
15573 // that merely allows (but never uses) intrabc.
15574 if allow_intrabc {
15575 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
15576 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15577 eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}", u8::from(use_intrabc), dec.debug_state().0);
15578 }
15579 if trace {
15580 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
15581 }
15582 if use_intrabc {
15583 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);
15584 if trace {
15585 eprintln!("TRACE intrabc dv={dv:?}");
15586 }
15587 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
15588 hit!(INTRABC_HITS);
15589 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
15590 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
15591 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
15592 // `DC_PRED` (which is also what the neighbour mode contexts and
15593 // the loop filter then see).
15594 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
15595 }
15596 }
15597 let above_ctx = INTRA_MODE_CTX[above_mode];
15598 let left_ctx = INTRA_MODE_CTX[left_mode];
15599 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
15600 if trace {
15601 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
15602 }
15603 istep!("mode", mode as i32);
15604 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
15605 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
15606 if trace {
15607 eprintln!(
15608 "TRACE angle_delta value={}",
15609 delta + ANGLE_DELTA_ZERO as i32
15610 );
15611 }
15612 delta
15613 } else {
15614 0
15615 };
15616 istep!("angle_y", angle_delta_y);
15617 // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette
15618 // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref`
15619 // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader
15620 // gates its chroma symbols on.
15621 let has_chroma = !mono(fctx);
15622 let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx);
15623 let uv_mode = if !has_chroma {
15624 DC_PRED
15625 } else if cfl {
15626 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
15627 } else {
15628 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
15629 };
15630 if trace {
15631 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
15632 }
15633 istep!("uv_mode", uv_mode as i32);
15634 let alpha = if cfl && uv_mode == UV_CFL_PRED {
15635 Some(read_cfl_alphas(dec, cdfs))
15636 } else {
15637 None
15638 };
15639 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
15640 // from this lane's directional chroma: a corner block with neither
15641 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
15642 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
15643 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
15644 // bug in that fallback this lane's own scope does not cover. Keep it
15645 // refused here rather than ship a silently-wrong decode.
15646 if (9..=12).contains(&uv_mode) {
15647 hit!(SMOOTH_UV_HITS);
15648 }
15649 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
15650 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
15651 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
15652 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
15653 // the `else` branch below and never reads one either way.
15654 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
15655 hit!(DIRECTIONAL_UV_HITS);
15656 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
15657 } else {
15658 0
15659 };
15660 istep!("angle_uv", angle_delta_uv);
15661 if angle_delta_uv != 0 {
15662 hit!(UV_ANGLE_DELTA_HITS);
15663 }
15664 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
15665 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
15666 // gated by `av1_allow_palette` (blockd.h -- size bound only,
15667 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
15668 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
15669 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
15670 // read the same CDF row whenever every neighbour really is non-palette).
15671 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
15672 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
15673 // neighbour lookup at all), so it is exact even at the excluded call
15674 // sites once Y decodes real syntax there too.
15675 //
15676 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
15677 // inline from `read_palette_mode_info` -- it runs later, from
15678 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
15679 // after the WHOLE mode-info read for the block, including UV palette
15680 // mode_info (`read_palette_mode_info`'s own second half, right below)
15681 // and `read_filter_intra_mode_info`. So this branch now only reads
15682 // mode/size/colours for both planes (deferring the two colour-index-map
15683 // decodes to after `filter_intra`, below) -- r6's range trace pinned
15684 // this exact ordering bug (`compare-range-not-tell`: ranges matched
15685 // bit-for-bit through the Y colours, diverged only at the old inline
15686 // `decode_color_index_map` call).
15687 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
15688 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
15689 if allow_screen_content_tools
15690 && let Some(bsize_ctx) = palette_bsize_ctx(side)
15691 {
15692 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
15693 if mode == DC_PRED {
15694 if trace {
15695 let (rng, _) = dec.debug_state();
15696 eprintln!(
15697 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
15698 );
15699 }
15700 }
15701 let use_palette_y =
15702 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
15703 if mode == DC_PRED && trace {
15704 let (rng, _) = dec.debug_state();
15705 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
15706 }
15707 if use_palette_y {
15708 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
15709 if trace {
15710 let (rng, _) = dec.debug_state();
15711 eprintln!("TRACE palette_y_size n={n} rng={rng}");
15712 }
15713 let colors = read_palette_colors_y(dec, n, cache, fctx);
15714 if trace {
15715 let (rng, _) = dec.debug_state();
15716 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
15717 }
15718 palette_y_pending = Some((n, colors));
15719 }
15720 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
15721 // unconditionally at this bit position whenever `uv_mode ==
15722 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
15723 // scope always reconstructs chroma alongside luma (`decode_block`
15724 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
15725 // is always true here and does not need threading in.
15726 //
15727 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
15728 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a
15729 // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size`
15730 // symbol even at this chroma-owning square block.
15731 let palette_uv_mode_ctx = usize::from(use_palette_y);
15732 if has_chroma
15733 && uv_mode == DC_PRED
15734 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
15735 {
15736 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
15737 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
15738 palette_uv_pending = Some((n, u_colors, v_colors));
15739 }
15740 }
15741 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
15742 // `use_filter_intra` symbol this decoder never read at all until
15743 // lane-av1real r10 -- silently skipping it left every bit past a
15744 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
15745 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
15746 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
15747 // symbol's bits were never consumed).
15748 let mut filter_intra = None;
15749 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
15750 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
15751 // `use_filter_intra` symbol for a Y-palette block, and reading one here
15752 // desynced every screen-content stream from the first palette block on
15753 // (it surfaced as a bogus "partition below 8x8" refusal further down the
15754 // tile).
15755 if mode == DC_PRED
15756 && enable_filter_intra
15757 && palette_y_pending.is_none()
15758 && let Some(class) = filter_intra_size_class(side)
15759 {
15760 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
15761 if trace {
15762 eprintln!(
15763 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
15764 use_filter_intra as i32
15765 );
15766 }
15767 istep!("use_filter_intra", use_filter_intra as i32);
15768 if use_filter_intra {
15769 hit!(FILTER_INTRA_HITS);
15770 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
15771 if trace {
15772 eprintln!("TRACE filter_intra_mode value={fi_mode}");
15773 }
15774 istep!("filter_intra_mode", fi_mode as i32);
15775 filter_intra = Some(fi_mode);
15776 }
15777 }
15778 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
15779 // shared U/V map) -- the same order libaom's own loop visits them in.
15780 let palette_y = palette_y_pending.map(|(n, colors)| {
15781 let map =
15782 decode_color_index_map(dec, cdfs, n, side, palette_onscreen(mi_r, mi_c, side, side, fctx), false);
15783 hit!(PALETTE_HITS);
15784 if trace {
15785 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
15786 }
15787 PaletteY { size: n, colors, map }
15788 });
15789 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
15790 let on = palette_onscreen_uv(
15791 (side, side),
15792 palette_onscreen(mi_r, mi_c, side, side, fctx),
15793 (side >> ss_x(fctx), side >> ss_y(fctx)),
15794 (ss_x(fctx), ss_y(fctx)),
15795 );
15796 let map = decode_color_index_map(dec, cdfs, n, side >> ss_x(fctx), on, true);
15797 hit!(PALETTE_UV_HITS);
15798 if trace {
15799 eprintln!(
15800 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
15801 &u_colors[..n],
15802 &v_colors[..n]
15803 );
15804 }
15805 PaletteUv { size: n, u_colors, v_colors, map }
15806 });
15807 Ok((
15808 skip,
15809 mode,
15810 angle_delta_y,
15811 uv_mode,
15812 angle_delta_uv,
15813 alpha,
15814 filter_intra,
15815 palette_y,
15816 palette_uv,
15817 ))
15818}
15819
15820/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
15821/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
15822/// intra modes.
15823const UV_CFL_PRED: usize = 13;
15824
15825/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
15826/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
15827/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
15828/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
15829/// joint sign the same way. Returns each plane's final signed `alpha_q3`
15830/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
15831fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
15832 hit!(CFL_BLOCK_HITS);
15833 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
15834 let sign_u = ((joint_sign + 1) * 11) >> 5;
15835 let sign_v = (joint_sign + 1) - 3 * sign_u;
15836 let alpha_u = if sign_u == 0 {
15837 0
15838 } else {
15839 let ctx_u = (joint_sign + 1 - 3) as usize;
15840 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
15841 if sign_u == 2 { mag } else { -mag }
15842 };
15843 let alpha_v = if sign_v == 0 {
15844 0
15845 } else {
15846 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
15847 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
15848 if sign_v == 2 { mag } else { -mag }
15849 };
15850 (alpha_u, alpha_v)
15851}
15852
15853/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
15854/// the reconstructed luma samples under a `side`-square block, subsampled
15855/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
15856/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
15857/// to give the AC values [`cfl_scaled`] scales by alpha.
15858fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
15859 cfl_ac_q3_at(px, py, side, side, |lx, ly| i32::from(y.data[ly * y.width + lx]))
15860}
15861
15862/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
15863/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
15864/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
15865/// reconstruction through THIS function rather than a second transcription of
15866/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
15867/// CfL AC at the frame's subsampling. 4:2:0 keeps the 2x2 average; 4:4:4
15868/// copies each luma sample shifted to Q3 (`cfl_luma_subsampling_444_lbd`).
15869fn cfl_ac_ss(
15870 y: &PlaneBuf<'_>,
15871 px: usize,
15872 py: usize,
15873 bw: usize,
15874 bh: usize,
15875 ss_x: usize,
15876 ss_y: usize,
15877) -> Vec<i32> {
15878 if ss_x == 0 && ss_y == 0 {
15879 let mut ac = vec![0i32; bw * bh];
15880 let mut sum = 0i32;
15881 for row in 0..bh {
15882 for col in 0..bw {
15883 let q3 = i32::from(y.data[(py + row) * y.width + px + col]) << 3;
15884 ac[row * bw + col] = q3;
15885 sum += q3;
15886 }
15887 }
15888 let num_pel = (bw * bh) as i32;
15889 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
15890 ac.iter_mut().for_each(|v| *v -= avg);
15891 ac
15892 } else if bw == bh {
15893 cfl_ac_q3(y, px, py, bw)
15894 } else {
15895 cfl_ac_q3_rect(y, px, py, bw, bh)
15896 }
15897}
15898
15899pub(crate) fn cfl_ac_q3_at(
15900 px: usize,
15901 py: usize,
15902 bw: usize,
15903 bh: usize,
15904 sample: impl Fn(usize, usize) -> i32,
15905) -> Vec<i32> {
15906 let (cw, ch) = (bw / 2, bh / 2);
15907 let mut ac = vec![0i32; cw * ch];
15908 let mut sum = 0i32;
15909 for cy in 0..ch {
15910 for cx in 0..cw {
15911 let (lx, ly) = (px + cx * 2, py + cy * 2);
15912 let q3 = (sample(lx, ly)
15913 + sample(lx + 1, ly)
15914 + sample(lx, ly + 1)
15915 + sample(lx + 1, ly + 1))
15916 << 1;
15917 ac[cy * cw + cx] = q3;
15918 sum += q3;
15919 }
15920 }
15921 let num_pel = (cw * ch) as i32;
15922 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
15923 ac.iter_mut().for_each(|v| *v -= avg);
15924 ac
15925}
15926
15927/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
15928/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
15929/// ties away from zero on the shifted-out sign).
15930pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
15931 let v = alpha_q3 * ac_q3;
15932 if v >= 0 {
15933 (v + 32) >> 6
15934 } else {
15935 -((-v + 32) >> 6)
15936 }
15937}
15938
15939/// One plane's reconstruction buffer, `width * height` samples, and the
15940/// prediction/residual reads and writes into it — the decode-side twin of
15941/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
15942/// (own-edge and reach clamps both), passing what it gathers straight to
15943/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
15944/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
15945/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
15946/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
15947/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
15948/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
15949/// lane-mc64 r1: the decode-order index the stage dumps below key their file
15950/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
15951/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
15952/// without this every frame overwrote `.f0` and a per-frame bisection silently
15953/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
15954#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
15955fn stage_dump_idx() -> usize {
15956 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1)
15957}
15958
15959fn dump_stage16(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, fw: usize, fh: usize) {
15960 use std::io::Write;
15961 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
15962 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
15963 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
15964 // not be read out at all.
15965 if let Ok(path) = crate::envflags::var(var)
15966 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
15967 {
15968 for (p, w, h) in [(y, fw, fh), (u, fw.div_ceil(2), fh.div_ceil(2)), (v, fw.div_ceil(2), fh.div_ceil(2))] {
15969 for row in 0..h {
15970 let mut bytes = Vec::with_capacity(w * 2);
15971 for &s in &p.data[row * p.width..][..w] {
15972 bytes.extend_from_slice(&s.to_le_bytes());
15973 }
15974 let _ = f.write_all(&bytes);
15975 }
15976 }
15977 }
15978}
15979
15980/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
15981/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
15982/// every frame overwrote the previous one and only the LAST frame survived,
15983/// which silently defeats any per-frame filter-stage bisection.
15984fn dump_stage_idx(var: &str) -> usize {
15985 use std::collections::HashMap;
15986 use std::sync::{Mutex, OnceLock};
15987 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
15988 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
15989 let e = m.entry(var.to_string()).or_insert(0);
15990 let i = *e;
15991 *e += 1;
15992 i
15993}
15994
15995fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
15996 use std::io::Write;
15997 if let Ok(path) = crate::envflags::var(var)
15998 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
15999 {
16000 for p in [y, u, v] {
16001 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
16002 let _ = f.write_all(&narrow);
16003 }
16004 }
16005}
16006
16007/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
16008/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
16009/// at most 4095), so a decode that hashes identically under the flag proves
16010/// the output does not depend on the plane buffer's initial content.
16011const PLANE_SENTINEL: u16 = 0xDEAD;
16012
16013/// A frame plane's own backing store, `n` samples, UNINITIALISED.
16014///
16015/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
16016/// by the tile walk's reconstruction before anything reads it, so the
16017/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
16018/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
16019/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
16020/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
16021/// ways (see the lane report) and the two agree, which is the proof that no
16022/// unwritten sample reaches the output.
16023fn fresh_plane(n: usize) -> Vec<u16> {
16024 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
16025 return vec![PLANE_SENTINEL; n];
16026 }
16027 let mut v: Vec<u16> = Vec::with_capacity(n);
16028 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
16029 // capacity was just reserved, so the vector owns `n` initialised-or-not
16030 // `u16` slots. Every one is written by reconstruction before it is read
16031 // (proven by the sentinel gate above).
16032 #[allow(unsafe_code)]
16033 unsafe {
16034 v.set_len(n);
16035 }
16036 v
16037}
16038
16039#[derive(Clone)]
16040struct PlaneBuf<'a> {
16041 data: std::borrow::Cow<'a, [u16]>,
16042 width: usize,
16043 height: usize,
16044 /// The frame's true, decodable extent in this plane's own units — past
16045 /// this, samples are the padded coding surface's invented tail, never a
16046 /// real decoder's edge or reach reads.
16047 true_width: usize,
16048 true_height: usize,
16049 /// This plane's own tile's top-left pixel origin (spec: intra prediction
16050 /// never reaches across a tile boundary even though an earlier-decoded
16051 /// tile's real pixels sit right there in the shared buffer) — set via
16052 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
16053 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
16054 /// is threaded (the two-tile column-split stage 1 fixture's tile always
16055 /// ends at the frame's own right/bottom edge); a non-last tile's own
16056 /// right/bottom reach bound is still open, tracked in the report.
16057 tile_x0: usize,
16058 tile_y0: usize,
16059 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
16060 /// (exclusive) -- a non-last tile column/row's own reach must stop at
16061 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
16062 /// full padded extent) for the single-tile/last-tile case, matching the
16063 /// old unclipped behaviour exactly.
16064 tile_x1: usize,
16065 tile_y1: usize,
16066}
16067
16068/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
16069/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
16070/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
16071/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
16072/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
16073/// `ALTREF2`/`ALTREF`).
16074
16075impl PlaneBuf<'_> {
16076 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
16077 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
16078 /// are already in this plane's own units (luma pixels for `y`, chroma
16079 /// pixels — halved — for `u`/`v`).
16080 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
16081 self.tile_x0 = x0;
16082 self.tile_y0 = y0;
16083 self.tile_x1 = x1;
16084 self.tile_y1 = y1;
16085 }
16086
16087 fn edges(
16088 &self,
16089 x: usize,
16090 y: usize,
16091 side: usize,
16092 reach: Reach,
16093 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
16094 let own_across = x + side.min(self.true_width.saturating_sub(x));
16095 let across = if reach.above_right {
16096 own_across + side.min(self.true_width.saturating_sub(own_across))
16097 } else {
16098 own_across
16099 }
16100 .min(self.width)
16101 .min(self.tile_x1);
16102 let own_down = y + side.min(self.true_height.saturating_sub(y));
16103 let down = if reach.below_left {
16104 own_down + side.min(self.true_height.saturating_sub(own_down))
16105 } else {
16106 own_down
16107 }
16108 .min(self.height)
16109 .min(self.tile_y1);
16110 let above = (y > self.tile_y0 && across > x)
16111 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
16112 let left = (x > self.tile_x0 && down > y).then(|| {
16113 (y..down)
16114 .map(|row| self.data[row * self.width + x - 1])
16115 .collect::<Vec<_>>()
16116 });
16117 let corner =
16118 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
16119 (above, left, corner)
16120 }
16121
16122 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
16123 /// the above/left reach each extend by their OWN axis (`bw` across,
16124 /// `bh` down), not one shared `side`.
16125 fn edges_rect(
16126 &self,
16127 x: usize,
16128 y: usize,
16129 bw: usize,
16130 bh: usize,
16131 reach: Reach,
16132 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
16133 let own_across = x + bw.min(self.true_width.saturating_sub(x));
16134 let across = if reach.above_right {
16135 own_across + bw.min(self.true_width.saturating_sub(own_across))
16136 } else {
16137 own_across
16138 }
16139 .min(self.width)
16140 .min(self.tile_x1);
16141 let own_down = y + bh.min(self.true_height.saturating_sub(y));
16142 let down = if reach.below_left {
16143 own_down + bh.min(self.true_height.saturating_sub(own_down))
16144 } else {
16145 own_down
16146 }
16147 .min(self.height)
16148 .min(self.tile_y1);
16149 let above = (y > self.tile_y0 && across > x)
16150 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
16151 let left = (x > self.tile_x0 && down > y).then(|| {
16152 (y..down)
16153 .map(|row| self.data[row * self.width + x - 1])
16154 .collect::<Vec<_>>()
16155 });
16156 let corner =
16157 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
16158 if matches!((bw, bh), (16, 8) | (8, 16)) {
16159 hit!(RECT_STRIP_PRED_HITS);
16160 if across > own_across || down > own_down {
16161 hit!(RECT_STRIP_REACH_HITS);
16162 }
16163 }
16164 (above, left, corner)
16165 }
16166
16167 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
16168 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
16169 /// already-rect-capable `(bw, bh)` pair.
16170 #[allow(clippy::too_many_arguments)]
16171 #[track_caller]
16172 fn reconstruct_rect(
16173 &mut self,
16174 x: usize,
16175 y: usize,
16176 bw: usize,
16177 bh: usize,
16178 mode: usize,
16179 angle_delta: i32,
16180 reach: Reach,
16181 residual: &[i32],
16182 cfl: Option<(i32, &[i32])>,
16183 filter_intra: Option<usize>,
16184 smooth_neighbor: bool,
16185 // lane-wave1 step (i): the palette/intrabc prediction override, taken
16186 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
16187 // than by this replay.
16188 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
16189 ) {
16190 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
16191 // (lane-palette2 r4): a palette block's prediction is the
16192 // reconstructed colour-index map, needing no edge pixels at all.
16193 let prediction = if let Some(buf) = pred {
16194 buf
16195 } else {
16196 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
16197 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
16198 eprintln!(
16199 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
16200 above.as_ref().map(|a| (a.len(), a[0])),
16201 left.as_ref().map(|l| l.len()),
16202 left.as_ref().map(|l| l[0]),
16203 self.tile_x0, self.tile_y0, self.true_width, self.true_height
16204 );
16205 }
16206 let mut prediction = vec![0u16; bw * bh];
16207 if let Some(fi_mode) = filter_intra {
16208 crate::intra::predict_filter_intra(
16209 fi_mode,
16210 above.as_deref(),
16211 left.as_deref(),
16212 corner,
16213 bw,
16214 bh,
16215 &mut prediction, fctx,
16216 );
16217 } else {
16218 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
16219 predict(
16220 mode as u8,
16221 angle_delta,
16222 above.as_deref(),
16223 left.as_deref(),
16224 corner,
16225 bw,
16226 bh,
16227 enable_edge_filter,
16228 smooth_neighbor,
16229 &mut prediction, fctx,
16230 );
16231 }
16232 prediction
16233 };
16234 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
16235 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
16236 if crate::envflags::env_flag!("EC_PRED") {
16237 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
16238 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
16239 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
16240 eprintln!(
16241 "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor)
16242 );
16243 }
16244 let residual = dense_residual(residual, bw * bh);
16245 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
16246 let res0: Vec<i32> = residual[..bw.min(8)].to_vec();
16247 let pred0: Vec<u16> = prediction[..bw.min(8)].to_vec();
16248 eprintln!("DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}");
16249 }
16250 for row in 0..bh {
16251 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
16252 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
16253 // whose padded width is not superblock aligned hangs past it.
16254 if y + row >= self.height {
16255 break;
16256 }
16257 for col in 0..bw {
16258 if x + col >= self.width {
16259 break;
16260 }
16261 let idx = row * bw + col;
16262 let mut base = i32::from(prediction[idx]);
16263 if let Some((alpha_q3, ac_q3)) = cfl {
16264 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
16265 }
16266 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
16267 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
16268 }
16269 }
16270 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
16271 // -- a block whose prediction matches the oracle's but whose written
16272 // samples do not is either a residual defect or a later overwrite, and
16273 // only this print separates the two.
16274 if crate::envflags::env_flag!("EC_PRED") {
16275 let row0: Vec<u16> =
16276 (0..bw.min(8)).map(|c| self.data[y * self.width + x + c]).collect();
16277 let col0: Vec<u16> =
16278 (0..bh.min(8)).map(|r| self.data[(y + r) * self.width + x]).collect();
16279 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
16280 }
16281 }
16282
16283 /// Predicts under `mode` then adds `residual` (side*side, raster),
16284 /// writing the clamped reconstruction back into the plane at `(x, y)`.
16285 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
16286 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
16287 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
16288 /// order (cfl.c).
16289 #[track_caller]
16290 fn reconstruct(
16291 &mut self,
16292 x: usize,
16293 y: usize,
16294 side: usize,
16295 mode: usize,
16296 angle_delta: i32,
16297 reach: Reach,
16298 residual: &[i32],
16299 cfl: Option<(i32, &[i32])>,
16300 filter_intra: Option<usize>,
16301 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
16302 // libaom `get_filt_type`): true when the block's above OR left
16303 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
16304 // Callers pass their own plane's neighbour-mode check
16305 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
16306 // callers until a smooth/paeth `uv_mode` can reach this call at all
16307 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
16308 // keeps `false` exact for chroma without this fn needing to know why.
16309 smooth_neighbor: bool,
16310 // lane-wave1 step (i): the palette/intrabc prediction override, taken
16311 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
16312 // than by this replay.
16313 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
16314 ) {
16315 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
16316 // takes priority over `predict()`/`predict_filter_intra` entirely --
16317 // palette prediction needs no edge pixels at all.
16318 let prediction = if let Some(buf) = pred {
16319 buf
16320 } else {
16321 let (above, left, corner) = self.edges(x, y, side, reach);
16322 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
16323 eprintln!(
16324 "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}",
16325 above.as_deref(),
16326 left.as_deref(),
16327 );
16328 }
16329 let mut prediction = vec![0u16; side * side];
16330 if let Some(fi_mode) = filter_intra {
16331 crate::intra::predict_filter_intra(
16332 fi_mode,
16333 above.as_deref(),
16334 left.as_deref(),
16335 corner,
16336 side,
16337 side,
16338 &mut prediction, fctx,
16339 );
16340 } else {
16341 // `enable_intra_edge_filter` is the sequence header's own flag
16342 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
16343 // call, never per-block) -- threading it through every
16344 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
16345 // dozen sites for a value that never changes mid-decode, so it
16346 // rides a thread-local instead (this decoder is single-threaded
16347 // per stream).
16348 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
16349 predict(
16350 mode as u8,
16351 angle_delta,
16352 above.as_deref(),
16353 left.as_deref(),
16354 corner,
16355 side,
16356 side,
16357 enable_edge_filter,
16358 smooth_neighbor,
16359 &mut prediction, fctx,
16360 );
16361 }
16362 prediction
16363 };
16364 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
16365 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
16366 if crate::envflags::env_flag!("EC_PRED") {
16367 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
16368 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
16369 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
16370 eprintln!(
16371 "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor)
16372 );
16373 }
16374 let residual = dense_residual(residual, side * side);
16375 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
16376 let res0: Vec<i32> = residual[..side.min(8)].to_vec();
16377 let pred0: Vec<u16> = prediction[..side.min(8)].to_vec();
16378 eprintln!("DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}", cfl.is_some());
16379 }
16380 for row in 0..side {
16381 // lane-sb128c r8: libaom's frame buffer is superblock
16382 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
16383 // transform unit of a 128x64 block at the BOTTOM frame edge
16384 // can hang past the last padded row (1920x792: a unit at
16385 // y=768 wants 832 rows of an 800-row buffer, which panicked
16386 // the film's key frames). Those samples are outside the
16387 // frame: never output, and no block below ever references
16388 // them.
16389 if y + row >= self.height {
16390 break;
16391 }
16392 for col in 0..side {
16393 if x + col >= self.width {
16394 break;
16395 }
16396 let idx = row * side + col;
16397 let mut base = i32::from(prediction[idx]);
16398 if let Some((alpha_q3, ac_q3)) = cfl {
16399 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
16400 }
16401 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
16402 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
16403 }
16404 }
16405 }
16406}
16407
16408/// Reads one plane's transform block, reconstructs it into `plane` at
16409/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
16410#[allow(clippy::too_many_arguments)]
16411fn read_plane(
16412 dec: &mut SymbolDecoder,
16413 cdfs: &mut Cdfs,
16414 set: TxbSet,
16415 scan: &[u16],
16416 plane_idx: usize,
16417 around: (bool, bool, i32),
16418 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
16419 // it for every plane's `txb` lookup (it is what an intra transform type's
16420 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
16421 tx_mode: usize,
16422 predict_mode: usize,
16423 angle_delta: i32,
16424 reach: Reach,
16425 // lane-wave1 step (i): unread -- this reader records its write
16426 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
16427 // stays in the signature so every call site still proves the plane is
16428 // exclusively held while its coefficients are parsed.
16429 _plane: &mut PlaneBuf<'static>,
16430 x: usize,
16431 y: usize,
16432 side: usize,
16433 tx_side: usize,
16434 base_q_idx: u8,
16435 cfl: Option<(i32, CflSrc)>,
16436 filter_intra: Option<usize>,
16437 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
16438 // smaller than its own block (spec `get_txb_ctx_general`'s
16439 // `plane_bsize != tx_size` branch), carrying the already-looked-up
16440 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
16441 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
16442 // formula below.
16443 luma_skip_ctx: Option<usize>,
16444 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
16445 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
16446) -> Result<Grid> {
16447 // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's
16448 // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`)
16449 // never reaches a chroma plane -- no u/v coefficient symbol is coded and
16450 // no chroma write is recorded. Return the all-zero grid the caller's
16451 // neighbour bookkeeping reads, without consuming a bit.
16452 if plane_idx > 0 && mono(fctx) {
16453 return Ok(Grid::Zero(side * side));
16454 }
16455 let skip_ctx = if plane_idx == 0 {
16456 luma_skip_ctx.unwrap_or(0)
16457 } else {
16458 // libaom `get_txb_ctx`: a chroma unit's context is
16459 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
16460 // plane block is bigger than the transform. Our chroma tables hold the
16461 // offset-7 rows first, so the caller adds 3 for the bigger-block case
16462 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
16463 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
16464 };
16465 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
16466 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
16467 // not by the block's ordinary `mode` (which is always DC_PRED whenever
16468 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
16469 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
16470 // filter-intra in AV1).
16471 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
16472 let mut coding = cdfs.txb(set, tx_mode);
16473 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
16474 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
16475 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
16476 // plane of a lossless block (the residual then goes through the WHT, so
16477 // the type only picks the scan, which is the default one).
16478 if lossless(fctx) {
16479 coding.tx_type = None;
16480 }
16481 // Luma's `default_tx_type` is only a fallback for the sizes whose
16482 // `TxbSet` carries no symbol at all (32-point and up), which the spec
16483 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
16484 // *never* its own coded symbol (`coding.tx_type` is always `None` for
16485 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
16486 // the plane's own predicted mode (`default_intra_tx_type`) -- except
16487 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
16488 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
16489 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
16490 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
16491 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
16492 // narrows there — only `Chroma32` and up do).
16493 let default_tx_type = if plane_idx == 0 || side >= 32 {
16494 TxType::DctDct
16495 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
16496 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
16497 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
16498 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
16499 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
16500 // [`read_inter_plane`]'s own `side < 32` guard).
16501 inherited
16502 } else {
16503 default_intra_tx_type(predict_mode as u8)
16504 };
16505 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
16506 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
16507 let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
16508 let (grid, tx_type) = read_coeffs(
16509 dec,
16510 &mut coding,
16511 scan,
16512 skip_ctx,
16513 dc_sign_ctx(around.2),
16514 default_tx_type,
16515 None,
16516 )?;
16517 note_chroma_class1(plane_idx, tx_type);
16518 if plane_idx == 0 {
16519 fctx.luma_tx_type.with(|c| c.set(tx_type));
16520 }
16521 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
16522 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
16523 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
16524 // guard also assumes.
16525 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
16526 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
16527 // keyed by that true size, not the coded corner's -- so the corner
16528 // goes into the top-left of a `side`-sized grid, not the reverse.
16529 let levels = extend_corner(grid, tx_side, tx_side, side, side);
16530 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
16531 let tx = TxParams {
16532 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
16533 ac_delta, tx_type, qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type), stride: 0,
16534 lossless: lossless(fctx),
16535 };
16536 if crate::envflags::env_flag!("EC_AV1_TRACE") {
16537 let residual = tx.run(&levels);
16538 eprintln!(
16539 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}", &*levels,
16540 );
16541 }
16542 push_intra_tx(
16543 plane_idx,
16544 x,
16545 y,
16546 side,
16547 side,
16548 false,
16549 predict_mode,
16550 angle_delta,
16551 reach,
16552 tx,
16553 &levels,
16554 cfl,
16555 filter_intra,
16556 smooth_neighbor, fctx,
16557 );
16558 // `record`'s neighbour state only reads whether *the coded grid* (not the
16559 // residual) has nonzero entries, so the levels this function already
16560 // built are what it wants back -- both arms of the old `tx_side == side`
16561 // branch returned exactly that, one of them through a full `to_vec` copy
16562 // of the grid per intra transform unit (lane-coefbuf).
16563 Ok(levels)
16564}
16565
16566/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
16567/// three planes, reconstructing them into `y`/`u`/`v` and updating
16568/// `neighbours`.
16569#[allow(clippy::too_many_arguments)]
16570fn decode_block(
16571 dec: &mut SymbolDecoder,
16572 cdfs: &mut Cdfs,
16573 neighbours: &mut Neighbours,
16574 at: (usize, usize),
16575 side: usize,
16576 luma_set: TxbSet,
16577 chroma_set: TxbSet,
16578 luma_tx: usize,
16579 chroma_tx: usize,
16580 scans: (&[u16], &[u16]),
16581 cfl: bool,
16582 y: &mut PlaneBuf<'static>,
16583 u: &mut PlaneBuf<'static>,
16584 v: &mut PlaneBuf<'static>,
16585 base_q_idx: u8,
16586 enable_filter_intra: bool,
16587 allow_screen_content_tools: bool,
16588 allow_intrabc: bool,
16589 scan32: &[u16],
16590 scan16: &[u16],
16591 scan8: &[u16],
16592 scan4: &[u16],
16593 tx_select: bool,
16594 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
16595) -> Result<()> {
16596 let (r, c) = at;
16597 let (px, py) = (c * SUB, r * SUB);
16598 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
16599 let palette_uv_cache = neighbours.palette_uv_cache(at);
16600 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
16601 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
16602 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
16603 read_intra_mode(
16604 dec,
16605 cdfs,
16606 nb_above_mode,
16607 nb_left_mode,
16608 cfl,
16609 side,
16610 enable_filter_intra,
16611 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
16612 allow_screen_content_tools,
16613 allow_intrabc,
16614 Some((palette_ctx, &palette_cache)),
16615 &palette_uv_cache,
16616 r * (SUB / MI),
16617 c * (SUB / MI), fctx,
16618 )?;
16619 if at_tile_left && palette_y.is_some() {
16620 hit!(PALETTE_TILE_LEFT_HITS);
16621 }
16622 // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane
16623 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
16624 // tables/scans are replaced by the 4x4 ones and the block always takes the
16625 // multi-transform-unit path below. lane-av1mixloss: this rewrite used to
16626 // sit at the TOP of the function -- before `read_intra_mode`, which is
16627 // where the block's own `segment_id` is read -- so a mixed frame resolved
16628 // every block's geometry against the PREVIOUS block's segment (a lossless
16629 // neighbour forced 4x4 units on a lossy block; a lossy one handed the
16630 // lossless TxParams an 8x8 grid). libaom's order is the opposite one:
16631 // `decode_mbmi_block` (segment id included) runs before any tx-size rule.
16632 // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this
16633 // rewrite (which sat above `read_intra_mode`) rides along here -- same
16634 // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own
16635 // segment like the lossless arm above it.
16636 let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) {
16637 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4))
16638 } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
16639 let tx = if side >= 64 { 32 } else { side };
16640 let (set, scan): (TxbSet, &[u16]) = match tx {
16641 32 => (TxbSet::Chroma32, scan32),
16642 16 => (TxbSet::Chroma16, scan16),
16643 8 => (TxbSet::Chroma8, scan8),
16644 _ => (TxbSet::Chroma4, scan4),
16645 };
16646 (luma_set, set, luma_tx, tx, (scans.0, scan))
16647 } else {
16648 (luma_set, chroma_set, luma_tx, chroma_tx, scans)
16649 };
16650 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
16651 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
16652 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
16653 // actual chroma-from-luma correlation, same as this decoder always did.
16654 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
16655 DC_PRED
16656 } else {
16657 uv_mode
16658 };
16659 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
16660 if smooth_neighbor {
16661 hit!(SMOOTH_LUMA_HITS);
16662 }
16663 let smooth_neighbor_uv =
16664 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
16665 if crate::envflags::env_flag!("EC_AV1_TRACE") {
16666 eprintln!(
16667 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
16668 angle_delta_uv={angle_delta_uv}"
16669 );
16670 }
16671 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
16672 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
16673 // block, skipped or not. `logical_tx` is what the loop filter's edge
16674 // lookup and the next block's own `get_tx_size_context` want (the *nominal*
16675 // transform size -- 64 even for the 64x64 corner-scanned case, spec
16676 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
16677 // which only differs from it at that one corner case.
16678 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
16679 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
16680 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
16681 // intrabc block reads NO tx-size symbol at all -- it takes
16682 // `maxRectTxSize` -- while every ordinary skipped intra block does read
16683 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
16684 // the tile from that block on (class `equal-range-means-unread`).
16685 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
16686 // tree instead (`read_var_tx_size`), the same syntax the inter block path
16687 // has always read -- libaom's `parse_decode_block` dispatches on
16688 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
16689 // intrabc block as inter.
16690 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
16691 // libaom `parse_decode_block`'s var-tx tree condition carries
16692 // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc
16693 // block inside a LOSSLESS segment of a mixed frame reads NO
16694 // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line
16695 // hands back TX_4X4. Invisible while every lossless frame was also
16696 // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which
16697 // is why the mixed frame is the first stream to reach it.
16698 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx);
16699 let intrabc_leaves = if intrabc_vartx {
16700 let max_tx = side.min(64);
16701 // `max_block_wide`/`max_block_high`: the frame's own mi grid
16702 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
16703 // right/bottom edge reads no split symbol for the units outside it.
16704 let mi_cols = 2 * y.true_width.div_ceil(8);
16705 let mi_rows = 2 * y.true_height.div_ceil(8);
16706 let side_mi = side / MI;
16707 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
16708 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
16709 let mut leaves = Vec::new();
16710 for row in (0..side_mi).step_by(max_tx / MI) {
16711 for col in (0..side_mi).step_by(max_tx / MI) {
16712 read_var_tx_size(
16713 dec, cdfs, neighbours, (mi_r, mi_c), side,
16714 (max_w_mi, max_h_mi), (max_tx, max_tx), 0, row, col, &mut leaves,
16715 );
16716 }
16717 }
16718 hit!(INTRABC_VARTX_HITS);
16719 // lane-t900 r33 census: the t900 recipes resolved every tree UNIFORM.
16720 // lane-av1-ibcvtx: a tree that resolved to mixed leaf sizes is no
16721 // longer refused -- the luma reconstruct below walks the tree's own
16722 // leaf list per leaf (libaom `decode_token_recon_block`, whose token
16723 // loop reconstructs whatever `read_tx_size_vartx` resolved, per
16724 // transform unit), so mixed sizes reconstruct at their own stride.
16725 // The counter marks the shape so a gate can prove a witness actually
16726 // carries a mixed tree and not merely another uniform one.
16727 let uniform = leaves
16728 .first()
16729 .is_some_and(|f| leaves.iter().all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3));
16730 if !uniform {
16731 hit!(INTRABC_VARTX_MIXED_LEAVES_HITS);
16732 if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") {
16733 eprintln!(
16734 "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \
16735 dv={intrabc_dv:?} leaves={leaves:?}"
16736 );
16737 }
16738 }
16739 Some(leaves)
16740 } else {
16741 None
16742 };
16743 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves.as_ref().map(|l| l[0].2) {
16744 (tx, if tx == 64 { 32 } else { tx })
16745 } else if tx_select && !intrabc_skip_tx {
16746 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx);
16747 (resolved, if resolved == 64 { 32 } else { resolved })
16748 } else {
16749 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
16750 // TX_64X64, so a 128x128 block is always FOUR luma transform units
16751 // even with `tx_select` off -- the TU loop below, never the
16752 // single-unit path.
16753 (lossless_tx(side.min(64), fctx), luma_tx)
16754 };
16755 if tx_select && logical_tx < side && uv_mode != DC_PRED {
16756 hit!(SQ_CHROMA_TX_HITS);
16757 }
16758 let luma_set = if tx_select {
16759 txbset_for(logical_tx, reduced_tx_set)
16760 } else {
16761 luma_set
16762 };
16763 let luma_set = if intrabc_dv.is_some() {
16764 inter_txbset_for(logical_tx, reduced_tx_set)
16765 } else {
16766 luma_set
16767 };
16768 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
16769 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
16770 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
16771 let chroma_side = side >> ss_x(fctx);
16772 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
16773 // frame's own pre-loop-filter reconstruction (all loop filters are off
16774 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
16775 // block vector, with the BILINEAR kernel libaom forces for intrabc --
16776 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
16777 // odd, which is exactly what the bilinear taps then interpolate.
16778 flush_recon(fctx, y, u, v);
16779 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
16780 let mut yb = vec![0u16; side * side];
16781 mc::predict_with_filter(
16782 &y.data, y.width, y.true_width, y.true_height,
16783 mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0),
16784 side, side, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
16785 );
16786 let mut ub = vec![0u16; chroma_side * chroma_side];
16787 mc::predict_with_filter(
16788 &u.data, u.width, u.true_width, u.true_height,
16789 mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_x(fctx)),
16790 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
16791 );
16792 let mut vb = vec![0u16; chroma_side * chroma_side];
16793 mc::predict_with_filter(
16794 &v.data, v.width, v.true_width, v.true_height,
16795 mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_x(fctx)),
16796 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
16797 );
16798 (yb, ub, vb)
16799 });
16800 // A palette-Y block's own prediction is the reconstructed colour-index
16801 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
16802 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
16803 // parameter through this function's dozen `y.reconstruct`/`read_plane`
16804 // sites. A split luma transform (`tx_select && logical_tx != side`)
16805 // would need the map sliced per-TU -- untested against a real
16806 // `--enable-palette=1` stream this round, so refuse by name rather than
16807 // guess at the slicing (charter's own named-acceptable fallback).
16808 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
16809 py.map
16810 .iter()
16811 .map(|&idx| py.colors[idx as usize])
16812 .collect()
16813 });
16814 // lane-t900 r32: the intrabc luma prediction rides the very same
16815 // whole-block override slot, so the multi-TU loop below windows it per
16816 // transform unit exactly like a palette map -- setting it once up front
16817 // handed the whole `side`x`side` buffer to the FIRST unit and left every
16818 // later one predicting off block edges (the var-tx tree above is what
16819 // first makes `logical_tx < side` reachable for an intrabc block).
16820 let palette_y_buf = match &intrabc_bufs {
16821 Some((yb, _, _)) => Some(yb.clone()),
16822 None => palette_y_buf,
16823 };
16824 // With one luma transform unit the whole `side`x`side` map is the
16825 // prediction; with several (`logical_tx != side`) each unit takes its own
16826 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
16827 // below (lane-palette2 r7) -- setting the full-block buffer here would be
16828 // taken by the FIRST unit and indexed at the wrong stride.
16829 // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call
16830 // (the `else` arm below -- a palette/intrabc block never takes the per-unit
16831 // `split_tx_skip` walk), so its map must be armed here even when the
16832 // transform is split. Gating the arm on `logical_tx == side` alone left a
16833 // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC
16834 // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen
16835 // key frame; class override-slot-on-one-arm). Neither prediction is
16836 // edge-derived, so the whole-block buffer at the block's own stride is
16837 // exactly what that single call wants.
16838 // Counted on the SHAPE, not on the arm below, so a gate can tell a stream
16839 // that reaches this block apart from one that never does (class
16840 // gate-blind-to-feature).
16841 if palette_y_buf.is_some() && skip && logical_tx < side {
16842 hit!(SKIP_SPLIT_TX_OVERRIDE_HITS);
16843 }
16844 if let Some(buf) = &palette_y_buf
16845 && (logical_tx == side || skip)
16846 {
16847 set_palette_pred(buf.clone(), fctx);
16848 }
16849 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
16850 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
16851 // plane's own `reconstruct`/`read_plane` call below (never both planes at
16852 // once), since Y's own set-then-take already emptied the slot by the time
16853 // either of these run.
16854 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
16855 (
16856 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
16857 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
16858 )
16859 });
16860 // The chroma half of the intrabc prediction rides the same per-plane
16861 // override slot the UV-palette buffers do (set fresh before each plane's
16862 // own `reconstruct`/`read_plane` call below).
16863 let palette_uv_bufs = match &intrabc_bufs {
16864 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
16865 None => palette_uv_bufs,
16866 };
16867 if skip {
16868 // A skipped block codes no residual syntax at all (spec 5.11.34):
16869 // straight prediction, on every plane.
16870 //
16871 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
16872 // is skipped (only an INTER skip forces the largest transform), and
16873 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
16874 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
16875 // already written left/above of it inside this same block. Predicting
16876 // the whole `side`x`side` at once gives a different (uniformly off by
16877 // ~1) answer, which is exactly the residue this lane was chasing.
16878 // The palette/intrabc override path keeps the single-call shape (its
16879 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
16880 // untested for skip and unreachable in these streams).
16881 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
16882 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
16883 // per-unit prediction is keyed on the transform being smaller than
16884 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
16885 // narrower meaning (a READ split tx depth).
16886 let split_tx_skip =
16887 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
16888 if split_tx_skip {
16889 if tx_select {
16890 hit!(SKIP_SPLIT_TX_HITS);
16891 }
16892 let n_axis = side / logical_tx;
16893 for tu_row in 0..n_axis {
16894 for tu_col in 0..n_axis {
16895 let tu_px = px + tu_col * logical_tx;
16896 let tu_py = py + tu_row * logical_tx;
16897 if tu_px >= y.true_width || tu_py >= y.true_height {
16898 continue;
16899 }
16900 let tu_reach = tu_reach(
16901 side,
16902 side,
16903 tu_col * logical_tx,
16904 tu_row * logical_tx,
16905 logical_tx,
16906 reach,
16907 px,
16908 py,
16909 y.width,
16910 y.height, fctx,
16911 );
16912 push_intra(0,
16913 tu_px,
16914 tu_py,
16915 logical_tx,
16916 mode,
16917 angle_delta_y,
16918 tu_reach,
16919 &ZERO_RESIDUAL[..logical_tx * logical_tx],
16920 None,
16921 filter_intra,
16922 smooth_neighbor, fctx,
16923 );
16924 }
16925 }
16926 } else {
16927 push_intra(0,
16928 px,
16929 py,
16930 side,
16931 mode,
16932 angle_delta_y,
16933 reach,
16934 &ZERO_RESIDUAL[..side * side],
16935 None,
16936 filter_intra,
16937 smooth_neighbor, fctx,
16938 );
16939 }
16940 let ac = alpha.map(|_| cfl_src(px, py, side));
16941 let cn = (chroma_side / chroma_tx).max(1);
16942 for cu_row in 0..cn {
16943 for cu_col in 0..cn {
16944 let luma_span = chroma_tx << ss_x(fctx);
16945 let cu_r = if cn == 1 {
16946 reach
16947 } else {
16948 tu_reach(
16949 side, side,
16950 cu_col * luma_span, cu_row * luma_span, luma_span,
16951 reach, px, py, y.width, y.height, fctx,
16952 )
16953 };
16954 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
16955 if let Some((ub, _)) = &palette_uv_bufs {
16956 set_palette_pred(ub.clone(), fctx);
16957 }
16958 push_intra(1,
16959 cu_x,
16960 cu_y,
16961 chroma_tx,
16962 uv_predict_mode,
16963 angle_delta_uv,
16964 cu_r,
16965 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
16966 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16967 None,
16968 smooth_neighbor_uv, fctx,
16969 );
16970 if let Some((_, vb)) = &palette_uv_bufs {
16971 set_palette_pred(vb.clone(), fctx);
16972 }
16973 push_intra(2,
16974 cu_x,
16975 cu_y,
16976 chroma_tx,
16977 uv_predict_mode,
16978 angle_delta_uv,
16979 cu_r,
16980 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
16981 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16982 None,
16983 smooth_neighbor_uv, fctx,
16984 );
16985 }
16986 }
16987 let luma_grid = vec![0i32; side * side];
16988 let u_grid = vec![0i32; chroma_side * chroma_side];
16989 let v_grid = vec![0i32; chroma_side * chroma_side];
16990 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
16991 } else if logical_tx == side {
16992 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
16993 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
16994 // that arm was redundant -- and wrong at 128, where
16995 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
16996 // block is four units whether or not `tx_select` is on.
16997 // A single luma transform unit -- the old path, unchanged (including
16998 // the 64x64 corner case, `logical_tx == side == 64` with
16999 // `coeff_tx_side == 32`).
17000 let around = neighbours.around(at, side);
17001 let luma_grid = read_plane(
17002 dec,
17003 cdfs,
17004 luma_set,
17005 luma_scan,
17006 0,
17007 around[0],
17008 mode,
17009 mode,
17010 angle_delta_y,
17011 reach,
17012 y,
17013 px,
17014 py,
17015 side,
17016 coeff_tx_side,
17017 base_q_idx,
17018 None,
17019 filter_intra,
17020 None,
17021 smooth_neighbor, fctx,
17022 )?;
17023 let ac = alpha.map(|_| cfl_src(px, py, side));
17024 // Armed for exactly this block's two chroma reads (see
17025 // [`INTRABC_CHROMA_TX`]); the luma call above just set
17026 // [`LUMA_TX_TYPE`] to the type it coded.
17027 if intrabc_dv.is_some() {
17028 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
17029 }
17030 // lane-av1-444: this arm is one luma TU (`logical_tx == side`), including
17031 // the 64x64 case whose coefficient grid is 32. At 4:4:4 the chroma plane
17032 // is the same size as luma and `av1_get_max_uv_txsize` caps it at
17033 // TX_32X32, so a 64x64 block codes four chroma units, plane-major
17034 // (every U, then every V) — the same loop the multi-TU arm runs.
17035 // At 4:2:0 `chroma_side == chroma_tx`, so it stays one read.
17036 let cn = (chroma_side / chroma_tx).max(1);
17037 let (u_grid, v_grid, chroma_units) = if cn == 1 {
17038 if let Some((ub, _)) = &palette_uv_bufs {
17039 set_palette_pred(ub.clone(), fctx);
17040 }
17041 let u_grid = read_plane(
17042 dec,
17043 cdfs,
17044 chroma_set,
17045 scans.1,
17046 1,
17047 around[1],
17048 mode,
17049 uv_predict_mode,
17050 angle_delta_uv,
17051 reach,
17052 u,
17053 cpx,
17054 cpy,
17055 chroma_side,
17056 chroma_tx,
17057 base_q_idx,
17058 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
17059 None,
17060 None,
17061 smooth_neighbor_uv, fctx,
17062 )?;
17063 if crate::envflags::env_flag!("EC_AV1_TRACE") {
17064 eprintln!(
17065 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
17066 &u.data[cpy * u.width + cpx..][..chroma_side]
17067 );
17068 }
17069 if let Some((_, vb)) = &palette_uv_bufs {
17070 set_palette_pred(vb.clone(), fctx);
17071 }
17072 let v_grid = read_plane(
17073 dec,
17074 cdfs,
17075 chroma_set,
17076 scans.1,
17077 2,
17078 around[2],
17079 mode,
17080 uv_predict_mode,
17081 angle_delta_uv,
17082 reach,
17083 v,
17084 cpx,
17085 cpy,
17086 chroma_side,
17087 chroma_tx,
17088 base_q_idx,
17089 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
17090 None,
17091 None,
17092 smooth_neighbor_uv, fctx,
17093 )?;
17094 (u_grid, v_grid, Vec::new())
17095 } else {
17096 let chroma_ctx_offset = Some(3);
17097 let mut u_pass: Vec<Grid> = Vec::new();
17098 let mut units: Vec<((usize, usize), usize, Grid, Grid)> = Vec::new();
17099 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
17100 for plane_pass in 1..=2usize {
17101 let mut pass_idx = 0usize;
17102 for cu_row in 0..cn {
17103 for cu_col in 0..cn {
17104 let luma_span = chroma_tx << ss_x(fctx);
17105 let cu_mi = (
17106 mi_r + cu_row * (luma_span / MI),
17107 mi_c + cu_col * (luma_span / MI),
17108 );
17109 let cu_around = neighbours.around_mi(cu_mi, luma_span);
17110 let cu_reach = tu_reach(
17111 side,
17112 side,
17113 cu_col * luma_span,
17114 cu_row * luma_span,
17115 luma_span,
17116 reach,
17117 px,
17118 py,
17119 y.width,
17120 y.height, fctx,
17121 );
17122 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
17123 if let Some((ub, vb)) = &palette_uv_bufs {
17124 let pbuf = if plane_pass == 1 { ub } else { vb };
17125 set_palette_pred(
17126 palette_window(
17127 pbuf, chroma_side, cu_col * chroma_tx, cu_row * chroma_tx,
17128 chroma_tx, chroma_tx,
17129 ),
17130 fctx,
17131 );
17132 }
17133 let buf: &mut PlaneBuf<'static> =
17134 if plane_pass == 1 { &mut *u } else { &mut *v };
17135 let cu_grid = read_plane(
17136 dec, cdfs, chroma_set, scans.1, plane_pass, cu_around[plane_pass], mode,
17137 uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y,
17138 chroma_tx, chroma_tx, base_q_idx,
17139 alpha.zip(ac).map(|((au, av), ac)| {
17140 (if plane_pass == 1 { au } else { av }, ac)
17141 }),
17142 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
17143 )?;
17144 hit!(CHROMA_SPLIT_TX_HITS);
17145 // Immediately, so the next unit of this block reads this
17146 // one's coefficient context. `record` below stamps one
17147 // chroma state across the whole block; the replay after
17148 // it puts the per-unit state back.
17149 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &cu_grid);
17150 if plane_pass == 1 {
17151 u_pass.push(cu_grid);
17152 } else {
17153 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
17154 units.push((cu_mi, luma_span, u_grid.clone(), cu_grid.clone()));
17155 last_grids = [u_grid, cu_grid];
17156 }
17157 pass_idx += 1;
17158 }
17159 }
17160 }
17161 (last_grids[0].clone(), last_grids[1].clone(), units)
17162 };
17163 fctx.intrabc_chroma_tx.with(|c| c.set(None));
17164 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
17165 for (cu_mi, luma_span, u_unit, v_unit) in &chroma_units {
17166 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_unit);
17167 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_unit);
17168 }
17169 } else {
17170 // Several luma transform units, raster order (spec
17171 // `transform_block`'s loop): the block's resolved transform is
17172 // genuinely smaller than its own side, so each tile of it predicts
17173 // and codes independently, its own context read fresh off whatever
17174 // the earlier tiles in this same block already wrote -- the same
17175 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
17176 let n_axis = side / logical_tx;
17177 let cn = (chroma_side / chroma_tx).max(1);
17178 // libaom's transform-block loop is over 64x64 luma "mu" chunks
17179 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
17180 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
17181 // before moving to the next one. Below 128 a block is a single chunk,
17182 // so this is byte-for-byte the all-luma-then-all-chroma order that has
17183 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
17184 // and reading all four luma units first desyncs the tile at the second
17185 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
17186 let nchunk = (side / 64).max(1);
17187 // `cn > 1` means the uv plane block is larger than the uv transform,
17188 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
17189 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
17190 let tpc = (n_axis / nchunk).max(1);
17191 let cpc = (cn / nchunk).max(1);
17192 // The block's luma transform units, raster order inside each mu
17193 // chunk. lane-av1-ibcvtx: an intrabc block's units are the var-tx
17194 // tree's own leaf list -- mixed sizes included, exactly what libaom's
17195 // `decode_token_recon_block` token loop reconstructs (one
17196 // `av1_read_coeffs_txb` + inverse transform per resolved unit) --
17197 // while every other block's list is the uniform `logical_tx` grid
17198 // this loop has always walked, generated here in the same order.
17199 let mut chunk_tus: Vec<Vec<(usize, usize, usize)>> = vec![Vec::new(); nchunk * nchunk];
17200 if let Some(leaves) = &intrabc_leaves {
17201 for &(lr, lc, tw, _th) in leaves {
17202 let (off_y, off_x) = (lr * MI, lc * MI);
17203 chunk_tus[(off_y / 64) * nchunk + (off_x / 64)].push((off_y, off_x, tw));
17204 }
17205 } else {
17206 for tu_row in 0..n_axis {
17207 for tu_col in 0..n_axis {
17208 chunk_tus[(tu_row / tpc) * nchunk + (tu_col / tpc)].push((
17209 tu_row * logical_tx,
17210 tu_col * logical_tx,
17211 logical_tx,
17212 ));
17213 }
17214 }
17215 }
17216 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
17217 let mut units: Vec<((usize, usize), usize, Grid, Grid)> = Vec::new();
17218 for ch_row in 0..nchunk {
17219 for ch_col in 0..nchunk {
17220 // lane-av1-ibcvtx: the chunk's chroma units inherit the CHROMA tx
17221 // type of the co-located luma position (`av1_get_tx_type`,
17222 // blockd.h:1278: a non-Y plane of an inter-classified block -- and
17223 // intrabc is one -- reads `tx_type_map`, i.e. the coded type of the
17224 // luma unit covering it). Inside a mu chunk that is the chunk's
17225 // FIRST luma unit in raster order (the chunk origin is always the
17226 // first leaf's own origin). Captured right after that unit's read;
17227 // the single-TU arm below does the same for a whole-block unit.
17228 let mut first_leaf_tx: Option<TxType> = None;
17229 for &(tu_off_y, tu_off_x, tu_tx) in &chunk_tus[ch_row * nchunk + ch_col] {
17230 let tu_mi = (mi_r + tu_off_y / MI, mi_c + tu_off_x / MI);
17231 let tu_px = px + tu_off_x;
17232 let tu_py = py + tu_off_y;
17233 // Same libaom clip as `decode_rect_split`'s loop above; a
17234 // square block only hangs off the frame when the frame's mi
17235 // dimensions are odd at the block's own level.
17236 if tu_px >= y.true_width || tu_py >= y.true_height {
17237 continue;
17238 }
17239 let tu_around = neighbours.around_mi(tu_mi, tu_tx)[0];
17240 // A transform unit inside a block is NOT a block at that
17241 // position (lane-palette2 r12): `Reach::of` granted the
17242 // top-right 8x8 unit of a 16x16 D203 block bottom-left
17243 // pixels libaom refuses outright (`col_off > 0`), which is
17244 // the diagonal wedge seed 46 reconstructed wrong.
17245 let tu_reach = tu_reach(
17246 side,
17247 side,
17248 tu_off_x,
17249 tu_off_y,
17250 tu_tx,
17251 reach,
17252 px,
17253 py,
17254 y.width,
17255 y.height, fctx,
17256 );
17257 // This transform unit's own bsize (`tu_tx`) is smaller
17258 // than the block it sits in (`side`), so `txb_skip_ctx` is
17259 // the neighbour-magnitude table, not the lone-TU 0 (spec
17260 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
17261 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tu_tx / MI);
17262 // An intrabc unit's CDF set and scan follow the unit's OWN
17263 // resolved size (`get_txsize_entropy_ctx` /
17264 // `av1_get_scan` per `av1_read_coeffs_txb` call); the
17265 // uniform grid's precomputed pair already matches because
17266 // `tu_tx == logical_tx` there.
17267 let (tu_set, tu_scan) = if intrabc_dv.is_some() {
17268 (
17269 inter_txbset_for(tu_tx, reduced_tx_set),
17270 scan_for(if tu_tx == 64 { 32 } else { tu_tx }, scan32, scan16, scan8, scan4),
17271 )
17272 } else {
17273 (luma_set, luma_scan)
17274 };
17275 if let Some(buf) = &palette_y_buf {
17276 hit!(PALETTE_SPLIT_TX_HITS);
17277 let mut window = vec![0u16; tu_tx * tu_tx];
17278 for row in 0..tu_tx {
17279 let src = (tu_off_y + row) * side + tu_off_x;
17280 window[row * tu_tx..][..tu_tx]
17281 .copy_from_slice(&buf[src..][..tu_tx]);
17282 }
17283 set_palette_pred(window, fctx);
17284 }
17285 let tu_grid = read_plane(
17286 dec,
17287 cdfs,
17288 tu_set,
17289 tu_scan,
17290 0,
17291 tu_around,
17292 mode,
17293 mode,
17294 angle_delta_y,
17295 tu_reach,
17296 y,
17297 tu_px,
17298 tu_py,
17299 tu_tx,
17300 // The unit's own COEFFICIENT grid, half its side at
17301 // TX_64X64 (a 64-point transform codes nothing past 32);
17302 // identical to `tu_tx` at every smaller size
17303 // (lane-sb128b r1).
17304 if tu_tx == 64 { 32 } else { tu_tx },
17305 base_q_idx,
17306 None,
17307 filter_intra,
17308 Some(tu_skip_ctx),
17309 smooth_neighbor, fctx,
17310 )?;
17311 if crate::envflags::env_flag!("EC_AV1_TRACE") {
17312 eprintln!(
17313 "TRACE tu_bitpos mi=({},{}) tell={}",
17314 tu_mi.0,
17315 tu_mi.1,
17316 dec.debug_bitpos()
17317 );
17318 }
17319 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);
17320 if first_leaf_tx.is_none() {
17321 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
17322 }
17323 }
17324 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
17325 // this still runs after every luma unit of the block.
17326 let ac = alpha.map(|_| cfl_src(px, py, side));
17327 // lane-av1-ibcvtx: an intrabc block's chroma rides the luma's coded
17328 // tx type (see `first_leaf_tx` above) -- the same arm the single-TU
17329 // branch sets before its own chroma reads.
17330 if intrabc_dv.is_some() {
17331 if let Some(t) = first_leaf_tx {
17332 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
17333 }
17334 }
17335 // The block's uv plane block is `chroma_side` across but its uv
17336 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
17337 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
17338 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
17339 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
17340 // FOUR units (lane-sb128b r2) -- one per mu chunk.
17341 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
17342 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
17343 // the chunk, then every V unit. At one unit per plane per chunk --
17344 // every non-lossless case this decoder reaches -- that is the same
17345 // symbol order as the interleaved pair this loop used to read; a
17346 // lossless frame's 4x4 chroma units are the case where it differs
17347 // (lane-lossless2).
17348 let mut u_pass: Vec<Grid> = Vec::new();
17349 for plane_pass in 1..=2usize {
17350 let mut pass_idx = 0usize;
17351 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
17352 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
17353 // libaom `decode_reconstruct_tx`'s frame-edge clip
17354 // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col
17355 // >= max_blocks_wide` returns before ANY symbol is read): a
17356 // transform unit whose 4x4 origin sits outside the frame's mi
17357 // grid is not coded at all. The luma loop above carries the
17358 // same clip; its absence here read `txb_skip` (+coeffs) for
17359 // chroma units libaom never wrote -- the lossless 64x64 block
17360 // at mi(48,0) of a 320x240 frame overhangs the bottom edge by
17361 // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not
17362 // eight (lane-av1-loss64; 48 chroma units per plane in
17363 // aomdec's EC_COEFF census vs the 64 this loop read).
17364 // `max_block_wide/high` (av1_common_int.h:1565): the plane
17365 // block's pixel span (4:2:0 halves the luma span, clamped to
17366 // 4 by `set_plane_n4`) plus the negative overhang
17367 // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4
17368 // units.
17369 let span_mi = side / MI;
17370 let over_w_mi =
17371 (2 * y.true_width.div_ceil(8)) as i32 - mi_c as i32 - span_mi as i32;
17372 let over_h_mi =
17373 (2 * y.true_height.div_ceil(8)) as i32 - mi_r as i32 - span_mi as i32;
17374 // `max_block_wide/high` in chroma pixels: the plane block's
17375 // own span (`side` at 4:4:4, `side / 2` at 4:2:0 -- the old
17376 // hardcoded `span_mi * 2` clipped three quarters of a 4:4:4
17377 // block's coded units and desynced the tile) plus the
17378 // negative overhang (`mb_to_*_edge >> (3 + ss)`), whose
17379 // chroma-px scale is `MI >> ss` per mi.
17380 let plane_px = (((span_mi * MI) >> ss_x(fctx)).max(4)) as i32;
17381 let over_w_px = over_w_mi.min(0) * (MI >> ss_x(fctx)) as i32;
17382 let over_h_px = over_h_mi.min(0) * (MI >> ss_y(fctx)) as i32;
17383 let max_units_w = ((plane_px + over_w_px) >> 2).max(0) as usize;
17384 let max_units_h = ((plane_px + over_h_px) >> 2).max(0) as usize;
17385 let unit = chroma_tx / 4; // TU side in 4x4 chroma units
17386 if cu_col * unit >= max_units_w || cu_row * unit >= max_units_h {
17387 hit!(CHROMA_EDGE_TU_CLIP_HITS);
17388 continue;
17389 }
17390 // The chroma context arrays are indexed in LUMA mi, so this
17391 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
17392 // pixels span `2 * chroma_tx` luma ones.
17393 let luma_span = chroma_tx << ss_x(fctx);
17394 let cu_mi = (
17395 mi_r + cu_row * (luma_span / MI),
17396 mi_c + cu_col * (luma_span / MI),
17397 );
17398 let cu_around = neighbours.around_mi(cu_mi, luma_span);
17399 let cu_reach = if cn == 1 {
17400 reach
17401 } else {
17402 tu_reach(
17403 side, side,
17404 cu_col * luma_span, cu_row * luma_span, luma_span,
17405 reach, px, py, y.width, y.height, fctx,
17406 )
17407 };
17408 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
17409 if let Some((ub, vb)) = &palette_uv_bufs {
17410 let pbuf = if plane_pass == 1 { ub } else { vb };
17411 set_palette_pred(
17412 palette_window(
17413 pbuf, chroma_side, cu_col * chroma_tx, cu_row * chroma_tx,
17414 chroma_tx, chroma_tx,
17415 ),
17416 fctx,
17417 );
17418 }
17419 let buf: &mut PlaneBuf<'static> =
17420 if plane_pass == 1 { &mut *u } else { &mut *v };
17421 let cu_grid = read_plane(
17422 dec, cdfs, chroma_set, scans.1, plane_pass, cu_around[plane_pass], mode,
17423 uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y,
17424 chroma_tx, chroma_tx, base_q_idx,
17425 alpha.zip(ac).map(|((au, av), ac)| {
17426 (if plane_pass == 1 { au } else { av }, ac)
17427 }),
17428 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
17429 )?;
17430 if cn > 1 {
17431 hit!(CHROMA_SPLIT_TX_HITS);
17432 // Immediately, so the NEXT unit of this same block reads
17433 // this one's coefficient context (libaom's chroma
17434 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
17435 // 1 from this left neighbour -- measured against aomdec).
17436 // The same writes are replayed after `record_split_luma`
17437 // below, which would otherwise clobber them whole-block.
17438 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &cu_grid);
17439 }
17440 if plane_pass == 1 {
17441 u_pass.push(cu_grid);
17442 } else {
17443 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
17444 if cn > 1 {
17445 units.push((cu_mi, luma_span, u_grid.clone(), cu_grid.clone()));
17446 }
17447 last_grids = [u_grid, cu_grid];
17448 }
17449 pass_idx += 1;
17450 }
17451 }
17452 }
17453 }
17454 if intrabc_dv.is_some() {
17455 fctx.intrabc_chroma_tx.with(|c| c.set(None));
17456 }
17457 }
17458 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
17459 // context write; at `cn > 1` the per-unit writes above are what the
17460 // next block reads, so they run after this (last writer wins).
17461 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
17462 for (cu_mi, luma_span, u_grid, v_grid) in &units {
17463 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
17464 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
17465 }
17466 }
17467 // Unconditional, `size == 0` for a non-palette block: clears any stale
17468 // neighbour palette state the same way [`Neighbours::record`] always
17469 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
17470 // (the split-luma-TU branch above always refuses before reaching here
17471 // when `palette_y` is `Some`, so it is never live for that branch).
17472 let (py_size, py_colors) = palette_y
17473 .as_ref()
17474 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
17475 neighbours.record_palette_y(at, side, py_size, py_colors);
17476 let (puv_size, puv_colors) = palette_uv
17477 .as_ref()
17478 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
17479 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
17480 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
17481 neighbours.fill_lf_grid(
17482 (r * (SUB / MI), c * (SUB / MI)),
17483 side / MI,
17484 logical_tx as u8,
17485 0, fctx,
17486 );
17487 // lane-t900 r32 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size,
17488 // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY
17489 // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM
17490 // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express
17491 // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED
17492 // intrabc block publish its BLOCK size instead, intrabc being the only
17493 // "inter" block an intra-only frame codes (`blockd.h:373`). So this call
17494 // stays the authority wherever one can appear; with `allow_intrabc` unset
17495 // it writes exactly what the grid already did.
17496 if allow_intrabc {
17497 set_txfm_ctxs(
17498 neighbours,
17499 (mi_r, mi_c),
17500 logical_tx,
17501 side / MI,
17502 side / MI,
17503 skip && intrabc_dv.is_some(),
17504 );
17505 }
17506 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, neighbours, fctx);
17507 Ok(())
17508}
17509
17510thread_local! {
17511 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
17512 /// root's HORZ arm, and 64x128 ones at its VERT arm.
17513 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
17514 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
17515 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
17516 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
17517 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
17518 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
17519 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
17520 /// inter frame) -- (128x64, 64x128).
17521 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
17522 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
17523 /// handed back var-tx leaves, so the per-transform-unit luma publication
17524 /// loop never ran and the block has to clear its own luma coefficient
17525 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
17526 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
17527 /// non-vacuous.
17528 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
17529 /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded
17530 /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the
17531 /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this
17532 /// shape non-vacuous -- a stream that never codes one reads 0.
17533 pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
17534}
17535
17536/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
17537pub fn skip_vartx_luma_reset_hits() -> usize {
17538 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
17539}
17540
17541/// [`INTRA128_LOSSLESS_HITS`], for a gate's own before/after delta.
17542pub(crate) fn intra128_lossless_hits() -> usize {
17543 INTRA128_LOSSLESS_HITS.with(std::cell::Cell::get)
17544}
17545
17546/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
17547pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
17548 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
17549}
17550
17551/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
17552/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
17553pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
17554 (
17555 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
17556 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
17557 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
17558 )
17559}
17560
17561/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
17562/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
17563/// `decode_inter_block`'s own rect path).
17564///
17565/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
17566/// transform unit, with the 128-specific geometry:
17567/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
17568/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
17569/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
17570/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
17571/// same CDF a 64x64 square block reads).
17572/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
17573/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
17574/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
17575/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
17576/// a chunk before moving to the next (the interleave lane-sb128b r3
17577/// measured at the 128x128 NONE root).
17578/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
17579/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
17580/// No CfL, no filter intra (both cap at 32x32) and no palette
17581/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
17582/// reader's own size gates already say so, and the guard below is defensive.
17583///
17584/// lane-lossless128: on a LOSSLESS frame every one of those sizes collapses to
17585/// TX_4X4 -- `read_tx_mode` returns `ONLY_4X4` before the frame codes a tx-size
17586/// symbol and `read_tx_size` returns `TX_4X4` before it looks at anything
17587/// (`decodeframe.c:141`, `:1183`) -- so the block is tiled into 4x4 luma units
17588/// and (because a lossless frame forces `TX_4X4` on CHROMA too) 4x4 chroma
17589/// units, plane-major inside each 64x64 mu chunk exactly as
17590/// `decode_token_recon_block` codes them. Reading the 64-point geometry there
17591/// reconstructs into a `side`-sized plane with a 16-sample residual (the panic
17592/// this lane closed); the geometry and the unit walks below are normalized on
17593/// `lossless_frame`.
17594#[allow(clippy::too_many_arguments)]
17595fn decode_block_128rect(
17596 dec: &mut SymbolDecoder,
17597 cdfs: &mut Cdfs,
17598 neighbours: &mut Neighbours,
17599 at: (usize, usize),
17600 bw: usize,
17601 bh: usize,
17602 y: &mut PlaneBuf<'static>,
17603 u: &mut PlaneBuf<'static>,
17604 v: &mut PlaneBuf<'static>,
17605 base_q_idx: u8,
17606 enable_filter_intra: bool,
17607 allow_screen_content_tools: bool,
17608 tx_select: bool,
17609 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
17610) -> Result<()> {
17611 let (r, c) = at;
17612 let (px, py) = (c * SUB, r * SUB);
17613 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
17614 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
17615 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
17616 let palette_uv_cache = neighbours.palette_uv_cache(at);
17617 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) =
17618 read_intra_mode_rect(
17619 dec,
17620 cdfs,
17621 nb_above_mode,
17622 nb_left_mode,
17623 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
17624 // 13-symbol no-CFL CDF here, never the 14-symbol one.
17625 false,
17626 true,
17627 bw,
17628 bh,
17629 enable_filter_intra,
17630 neighbours.skip_txfm_ctx(mi_r, mi_c),
17631 allow_screen_content_tools,
17632 Some((palette_ctx, &palette_cache)),
17633 &palette_uv_cache,
17634 mi_r,
17635 mi_c, fctx,
17636 )?;
17637 if let Some((dv_row, dv_col)) = intrabc {
17638 // lane-av1-ibcrect: the reconstruction is ported -- an intrabc block
17639 // is is_inter_block, so libaom predicts the whole 128x64/64x128 strip
17640 // from this frame's own reconstruction and runs the INTER residual
17641 // walk (`decode_token_recon_block`'s else arm) over it.
17642 return decode_intrabc_128rect(
17643 dec,
17644 cdfs,
17645 neighbours,
17646 (mi_r, mi_c),
17647 (bw, bh),
17648 skip,
17649 (dv_row, dv_col),
17650 y,
17651 u,
17652 v,
17653 base_q_idx, fctx,
17654 );
17655 }
17656 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
17657 return Err(unsupported(
17658 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
17659 their size gates caps at 64x64 or below, so none of these symbols exists there)",
17660 ));
17661 }
17662 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
17663 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
17664 if smooth_neighbor {
17665 hit!(SMOOTH_LUMA_HITS);
17666 }
17667 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
17668 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
17669 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
17670 // lane-lossless128: a LOSSLESS frame codes no tx-size symbol at all --
17671 // libaom's `read_tx_mode` returns `ONLY_4X4` for a `coded_lossless` frame
17672 // before the symbol is even considered (`decodeframe.c:141`) and
17673 // `read_tx_size` returns `TX_4X4` before it looks at anything
17674 // (`decodeframe.c:1183`). So `tx_select` is off, every plane is walked as
17675 // TX_4X4 transform units, and no `tx_size_cat3` symbol may be consumed.
17676 let lossless_frame = lossless(fctx);
17677 let in_inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some();
17678 let depth = if tx_select && !lossless_frame {
17679 // lane-inter128intra r1: `get_tx_size_context` compares the bands
17680 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --
17681 // TX_64X64 for every 128-axis block, hence the `min(64)`.
17682 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
17683 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
17684 } else {
17685 0
17686 };
17687 if depth != 0 {
17688 hit!(TX_DEPTH_HITS);
17689 }
17690 hit_do! {
17691 INTRA_SB128_DEPTH_HITS.with(|c| {
17692 let mut h = c.get();
17693 h[depth.min(2)] += 1;
17694 c.set(h);
17695 });
17696 }
17697 let logical_tx = if lossless_frame { 4 } else { 64 >> depth };
17698 if lossless_frame {
17699 hit!(INTRA128_LOSSLESS_HITS);
17700 }
17701 // A 64-point transform codes nothing past its low 32 coefficients.
17702 let coeff_tx_side = logical_tx.min(32);
17703 let luma_set = if lossless_frame {
17704 TxbSet::Luma4
17705 } else {
17706 txbset_for(logical_tx, reduced_tx_set)
17707 };
17708 let luma_scan = default_scan(coeff_tx_side);
17709 // `av1_get_max_uv_txsize` caps at TX_32X32 normally; a lossless frame
17710 // forces every plane to TX_4X4 (its own `Chroma4` set and 4x4 scan).
17711 let chroma_tx = if lossless_frame { 4 } else { 32 };
17712 let chroma_set = if lossless_frame {
17713 TxbSet::Chroma4
17714 } else {
17715 TxbSet::Chroma32
17716 };
17717 let chroma_scan = default_scan(chroma_tx);
17718 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
17719 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
17720 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
17721 let (nch_x, nch_y) = (bw / 64, bh / 64);
17722 // The frame's own mi grid (`av1_calc_mi_size`, 8-px aligned): libaom's
17723 // `decode_token_recon_block` clips each vector's walk to
17724 // `max_block_wide/high`, so a chroma unit whose top-left is off the frame
17725 // codes nothing.
17726 let mi_cols = 2 * y.true_width.div_ceil(8);
17727 let mi_rows = 2 * y.true_height.div_ceil(8);
17728 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
17729 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
17730 // Non-lossless: per mu chunk, `(64 >> ss) / chroma_tx` chroma units per
17731 // axis (one 32x32 at 4:2:0, four 32x32 at 4:4:4 — lane-av1-444sb).
17732 debug_assert!(
17733 lossless_frame
17734 || (chroma_w / chroma_tx, chroma_h / chroma_tx)
17735 == (
17736 nch_x * ((64 >> ss_x(fctx)) / chroma_tx),
17737 nch_y * ((64 >> ss_y(fctx)) / chroma_tx)
17738 )
17739 );
17740 let tpc = 64 / logical_tx;
17741 let zero_tu = vec![0i32; logical_tx * logical_tx];
17742 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
17743 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
17744 let mut units: Vec<(usize, (usize, usize), Grid)> = Vec::new();
17745 // The chroma context arrays are indexed in LUMA mi; every chroma unit of
17746 // every chunk shares this luma span (2 chroma pixels per luma unit).
17747 let luma_span = chroma_tx << ss_x(fctx);
17748 for ch_row in 0..nch_y {
17749 for ch_col in 0..nch_x {
17750 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
17751 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
17752 let tu_mi = (
17753 mi_r + tu_row * (logical_tx / MI),
17754 mi_c + tu_col * (logical_tx / MI),
17755 );
17756 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
17757 // libaom clips the transform loop to
17758 // `max_blocks_wide/high`: a unit whose top-left sample is
17759 // outside the frame is never coded.
17760 if tu_px >= y.true_width || tu_py >= y.true_height {
17761 continue;
17762 }
17763 // Edge availability of a unit INSIDE a block, with the
17764 // 128 geometry -- `has_top_right` is false for a block
17765 // whose largest side is > 64, which [`Reach::of_rect`]
17766 // already answered for the block and [`tu_reach`] carries
17767 // down to the units on its own top row.
17768 let tu_r = tu_reach(
17769 bw,
17770 bh,
17771 tu_col * logical_tx,
17772 tu_row * logical_tx,
17773 logical_tx,
17774 reach,
17775 px,
17776 py,
17777 y.width,
17778 y.height, fctx,
17779 );
17780 if skip {
17781 push_intra(0,
17782 tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None,
17783 None, smooth_neighbor, fctx,
17784 );
17785 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
17786 continue;
17787 }
17788 // The unit is smaller than its block, so `txb_skip_ctx`
17789 // is the neighbour-magnitude table, never the lone-TU 0.
17790 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
17791 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
17792 let tu_grid = read_plane(
17793 dec,
17794 cdfs,
17795 luma_set,
17796 &luma_scan,
17797 0,
17798 tu_around,
17799 mode,
17800 mode,
17801 angle_delta_y,
17802 tu_r,
17803 y,
17804 tu_px,
17805 tu_py,
17806 logical_tx,
17807 coeff_tx_side,
17808 base_q_idx,
17809 None,
17810 None,
17811 Some(tu_skip_ctx),
17812 smooth_neighbor, fctx,
17813 )?;
17814 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
17815 }
17816 }
17817 // Transform units per axis inside this mu chunk's chroma span:
17818 // a 64x64 luma chunk covers `64 >> ss` chroma pixels per axis, so
17819 // it holds `(64 >> ss) / chroma_tx` units — one 32x32 at 4:2:0,
17820 // four at 4:4:4 (lane-av1-444sb: the hardcoded 4:2:0 span read
17821 // one unit per chunk there, left six of a 128x64 block's eight
17822 // 32x32 units unread and desynced the tile from that block on).
17823 let cn = ((64 >> ss_x(fctx)) / chroma_tx).max(1);
17824 // libaom's per-chunk `unit_width/height` (plane-mi units of the
17825 // luma mi grid): `min(mu_blocks + col, max_blocks) >> ss`.
17826 let unit_w = ((ch_col + 1) * 16).min(max_w_mi) >> ss_x(fctx);
17827 let unit_h = ((ch_row + 1) * 16).min(max_h_mi) >> ss_y(fctx);
17828 let stepc = (chroma_tx / 4).max(1);
17829 // `decode_token_recon_block` codes a mu chunk PLANE-MAJOR: every U
17830 // unit of the chunk, then every V unit. At one unit per plane per
17831 // chunk (every non-lossless 128-axis block) that is the same
17832 // symbol order the interleaved pair used to read; a lossless
17833 // frame's 4x4 chroma units are where it becomes observable.
17834 for plane_pass in 1..=2usize {
17835 for ci_row in 0..cn {
17836 for ci_col in 0..cn {
17837 if ch_col * (16 >> ss_x(fctx)) + ci_col * stepc >= unit_w
17838 || ch_row * (16 >> ss_y(fctx)) + ci_row * stepc >= unit_h
17839 {
17840 continue;
17841 }
17842 let cu_x = cpx + ch_col * (64 >> ss_x(fctx)) + ci_col * chroma_tx;
17843 let cu_y = cpy + ch_row * (64 >> ss_y(fctx)) + ci_row * chroma_tx;
17844 let cu_mi = (
17845 mi_r + ch_row * 16 + ci_row * ((chroma_tx << ss_y(fctx)) / 4),
17846 mi_c + ch_col * 16 + ci_col * ((chroma_tx << ss_x(fctx)) / 4),
17847 );
17848 let cu_r = tu_reach(
17849 bw,
17850 bh,
17851 ch_col * 64 + ci_col * luma_span,
17852 ch_row * 64 + ci_row * luma_span,
17853 luma_span,
17854 reach,
17855 px,
17856 py,
17857 y.width,
17858 y.height, fctx,
17859 );
17860 if skip {
17861 push_intra(plane_pass,
17862 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r,
17863 &zero_cu, None, None, smooth_neighbor_uv, fctx,
17864 );
17865 continue;
17866 }
17867 let cu_around = neighbours.around_mi(cu_mi, luma_span);
17868 let buf: &mut PlaneBuf<'static> =
17869 if plane_pass == 1 { &mut *u } else { &mut *v };
17870 let grid = read_plane(
17871 dec, cdfs, chroma_set, &chroma_scan, plane_pass, cu_around[plane_pass],
17872 mode, uv_predict_mode, angle_delta_uv, cu_r, buf, cu_x, cu_y,
17873 chroma_tx, chroma_tx, base_q_idx, None, None, Some(3),
17874 smooth_neighbor_uv, fctx,
17875 )?;
17876 last_grids[plane_pass - 1] = grid.clone();
17877 // Immediately, so the NEXT unit of this same block
17878 // reads this one's coefficient context; replayed after
17879 // `record_split_luma_rect` below, which would otherwise
17880 // clobber them whole-block.
17881 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &grid);
17882 units.push((plane_pass, cu_mi, grid));
17883 }
17884 }
17885 }
17886 if !skip {
17887 hit!(CHROMA_SPLIT_TX_HITS);
17888 }
17889 }
17890 }
17891 if skip {
17892 neighbours.record_rect(
17893 at,
17894 bw,
17895 bh,
17896 mode,
17897 uv_predict_mode,
17898 &[
17899 &ZERO_RESIDUAL[..bw * bh],
17900 &ZERO_RESIDUAL[..chroma_w * chroma_h],
17901 &ZERO_RESIDUAL[..chroma_w * chroma_h],
17902 ],
17903 );
17904 } else {
17905 neighbours.record_split_luma_rect(
17906 at,
17907 bw,
17908 bh,
17909 mode,
17910 uv_predict_mode,
17911 [&last_grids[0], &last_grids[1]],
17912 );
17913 for (plane, cu_mi, grid) in &units {
17914 neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span, *plane, grid);
17915 }
17916 }
17917 // No palette exists at this size; the unconditional stamp clears any
17918 // stale neighbour palette state, as every other block path does.
17919 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
17920 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
17921 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
17922 neighbours.fill_lf_grid_rect(
17923 (mi_r, mi_c),
17924 bw / MI,
17925 bh / MI,
17926 logical_tx as u8,
17927 logical_tx as u8,
17928 0, fctx,
17929 );
17930 if in_inter || allow_intrabc_frame(fctx) {
17931 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
17932 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
17933 // inter frame, intra ones included: an intra block stamps its
17934 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
17935 // A key frame reads those bands only when it allows intrabc
17936 // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom
17937 // stamps here too -- lane-av1-intrabc r3.
17938 txfm_partition_update_rect(
17939 neighbours,
17940 (mi_r, mi_c),
17941 (logical_tx, logical_tx),
17942 (bw, bh),
17943 );
17944 }
17945 if in_inter {
17946 hit_do! {
17947 INTRA128_IN_INTER_HITS.with(|c| {
17948 let mut h = c.get();
17949 h[usize::from(bw < bh)] += 1;
17950 c.set(h);
17951 });
17952 }
17953 } else if bw > bh {
17954 hit!(INTRA_SB128_HORZ_HITS);
17955 } else {
17956 hit!(INTRA_SB128_VERT_HITS);
17957 }
17958 Ok(())
17959}
17960
17961
17962/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
17963/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
17964/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
17965/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
17966/// just-decoded mode, not the enclosing slot's stale one, is the true
17967/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
17968/// units, which is what its coefficient context (finer than [`SUB`]) is read
17969/// at. Returns the mode this leaf decoded, for the caller's own
17970/// `prev_leaf`/final mode-writeback bookkeeping.
17971#[allow(clippy::too_many_arguments)]
17972/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
17973/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
17974/// `above_mode[col]`, and its true above neighbour is the mi directly above
17975/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
17976/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
17977/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
17978/// (bottom-right) into both, as this path did, is right only when all four
17979/// leaves happen to share a mode. `done` may be short at the true frame edge
17980/// (the straddle caller filters positions off the frame), so each side falls
17981/// back to the last leaf actually decoded.
17982fn write_back_split_modes(
17983 neighbours: &mut Neighbours,
17984 done: &[((usize, usize), usize)],
17985 parent_mi: (usize, usize),
17986 slot: (usize, usize),
17987) {
17988 let (sr, sc) = slot;
17989 let Some(&(_, last)) = done.last() else {
17990 return;
17991 };
17992 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
17993 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
17994 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
17995}
17996
17997fn decode_leaf8(
17998 dec: &mut SymbolDecoder,
17999 cdfs: &mut Cdfs,
18000 neighbours: &mut Neighbours,
18001 outer_at: (usize, usize),
18002 leaf_mi: (usize, usize),
18003 scans: (&[u16], &[u16]),
18004 prev_leaf: Option<((usize, usize), usize)>,
18005 y: &mut PlaneBuf<'static>,
18006 u: &mut PlaneBuf<'static>,
18007 v: &mut PlaneBuf<'static>,
18008 base_q_idx: u8,
18009 enable_filter_intra: bool,
18010 allow_screen_content_tools: bool,
18011 allow_intrabc: bool,
18012 tx_select: bool,
18013 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
18014) -> Result<usize> {
18015 let (r, c) = outer_at;
18016 // lane-modectx r1: the group's own availability-correct fallback pair, not
18017 // the raw coarse bands (which leak across a tile edge -- see
18018 // `modes_above_left`).
18019 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
18020 if let Some(((pr, pc), pmode)) = prev_leaf {
18021 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
18022 above_mode = pmode;
18023 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
18024 left_mode = pmode;
18025 }
18026 }
18027 // The mi-exact neighbour wins over both the coarse 16x16 slot and
18028 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
18029 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
18030 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
18031 // lane-rectsplitx r2 swept this arm into
18032 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
18033 // "no neighbour" at a tile edge, where the coarse cell holds the block
18034 // above/left of it inside the same 16x16.
18035 let (above_mode, left_mode) =
18036 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
18037 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
18038 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
18039 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
18040 // this leaf's `smooth_neighbor` is built from -- passing `false` here
18041 // filtered a directional chroma block's edge at the wrong strength
18042 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
18043 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
18044 // with the coarse [`SUB`] slot as the fallback when no block recorded
18045 // that exact mi cell.
18046 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
18047 if smooth_neighbor {
18048 hit!(SMOOTH_LUMA_HITS);
18049 }
18050 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
18051 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
18052 // `decode_block` caller at 16x16 and up.
18053 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
18054 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
18055 // `read_palette_mode_info`), at its REAL mi position -- passing
18056 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
18057 // moment a real 8x8 palette block fired, which is where every 8-bit
18058 // `--tune-content=screen --min-partition-size=8` stream stopped.
18059 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
18060 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
18061 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
18062 read_intra_mode(
18063 dec,
18064 cdfs,
18065 above_mode,
18066 left_mode,
18067 true,
18068 8,
18069 enable_filter_intra,
18070 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
18071 allow_screen_content_tools,
18072 allow_intrabc,
18073 Some((palette_ctx, &palette_cache)),
18074 &palette_uv_cache,
18075 leaf_mi.0,
18076 leaf_mi.1, fctx,
18077 )?;
18078 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
18079 // `read_intra_mode` and then decoded the block as if it were ordinary
18080 // intra. libaom's `is_inter_block` counts an intrabc block
18081 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
18082 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
18083 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
18084 // same value with a different interval, so the tile desynced at the very
18085 // next symbol (class `wrong-alphabet-same-value`). Everything below
18086 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
18087 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
18088 if intrabc_dv.is_some() {
18089 hit!(LEAF8_INTRABC_HITS);
18090 }
18091 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
18092 // index map, mapped through the base colours, IS the block's prediction --
18093 // carried to the next `reconstruct`/`read_plane` through the same
18094 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
18095 let palette_y_buf: Option<Vec<u16>> = palette_y
18096 .as_ref()
18097 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
18098 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
18099 (
18100 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
18101 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
18102 )
18103 });
18104 let (pal_y_size, pal_y_colors) =
18105 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
18106 let (pal_uv_size, pal_uv_colors) =
18107 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
18108 if palette_y.is_some() || palette_uv.is_some() {
18109 hit!(PALETTE_LEAF8_HITS);
18110 }
18111 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
18112 DC_PRED
18113 } else {
18114 uv_mode
18115 };
18116 neighbours.above_uv_mode[c] = uv_predict_mode;
18117 neighbours.left_uv_mode[r] = uv_predict_mode;
18118 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
18119 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
18120 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
18121 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
18122 // transform units, same raster-order per-TU pattern `decode_block`'s
18123 // multi-TU branch runs).
18124 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
18125 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
18126 // intrabc block, so a SKIPPED one takes the largest transform and an
18127 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
18128 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
18129 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
18130 // `parse_decode_block`'s tree condition carries
18131 // `!xd->lossless[mbmi->segment_id]` (see [`decode_block`]'s own copy):
18132 // a lossless segment's intrabc leaf reads no tree, TX_4X4 via
18133 // `read_tx_size`'s first line (lane-av1mixloss).
18134 let resolved = if tx_select && intrabc_dv.is_some() && !skip && !lossless(fctx) {
18135 let mut leaves = Vec::new();
18136 let mi_cols = 2 * y.true_width.div_ceil(8);
18137 let mi_rows = 2 * y.true_height.div_ceil(8);
18138 read_var_tx_size(
18139 dec,
18140 cdfs,
18141 neighbours,
18142 leaf_mi,
18143 8,
18144 (
18145 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
18146 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
18147 ),
18148 (8, 8),
18149 0,
18150 0,
18151 0,
18152 &mut leaves,
18153 );
18154 hit!(INTRABC_VARTX_HITS);
18155 leaves.first().map_or(8, |l| l.2)
18156 } else if tx_select && intrabc_dv.is_none() {
18157 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, fctx)
18158 } else {
18159 // lane-lossless: TX_4X4 on a lossless frame, no symbol
18160 // (libaom `read_tx_size`).
18161 lossless_tx(8, fctx)
18162 };
18163 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
18164 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
18165 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
18166 // 4:4:4: this 8x8 block's chroma plane block is 8x8 (same scan as luma,
18167 // `scans.0`). 4:2:0 stays the 4x4 unit this leaf was written for.
18168 let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
18169 let (csz, cset, cscan) = if chroma_444 {
18170 (8usize, TxbSet::Chroma8, scans.0)
18171 } else {
18172 (4usize, TxbSet::Chroma4, scans.1)
18173 };
18174 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
18175 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
18176 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
18177 // the full-pel block vector, with the BILINEAR kernel libaom forces.
18178 flush_recon(fctx, y, u, v);
18179 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
18180 let mut yb = vec![0u16; 8 * 8];
18181 mc::predict_with_filter(
18182 &y.data, y.width, y.true_width, y.true_height,
18183 mv_to_q4(px, dv_col, 0), mv_to_q4(py, dv_row, 0),
18184 8, 8, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
18185 );
18186 let mut ub = vec![0u16; 4 * 4];
18187 mc::predict_with_filter(
18188 &u.data, u.width, u.true_width, u.true_height,
18189 mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_x(fctx)),
18190 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
18191 );
18192 let mut vb = vec![0u16; 4 * 4];
18193 mc::predict_with_filter(
18194 &v.data, v.width, v.true_width, v.true_height,
18195 mv_to_q4(cpx, dv_col, ss_x(fctx)), mv_to_q4(cpy, dv_row, ss_x(fctx)),
18196 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
18197 );
18198 (yb, ub, vb)
18199 });
18200 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
18201 // `decode_block` uses: set fresh right before each plane's own
18202 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
18203 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
18204 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
18205 // first shape that reaches that loop with an override set).
18206 let palette_y_buf = match &intrabc_bufs {
18207 Some((yb, _, _)) => Some(yb.clone()),
18208 None => palette_y_buf,
18209 };
18210 // lane-av1intrapred: the chroma twin of the `palette_y_buf` wrap above --
18211 // `decode_block` does the same for its own `palette_uv_bufs`
18212 // (decode.rs's single-TU and multi-TU chroma reads). Without it, an
18213 // intrabc leaf whose var-tx tree split to TX_4X4 reached the TX4 arm's
18214 // chroma reads with the override unset: the unit predicted INTRA from
18215 // the UV mode (intrabc's is DC) instead of copying the frame at the DV,
18216 // R5 first differing pixel U(184,4), block mi (2,92).
18217 let palette_uv_bufs = match &intrabc_bufs {
18218 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
18219 None => palette_uv_bufs,
18220 };
18221 let (luma_grid, u_grid, v_grid);
18222 if skip {
18223 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
18224 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
18225 // transform units, each off the units already written left/above of
18226 // it inside this same leaf -- an intra block's transform size is read
18227 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
18228 // A palette block's prediction is the whole-block index map, never
18229 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
18230 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
18231 // even when `tx_depth` resolved to TX_4X4.
18232 if resolved == 4 && palette_y_buf.is_none() {
18233 hit!(SKIP_SPLIT_TX_HITS);
18234 for tu_row in 0..2 {
18235 for tu_col in 0..2 {
18236 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
18237 if tu_px >= y.true_width || tu_py >= y.true_height {
18238 continue;
18239 }
18240 let tu_reach = tu_reach(
18241 8,
18242 8,
18243 tu_col * 4,
18244 tu_row * 4,
18245 4,
18246 reach,
18247 px,
18248 py,
18249 y.width,
18250 y.height, fctx,
18251 );
18252 push_intra(0,
18253 tu_px,
18254 tu_py,
18255 4,
18256 mode,
18257 angle_delta_y,
18258 tu_reach,
18259 &ZERO_RESIDUAL[..16],
18260 None,
18261 filter_intra,
18262 smooth_neighbor, fctx,
18263 );
18264 }
18265 }
18266 } else {
18267 if let Some(buf) = &palette_y_buf {
18268 set_palette_pred(buf.clone(), fctx);
18269 }
18270 push_intra(0,
18271 px,
18272 py,
18273 8,
18274 mode,
18275 angle_delta_y,
18276 reach,
18277 &ZERO_RESIDUAL[..64],
18278 None,
18279 filter_intra,
18280 smooth_neighbor, fctx,
18281 );
18282 }
18283 let ac = alpha.map(|_| cfl_src(px, py, 8));
18284 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster of
18285 // TX_4X4 units (`av1_get_tx_size`: lossless forces TX_4X4 on EVERY
18286 // plane), so a skipped leaf predicts per unit -- each from its own
18287 // edges -- like the luma `SKIP_SPLIT_TX` loop above. CfL never fires
18288 // here (`is_cfl_allowed` at lossless needs plane_bsize == 4x4; this
18289 // chroma plane block is 8x8), and intrabc/palette keep the
18290 // whole-plane-block prediction they already run.
18291 let chroma_units_444 = chroma_444
18292 && lossless(fctx)
18293 && intrabc_bufs.is_none()
18294 && palette_uv_bufs.is_none();
18295 if let Some((_, ub, _)) = &intrabc_bufs {
18296 set_palette_pred(ub.clone(), fctx);
18297 } else if let Some((ub, _)) = &palette_uv_bufs {
18298 set_palette_pred(ub.clone(), fctx);
18299 }
18300 if chroma_units_444 {
18301 for cu_row in 0..2 {
18302 for cu_col in 0..2 {
18303 let cu_reach = tu_reach(
18304 8, 8, cu_col * 4, cu_row * 4, 4,
18305 reach, px, py, y.width, y.height, fctx,
18306 );
18307 push_intra(1,
18308 cpx + cu_col * 4,
18309 cpy + cu_row * 4,
18310 4,
18311 uv_predict_mode,
18312 angle_delta_uv,
18313 cu_reach,
18314 &ZERO_RESIDUAL[..16],
18315 None,
18316 None,
18317 smooth_neighbor_uv, fctx,
18318 );
18319 }
18320 }
18321 } else {
18322 push_intra(1,
18323 cpx,
18324 cpy,
18325 csz,
18326 uv_predict_mode,
18327 angle_delta_uv,
18328 reach,
18329 &ZERO_RESIDUAL[..csz * csz],
18330 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
18331 None,
18332 smooth_neighbor_uv, fctx,
18333 );
18334 }
18335 if let Some((_, _, vb)) = &intrabc_bufs {
18336 set_palette_pred(vb.clone(), fctx);
18337 } else if let Some((_, vb)) = &palette_uv_bufs {
18338 set_palette_pred(vb.clone(), fctx);
18339 }
18340 if chroma_units_444 {
18341 for cu_row in 0..2 {
18342 for cu_col in 0..2 {
18343 let cu_reach = tu_reach(
18344 8, 8, cu_col * 4, cu_row * 4, 4,
18345 reach, px, py, y.width, y.height, fctx,
18346 );
18347 push_intra(2,
18348 cpx + cu_col * 4,
18349 cpy + cu_row * 4,
18350 4,
18351 uv_predict_mode,
18352 angle_delta_uv,
18353 cu_reach,
18354 &ZERO_RESIDUAL[..16],
18355 None,
18356 None,
18357 smooth_neighbor_uv, fctx,
18358 );
18359 }
18360 }
18361 } else {
18362 push_intra(2,
18363 cpx,
18364 cpy,
18365 csz,
18366 uv_predict_mode,
18367 angle_delta_uv,
18368 reach,
18369 &ZERO_RESIDUAL[..csz * csz],
18370 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
18371 None,
18372 smooth_neighbor_uv, fctx,
18373 );
18374 }
18375 luma_grid = Grid::Zero(64);
18376 u_grid = Grid::Zero(csz * csz);
18377 v_grid = Grid::Zero(csz * csz);
18378 } else if resolved != 4 {
18379 let around = neighbours.around_mi(leaf_mi, 8);
18380 if let Some(buf) = &palette_y_buf {
18381 set_palette_pred(buf.clone(), fctx);
18382 }
18383 luma_grid = read_plane(
18384 dec,
18385 cdfs,
18386 if intrabc_dv.is_some() {
18387 inter_txbset_for(8, reduced_tx_set)
18388 } else if reduced_tx_set {
18389 TxbSet::Luma8
18390 } else {
18391 TxbSet::Luma8Set1
18392 },
18393 scans.0,
18394 0,
18395 around[0],
18396 mode,
18397 mode,
18398 angle_delta_y,
18399 reach,
18400 y,
18401 px,
18402 py,
18403 8,
18404 TX8,
18405 base_q_idx,
18406 None,
18407 filter_intra,
18408 None,
18409 smooth_neighbor, fctx,
18410 )?;
18411 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
18412 // an intrabc block's chroma tx_type is the colocated LUMA transform's
18413 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
18414 if intrabc_dv.is_some() {
18415 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
18416 }
18417 let ac = alpha.map(|_| cfl_src(px, py, 8));
18418 if let Some((_, ub, _)) = &intrabc_bufs {
18419 set_palette_pred(ub.clone(), fctx);
18420 } else if let Some((ub, _)) = &palette_uv_bufs {
18421 set_palette_pred(ub.clone(), fctx);
18422 }
18423 u_grid = read_plane(
18424 dec,
18425 cdfs,
18426 cset,
18427 cscan,
18428 1,
18429 around[1],
18430 mode,
18431 uv_predict_mode,
18432 angle_delta_uv,
18433 reach,
18434 u,
18435 cpx,
18436 cpy,
18437 csz,
18438 csz,
18439 base_q_idx,
18440 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
18441 None,
18442 None,
18443 smooth_neighbor_uv, fctx,
18444 )?;
18445 if let Some((_, _, vb)) = &intrabc_bufs {
18446 set_palette_pred(vb.clone(), fctx);
18447 } else if let Some((_, vb)) = &palette_uv_bufs {
18448 set_palette_pred(vb.clone(), fctx);
18449 }
18450 v_grid = read_plane(
18451 dec,
18452 cdfs,
18453 cset,
18454 cscan,
18455 2,
18456 around[2],
18457 mode,
18458 uv_predict_mode,
18459 angle_delta_uv,
18460 reach,
18461 v,
18462 cpx,
18463 cpy,
18464 csz,
18465 csz,
18466 base_q_idx,
18467 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
18468 None,
18469 None,
18470 smooth_neighbor_uv, fctx,
18471 )?;
18472 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
18473 // two chroma reads (`decode_block`'s own tail does the same) -- left
18474 // set, every later chroma block would inherit this luma tx_type,
18475 // which picks the scan and the inverse transform.
18476 fctx.intrabc_chroma_tx.with(|c| c.set(None));
18477 } else {
18478 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
18479 // grid of 4x4 transform units, each predicted from the leaf's own
18480 // 8x8 `mode` and reading its own fresh context off the earlier
18481 // units in this same leaf (the same per-TU pattern `decode_block`'s
18482 // multi-TU branch runs at bigger blocks).
18483 let mut first_leaf_tx: Option<TxType> = None;
18484 for tu_row in 0..2 {
18485 for tu_col in 0..2 {
18486 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
18487 let tu_px = px + tu_col * 4;
18488 let tu_py = py + tu_row * 4;
18489 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
18490 if crate::encode::Reach::in_vert_ab() {
18491 hit!(VERT_AB_TX4_HITS);
18492 }
18493 let tu_reach = tu_reach(
18494 8,
18495 8,
18496 tu_col * 4,
18497 tu_row * 4,
18498 4,
18499 reach,
18500 px,
18501 py,
18502 y.width,
18503 y.height, fctx,
18504 );
18505 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
18506 // Each 4x4 unit predicts from its own window of the block's
18507 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
18508 // 16x16 and up) -- the whole-block buffer would be taken by
18509 // the FIRST unit and indexed at the wrong stride.
18510 if let Some(buf) = &palette_y_buf {
18511 hit!(PALETTE_SPLIT_TX_HITS);
18512 let mut window = vec![0u16; 16];
18513 for row in 0..4 {
18514 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
18515 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
18516 }
18517 set_palette_pred(window, fctx);
18518 }
18519 let tu_grid = read_plane(
18520 dec,
18521 cdfs,
18522 if intrabc_dv.is_some() {
18523 inter_txbset_for(4, reduced_tx_set)
18524 } else if reduced_tx_set {
18525 TxbSet::Luma4
18526 } else {
18527 TxbSet::Luma4Set1
18528 },
18529 scans.1,
18530 0,
18531 tu_around,
18532 mode,
18533 mode,
18534 angle_delta_y,
18535 tu_reach,
18536 y,
18537 tu_px,
18538 tu_py,
18539 4,
18540 4,
18541 base_q_idx,
18542 None,
18543 filter_intra,
18544 Some(tu_skip_ctx),
18545 smooth_neighbor, fctx,
18546 )?;
18547 if crate::envflags::env_flag!("EC_AV1_TRACE") {
18548 eprintln!(
18549 "TRACE tu_bitpos mi=({},{}) tell={}",
18550 tu_mi.0,
18551 tu_mi.1,
18552 dec.debug_bitpos()
18553 );
18554 }
18555 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
18556 // The FIRST (top-left, co-located with this group's chroma)
18557 // TU's coded tx_type is what the group's chroma inherits --
18558 // the same capture [`decode_block`]'s multi-TU branch makes
18559 // for `first_leaf_tx` (libaom `av1_get_tx_type`, blockd.h:
18560 // an inter-classified block's `PLANE_TYPE_UV` reads
18561 // `tx_type_map`, and intrabc is inter-classified).
18562 if first_leaf_tx.is_none() {
18563 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
18564 }
18565 }
18566 }
18567 // lane-av1intrapred: an intrabc leaf whose var-tx tree split to
18568 // TX_4X4 never armed [`INTRABC_CHROMA_TX`], so its chroma reads fell
18569 // back to `default_intra_tx_type(DC_PRED)` = `DCT_DCT` and took the
18570 // 2D scan, the 2D eob row and the 2D nz contexts where libaom takes
18571 // the inherited luma type's (R5's first fork: mi (36,66), luma
18572 // (0,0) coded `H_ADST` off the 16-symbol inter set, chroma U then
18573 // decoded its `eob` from the wrong CDF row). Same arm the
18574 // `resolved != 4` branch above runs for its whole-leaf unit.
18575 if intrabc_dv.is_some() {
18576 if let Some(t) = first_leaf_tx {
18577 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
18578 }
18579 }
18580 let ac = alpha.map(|_| cfl_src(px, py, 8));
18581 let chroma_around = neighbours.around_mi(leaf_mi, 8);
18582 // lane-av1intrapred: the non-vacuity counter -- armed slot consulted
18583 // by this arm's chroma reads means the frame-copy + inherited-type
18584 // route ran; zero at gate time means the fixture stopped reaching it.
18585 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
18586 hit!(INTRABC_TX4_CHROMA_COPY_HITS);
18587 }
18588 if chroma_444 && lossless(fctx) {
18589 // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster
18590 // of TX_4X4 units per plane, PLANE-MAJOR (`av1_get_tx_size`:
18591 // lossless forces TX_4X4 on EVERY plane) -- the same walk
18592 // `read_intra_chroma_lossless` runs for whole blocks. Reading one
18593 // TX_8X8 unit here panicked before: the lossless inverse is the
18594 // 4x4-only WHT (`TxParams::run`'s own `(w, h) == (4, 4)`
18595 // invariant), and the unit count desyncs the tile either way.
18596 // Per-unit `record_mi_chroma` calls stamp the neighbour bands
18597 // inside, which is why the tail's whole-leaf chroma stamp below
18598 // is skipped for this shape.
18599 let (mut uo, mut vo) = (Vec::new(), Vec::new());
18600 read_intra_chroma_lossless(
18601 dec, cdfs, neighbours, u, v, leaf_mi, (px, py), (cpx, cpy),
18602 8, (8, 8), (0, 0), (8, 8), 8, reach, (y.width, y.height), mode,
18603 uv_predict_mode, angle_delta_uv,
18604 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
18605 smooth_neighbor_uv, base_q_idx, &mut uo, &mut vo, fctx,
18606 )?;
18607 u_grid = if uo.is_empty() { Grid::Zero(64) } else { Grid::Own(uo) };
18608 v_grid = if vo.is_empty() { Grid::Zero(64) } else { Grid::Own(vo) };
18609 } else {
18610 if let Some((ub, _)) = &palette_uv_bufs {
18611 set_palette_pred(ub.clone(), fctx);
18612 }
18613 u_grid = read_plane(
18614 dec,
18615 cdfs,
18616 cset,
18617 cscan,
18618 1,
18619 chroma_around[1],
18620 mode,
18621 uv_predict_mode,
18622 angle_delta_uv,
18623 reach,
18624 u,
18625 cpx,
18626 cpy,
18627 csz,
18628 csz,
18629 base_q_idx,
18630 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
18631 None,
18632 None,
18633 smooth_neighbor_uv, fctx,
18634 )?;
18635 if let Some((_, vb)) = &palette_uv_bufs {
18636 set_palette_pred(vb.clone(), fctx);
18637 }
18638 v_grid = read_plane(
18639 dec,
18640 cdfs,
18641 cset,
18642 cscan,
18643 2,
18644 chroma_around[2],
18645 mode,
18646 uv_predict_mode,
18647 angle_delta_uv,
18648 reach,
18649 v,
18650 cpx,
18651 cpy,
18652 csz,
18653 csz,
18654 base_q_idx,
18655 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
18656 None,
18657 None,
18658 smooth_neighbor_uv, fctx,
18659 )?;
18660 }
18661 // The two chroma reads above are the only consulters of this leaf's
18662 // armed [`INTRABC_CHROMA_TX`]; leaving it set would make the NEXT
18663 // leaf's chroma inherit this leaf's luma type instead of its own
18664 // derivation (class armed-slot-leak-into-next-leaf, seen live: the
18665 // regular-intra leaf after an intrabc TX4 leaf took the intrabc
18666 // luma's `V_ADST` for its chroma eob row).
18667 if intrabc_dv.is_some() {
18668 fctx.intrabc_chroma_tx.with(|c| c.set(None));
18669 }
18670 // `record_split_luma` expects a `record`-style `(r, c)` position in
18671 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
18672 // already in mi units, so calling it here double-scaled the
18673 // position. Plane 0 is already correct per-TU from the
18674 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
18675 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
18676 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
18677 // leaf's own 8x8 side over `MI`).
18678 let side_mi = 2;
18679 for cell in 0..side_mi {
18680 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
18681 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
18682 }
18683 let round_up_even = |n: usize| n.div_ceil(2) * 2;
18684 let bound_h = round_up_even(neighbours.mi_rows);
18685 let bound_w = round_up_even(neighbours.mi_cols);
18686 let u_state = neighbour_state(&u_grid);
18687 let v_state = neighbour_state(&v_grid);
18688 // The 4:4:4 lossless walk above already stamped these bands PER UNIT
18689 // (its raster-order last writer per cell is exactly libaom's
18690 // per-entry last update); this whole-leaf aggregate would clobber
18691 // four distinct unit states with one, so it runs only for the shapes
18692 // whose chroma really is one unit.
18693 if !(chroma_444 && lossless(fctx)) {
18694 for cell in 0..side_mi {
18695 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
18696 neighbours.left[leaf_mi.0 + cell][1] = u_state;
18697 neighbours.left[leaf_mi.0 + cell][2] = v_state;
18698 }
18699 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
18700 neighbours.above[leaf_mi.1 + cell][1] = u_state;
18701 neighbours.above[leaf_mi.1 + cell][2] = v_state;
18702 }
18703 }
18704 }
18705 // This leaf's own palette state into the mi-granular above/left bands
18706 // (sizes 0 when it used none, which is what clears a previous block's
18707 // palette out of the next block's ctx and colour cache).
18708 {
18709 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
18710 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
18711 }
18712 neighbours.fill_skip_grid(leaf_mi, 2, skip);
18713 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
18714 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
18715 // own copy; only an intrabc var-tx read consumes these bands on the intra
18716 // path, so the write is armed by `allow_intrabc`.
18717 if allow_intrabc {
18718 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
18719 }
18720 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
18721 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
18722 return Ok(mode);
18723 }
18724 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
18725 // This leaf's own palette state into the mi-granular above/left bands
18726 // (sizes 0 when it used none, which is what clears a previous block's
18727 // palette out of the next block's ctx and colour cache).
18728 {
18729 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
18730 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
18731 }
18732 hit!(INTER8_SKIP_BAND_HITS);
18733 neighbours.fill_skip_grid(leaf_mi, 2, skip);
18734 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
18735 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
18736 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
18737 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
18738 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
18739 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
18740 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
18741 // wrong CDF row, so the msac range diverged mid-frame with no refusal
18742 // (class `wrong-alphabet-same-value`; the ReelB key frame at
18743 // -ss 900, first bad luma sample row 186 col 1803).
18744 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
18745 // lane-t900 r32 / lane-av1txbands: `set_txfm_ctxs` for an 8x8 leaf -- see
18746 // `decode_block`'s own copy for why this stays beside
18747 // [`Neighbours::fill_lf_grid_rect`]'s publish (the skipped-intrabc
18748 // BLOCK-size term).
18749 if allow_intrabc {
18750 set_txfm_ctxs(neighbours, leaf_mi, resolved, 2, 2, skip && intrabc_dv.is_some());
18751 }
18752 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
18753 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
18754 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
18755 // publish its own cells exactly like `decode_block` does.
18756 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
18757 Ok(mode)
18758}
18759
18760/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
18761/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
18762/// bottom, where no partition symbol is read at all -- `decode_block` runs
18763/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
18764/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
18765/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
18766/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
18767/// of the 2x2 4x4 group carries chroma syntax at all.
18768#[allow(clippy::too_many_arguments)]
18769fn read_intra_mode_sub8(
18770 dec: &mut SymbolDecoder,
18771 cdfs: &mut Cdfs,
18772 above_mode: usize,
18773 left_mode: usize,
18774 has_chroma: bool,
18775 enable_filter_intra: bool,
18776 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
18777 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
18778 // from the wrong row is the same VALUE with a different interval, so it
18779 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
18780 fi_class: usize,
18781 skip_ctx: usize,
18782 allow_intrabc: bool,
18783 mi_r: usize,
18784 mi_c: usize,
18785 // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4`
18786 // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf
18787 // left the second mi column at segment 0, which reads back as a
18788 // neighbour's `cdf_index`/prediction two blocks later.
18789 seg_w_mi: usize,
18790 seg_h_mi: usize, fctx: &crate::decode::FrameCtx,
18791) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>, Option<(i32, i32)>)> {
18792 // lane-av1mono: a monochrome leaf codes no chroma mode (libaom
18793 // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`.
18794 let has_chroma = has_chroma && !mono(fctx);
18795 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
18796 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
18797 if ec_istep {
18798 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
18799 }
18800 // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder
18801 // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block.
18802 macro_rules! istep {
18803 ($name:literal, $val:expr) => {
18804 if ec_istep {
18805 eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}", $name, $val, dec.debug_state().0);
18806 }
18807 };
18808 }
18809 // lane-seg2: same `intra_segment_id` placement as the square and rect
18810 // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id`
18811 // like any other block, over its own 1x1 mi footprint. Dropping it here
18812 // both ate a symbol (the tile desynced at the frame's first sub-8x8
18813 // split) and left `cur_segment_id` on the previous block, so the leaf
18814 // dequantized with a neighbour's `SEG_LVL_ALT_Q`.
18815 if seg_id_pre_skip(fctx) {
18816 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
18817 }
18818 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
18819 if trace {
18820 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
18821 }
18822 istep!("skip", skip as i32);
18823 if !seg_id_pre_skip(fctx) {
18824 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
18825 }
18826 maybe_read_cdef_idx(dec, mi_r, mi_c, (2, 2), skip, fctx);
18827 istep!("cdef", 0);
18828 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
18829 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
18830 istep!("dq", 0);
18831 if allow_intrabc {
18832 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
18833 if ec_istep {
18834 eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}", u8::from(use_intrabc), dec.debug_state().0);
18835 }
18836 if use_intrabc {
18837 // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block
18838 // vector right after the flag and RETURNS -- no y/uv mode, angle
18839 // delta, palette, CfL or filter-intra syntax follows, and the
18840 // block is reconstructed by the INTER path (libaom's
18841 // `is_inter_block` counts an intrabc block), so the caller takes
18842 // the frame-copy prediction + inter residual.
18843 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (seg_w_mi, seg_h_mi), fctx);
18844 // lane-av1txr: the DV travels back in the RETURN value -- it is
18845 // NOT published through `FrameCtx::intrabc_dv`. That slot is the
18846 // SQUARE paths' handoff (`decode_block`/`decode_leaf8` arm it,
18847 // then `take()` it in the same call), so a sub-8x8 leaf that
18848 // armed it left the vector standing for the NEXT >=8x8 block:
18849 // `warped.obu`'s (38,60) 8x8 intra block took it as its own
18850 // intrabc and read an inter var-tx `txfm_split` where libaom read
18851 // an intra `tx_depth` (class `stale-slot-handoff`).
18852 hit!(INTRABC_HITS);
18853 return Ok((skip, DC_PRED, 0, None, None, Some(dv)));
18854 }
18855 }
18856 let above_ctx = INTRA_MODE_CTX[above_mode];
18857 let left_ctx = INTRA_MODE_CTX[left_mode];
18858 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
18859 istep!("mode", mode);
18860 if trace {
18861 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
18862 }
18863 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
18864 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
18865 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
18866 // symbol. Reading one consumed a symbol the encoder never wrote and
18867 // desynced the tile at the very next element.
18868 let angle_delta_y = 0;
18869 let chroma = if has_chroma {
18870 // `is_cfl_allowed` (blockd.h): at lossless CfL needs the CHROMA plane
18871 // block to be a single TX_4X4 (`cfl_allowed_px`). True for this leaf
18872 // at 4:2:0 (the group's plane block is 4x4) and for a 4:4:4
18873 // `BLOCK_4X4` split leaf, but FALSE for a 4:4:4 `BLOCK_8X4`/`BLOCK_4X8`
18874 // rect leaf, whose plane block is the rect itself -- that shape reads
18875 // the 13-symbol `uv_mode_no_cfl` CDF, and reading the CFL alphabet
18876 // there desynced the tile at the rect leaf's own uv_mode symbol (measured:
18877 // ours consumed the 14-symbol interval where the oracle read 13, first
18878 // divergence at the rect leaf mi (8,16) of `ll444.obu`; class
18879 // `wrong-alphabet-same-value`, lane-av1-llsub8).
18880 let uv_mode = if cfl_allowed_px(seg_w_mi * MI, seg_h_mi * MI, fctx) {
18881 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
18882 } else {
18883 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
18884 };
18885 if trace {
18886 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
18887 }
18888 if (9..=12).contains(&uv_mode) {
18889 hit!(SMOOTH_UV_HITS);
18890 }
18891 let alpha = if uv_mode == UV_CFL_PRED {
18892 Some(read_cfl_alphas(dec, cdfs))
18893 } else {
18894 None
18895 };
18896 if (V_PRED..=D67_PRED).contains(&uv_mode) {
18897 hit!(DIRECTIONAL_UV_HITS);
18898 }
18899 // See the luma comment above: no angle delta below 8x8.
18900 let angle_delta_uv = 0;
18901 Some((uv_mode, angle_delta_uv, alpha))
18902 } else {
18903 None
18904 };
18905 let mut filter_intra = None;
18906 if mode == DC_PRED && enable_filter_intra {
18907 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
18908 if trace {
18909 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
18910 }
18911 if use_filter_intra {
18912 hit!(FILTER_INTRA_HITS);
18913 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
18914 filter_intra = Some(fi_mode);
18915 }
18916 }
18917 Ok((skip, mode, angle_delta_y, chroma, filter_intra, None))
18918}
18919/// 4:4:4 sub-8x8 key-frame leaf chroma (lane-av1-444). At subsampling 0/0
18920/// `is_chroma_reference` (av1_common_int.h:1459) is unconditional, so EVERY
18921/// 4x4 / 4x8 / 8x4 leaf codes its own full-resolution chroma unit right
18922/// after its own luma (`read_intra_mode_sub8` already read this leaf's own
18923/// `uv_mode`), not the one shared 4x4 unit [`decode_leaf_split4`] /
18924/// [`decode_leaf_rect8`]'s group tails decode at 4:2:0. Mirrors those tails
18925/// arm for arm at leaf scale: a skipped leaf keeps its CfL contribution, an
18926/// intrabc leaf predicts a frame copy at its DV with the luma `tx_type`
18927/// inherited through [`INTRABC_CHROMA_TX`] (the caller arms it right after
18928/// the luma read). The chroma position, reach and entropy-context span are
18929/// the leaf's own (ss 0/0); the 4x8/8x4 unit reads the same
18930/// `ChromaRect8x4` tables [`decode_rect_split`] proves for that shape.
18931/// Records the leaf's own `uv_mode` map entry and chroma above/left state,
18932/// and returns the (u, v) grids for the caller's coarse slots.
18933#[allow(clippy::too_many_arguments)]
18934fn sub8_leaf_chroma444(
18935 dec: &mut SymbolDecoder,
18936 cdfs: &mut Cdfs,
18937 neighbours: &mut Neighbours,
18938 lmi: (usize, usize),
18939 bw: usize,
18940 bh: usize,
18941 uv_mode: usize,
18942 alpha: Option<(i32, i32)>,
18943 skip: bool,
18944 intrabc_dv: Option<(i32, i32)>,
18945 y: &PlaneBuf<'static>,
18946 u: &mut PlaneBuf<'static>,
18947 v: &mut PlaneBuf<'static>,
18948 scan4: &[u16],
18949 base_q_idx: u8,
18950 smooth_neighbor_uv: bool,
18951 fctx: &crate::decode::FrameCtx,
18952) -> Result<(Grid, Grid, usize, usize)> {
18953 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
18954 let (w_mi, h_mi) = (bw / MI, bh / MI);
18955 neighbours.record_uv_mode_mi(lmi.0, lmi.1, w_mi, h_mi, uv_predict_mode);
18956 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
18957 let square = (bw, bh) == (4, 4);
18958 // `Reach::of_rect` has no 4x4 table (`rect_reach_tables` starts at 4x8);
18959 // the square unit takes the leaf's own `Reach::of`, as its luma does.
18960 let reach = if square {
18961 Reach::of(4, px, py, y.width, y.height, fctx)
18962 } else {
18963 Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx)
18964 };
18965 let grids = if skip {
18966 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
18967 if square {
18968 push_intra(1, px, py, 4, uv_predict_mode, 0, reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx);
18969 push_intra(2, px, py, 4, uv_predict_mode, 0, reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx);
18970 } else {
18971 push_intra_rect(1, px, py, bw, bh, uv_predict_mode, 0, reach, &ZERO_RESIDUAL[..bw * bh], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx);
18972 push_intra_rect(2, px, py, bw, bh, uv_predict_mode, 0, reach, &ZERO_RESIDUAL[..bw * bh], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx);
18973 }
18974 // The same arm-without-clear route the 4:2:0 tails count: a skipped
18975 // leaf reads no coefficient, so an armed intrabc slot is dropped.
18976 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
18977 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
18978 fctx.intrabc_chroma_tx.with(|c| c.set(None));
18979 }
18980 (Grid::Zero(bw * bh), Grid::Zero(bw * bh), 4, 4)
18981 } else if let Some(dv) = intrabc_dv {
18982 // Frame copy at the DV; the residual still reads the ordinary chroma
18983 // tables with the inherited luma `tx_type` (see the 4:2:0 tails).
18984 let mut ub = vec![0u16; bw * bh];
18985 mc::predict_with_filter(
18986 &u.data, u.width, u.true_width, u.true_height,
18987 mv_to_q4(px, dv.1, 0), mv_to_q4(py, dv.0, 0),
18988 bw, bh, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
18989 );
18990 let mut vb = vec![0u16; bw * bh];
18991 mc::predict_with_filter(
18992 &v.data, v.width, v.true_width, v.true_height,
18993 mv_to_q4(px, dv.1, 0), mv_to_q4(py, dv.0, 0),
18994 bw, bh, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
18995 );
18996 let around = neighbours.around_mi_rect(lmi, bw, bh);
18997 let pair = if square {
18998 set_palette_pred(ub, fctx);
18999 let ug = read_plane(
19000 dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], DC_PRED, DC_PRED,
19001 0, reach, u, px, py, 4, TX4, base_q_idx,
19002 None, None, None, smooth_neighbor_uv, fctx,
19003 )?;
19004 set_palette_pred(vb, fctx);
19005 let vg = read_plane(
19006 dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], DC_PRED, DC_PRED,
19007 0, reach, v, px, py, 4, TX4, base_q_idx,
19008 None, None, None, smooth_neighbor_uv, fctx,
19009 )?;
19010 (ug, vg, 4, 4)
19011 } else {
19012 let scan: &[u16] = if bw > bh { &SCAN_8X4 } else { &SCAN_4X8 };
19013 let default_tx =
19014 fctx.intrabc_chroma_tx.with(std::cell::Cell::get).unwrap_or(TxType::DctDct);
19015 let mut out = (Grid::Zero(bw * bh), Grid::Zero(bw * bh), bw, bh);
19016 for (plane_idx, buf) in [(1usize, ub), (2usize, vb)] {
19017 let skip_ctx =
19018 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
19019 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, DC_PRED);
19020 let (levels, tx_type) = read_coeffs_rect(
19021 dec, &mut coding, scan, bw, bh, skip_ctx,
19022 dc_sign_ctx(around[plane_idx].2), default_tx,
19023 )?;
19024 let residual = dequant_and_inverse_typed_wh(
19025 &levels, bw, bh, crate::decode::bit_depth(fctx), block_q_idx(fctx),
19026 plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1,
19027 tx_type,
19028 block_iqmatrix(fctx, plane_idx, bw, bh, tx_type),
19029 );
19030 set_palette_pred(buf, fctx);
19031 push_intra_rect(
19032 plane_idx, px, py, bw, bh, DC_PRED, 0, reach, &residual,
19033 None, None, smooth_neighbor_uv, fctx,
19034 );
19035 if plane_idx == 1 { out.0 = levels; } else { out.1 = levels; }
19036 }
19037 out
19038 };
19039 fctx.intrabc_chroma_tx.with(|c| c.set(None));
19040 pair
19041 } else {
19042 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
19043 let around = neighbours.around_mi_rect(lmi, bw, bh);
19044 if square {
19045 let ug = read_plane(
19046 dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], uv_mode, uv_predict_mode,
19047 0, reach, u, px, py, 4, TX4, base_q_idx,
19048 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
19049 )?;
19050 let vg = read_plane(
19051 dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], uv_mode, uv_predict_mode,
19052 0, reach, v, px, py, 4, TX4, base_q_idx,
19053 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
19054 )?;
19055 (ug, vg, 4, 4)
19056 } else if lossless(fctx) {
19057 // lane-av1-llsub8: `read_tx_size` answers TX_4X4 for EVERY plane of
19058 // a lossless block, so this rect leaf's chroma is (bw/4)*(bh/4)
19059 // TX_4X4 units at their own 4x4 origins -- not the single
19060 // TX_8X4/TX_4X8 rect unit the non-lossless arm below reads (that
19061 // one is `av1_get_max_uv_txsize(BLOCK_8X4)`'s rect transform, which
19062 // lossless never reaches). Measured on `ll444.obu`'s HORZ leaf at
19063 // mi (8,16): the oracle codes U units at bc 0,1 with
19064 // `get_txb_ctx`'s +10 rows (`txb_skip_cdf[0][10..12]`,
19065 // plane pels 32 > tx pels 16) where the rect-unit read consumed
19066 // `txb_skip_cdf[1][0]` -- the tile desynced at that U unit's
19067 // all_zero symbol. Walk is plane-major like libaom
19068 // `decode_token_recon_block`'s plane/row/col loop; each unit adds
19069 // 3 to the chroma context (Chroma4's `big` rows, the same fold
19070 // [`read_plane`]'s 128x128 caller uses); CFL is never allowed at
19071 // lossless, so no alpha rides along.
19072 let mut out_u = Grid::Own(vec![0i32; bw * bh]);
19073 let mut out_v = Grid::Own(vec![0i32; bw * bh]);
19074 for (plane_idx, buf) in [(1usize, u), (2usize, v)] {
19075 for ur in 0..bh / 4usize {
19076 for uc in 0..bw / 4usize {
19077 let (umi_r, umi_c) = (lmi.0 + ur, lmi.1 + uc);
19078 let (upx, upy) = (px + uc * 4, py + ur * 4);
19079 let unit_around = neighbours.around_mi_rect((umi_r, umi_c), 4, 4);
19080 let unit_reach = Reach::of(4, upx, upy, y.width, y.height, fctx);
19081 let grid = read_plane(
19082 dec, cdfs, TxbSet::Chroma4, scan4, plane_idx, unit_around[plane_idx],
19083 uv_mode, uv_predict_mode, 0, unit_reach, buf, upx, upy, 4,
19084 TX4, base_q_idx, None, None, Some(3), smooth_neighbor_uv, fctx,
19085 )?;
19086 let cell = grid_unit_state(&grid, 4, 0, 0, 4, 4);
19087 if umi_r < neighbours.mi_rows {
19088 neighbours.left[umi_r][plane_idx] = cell;
19089 }
19090 if umi_c < neighbours.mi_cols {
19091 neighbours.above[umi_c][plane_idx] = cell;
19092 }
19093 let out = if plane_idx == 1 { &mut out_u } else { &mut out_v };
19094 if let Grid::Own(v) = out {
19095 for r in 0..4usize {
19096 v[(ur * 4 + r) * bw + uc * 4..][..4]
19097 .copy_from_slice(&grid[r * 4..][..4]);
19098 }
19099 }
19100 }
19101 }
19102 }
19103 (out_u, out_v, 4, 4)
19104 } else {
19105 // `av1_get_max_uv_txsize(BLOCK_4X8/8X4)` at ss 0/0 is the rect
19106 // transform itself; its `tx_type` is mode-derived with the
19107 // <32 set (`decode_rect_split`'s own rule for this shape).
19108 let scan: &[u16] = if bw > bh { &SCAN_8X4 } else { &SCAN_4X8 };
19109 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
19110 let mut out = (Grid::Zero(bw * bh), Grid::Zero(bw * bh), bw, bh);
19111 for plane_idx in 1..=2usize {
19112 let skip_ctx =
19113 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
19114 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
19115 let (levels, tx_type) = read_coeffs_rect(
19116 dec, &mut coding, scan, bw, bh, skip_ctx,
19117 dc_sign_ctx(around[plane_idx].2), default_tx,
19118 )?;
19119 let residual = dequant_and_inverse_typed_wh(
19120 &levels, bw, bh, crate::decode::bit_depth(fctx), block_q_idx(fctx),
19121 plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1,
19122 tx_type,
19123 block_iqmatrix(fctx, plane_idx, bw, bh, tx_type),
19124 );
19125 let cfl = alpha
19126 .zip(ac)
19127 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
19128 push_intra_rect(
19129 plane_idx, px, py, bw, bh, uv_predict_mode, 0, reach, &residual,
19130 cfl, None, smooth_neighbor_uv, fctx,
19131 );
19132 if plane_idx == 1 { out.0 = levels; } else { out.1 = levels; }
19133 }
19134 out
19135 }
19136 };
19137 // libaom `av1_set_entropy_contexts` stamps above/left PER TRANSFORM UNIT:
19138 // the leaf's own chroma span, not the 8x8 group's. A rect leaf's lossless
19139 // units (4x4) each carry their own state -- a 4:2:0-style whole-leaf smear
19140 // gave one unit's state to its neighbour's cells (lane-av1-llsub8).
19141 let (u_grid, v_grid, unit_w, unit_h) = grids;
19142 // One unit covers `unit_w/MI` mi columns and `unit_h/MI` mi rows (a 4x4
19143 // unit: one cell each; the non-lossless rect unit: the whole leaf).
19144 let (uw_cells, uh_cells) = ((unit_w / MI).max(1), (unit_h / MI).max(1));
19145 for ur in 0..h_mi / uh_cells {
19146 for uc in 0..w_mi / uw_cells {
19147 let (x0, y0) = (uc * unit_w, ur * unit_h);
19148 let us = grid_unit_state(&u_grid, bw, x0, y0, unit_w, unit_h);
19149 let vs = grid_unit_state(&v_grid, bw, x0, y0, unit_w, unit_h);
19150 for cell in 0..uh_cells {
19151 if lmi.0 + ur * uh_cells + cell < neighbours.mi_rows {
19152 neighbours.left[lmi.0 + ur * uh_cells + cell][1] = us;
19153 neighbours.left[lmi.0 + ur * uh_cells + cell][2] = vs;
19154 }
19155 }
19156 for cell in 0..uw_cells {
19157 if lmi.1 + uc * uw_cells + cell < neighbours.mi_cols {
19158 neighbours.above[lmi.1 + uc * uw_cells + cell][1] = us;
19159 neighbours.above[lmi.1 + uc * uw_cells + cell][2] = vs;
19160 }
19161 }
19162 }
19163 }
19164 Ok((u_grid, v_grid, unit_w, unit_h))
19165}
19166
19167/// [`neighbour_state`] over one `(unit_w x unit_h)` transform unit at offset
19168/// `(x0, y0)` inside a `bw`-wide assembled chroma grid -- the per-unit stamp
19169/// the rect arms need when a leaf carries more than one unit.
19170fn grid_unit_state(grid: &Grid, bw: usize, x0: usize, y0: usize, unit_w: usize, unit_h: usize) -> Neighbour {
19171 let mut cul = 0u32;
19172 let mut dc = None;
19173 for r in 0..unit_h {
19174 for c in 0..unit_w {
19175 let v = grid[(y0 + r) * bw + x0 + c];
19176 cul += v.unsigned_abs();
19177 if r == 0 && c == 0 && v != 0 {
19178 dc = Some(v < 0);
19179 }
19180 }
19181 }
19182 if cul == 0 {
19183 return Neighbour::default();
19184 }
19185 Neighbour { level: cul.min(7) as u8, dc }
19186}
19187
19188
19189/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
19190/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
19191/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
19192/// bookkeeping needs no change. Each leaf reads its own luma mode info,
19193/// neighboured off the *previously decoded leaf in this same group* on
19194/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
19195/// pattern, one level deeper); chroma is read and reconstructed exactly
19196/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
19197/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
19198/// derivation.
19199#[allow(clippy::too_many_arguments)]
19200fn decode_leaf_split4(
19201 dec: &mut SymbolDecoder,
19202 cdfs: &mut Cdfs,
19203 neighbours: &mut Neighbours,
19204 outer_at: (usize, usize),
19205 leaf_mi: (usize, usize),
19206 scan4: &[u16],
19207 prev_leaf: Option<((usize, usize), usize)>,
19208 y: &mut PlaneBuf<'static>,
19209 u: &mut PlaneBuf<'static>,
19210 v: &mut PlaneBuf<'static>,
19211 base_q_idx: u8,
19212 enable_filter_intra: bool,
19213 allow_intrabc: bool,
19214 reduced_tx_set: bool,
19215 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
19216 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
19217 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx
19218 fctx: &crate::decode::FrameCtx,
19219) -> Result<(usize, usize)> {
19220 hit!(SUB8_SPLIT_HITS);
19221 let (r, c) = outer_at;
19222 let mut above_mode = neighbours.above_mode[c];
19223 let mut left_mode = neighbours.left_mode[r];
19224 if let Some(((pr, pc), pmode)) = prev_leaf {
19225 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
19226 above_mode = pmode;
19227 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
19228 left_mode = pmode;
19229 }
19230 }
19231 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
19232 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
19233 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
19234 let mut leaf_modes = [0usize; 4];
19235 let mut leaf_skips = [false; 4];
19236 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
19237 // lane-av1txr: the chroma-reference (i==3) leaf's block vector when that
19238 // leaf is an intrabc block -- its prediction/reconstruction below is a
19239 // frame copy at this DV, not an intra one.
19240 let mut last_intrabc: Option<(i32, i32)> = None;
19241 // 4:4:4 (lane-av1-444): `is_chroma_reference` (av1_common_int.h:1459) is
19242 // unconditional at subsampling 0/0, so EVERY 4x4 leaf reads its own
19243 // `uv_mode` and codes its own full-resolution 4x4 chroma unit right
19244 // after its luma -- there is no shared group unit at all.
19245 let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
19246 // The last leaf's own `uv_predict_mode`, for the coarse above/left slots
19247 // the 4:2:0 tail fills from the group's single unit.
19248 let mut last_uv444 = DC_PRED;
19249 for i in 0..4usize {
19250 let (dr, dc) = (i / 2, i % 2);
19251 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
19252 // Neighbour modes at real mi granularity: inside the group the
19253 // sibling leaf, outside it the split-leaf map when the adjacent mi
19254 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
19255 // `sub8_mode_col`'s doc).
19256 let leaf_above = if dr == 0 {
19257 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
19258 } else {
19259 leaf_modes[i - 2]
19260 };
19261 let leaf_left = if dc == 0 {
19262 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
19263 } else {
19264 leaf_modes[i - 1]
19265 };
19266 let has_chroma = chroma_444 || i == 3;
19267 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
19268 let (skip, mode, angle_delta_y, chroma, filter_intra, intrabc) = read_intra_mode_sub8(
19269 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
19270 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
19271 skip_ctx, allow_intrabc, lmi.0, lmi.1, 1, 1, fctx,
19272 )?;
19273 leaf_modes[i] = mode;
19274 leaf_skips[i] = skip;
19275 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
19276 // lane-av1txr: libaom `parse_decode_block`'s `set_txfm_ctxs` for this
19277 // `BLOCK_4X4` leaf -- EVERY block publishes its transform size into
19278 // the TXFM context bands, and an intrabc block's later `txfm_split`
19279 // context is read off them (`txfm_partition_context`). A 4x4 never
19280 // signals a tx size, so it is always TX_4X4 (`set_txfm_ctxs`'s
19281 // `skip && is_inter` branch writes the block's own 4 pixels -- the
19282 // same value).
19283 set_txfm_ctxs(neighbours, lmi, 4, 1, 1, false);
19284 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
19285 if smooth_neighbor {
19286 hit!(SMOOTH_LUMA_HITS);
19287 }
19288 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
19289 let reach = Reach::of(4, px, py, y.width, y.height, fctx);
19290 if let Some(dv) = intrabc {
19291 // lane-av1txr: an intrabc `BLOCK_4X4` leaf -- prediction is the
19292 // CURRENT frame at the block vector (`predict_inter_block`'s
19293 // intrabc arm, spec 7.11.3.4), residual the INTER coefficient set
19294 // (libaom reads `tx_type` off `inter_ext_tx_cdf` for
19295 // `is_inter_block`, which counts intrabc). Published into
19296 // `intrabc_dv` so the group's chroma arm (below, when the
19297 // chroma-reference leaf is the intrabc one) and
19298 // [`record_intrabc_mi`] see it.
19299 flush_recon(fctx, y, u, v);
19300 let mut yb = vec![0u16; 16];
19301 mc::predict_with_filter(
19302 &y.data, y.width, y.true_width, y.true_height,
19303 mv_to_q4(px, dv.1, 0), mv_to_q4(py, dv.0, 0),
19304 4, 4, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
19305 );
19306 set_palette_pred(yb.clone(), fctx);
19307 if skip {
19308 push_intra(0, px, py, 4, DC_PRED, 0, reach, &ZERO_RESIDUAL[..16], None, None, smooth_neighbor, fctx);
19309 neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]);
19310 } else {
19311 let tu_around = neighbours.around_mi(lmi, 4)[0];
19312 let tu_grid = read_plane(
19313 dec,
19314 cdfs,
19315 if reduced_tx_set { TxbSet::Luma4Inter } else { TxbSet::Luma4InterSet1 },
19316 scan4,
19317 0,
19318 tu_around,
19319 DC_PRED,
19320 DC_PRED,
19321 0,
19322 reach,
19323 y,
19324 px,
19325 py,
19326 4,
19327 4,
19328 base_q_idx,
19329 None,
19330 None,
19331 None,
19332 smooth_neighbor, fctx,
19333 )?;
19334 neighbours.record_mi_luma(lmi, 4, &tu_grid);
19335 }
19336 neighbours.fill_skip_grid(lmi, 1, skip);
19337 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
19338 record_intrabc_mi(lmi.0, lmi.1, 1, Some(dv), neighbours, fctx);
19339 if has_chroma {
19340 // An intrabc block is an INTER block for `av1_get_tx_type`, so
19341 // the chroma inherits the LUMA's coded transform type
19342 // (`xd->tx_type_map` at the co-located luma position) -- the
19343 // luma `read_plane` above just set [`LUMA_TX_TYPE`]. Armed for
19344 // exactly this leaf's two chroma reads.
19345 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
19346 if chroma_444 {
19347 // lane-av1-444: this leaf codes its OWN 4x4 chroma unit
19348 // right here (frame copy at the DV); no group tail.
19349 sub8_leaf_chroma444(
19350 dec, cdfs, neighbours, lmi, 4, 4, DC_PRED, None, skip,
19351 Some(dv), y, u, v, scan4, base_q_idx,
19352 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx,
19353 )?;
19354 last_uv444 = DC_PRED;
19355 } else {
19356 last_uv = Some((DC_PRED, 0, None));
19357 // lane-av1txbands: the group's chroma is the CHROMA-REFERENCE
19358 // leaf's own block -- libaom codes one chroma unit under the
19359 // last sub-block only (`is_chroma_reference`), so its prediction
19360 // is that leaf's `uv_mode` (CfL alpha and all) unless THAT leaf
19361 // is the intrabc one. Arming this from a non-chroma-reference
19362 // leaf's DV made `warped.obu`'s 8x8 group at mi(40,62) copy
19363 // frame bytes at mi(41,62)'s vector where aomdec predicts
19364 // `uv_mode=UV_CFL_PRED`: luma stayed byte-exact and only chroma
19365 // moved (class chroma-keyed-at-a-non-chroma-leaf). Mirrors
19366 // [`decode_leaf_rect8`]'s own placement.
19367 last_intrabc = Some(dv);
19368 }
19369 }
19370 continue;
19371 }
19372 if skip {
19373 push_intra(0, px, py, 4, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..16], None, filter_intra, smooth_neighbor, fctx);
19374 neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]);
19375 } else {
19376 let tu_around = neighbours.around_mi(lmi, 4)[0];
19377 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
19378 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
19379 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
19380 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
19381 // off the wrong CDF on the very first leaf and desynced the tile.
19382 let tu_grid = read_plane(
19383 dec,
19384 cdfs,
19385 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
19386 scan4,
19387 0,
19388 tu_around,
19389 mode,
19390 mode,
19391 angle_delta_y,
19392 reach,
19393 y,
19394 px,
19395 py,
19396 4,
19397 4,
19398 base_q_idx,
19399 None,
19400 filter_intra,
19401 None,
19402 smooth_neighbor, fctx,
19403 )?;
19404 neighbours.record_mi_luma(lmi, 4, &tu_grid);
19405 }
19406 neighbours.fill_skip_grid(lmi, 1, skip);
19407 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
19408 if has_chroma {
19409 if chroma_444 {
19410 // lane-av1-444: the leaf's own 4x4 chroma unit, coded right
19411 // after its luma (no shared group unit at ss 0/0).
19412 let (uv_mode, _, alpha) =
19413 chroma.expect("4:4:4 reads uv_mode on every leaf");
19414 sub8_leaf_chroma444(
19415 dec, cdfs, neighbours, lmi, 4, 4, uv_mode, alpha, skip,
19416 None, y, u, v, scan4, base_q_idx,
19417 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx,
19418 )?;
19419 last_uv444 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
19420 } else {
19421 last_uv = chroma;
19422 }
19423 }
19424 }
19425 // lane-av1mono: as [`decode_leaf_rect8`] -- a monochrome frame has no
19426 // chroma to reconstruct and no uv_mode was read.
19427 let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) {
19428 (Grid::Zero(16), Grid::Zero(16))
19429 } else if chroma_444 {
19430 // lane-av1-444: every leaf coded and reconstructed its own chroma in
19431 // the loop above ([`sub8_leaf_chroma444`] stamped the mi-exact maps
19432 // and per-leaf entropy state); only the coarse slots remain, filled
19433 // from the bottom-right leaf like the 4:2:0 tail's single unit.
19434 neighbours.above_uv_mode[c] = last_uv444;
19435 neighbours.left_uv_mode[r] = last_uv444;
19436 (Grid::Zero(16), Grid::Zero(16))
19437 } else {
19438 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
19439 let (cpx, cpy) = (gpx >> ss_x(fctx), gpy >> ss_y(fctx));
19440 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
19441 let (uv_mode, angle_delta_uv, alpha) =
19442 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
19443 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
19444 neighbours.above_uv_mode[c] = uv_predict_mode;
19445 neighbours.left_uv_mode[r] = uv_predict_mode;
19446 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
19447 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[3] {
19448 // A skipped chroma block still gets its CfL contribution: libaom's
19449 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
19450 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
19451 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
19452 // added -- `skip_txfm` only drops the residual, never the alpha.
19453 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
19454 // merge keeps one fix and feeds both lanes' counters so neither of
19455 // their gates goes vacuous.
19456 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
19457 if alpha.is_some() {
19458 hit!(CHROMA_SKIP_CFL_HITS);
19459 hit!(SKIP_CFL_HITS);
19460 }
19461 push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx);
19462 push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx);
19463 // lane-av1txbands: a SKIPPED chroma-reference leaf reads no chroma
19464 // coefficient, so it never consults the inherited luma transform type
19465 // -- but an intrabc chroma-reference leaf did arm
19466 // [`INTRABC_CHROMA_TX`] above (`has_chroma`), and the two coefficient
19467 // branches below are the only ones that disarm it. Left armed, the slot
19468 // picks the NEXT block's chroma scan and inverse transform (class
19469 // arm-without-clear-on-a-skip-route). Counted so a gate can tell a
19470 // stream that reaches this route from one that never does.
19471 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
19472 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
19473 fctx.intrabc_chroma_tx.with(|c| c.set(None));
19474 }
19475 (Grid::Zero(16), Grid::Zero(16))
19476 } else if let Some(dv) = last_intrabc {
19477 // lane-av1txr: the chroma-reference leaf was an intrabc block, so the
19478 // group's one chroma unit is a frame copy at that DV too (its residual
19479 // still reads the ordinary `Chroma4` coefficient tables -- libaom
19480 // codes a chroma `tx_type` nowhere).
19481 let mut ub = vec![0u16; 16];
19482 mc::predict_with_filter(
19483 &u.data, u.width, u.true_width, u.true_height,
19484 mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_x(fctx)),
19485 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
19486 );
19487 let mut vb = vec![0u16; 16];
19488 mc::predict_with_filter(
19489 &v.data, v.width, v.true_width, v.true_height,
19490 mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_x(fctx)),
19491 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
19492 );
19493 let chroma_around = neighbours.around_mi(leaf_mi, 8);
19494 set_palette_pred(ub, fctx);
19495 let ug = read_plane(
19496 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], DC_PRED, DC_PRED,
19497 0, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
19498 None, None, None, smooth_neighbor_uv, fctx,
19499 )?;
19500 set_palette_pred(vb, fctx);
19501 let vg = read_plane(
19502 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], DC_PRED, DC_PRED,
19503 0, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
19504 None, None, None, smooth_neighbor_uv, fctx,
19505 )?;
19506 fctx.intrabc_chroma_tx.with(|c| c.set(None));
19507 (ug, vg)
19508 } else {
19509 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
19510 let chroma_around = neighbours.around_mi(leaf_mi, 8);
19511 let ug = read_plane(
19512 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
19513 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
19514 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
19515 )?;
19516 let vg = read_plane(
19517 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
19518 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
19519 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
19520 )?;
19521 (ug, vg)
19522 };
19523 (u_grid, v_grid)
19524 };
19525 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
19526 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
19527 // rescaling is wrong for an already-mi-unit position, so this inlines
19528 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
19529 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
19530 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
19531 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
19532 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
19533 // bottom). libaom's `update_ext_partition_context` writes
19534 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
19535 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
19536 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
19537 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
19538 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
19539 // round's bug) makes the very next sibling 8x8's `partition_w8` read
19540 // with the wrong context and desync immediately.
19541 let side_mi = 2;
19542 for cell in 0..side_mi {
19543 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
19544 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
19545 }
19546 // lane-av1-444: at 4:4:4 [`sub8_leaf_chroma444`] already stamped each
19547 // leaf's own span as it decoded; these placeholder grids carry no state.
19548 if !chroma_444 {
19549 let round_up_even = |n: usize| n.div_ceil(2) * 2;
19550 let bound_h = round_up_even(neighbours.mi_rows);
19551 let bound_w = round_up_even(neighbours.mi_cols);
19552 let u_state = neighbour_state(&u_grid);
19553 let v_state = neighbour_state(&v_grid);
19554 for cell in 0..side_mi {
19555 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
19556 neighbours.left[leaf_mi.0 + cell][1] = u_state;
19557 neighbours.left[leaf_mi.0 + cell][2] = v_state;
19558 }
19559 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
19560 neighbours.above[leaf_mi.1 + cell][1] = u_state;
19561 neighbours.above[leaf_mi.1 + cell][2] = v_state;
19562 }
19563 }
19564 }
19565 // lane-dkey: a sub-8x8 leaf can never use palette (`av1_allow_palette`
19566 // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its
19567 // `palette_size` is 0 in every one of these mi cells, so the NEXT block's
19568 // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder
19569 // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette
19570 // block above a 4x4 group left its size/colours standing in the mi-granular
19571 // bands: the block below the group read `palette_y_mode` off CDF row 1
19572 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a
19573 // palette libaom never coded, and then skipped the `use_filter_intra`
19574 // symbol that a palette block has none of -- one symbol short, tile
19575 // desynced. Publishing the group's own zeros is the clear.
19576 neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
19577 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
19578 Ok((leaf_modes[2], leaf_modes[1]))
19579}
19580
19581/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
19582/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
19583/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
19584/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
19585/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
19586/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
19587/// every sub-block one mi wide or high but the last) -- differing only where
19588/// the shape does:
19589///
19590/// * the transform is a true `TX_4X8`/`TX_8X4`
19591/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
19592/// `av1_inv_txfm_shift_ls` row already cover this size pair);
19593/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
19594/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
19595/// row -- see that variant's doc comment;
19596/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
19597/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
19598/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
19599/// ([`Reach::of_rect`]);
19600/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
19601/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
19602/// `BLOCK_4X4` split writes.
19603///
19604/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
19605/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
19606/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
19607/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
19608/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
19609/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
19610#[allow(clippy::too_many_arguments)]
19611fn decode_leaf_rect8(
19612 dec: &mut SymbolDecoder,
19613 cdfs: &mut Cdfs,
19614 neighbours: &mut Neighbours,
19615 outer_at: (usize, usize),
19616 leaf_mi: (usize, usize),
19617 vert: bool,
19618 scan4: &[u16],
19619 y: &mut PlaneBuf<'static>,
19620 u: &mut PlaneBuf<'static>,
19621 v: &mut PlaneBuf<'static>,
19622 base_q_idx: u8,
19623 enable_filter_intra: bool,
19624 allow_intrabc: bool,
19625 tx_select: bool,
19626 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
19627) -> Result<(usize, usize)> {
19628 let (r, c) = outer_at;
19629 // lane-modectx r1: availability-correct fallback pair (see
19630 // `modes_above_left`), not the raw coarse bands.
19631 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
19632 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
19633 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
19634 let (w_mi, h_mi) = (bw / MI, bh / MI);
19635 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
19636 let mut leaf_modes = [0usize; 2];
19637 let mut leaf_skips = [false; 2];
19638 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
19639 // lane-av1txr: as [`decode_leaf_split4`]'s own `last_intrabc`.
19640 let mut last_intrabc: Option<(i32, i32)> = None;
19641 // 4:4:4 (lane-av1-444): as [`decode_leaf_split4`] -- at subsampling 0/0
19642 // EVERY 4x8/8x4 leaf reads its own `uv_mode` and codes its own
19643 // full-resolution rect chroma unit right after its luma.
19644 let chroma_444 = ss_x(fctx) == 0 && ss_y(fctx) == 0;
19645 let mut last_uv444 = DC_PRED;
19646 for i in 0..2usize {
19647 let lmi = if vert {
19648 (leaf_mi.0, leaf_mi.1 + i)
19649 } else {
19650 (leaf_mi.0 + i, leaf_mi.1)
19651 };
19652 // Inside the pair the sibling is the neighbour on the split axis;
19653 // outside it the mi-granular map, else the coarse 16x16 slot.
19654 let leaf_above = if !vert && i == 1 {
19655 leaf_modes[0]
19656 } else {
19657 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
19658 };
19659 let leaf_left = if vert && i == 1 {
19660 leaf_modes[0]
19661 } else {
19662 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
19663 };
19664 let has_chroma = chroma_444 || i == 1;
19665 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
19666 let (skip, mode, angle_delta_y, chroma, filter_intra, intrabc) = read_intra_mode_sub8(
19667 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
19668 filter_intra_size_class_rect(bw, bh)
19669 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
19670 skip_ctx, allow_intrabc, lmi.0, lmi.1, bw / 4, bh / 4, fctx,
19671 )?;
19672 leaf_modes[i] = mode;
19673 leaf_skips[i] = skip;
19674 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
19675 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
19676 if let Some(dv) = intrabc {
19677 // lane-av1txr: an intrabc `BLOCK_4X8`/`BLOCK_8X4` leaf. The
19678 // prediction is a frame copy at the DV and the residual reads the
19679 // INTER `LumaRect8x4` set -- but with `TxMode::Select` the leaf
19680 // reads the INTER var-tx tree, exactly like every other intrabc
19681 // block: libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`
19682 // (`blockd.h:1027`), TRUE at `BLOCK_4X8`/`BLOCK_8X4`, so
19683 // `parse_decode_block` sends an unskipped `inter_block_tx` block
19684 // (intrabc counts, `is_inter_block`) of a signalling bsize into
19685 // `read_tx_size_vartx` over `max_txsize_rect_lookup[BLOCK_4X8] ==
19686 // TX_4X8`; only `BLOCK_4X4` reads no tx symbol at all. Measured on
19687 // `warped.obu` mi (37,62): reading NO symbol here left the
19688 // arithmetic decoder one symbol short and desynced the very next
19689 // block's `skip` (ours 60320 vs aomdec 48630, class
19690 // `symbol-consumption-gap`).
19691 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
19692 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
19693 flush_recon(fctx, y, u, v);
19694 let mut luma_leaves: Vec<(usize, usize, usize, usize)> = Vec::new();
19695 if tx_select && !skip {
19696 // `max_block_wide`/`max_block_high`: the frame's own mi grid,
19697 // so a leaf hanging over the right/bottom edge reads no split
19698 // symbol for the units outside it (as in `decode_block`).
19699 let mi_cols = 2 * y.true_width.div_ceil(8);
19700 let mi_rows = 2 * y.true_height.div_ceil(8);
19701 let max_w_mi = w_mi.min(mi_cols.saturating_sub(lmi.1));
19702 let max_h_mi = h_mi.min(mi_rows.saturating_sub(lmi.0));
19703 read_var_tx_size(
19704 dec,
19705 cdfs,
19706 neighbours,
19707 lmi,
19708 bw.max(bh),
19709 (max_w_mi, max_h_mi),
19710 (bw, bh),
19711 0,
19712 0,
19713 0,
19714 &mut luma_leaves,
19715 );
19716 hit!(RECT_INTRABC_VARTX_HITS);
19717 } else {
19718 luma_leaves.push((0, 0, bw, bh));
19719 // The non-var-tx arm: a SKIPPED intrabc leaf (or a frame
19720 // outside `TxMode::Select`) publishes its own rect transform
19721 // (`set_txfm_ctxs`'s `skip && is_inter` branch writes the
19722 // block's own pixels -- the same size here).
19723 txfm_partition_update_rect(neighbours, lmi, (bw, bh), (bw, bh));
19724 }
19725 // The transform type an intrabc block's CHROMA inherits is the
19726 // `tx_type_map` entry at the chroma unit's co-located luma
19727 // position (`av1_get_tx_type`, `blockd.h:1278`), i.e. the FIRST
19728 // luma unit the tree resolved.
19729 let single = luma_leaves.len() == 1;
19730 let mut chroma_tx = TxType::DctDct;
19731 let mut grid = Grid::Zero(bw * bh);
19732 for (li, &(tu_row, tu_col, tw, th)) in luma_leaves.iter().enumerate() {
19733 let tu_mi = (lmi.0 + tu_row, lmi.1 + tu_col);
19734 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
19735 let tu_reach = if single {
19736 reach
19737 } else {
19738 tu_reach(
19739 bw, bh, tu_px - px, tu_py - py, tw, reach, px, py, y.width, y.height, fctx,
19740 )
19741 };
19742 let mut yb = vec![0u16; tw * th];
19743 mc::predict_with_filter(
19744 &y.data, y.width, y.true_width, y.true_height,
19745 mv_to_q4(tu_px, dv.1, 0), mv_to_q4(tu_py, dv.0, 0),
19746 tw, th, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
19747 );
19748 set_palette_pred(yb, fctx);
19749 let tu_grid = if skip {
19750 let zeros = Grid::Zero(tw * th);
19751 if (tw, th) == (4, 4) {
19752 push_intra(0, tu_px, tu_py, 4, DC_PRED, 0, tu_reach, &zeros, None, None, smooth_neighbor, fctx);
19753 } else {
19754 push_intra_rect(0, tu_px, tu_py, tw, th, DC_PRED, 0, tu_reach, &zeros, None, None, smooth_neighbor, fctx);
19755 }
19756 zeros
19757 } else {
19758 // A unit smaller than its own block (the var-tx split)
19759 // reads its `txb_skip_ctx` off the neighbours; the
19760 // whole-leaf unit's `plane_bsize == txsize_to_bsize` fixes
19761 // it at 0.
19762 let (set, tu_scan, around, skip_ctx) = if (tw, th) == (4, 4) {
19763 (
19764 inter_txbset_for(4, reduced_tx_set),
19765 scan4,
19766 neighbours.around_mi(tu_mi, 4)[0],
19767 neighbours.luma_skip_ctx(tu_mi, 1),
19768 )
19769 } else {
19770 (
19771 if reduced_tx_set {
19772 TxbSet::LumaRect8x4Inter
19773 } else {
19774 TxbSet::LumaRect8x4InterSet1
19775 },
19776 scan,
19777 neighbours.around_mi_rect(tu_mi, tw, th)[0],
19778 0,
19779 )
19780 };
19781 let mut coding = cdfs.txb(set, DC_PRED);
19782 let (levels, tx_type) = read_coeffs_rect(
19783 dec, &mut coding, tu_scan, tw, th, skip_ctx, dc_sign_ctx(around.2),
19784 TxType::DctDct,
19785 )?;
19786 if li == 0 {
19787 chroma_tx = tx_type;
19788 fctx.luma_tx_type.with(|c| c.set(tx_type));
19789 }
19790 let residual = dequant_and_inverse_typed_wh(
19791 &levels, tw, th, crate::decode::bit_depth(fctx), block_q_idx(fctx),
19792 plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tx_type,
19793 block_iqmatrix(fctx, 0, tw, th, tx_type),
19794 );
19795 if (tw, th) == (4, 4) {
19796 push_intra(0, tu_px, tu_py, 4, DC_PRED, 0, tu_reach, &residual, None, None, smooth_neighbor, fctx);
19797 } else {
19798 push_intra_rect(0, tu_px, tu_py, tw, th, DC_PRED, 0, tu_reach, &residual, None, None, smooth_neighbor, fctx);
19799 }
19800 levels
19801 };
19802 if single {
19803 grid = tu_grid;
19804 } else {
19805 // Per-unit neighbour state, the same shape the intra rect
19806 // leaf's own split path runs (`decode_leaf8`'s depth-1
19807 // loop): a transform unit inside a block is not a block at
19808 // that position.
19809 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
19810 }
19811 }
19812 if single {
19813 let state = neighbour_state(&grid);
19814 for cell in 0..h_mi {
19815 if lmi.0 + cell < neighbours.mi_rows {
19816 neighbours.left[lmi.0 + cell][0] = state;
19817 }
19818 }
19819 for cell in 0..w_mi {
19820 if lmi.1 + cell < neighbours.mi_cols {
19821 neighbours.above[lmi.1 + cell][0] = state;
19822 }
19823 }
19824 }
19825 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
19826 neighbours.fill_lf_grid_rect(
19827 lmi,
19828 w_mi,
19829 h_mi,
19830 if single { bw as u8 } else { 4 },
19831 if single { bh as u8 } else { 4 },
19832 0,
19833 fctx,
19834 );
19835 // `record_intrabc_mi` publishes a square `n4`x`n4` footprint; a
19836 // 4x8/8x4 leaf needs its true `w_mi`x`h_mi` (lane-av1txr).
19837 record_intrabc_mi_rect(lmi.0, lmi.1, w_mi, h_mi, Some(dv), neighbours, fctx);
19838 if has_chroma {
19839 // See [`decode_leaf_split4`]: an intrabc block's chroma
19840 // inherits the luma transform type.
19841 fctx.intrabc_chroma_tx.with(|c| c.set(Some(chroma_tx)));
19842 if chroma_444 {
19843 // lane-av1-444: this leaf codes its OWN rect chroma unit
19844 // right here (frame copy at the DV); no group tail.
19845 sub8_leaf_chroma444(
19846 dec, cdfs, neighbours, lmi, bw, bh, DC_PRED, None, skip,
19847 Some(dv), y, u, v, scan4, base_q_idx,
19848 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx,
19849 )?;
19850 last_uv444 = DC_PRED;
19851 } else {
19852 last_uv = Some((DC_PRED, 0, None));
19853 last_intrabc = Some(dv);
19854 }
19855 }
19856 continue;
19857 }
19858 if filter_intra.is_some() {
19859 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
19860 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
19861 // same `reconstruct_rect`/`reconstruct` calls below -- and under
19862 // a split transform, per 4x4 unit with that unit's own edge,
19863 // which is exactly what the depth-1 loop already does.
19864 hit!(FILTER_INTRA_RECT_HITS);
19865 hit!(FILTER_INTRA_RECT_SUB8_HITS);
19866 }
19867 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
19868 // leaf too, and is read for every intra block, skipped or not. Its
19869 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
19870 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
19871 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
19872 // `tx_size_cat2` the 32x16 strips read -- with the rect context
19873 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
19874 // Missing this read consumed one symbol fewer than the encoder wrote
19875 // and desynced the tile at the very first rect leaf (class
19876 // `symbol-consumption-gap`).
19877 // lane-av1mix: libaom `read_tx_size`'s FIRST line
19878 // (`decodeframe.c:1203`, `if (xd->lossless[...]) return TX_4X4`)
19879 // fires before the `TX_MODE_SELECT` test, so a lossless-segment leaf
19880 // codes NO depth symbol even in `TxMode::Select` -- the mixed-lossless
19881 // frame's sub8 leaves forked exactly here (ours read the symbol at
19882 // (12477,50864) bit 3011, the oracle's all_zero used it).
19883 let depth = if tx_select && !lossless(fctx) {
19884 // lane-av1txbands: the `TXFM_CONTEXT` band read every other rect
19885 // reader already does.
19886 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
19887 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
19888 } else {
19889 0
19890 };
19891 if depth != 0 {
19892 hit!(TX_DEPTH_HITS);
19893 hit!(RECT8_SPLIT_TX_HITS);
19894 }
19895 if smooth_neighbor {
19896 hit!(SMOOTH_LUMA_HITS);
19897 }
19898 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
19899 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
19900 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
19901 // two 4x4 transform units along its long axis, each predicted from
19902 // the previous unit's reconstruction and reading its own `txb_skip`
19903 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
19904 // four. The per-TU path writes its own neighbour state, so the
19905 // block-level write below is skipped for it.
19906 let split = depth != 0 || lossless(fctx);
19907 // lane-av1txr: libaom `parse_decode_block`'s `set_txfm_ctxs` for this
19908 // leaf -- the size the `tx_depth` symbol resolved (depth 1 -> TX_4X4,
19909 // else the leaf's own rect transform), published over the leaf's own
19910 // mi span. An intrabc block's `txfm_partition_context` reads these
19911 // bands, and the key-frame sub-8x8 leaves had no write at all:
19912 // `warped.obu` mi (37,62) read a stale 8 where aomdec read 4 (ctx 18
19913 // vs 19) and the tile desynced (class `context-band-not-published`).
19914 let (ctx_tx_w, ctx_tx_h) = if split { (4, 4) } else { (bw, bh) };
19915 txfm_partition_update_rect(neighbours, lmi, (ctx_tx_w, ctx_tx_h), (bw, bh));
19916 if split {
19917 let mut done = 0usize;
19918 for tu in 0..2usize {
19919 let tu_mi = if vert {
19920 (lmi.0 + tu, lmi.1)
19921 } else {
19922 (lmi.0, lmi.1 + tu)
19923 };
19924 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
19925 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
19926 // Same per-TU rule as every other split-transform site
19927 // (lane-palette2 r12): a transform unit inside a block is not
19928 // a block at that position, so its reach comes from the
19929 // block's own row, offset by the unit's position.
19930 let tu_reach = tu_reach(
19931 bw,
19932 bh,
19933 tu_px - px,
19934 tu_py - py,
19935 4,
19936 reach,
19937 px,
19938 py,
19939 y.width,
19940 y.height, fctx,
19941 );
19942 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
19943 if skip {
19944 // A skipped leaf still predicts per transform unit: the
19945 // second 4x4 takes its above/left edge from the first
19946 // one's reconstruction, which is NOT what a single 4x8
19947 // prediction of the same mode produces.
19948 let zeros = vec![0i32; 16];
19949 push_intra(0,
19950 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
19951 filter_intra, smooth_neighbor, fctx,
19952 );
19953 neighbours.record_mi_luma(tu_mi, 4, &zeros);
19954 continue;
19955 }
19956 let tu_grid = read_plane(
19957 dec,
19958 cdfs,
19959 if reduced_tx_set {
19960 TxbSet::Luma4
19961 } else {
19962 TxbSet::Luma4Set1
19963 },
19964 scan4,
19965 0,
19966 tu_around,
19967 mode,
19968 mode,
19969 angle_delta_y,
19970 tu_reach,
19971 y,
19972 tu_px,
19973 tu_py,
19974 4,
19975 TX4,
19976 base_q_idx,
19977 None,
19978 filter_intra,
19979 Some(tu_skip_ctx),
19980 smooth_neighbor, fctx,
19981 )?;
19982 if tu_grid.iter().any(|&l| l != 0) {
19983 done += 1;
19984 }
19985 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
19986 }
19987 if done > 0 {
19988 if vert {
19989 hit!(TX4X8_CODED_HITS);
19990 } else {
19991 hit!(TX8X4_CODED_HITS);
19992 }
19993 }
19994 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
19995 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0, fctx);
19996 if has_chroma {
19997 if chroma_444 {
19998 // lane-av1-444: the leaf's own rect chroma unit after its
19999 // split luma (no shared group unit at ss 0/0).
20000 let (uv_mode, _, alpha) =
20001 chroma.expect("4:4:4 reads uv_mode on every leaf");
20002 sub8_leaf_chroma444(
20003 dec, cdfs, neighbours, lmi, bw, bh, uv_mode, alpha, skip,
20004 None, y, u, v, scan4, base_q_idx,
20005 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx,
20006 )?;
20007 last_uv444 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
20008 } else {
20009 last_uv = chroma;
20010 }
20011 }
20012 continue;
20013 }
20014 let grid = if skip {
20015 let zeros = Grid::Zero(bw * bh);
20016 push_intra_rect(0,
20017 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
20018 smooth_neighbor, fctx,
20019 );
20020 zeros
20021 } else {
20022 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
20023 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
20024 // at 0 -- see `decode_leaf_split4`'s own note.
20025 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
20026 let set = if reduced_tx_set {
20027 TxbSet::LumaRect4x8
20028 } else {
20029 TxbSet::LumaRect4x8Set1
20030 };
20031 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
20032 let (levels, tx_type) = read_coeffs_rect(
20033 dec,
20034 &mut coding,
20035 scan,
20036 bw,
20037 bh,
20038 0,
20039 dc_sign_ctx(around.2),
20040 TxType::DctDct,
20041 )?;
20042 if levels.iter().any(|&l| l != 0) {
20043 if vert {
20044 hit!(TX4X8_CODED_HITS);
20045 } else {
20046 hit!(TX8X4_CODED_HITS);
20047 }
20048 }
20049 let residual = dequant_and_inverse_typed_wh(
20050 &levels,
20051 bw,
20052 bh,
20053 crate::decode::bit_depth(fctx),
20054 // lane-d792 sweep: the block's segment `SEG_LVL_ALT_Q`, as at
20055 // every other dequant site (class `parsed-then-discarded`).
20056 block_q_idx(fctx),
20057 plane_q_delta(0, fctx).0,
20058 plane_q_delta(0, fctx).1,
20059 tx_type,
20060 block_iqmatrix(fctx, 0, bw, bh, tx_type),
20061 );
20062 push_intra_rect(0,
20063 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
20064 smooth_neighbor, fctx,
20065 );
20066 levels
20067 };
20068 // Plane 0's per-TU coefficient context over this leaf's own mi span
20069 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
20070 // for the whole 8x8 group below).
20071 let state = neighbour_state(&grid);
20072 for cell in 0..h_mi {
20073 if lmi.0 + cell < neighbours.mi_rows {
20074 neighbours.left[lmi.0 + cell][0] = state;
20075 }
20076 }
20077 for cell in 0..w_mi {
20078 if lmi.1 + cell < neighbours.mi_cols {
20079 neighbours.above[lmi.1 + cell][0] = state;
20080 }
20081 }
20082 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
20083 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
20084 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0, fctx);
20085 if has_chroma {
20086 if chroma_444 {
20087 // lane-av1-444: the leaf's own rect chroma unit after its
20088 // luma (no shared group unit at ss 0/0).
20089 let (uv_mode, _, alpha) =
20090 chroma.expect("4:4:4 reads uv_mode on every leaf");
20091 sub8_leaf_chroma444(
20092 dec, cdfs, neighbours, lmi, bw, bh, uv_mode, alpha, skip,
20093 None, y, u, v, scan4, base_q_idx,
20094 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx,
20095 )?;
20096 last_uv444 = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
20097 } else {
20098 last_uv = chroma;
20099 }
20100 }
20101 }
20102 // lane-av1mono: a monochrome frame codes no chroma at all -- no
20103 // `uv_mode` was read ([`read_intra_mode_sub8`] folds the plane count in),
20104 // so there is no chroma to reconstruct and no chroma coefficient to read.
20105 let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) {
20106 (Grid::Zero(16), Grid::Zero(16))
20107 } else if chroma_444 {
20108 // lane-av1-444: every leaf coded and reconstructed its own chroma in
20109 // the loop above; only the coarse slots remain (last leaf's mode).
20110 neighbours.above_uv_mode[c] = last_uv444;
20111 neighbours.left_uv_mode[r] = last_uv444;
20112 (Grid::Zero(16), Grid::Zero(16))
20113 } else {
20114 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
20115 let (cpx, cpy) = (gpx >> ss_x(fctx), gpy >> ss_y(fctx));
20116 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
20117 let (uv_mode, angle_delta_uv, alpha) =
20118 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
20119 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
20120 neighbours.above_uv_mode[c] = uv_predict_mode;
20121 neighbours.left_uv_mode[r] = uv_predict_mode;
20122 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
20123 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[1] && last_intrabc.is_none() {
20124 // A skipped chroma block still gets its CfL contribution: libaom's
20125 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
20126 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
20127 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
20128 // added -- `skip_txfm` only drops the residual, never the alpha.
20129 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
20130 // merge keeps one fix and feeds both lanes' counters so neither of
20131 // their gates goes vacuous.
20132 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
20133 if alpha.is_some() {
20134 hit!(CHROMA_SKIP_CFL_HITS);
20135 hit!(SKIP_CFL_HITS);
20136 }
20137 push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx);
20138 push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx);
20139 // lane-av1txbands: a SKIPPED chroma-reference leaf reads no chroma
20140 // coefficient, so it never consults the inherited luma transform type
20141 // -- but an intrabc chroma-reference leaf did arm
20142 // [`INTRABC_CHROMA_TX`] above (`has_chroma`), and the two coefficient
20143 // branches below are the only ones that disarm it. Left armed, the slot
20144 // picks the NEXT block's chroma scan and inverse transform (class
20145 // arm-without-clear-on-a-skip-route). Counted so a gate can tell a
20146 // stream that reaches this route from one that never does.
20147 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
20148 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
20149 fctx.intrabc_chroma_tx.with(|c| c.set(None));
20150 }
20151 (Grid::Zero(16), Grid::Zero(16))
20152 } else if let Some(dv) = last_intrabc {
20153 // A 4:2:0 `BLOCK_4X8`/`BLOCK_8X4` leaf maps to a clamped chroma
20154 // `BLOCK_4X4` (`get_plane_block_size`, blockd.h:1184; `set_plane_n4`,
20155 // av1_common_int.h:1344). The chroma reference is still the whole
20156 // 8x8 group's 4x4 plane block at `(cpx, cpy)`, so prediction uses the
20157 // group's destination origin, not the odd-mi leaf's nominal 2x4/4x2
20158 // extent. The old route treated a skipped intrabc leaf as skipped
20159 // intra and predicted this block with DC, first differing at
20160 // mi(46,52), U(104,92), while consuming identical symbols.
20161 // `decode_reconstruct_tx` reads no chroma coefficients for a skipped
20162 // intrabc block, but an unskipped one reads the ordinary Chroma4
20163 // tables; chroma inherits no coded tx_type of its own.
20164 let mut ub = vec![0u16; 16];
20165 mc::predict_with_filter(
20166 &u.data, u.width, u.true_width, u.true_height,
20167 mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_x(fctx)),
20168 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
20169 );
20170 let mut vb = vec![0u16; 16];
20171 mc::predict_with_filter(
20172 &v.data, v.width, v.true_width, v.true_height,
20173 mv_to_q4(cpx, dv.1, ss_x(fctx)), mv_to_q4(cpy, dv.0, ss_x(fctx)),
20174 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
20175 );
20176 if leaf_skips[1] {
20177 // `skip_txfm` still reconstructs an intrabc prediction, but
20178 // libaom's `decode_reconstruct_tx` reads NO chroma coefficients.
20179 // The ordinary skipped-intra arm above is therefore not valid for
20180 // an intrabc leaf: use the copied, clamped 4x4 prediction directly.
20181 push_mc_rect(
20182 1, cpx, cpy, 4, 4, 4, Pred::Inline(&ub, 4),
20183 &ZERO_RESIDUAL[..16], fctx,
20184 );
20185 push_mc_rect(
20186 2, cpx, cpy, 4, 4, 4, Pred::Inline(&vb, 4),
20187 &ZERO_RESIDUAL[..16], fctx,
20188 );
20189 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
20190 fctx.intrabc_chroma_tx.with(|c| c.set(None));
20191 (Grid::Zero(16), Grid::Zero(16))
20192 } else {
20193 let chroma_around = neighbours.around_mi(leaf_mi, 8);
20194 set_palette_pred(ub, fctx);
20195 let ug = read_plane(
20196 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], DC_PRED, DC_PRED,
20197 0, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
20198 None, None, None, smooth_neighbor_uv, fctx,
20199 )?;
20200 set_palette_pred(vb, fctx);
20201 let vg = read_plane(
20202 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], DC_PRED, DC_PRED,
20203 0, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
20204 None, None, None, smooth_neighbor_uv, fctx,
20205 )?;
20206 fctx.intrabc_chroma_tx.with(|c| c.set(None));
20207 (ug, vg)
20208 }
20209 } else {
20210 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
20211 let chroma_around = neighbours.around_mi(leaf_mi, 8);
20212 let ug = read_plane(
20213 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
20214 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
20215 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
20216 )?;
20217 let vg = read_plane(
20218 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
20219 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
20220 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
20221 )?;
20222 (ug, vg)
20223 };
20224 (u_grid, v_grid)
20225 };
20226 // `update_partition_context` at the 8x8 level writes
20227 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
20228 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
20229 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
20230 // `partition_ctx_mi` reads back off these side values.
20231 for cell in 0..2 {
20232 neighbours.above_side_mi[leaf_mi.1 + cell] = bw as u8;
20233 neighbours.left_side_mi[leaf_mi.0 + cell] = bh as u8;
20234 }
20235 // lane-av1-444: at 4:4:4 [`sub8_leaf_chroma444`] already stamped each
20236 // leaf's own span as it decoded; these placeholder grids carry no state.
20237 if !chroma_444 {
20238 let round_up_even = |n: usize| n.div_ceil(2) * 2;
20239 let bound_h = round_up_even(neighbours.mi_rows);
20240 let bound_w = round_up_even(neighbours.mi_cols);
20241 let u_state = neighbour_state(&u_grid);
20242 let v_state = neighbour_state(&v_grid);
20243 for cell in 0..2usize {
20244 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
20245 neighbours.left[leaf_mi.0 + cell][1] = u_state;
20246 neighbours.left[leaf_mi.0 + cell][2] = v_state;
20247 }
20248 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
20249 neighbours.above[leaf_mi.1 + cell][1] = u_state;
20250 neighbours.above[leaf_mi.1 + cell][2] = v_state;
20251 }
20252 }
20253 }
20254 // lane-dkey (same clear as `decode_leaf_split4`): a sub-8x8 leaf can never use palette (`av1_allow_palette`
20255 // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its
20256 // `palette_size` is 0 in every one of these mi cells, so the NEXT block's
20257 // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder
20258 // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette
20259 // block above a 4x4 group left its size/colours standing in the mi-granular
20260 // bands: the block below the group read `palette_y_mode` off CDF row 1
20261 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a
20262 // palette libaom never coded, and then skipped the `use_filter_intra`
20263 // symbol that a palette block has none of -- one symbol short, tile
20264 // desynced. Publishing the group's own zeros is the clear.
20265 neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
20266 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
20267 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
20268 // bottom one (the second under HORZ, the left one under VERT), the one a
20269 // neighbour to the right sees is the top-right (the second under VERT).
20270 Ok(if vert {
20271 (leaf_modes[0], leaf_modes[1])
20272 } else {
20273 (leaf_modes[1], leaf_modes[0])
20274 })
20275}
20276
20277/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
20278/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
20279/// (mod 8) reuse the same table.
20280const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
20281 [(-1, 1), (-2, 2)],
20282 [(0, 1), (-1, 2)],
20283 [(0, 1), (0, 2)],
20284 [(0, 1), (1, 2)],
20285 [(1, 1), (2, 2)],
20286 [(1, 0), (2, 1)],
20287 [(1, 0), (2, 0)],
20288 [(1, 0), (2, -1)],
20289];
20290/// A neighbour tap outside the frame's true extent -- `constrain` reads this
20291/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
20292const CDEF_VERY_LARGE: i32 = 0x4000;
20293const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
20294const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
20295/// lane-av1422filter: libaom `av1_cdef_filter_fb` (cdef_block.c) remaps the
20296/// luma direction before filtering CHROMA whenever `xdec != ydec` — the
20297/// direction grid lives on the subsampled chroma grid, so a direction found
20298/// on the 8x8 luma block means a different line there. `conv422` applies
20299/// under 4:2:2 (`xdec` set), `conv440` under its mirror (not expressible in
20300/// the profiles this decoder accepts, kept for fidelity). 4:2:0 and 4:4:4
20301/// (`xdec == ydec`) take no remap, exactly as before this lane.
20302const CDEF_DIR_CONV422: [usize; 8] = [7, 0, 2, 4, 5, 6, 6, 6];
20303const CDEF_DIR_CONV440: [usize; 8] = [1, 2, 2, 2, 3, 4, 6, 0];
20304
20305fn cdef_msb(x: i32) -> i32 {
20306 31 - x.leading_zeros() as i32
20307}
20308
20309/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
20310/// centre sample a filter tap is allowed to contribute.
20311#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
20312fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
20313 if threshold == 0 {
20314 return 0;
20315 }
20316 cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
20317}
20318
20319/// `constrain`'s damping shift: a function of the block's threshold and
20320/// damping alone, so the filter loop computes it once per block instead of
20321/// the `leading_zeros` + branch it used to do twice per tap read.
20322fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 {
20323 (damping - cdef_msb(threshold)).max(0)
20324}
20325
20326/// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is
20327/// non-zero on every call (the caller only filters when its strength is).
20328fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 {
20329 let a = diff.abs();
20330 diff.signum() * (threshold - (a >> shift)).clamp(0, a)
20331}
20332
20333/// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads
20334/// lies inside its own samples grown by this much.
20335const CDEF_BORDER: usize = 2;
20336
20337/// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the
20338/// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row
20339/// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops
20340/// index a small contiguous window instead of re-deriving the frame-bounds
20341/// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get
20342/// `CDEF_VERY_LARGE`, exactly as the per-sample closure did.
20343fn cdef_gather(
20344 src: &[u16],
20345 stride: usize,
20346 true_w: usize,
20347 true_h: usize,
20348 ox: usize,
20349 oy: usize,
20350 bw: usize,
20351 bh: usize,
20352 buf: &mut [i16],
20353) {
20354 let bstride = bw + 2 * CDEF_BORDER;
20355 let rows = bh + 2 * CDEF_BORDER;
20356 if oy >= CDEF_BORDER
20357 && ox >= CDEF_BORDER
20358 && oy + bh + CDEF_BORDER <= true_h
20359 && ox + bw + CDEF_BORDER <= true_w
20360 {
20361 // Interior block: every tap is inside the frame, so the whole window
20362 // is `rows` contiguous runs.
20363 for r in 0..rows {
20364 let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER);
20365 let src_row = &src[s0..s0 + bstride];
20366 let dst_row = &mut buf[r * bstride..r * bstride + bstride];
20367 for (d, &v) in dst_row.iter_mut().zip(src_row) {
20368 *d = v as i16;
20369 }
20370 }
20371 return;
20372 }
20373 for r in 0..rows {
20374 let ny = oy as isize + r as isize - CDEF_BORDER as isize;
20375 for c in 0..bstride {
20376 let nx = ox as isize + c as isize - CDEF_BORDER as isize;
20377 buf[r * bstride + c] =
20378 if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w {
20379 CDEF_VERY_LARGE as i16
20380 } else {
20381 src[ny as usize * stride + nx as usize] as i16
20382 };
20383 }
20384 }
20385}
20386
20387/// libaom `cdef_find_dir_c`'s eight partial-sum arrays, row at a time: each
20388/// array takes the row, its reverse, its pairwise sums or its total added
20389/// into consecutive slots, so the 512 scalar read-modify-writes on i64 the
20390/// per-sample form did become a handful of lane-wide adds per row. i32 is
20391/// exact here: every partial is a sum of at most eight values in -128..127,
20392/// and slot 15 exists only so an eight-lane store at offset 7 fits.
20393fn cdef_find_dir_partials(win: &[i16], bstride: usize, coeff_shift: i32) -> [[i32; 16]; 8] {
20394 fn add_at<const N: usize>(dst: &mut [i32; 16], off: usize, src: &[i32; N]) {
20395 for (d, &x) in dst[off..off + N].iter_mut().zip(src.iter()) {
20396 *d += x;
20397 }
20398 }
20399 let mut partial = [[0i32; 16]; 8];
20400 for i in 0..8usize {
20401 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
20402 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
20403 // accumulating, same as `constrain`'s threshold shift.
20404 let row: [i32; 8] = core::array::from_fn(|j| (i32::from(win[base + j]) >> coeff_shift) - 128);
20405 let rev: [i32; 8] = core::array::from_fn(|j| row[7 - j]);
20406 let pair: [i32; 4] = core::array::from_fn(|k| row[2 * k] + row[2 * k + 1]);
20407 let rpair: [i32; 4] = core::array::from_fn(|k| pair[3 - k]);
20408 let (p, rest) = partial.split_at_mut(1);
20409 add_at(&mut p[0], i, &row); // partial[0][i + j]
20410 add_at(&mut rest[0], i, &pair); // partial[1][i + j / 2]
20411 rest[1][i] = row.iter().sum(); // partial[2][i]
20412 add_at(&mut rest[2], i, &rpair); // partial[3][3 + i - j / 2]
20413 add_at(&mut rest[3], i, &rev); // partial[4][7 + i - j]
20414 add_at(&mut rest[4], 3 - i / 2, &row); // partial[5][3 - i / 2 + j]
20415 add_at(&mut rest[5], 0, &row); // partial[6][j]
20416 add_at(&mut rest[6], i / 2, &row); // partial[7][i / 2 + j]
20417 }
20418 partial
20419}
20420
20421/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
20422/// direction of an 8x8 luma window and the variance gap between it and its
20423/// orthogonal, reading [`cdef_gather`]'s window (row stride `bstride`, the
20424/// block's own samples starting at `CDEF_BORDER, CDEF_BORDER`).
20425fn cdef_find_dir(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) {
20426 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
20427 #[cfg(target_arch = "x86_64")]
20428 let partial = if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
20429 // SAFETY: reached only when the CPU reports avx2; the kernel reads
20430 // the same eight rows of eight samples the scalar form does.
20431 #[allow(unsafe_code)]
20432 unsafe {
20433 cdef_simd::find_dir_partials_avx2(win, bstride, coeff_shift)
20434 }
20435 } else {
20436 cdef_find_dir_partials(win, bstride, coeff_shift)
20437 };
20438 #[cfg(not(target_arch = "x86_64"))]
20439 let partial = cdef_find_dir_partials(win, bstride, coeff_shift);
20440 let sq = |a: i32| -> i64 { i64::from(a) * i64::from(a) };
20441 let mut cost = [0i64; 8];
20442 for i in 0..8usize {
20443 cost[2] += sq(partial[2][i]);
20444 cost[6] += sq(partial[6][i]);
20445 }
20446 cost[2] *= DIV_TABLE[8];
20447 cost[6] *= DIV_TABLE[8];
20448 for i in 0..7usize {
20449 cost[0] += (sq(partial[0][i]) + sq(partial[0][14 - i])) * DIV_TABLE[i + 1];
20450 cost[4] += (sq(partial[4][i]) + sq(partial[4][14 - i])) * DIV_TABLE[i + 1];
20451 }
20452 cost[0] += sq(partial[0][7]) * DIV_TABLE[8];
20453 cost[4] += sq(partial[4][7]) * DIV_TABLE[8];
20454 for i in (1..8).step_by(2) {
20455 for j in 0..5usize {
20456 cost[i] += sq(partial[i][3 + j]);
20457 }
20458 cost[i] *= DIV_TABLE[8];
20459 for j in 0..3usize {
20460 cost[i] += (sq(partial[i][j]) + sq(partial[i][10 - j])) * DIV_TABLE[2 * j + 2];
20461 }
20462 }
20463 let mut best_cost = 0i64;
20464 let mut best_dir = 0usize;
20465 for (i, &c) in cost.iter().enumerate() {
20466 if c > best_cost {
20467 best_cost = c;
20468 best_dir = i;
20469 }
20470 }
20471 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
20472 (best_dir, var as i32)
20473}
20474
20475/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
20476/// (high variance gap) gets more deringing than a flat or non-directional
20477/// one, only ever applied to the luma primary strength.
20478fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
20479 if var == 0 {
20480 return 0;
20481 }
20482 let i = if var >> 6 != 0 {
20483 cdef_msb(var >> 6).min(12)
20484 } else {
20485 0
20486 };
20487 (strength * (4 + i) + 8) >> 4
20488}
20489
20490/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
20491/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
20492/// previously-filtered neighbour must never feed this block's own sum).
20493#[allow(clippy::too_many_arguments)]
20494#[allow(unsafe_code)]
20495fn cdef_filter_block(
20496 src: &[i16],
20497 dst: &mut PlaneBuf<'static>,
20498 ox: usize,
20499 oy: usize,
20500 bw: usize,
20501 bh: usize,
20502 pri_strength: i32,
20503 sec_strength: i32,
20504 dir: usize,
20505 pri_damping: i32,
20506 sec_damping: i32,
20507 enable_primary: bool,
20508 enable_secondary: bool,
20509 coeff_shift: i32, fctx: &crate::decode::FrameCtx,
20510) {
20511 let (stride, smax) = (dst.width, sample_max(fctx));
20512 #[cfg(target_arch = "x86_64")]
20513 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0
20514 {
20515 // SAFETY: reached only when the CPU reports avx2; the kernel reads
20516 // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the
20517 // `bh` runs of `bw` samples the scalar form writes.
20518 unsafe {
20519 cdef_simd::filter_block_avx2(
20520 src,
20521 dst.data.to_mut(),
20522 stride,
20523 ox,
20524 oy,
20525 bw,
20526 bh,
20527 pri_strength,
20528 sec_strength,
20529 dir,
20530 pri_damping,
20531 sec_damping,
20532 enable_primary,
20533 enable_secondary,
20534 coeff_shift,
20535 smax,
20536 )
20537 };
20538 return;
20539 }
20540 cdef_filter_block_scalar(
20541 src,
20542 dst.data.to_mut(),
20543 stride,
20544 ox,
20545 oy,
20546 bw,
20547 bh,
20548 pri_strength,
20549 sec_strength,
20550 dir,
20551 pri_damping,
20552 sec_damping,
20553 enable_primary,
20554 enable_secondary,
20555 coeff_shift,
20556 smax,
20557 );
20558}
20559
20560/// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample,
20561/// the form every non-AVX2 build decodes through and the one
20562/// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against.
20563#[allow(clippy::too_many_arguments)]
20564fn cdef_filter_block_scalar(
20565 src: &[i16],
20566 dst: &mut [u16],
20567 stride: usize,
20568 ox: usize,
20569 oy: usize,
20570 bw: usize,
20571 bh: usize,
20572 pri_strength: i32,
20573 sec_strength: i32,
20574 dir: usize,
20575 pri_damping: i32,
20576 sec_damping: i32,
20577 enable_primary: bool,
20578 enable_secondary: bool,
20579 coeff_shift: i32,
20580 smax: i32,
20581) {
20582 let clipping_required = enable_primary && enable_secondary;
20583 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
20584 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
20585 // derivative) carries the bit-depth shift, so the tap-set parity bit
20586 // must be read back above that shift, not off the raw low bit.
20587 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
20588 // Both damping shifts depend only on this block's strengths (spec 7.15.3's
20589 // `constrain`), so they are resolved here rather than per tap read.
20590 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
20591 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
20592 let bstride = bw + 2 * CDEF_BORDER;
20593 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
20594 // reaching +-CDEF_BORDER, so every index below is in range by construction.
20595 let at = |i: i32, j: i32| -> i32 {
20596 i32::from(src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize])
20597 };
20598 let (pri_dir, sec_dir0, sec_dir1) =
20599 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
20600 for i in 0..bh {
20601 for j in 0..bw {
20602 let (i32i, i32j) = (i as i32, j as i32);
20603 let x = at(i32i, i32j);
20604 let mut sum = 0i32;
20605 let mut max = x;
20606 let mut min = x;
20607 for k in 0..2usize {
20608 if enable_primary {
20609 let (tr, tc) = pri_dir[k];
20610 let p0 = at(i32i + tr, i32j + tc);
20611 let p1 = at(i32i - tr, i32j - tc);
20612 sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
20613 sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
20614 if clipping_required {
20615 if p0 != CDEF_VERY_LARGE {
20616 max = max.max(p0);
20617 }
20618 if p1 != CDEF_VERY_LARGE {
20619 max = max.max(p1);
20620 }
20621 min = min.min(p0).min(p1);
20622 }
20623 }
20624 if enable_secondary {
20625 let (tr0, tc0) = sec_dir0[k];
20626 let (tr1, tc1) = sec_dir1[k];
20627 let s0 = at(i32i + tr0, i32j + tc0);
20628 let s1 = at(i32i - tr0, i32j - tc0);
20629 let s2 = at(i32i + tr1, i32j + tc1);
20630 let s3 = at(i32i - tr1, i32j - tc1);
20631 if clipping_required {
20632 for s in [s0, s1, s2, s3] {
20633 if s != CDEF_VERY_LARGE {
20634 max = max.max(s);
20635 }
20636 }
20637 min = min.min(s0).min(s1).min(s2).min(s3);
20638 }
20639 sum += CDEF_SEC_TAPS[k]
20640 * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
20641 + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
20642 + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
20643 + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
20644 }
20645 }
20646 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
20647 if clipping_required {
20648 y = y.clamp(min, max);
20649 }
20650 dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16;
20651 }
20652 }
20653}
20654
20655/// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar
20656/// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic:
20657/// the same taps, the same `constrain`, the same `min`/`max` clamp with the
20658/// `CDEF_VERY_LARGE` sentinel excluded from the max, the same
20659/// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at
20660/// a time in 16-bit lanes.
20661///
20662/// 16-bit lanes are exact for every value this filter sees: window samples
20663/// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in
20664/// `i16`, a `constrain` result is bounded by the threshold (at most
20665/// `15 << 4`), and the tap-weighted sum by `24 *` that.
20666#[cfg(target_arch = "x86_64")]
20667#[allow(unsafe_code)]
20668#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
20669mod cdef_simd {
20670 use super::{
20671 cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS,
20672 CDEF_VERY_LARGE,
20673 };
20674 use std::arch::x86_64::*;
20675
20676 /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit
20677 /// register (low half = row `i`).
20678 ///
20679 /// # Safety
20680 /// Requires AVX2; `off + bstride + 8` must be inside `w`.
20681 #[target_feature(enable = "avx2")]
20682 #[inline]
20683 unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i {
20684 let lo = _mm_loadu_si128(w.offset(off).cast());
20685 let hi = _mm_loadu_si128(w.offset(off + bstride).cast());
20686 _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1)
20687 }
20688
20689 /// Spec 7.15.3's `constrain`, lane-parallel:
20690 /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`.
20691 /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the
20692 /// clamped magnitude is already 0 where `diff` is).
20693 ///
20694 /// # Safety
20695 /// Requires AVX2.
20696 #[target_feature(enable = "avx2")]
20697 #[inline]
20698 unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i {
20699 let diff = _mm256_sub_epi16(p, x);
20700 let a = _mm256_abs_epi16(diff);
20701 let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift));
20702 let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a);
20703 _mm256_sign_epi16(t, diff)
20704 }
20705
20706 /// [`super::cdef_find_dir_partials`] in AVX2 (libaom
20707 /// `cdef_find_dir_avx2`'s shape): eight i32 lanes per row instead of the
20708 /// four the auto-vectorised scalar form gets without the feature.
20709 ///
20710 /// # Safety
20711 /// Requires AVX2. `win` must hold [`super::cdef_gather`]'s 8x8 window
20712 /// grown by `CDEF_BORDER` at row stride `bstride`.
20713 #[target_feature(enable = "avx2")]
20714 pub unsafe fn find_dir_partials_avx2(
20715 win: &[i16],
20716 bstride: usize,
20717 coeff_shift: i32,
20718 ) -> [[i32; 16]; 8] {
20719 #[target_feature(enable = "avx2")]
20720 unsafe fn add8(dst: &mut [i32; 16], off: usize, v: __m256i) {
20721 let p = dst.as_mut_ptr().add(off) as *mut __m256i;
20722 _mm256_storeu_si256(p, _mm256_add_epi32(_mm256_loadu_si256(p), v));
20723 }
20724 #[target_feature(enable = "avx2")]
20725 unsafe fn add4(dst: &mut [i32; 16], off: usize, v: __m128i) {
20726 let p = dst.as_mut_ptr().add(off) as *mut __m128i;
20727 _mm_storeu_si128(p, _mm_add_epi32(_mm_loadu_si128(p), v));
20728 }
20729 let mut partial = [[0i32; 16]; 8];
20730 let shift = _mm_cvtsi32_si128(coeff_shift);
20731 let c128 = _mm256_set1_epi32(128);
20732 let revidx = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0);
20733 let mut p6 = _mm256_setzero_si256();
20734 for i in 0..8usize {
20735 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
20736 let raw = _mm_loadu_si128(win.as_ptr().add(base) as *const __m128i);
20737 let row = _mm256_sub_epi32(_mm256_sra_epi32(_mm256_cvtepi16_epi32(raw), shift), c128);
20738 let rev = _mm256_permutevar8x32_epi32(row, revidx);
20739 // `hadd(row, row)` is [p0, p1, p0, p1 | p2, p3, p2, p3], so the
20740 // four pairwise sums are the two lanes' low halves joined.
20741 let h = _mm256_hadd_epi32(row, row);
20742 let pair =
20743 _mm_unpacklo_epi64(_mm256_castsi256_si128(h), _mm256_extracti128_si256(h, 1));
20744 let rpair = _mm_shuffle_epi32(pair, 0b00_01_10_11);
20745 let hs = _mm_hadd_epi32(pair, pair);
20746 let total = _mm_cvtsi128_si32(_mm_hadd_epi32(hs, hs));
20747 add8(&mut partial[0], i, row);
20748 add4(&mut partial[1], i, pair);
20749 partial[2][i] = total;
20750 add4(&mut partial[3], i, rpair);
20751 add8(&mut partial[4], i, rev);
20752 add8(&mut partial[5], 3 - i / 2, row);
20753 p6 = _mm256_add_epi32(p6, row);
20754 add8(&mut partial[7], i / 2, row);
20755 }
20756 _mm256_storeu_si256(partial[6].as_mut_ptr() as *mut __m256i, p6);
20757 partial
20758 }
20759
20760 /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per
20761 /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for
20762 /// `bw == 4` the upper four lanes of each half are window samples read
20763 /// past the row (never past the buffer -- `w` is padded to 256 entries),
20764 /// computed and then dropped by the 64-bit store.
20765 ///
20766 /// # Safety
20767 /// Requires AVX2. `src` must be [`super::cdef_gather`]'s 256-entry window
20768 /// buffer (the tap loads read up to 152 entries past its start, i.e. past
20769 /// the `(bw + 4) x (bh + 4)` samples themselves) and `dst` the `bh` rows
20770 /// of `bw` samples at `(ox, oy)`.
20771 #[target_feature(enable = "avx2")]
20772 #[allow(clippy::too_many_arguments)]
20773 pub unsafe fn filter_block_avx2(
20774 src: &[i16],
20775 dst: &mut [u16],
20776 stride: usize,
20777 ox: usize,
20778 oy: usize,
20779 bw: usize,
20780 bh: usize,
20781 pri_strength: i32,
20782 sec_strength: i32,
20783 dir: usize,
20784 pri_damping: i32,
20785 sec_damping: i32,
20786 enable_primary: bool,
20787 enable_secondary: bool,
20788 coeff_shift: i32,
20789 smax: i32,
20790 ) {
20791 let bstride = bw + 2 * CDEF_BORDER;
20792 // The caller's window is already `i16` and 256 entries long, so the
20793 // kernel taps it in place: the largest two-row load is
20794 // (bh + 3) * bstride + 8 <= 152 for the 8x8 luma block, 72 for the
20795 // 4x4 chroma one, both inside the buffer's zeroed tail.
20796 let w = src;
20797 let clipping_required = enable_primary && enable_secondary;
20798 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
20799 let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping));
20800 let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping));
20801 let pri_thr = _mm256_set1_epi16(pri_strength as i16);
20802 let sec_thr = _mm256_set1_epi16(sec_strength as i16);
20803 let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16);
20804 let zero = _mm256_setzero_si256();
20805 let eight = _mm256_set1_epi16(8);
20806 let smaxv = _mm256_set1_epi16(smax as i16);
20807 let (pri_dir, sec_dir0, sec_dir1) =
20808 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
20809 let wp = w.as_ptr();
20810 let bs = bstride as isize;
20811 let dp = dst.as_mut_ptr();
20812 let mut i = 0usize;
20813 while i < bh {
20814 let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize;
20815 let x = ld2(wp, base, bs);
20816 let mut sum = zero;
20817 let mut max = x;
20818 let mut min = x;
20819 for k in 0..2usize {
20820 if enable_primary {
20821 let (tr, tc) = pri_dir[k];
20822 let off = tr as isize * bs + tc as isize;
20823 let p0 = ld2(wp, base + off, bs);
20824 let p1 = ld2(wp, base - off, bs);
20825 let tap = _mm256_set1_epi16(pri_taps[k] as i16);
20826 sum = _mm256_add_epi16(
20827 sum,
20828 _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)),
20829 );
20830 sum = _mm256_add_epi16(
20831 sum,
20832 _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)),
20833 );
20834 if clipping_required {
20835 // The sentinel is excluded from the max exactly as the
20836 // scalar `if p != CDEF_VERY_LARGE` does: masking it to
20837 // 0 cannot win a max whose seed `x` is non-negative.
20838 max = _mm256_max_epi16(
20839 max,
20840 _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0),
20841 );
20842 max = _mm256_max_epi16(
20843 max,
20844 _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1),
20845 );
20846 min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1));
20847 }
20848 }
20849 if enable_secondary {
20850 let (tr0, tc0) = sec_dir0[k];
20851 let (tr1, tc1) = sec_dir1[k];
20852 let off0 = tr0 as isize * bs + tc0 as isize;
20853 let off1 = tr1 as isize * bs + tc1 as isize;
20854 let s0 = ld2(wp, base + off0, bs);
20855 let s1 = ld2(wp, base - off0, bs);
20856 let s2 = ld2(wp, base + off1, bs);
20857 let s3 = ld2(wp, base - off1, bs);
20858 if clipping_required {
20859 for s in [s0, s1, s2, s3] {
20860 max = _mm256_max_epi16(
20861 max,
20862 _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s),
20863 );
20864 }
20865 min = _mm256_min_epi16(
20866 min,
20867 _mm256_min_epi16(
20868 _mm256_min_epi16(s0, s1),
20869 _mm256_min_epi16(s2, s3),
20870 ),
20871 );
20872 }
20873 let c = _mm256_add_epi16(
20874 _mm256_add_epi16(
20875 constrain(s0, x, sec_thr, sec_shift),
20876 constrain(s1, x, sec_thr, sec_shift),
20877 ),
20878 _mm256_add_epi16(
20879 constrain(s2, x, sec_thr, sec_shift),
20880 constrain(s3, x, sec_thr, sec_shift),
20881 ),
20882 );
20883 sum = _mm256_add_epi16(
20884 sum,
20885 _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c),
20886 );
20887 }
20888 }
20889 // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`.
20890 let neg = _mm256_cmpgt_epi16(zero, sum);
20891 let mut y = _mm256_add_epi16(
20892 x,
20893 _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4),
20894 );
20895 if clipping_required {
20896 y = _mm256_min_epi16(_mm256_max_epi16(y, min), max);
20897 }
20898 y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv);
20899 let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1));
20900 let o0 = ((oy + i) * stride + ox) as isize;
20901 let o1 = o0 + stride as isize;
20902 if bw == 8 {
20903 _mm_storeu_si128(dp.offset(o0).cast(), lo);
20904 _mm_storeu_si128(dp.offset(o1).cast(), hi);
20905 } else {
20906 _mm_storel_epi64(dp.offset(o0).cast(), lo);
20907 _mm_storel_epi64(dp.offset(o1).cast(), hi);
20908 }
20909 i += 2;
20910 }
20911 }
20912}
20913
20914/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
20915/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
20916/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
20917/// every block's level comes from [`LoopFilterParams::level`] plus the
20918/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
20919/// `get_filter_level`, precomputed per-block here rather than cached in a
20920/// table the way libaom's `av1_loop_filter_frame_init` does).
20921///
20922/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
20923/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
20924fn apply_deblock(
20925 y: &mut PlaneBuf<'static>,
20926 u: &mut PlaneBuf<'static>,
20927 v: &mut PlaneBuf<'static>,
20928 lf: &LoopFilterParams,
20929 n: &Neighbours,
20930 frame_width: usize,
20931 frame_height: usize, fctx: &crate::decode::FrameCtx,
20932) {
20933 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
20934 // mismatch between the raw reconstruction and post-filter output.
20935 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
20936 return;
20937 }
20938 if lf.level[0] != 0 || lf.level[1] != 0 {
20939 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);
20940 }
20941 if lf.level[2] != 0 {
20942 deblock_plane(u, 1, lf, n, frame_width, frame_height, fctx);
20943 }
20944 if lf.level[3] != 0 {
20945 deblock_plane(v, 2, lf, n, frame_width, frame_height, fctx);
20946 }
20947}
20948
20949/// [`apply_deblock`] for ONE pass over ONE band of luma rows
20950/// (`y_lo..y_hi`), the form [`pipe_run`] calls it in. Running the three
20951/// planes' vertical passes and then their three horizontal ones is the same
20952/// output as `apply_deblock`'s plane-at-a-time order: the planes are
20953/// separate buffers and neither pass reads another plane.
20954#[allow(clippy::too_many_arguments)]
20955fn deblock_span(
20956 y: &mut PlaneBuf<'static>,
20957 u: &mut PlaneBuf<'static>,
20958 v: &mut PlaneBuf<'static>,
20959 lf: &LoopFilterParams,
20960 n: &Neighbours,
20961 frame_width: usize,
20962 frame_height: usize,
20963 y_lo: usize,
20964 y_hi: usize,
20965 horz: bool,
20966 fctx: &crate::decode::FrameCtx,
20967) {
20968 if lf.level[0] != 0 || lf.level[1] != 0 {
20969 deblock_plane_span(y, 0, lf, n, frame_width, frame_height, y_lo, y_hi, horz, fctx);
20970 }
20971 if lf.level[2] != 0 {
20972 deblock_plane_span(u, 1, lf, n, frame_width, frame_height, y_lo >> ss_y(fctx), y_hi >> ss_y(fctx), horz, fctx);
20973 }
20974 if lf.level[3] != 0 {
20975 deblock_plane_span(v, 2, lf, n, frame_width, frame_height, y_lo >> ss_y(fctx), y_hi >> ss_y(fctx), horz, fctx);
20976 }
20977}
20978
20979/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
20980/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
20981/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
20982/// mi unit under this decoder's assumed 4:2:0 subsampling).
20983///
20984/// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as
20985/// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz |
20986/// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma
20987/// prediction mode is obtained from the bottom/right mi structure of the
20988/// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col
20989/// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which
20990/// is the same cell for every block 8x8 and larger and a DIFFERENT coded
20991/// block (different tx size, ref frame, skip flag and delta_lf) as soon as
20992/// the group is split into 4x4 luma blocks (class
20993/// `context-read-from-one-cell`).
20994fn plane_to_mi(chroma: bool, coord: usize, ss: usize) -> usize {
20995 // scale | ((coord << scale) >> 2). ss=1 is (coord/2)|1; ss=0 is coord/4.
20996 if chroma { ss | ((coord << ss) >> 2) } else { coord / 4 }
20997}
20998
20999/// This plane's own transform width in pixels at the covering block, spec
21000/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
21001/// width directly; chroma halves it (this decoder's UV transform is always
21002/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
21003/// under 4:2:0 and a block that never splits its own transform).
21004fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
21005 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
21006 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
21007}
21008
21009/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
21010/// edges step and gate by transform height, which differs from width only
21011/// on rect partition strips.
21012fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
21013 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
21014 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
21015}
21016
21017/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
21018/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
21019/// present only when its neighbour exists inside the true frame -- whether
21020/// the block immediately above (at this block's own leftmost mi column) or
21021/// to the left (at its own topmost mi row) coded a transform at least as wide
21022/// (tall) as this block's own `max_txsize_rect_lookup[bsize]`.
21023///
21024/// lane-av1txbands: this reads the real `TXFM_CONTEXT` bands
21025/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`]) for EVERY frame
21026/// now -- libaom maintains them on intra-only frames too (`parse_decode_block`
21027/// runs `set_txfm_ctxs` for every block, and
21028/// [`Neighbours::fill_lf_grid_rect`] publishes them there), except that an
21029/// *inter* neighbour contributes its own BLOCK size rather than its transform
21030/// size -- and libaom's `is_inter_block` counts an INTRABC block
21031/// (`blockd.h:373`), which is what the `above_inter`/`left_inter` bands carry.
21032/// The previous deblock-grid approximation coincided with this only while
21033/// every neighbour coded one whole-block transform, which is exactly what
21034/// `TxMode::Select` ends.
21035///
21036/// The rect form (lane-intrasplit r1): `get_tx_size_context` compares the
21037/// neighbour ABOVE against `tx_size_wide[max_txsize_rect_lookup[bsize]]` and
21038/// the neighbour to the LEFT against `tx_size_high[...]` (libaom
21039/// `pred_common.h:342`), which for a 2:1 strip are two different numbers.
21040fn tx_size_context_txfm_rect(
21041 n: &Neighbours,
21042 (mi_r, mi_c): (usize, usize),
21043 own_w: usize,
21044 own_h: usize, fctx: &crate::decode::FrameCtx,
21045) -> usize {
21046 hit!(INTRA_IN_INTER_TXCTX_HITS);
21047 // `max_txsize_rect_lookup[bsize]` tops out at TX_64X64: no transform is
21048 // wider or taller than 64, so a block with a 128 side resolves against 64
21049 // (lane-sb128b r1).
21050 let (own_w, own_h) = (own_w.min(64), own_h.min(64));
21051 let has_above = mi_r > n.tile_row0_mi;
21052 let has_left = mi_c > n.tile_col0_mi;
21053 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
21054 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
21055 if has_above && n.above_inter[mi_c] {
21056 above = usize::from(n.above_side_mi[mi_c]) >= own_w;
21057 }
21058 if has_left && n.left_inter[mi_r] {
21059 left = usize::from(n.left_side_mi[mi_r]) >= own_h;
21060 }
21061 if crate::envflags::env_flag!("EC_TXCTX") {
21062 eprintln!(
21063 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
21064 intra_only={} above_txfm={} left_txfm={} above_inter={} left_inter={} \
21065 above_side={} left_side={} above={above} left={left}",
21066 fctx.intra_only.with(std::cell::Cell::get),
21067 n.above_txfm[mi_c],
21068 n.left_txfm[mi_r],
21069 n.above_inter[mi_c],
21070 n.left_inter[mi_r],
21071 n.above_side_mi[mi_c],
21072 n.left_side_mi[mi_r],
21073 );
21074 }
21075 let ctx = match (has_above, has_left) {
21076 (true, true) => usize::from(above) + usize::from(left),
21077 (true, false) => usize::from(above),
21078 (false, true) => usize::from(left),
21079 (false, false) => 0,
21080 };
21081 {
21082 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w)
21083 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h);
21084 if ctx != stale {
21085 hit!(TXCTX_DEBLOCK_DIVERGENCE_HITS);
21086 }
21087 }
21088 ctx
21089}
21090
21091/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
21092/// are written and read everywhere else with a raw mi index); the SUB-cell
21093/// division this pair used read a cell four blocks away, so the inter-neighbour
21094/// override above fired on the wrong neighbour -- the first divergence of the
21095/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
21096/// at the intra block right of an inter one).
21097fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
21098 let has_above = mi_r > n.tile_row0_mi;
21099 let has_left = mi_c > n.tile_col0_mi;
21100 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
21101 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
21102 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
21103 // `above_inter`/`left_inter` bands are written per MI unit
21104 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
21105 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
21106 // block whenever the neighbour column/row is not the cell's first. A
21107 // 16x16 intra block whose left neighbour is an inter block at mi row 4
21108 // then missed libaom's "an inter neighbour contributes its BLOCK size"
21109 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
21110 if has_above && n.above_inter[mi_c] {
21111 above = usize::from(n.above_side_mi[mi_c]) >= side;
21112 }
21113 if has_left && n.left_inter[mi_r] {
21114 left = usize::from(n.left_side_mi[mi_r]) >= side;
21115 }
21116 if crate::envflags::env_flag!("EC_TXCTX") {
21117 eprintln!(
21118 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
21119 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
21120 above={above} left={left}",
21121 n.above_txfm[mi_c],
21122 n.left_txfm[mi_r],
21123 n.above_inter[mi_c],
21124 n.left_inter[mi_r],
21125 n.above_side_mi[mi_c],
21126 n.left_side_mi[mi_r],
21127 );
21128 }
21129 match (has_above, has_left) {
21130 (true, true) => usize::from(above) + usize::from(left),
21131 (true, false) => usize::from(above),
21132 (false, true) => usize::from(left),
21133 (false, false) => 0,
21134 }
21135}
21136
21137/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
21138/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
21139/// the transform's own side in pixels (`side >> depth`) -- this decoder's
21140/// four square categories (8/16/32/64) each halve at most twice, matching
21141/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
21142fn read_tx_size(
21143 dec: &mut SymbolDecoder,
21144 cdfs: &mut Cdfs,
21145 n: &Neighbours,
21146 at_mi: (usize, usize),
21147 side: usize,
21148 fctx: &crate::decode::FrameCtx,
21149) -> usize {
21150 // libaom `read_tx_size`'s FIRST line (decodeframe.c:1203):
21151 // `if (xd->lossless[xd->mi[0]->segment_id]) return TX_4X4;` -- before the
21152 // `tx_mode == TX_MODE_SELECT` test and before any symbol. Invisible while
21153 // every lossless frame was ALSO `CodedLossless` (its `tx_mode` is forced
21154 // `Only4x4`, so this function never ran); a MIXED frame keeps
21155 // `TxMode::Select`, so its lossless segments reach the symbol read and
21156 // must take the early return (lane-av1mixloss).
21157 if lossless(fctx) {
21158 return 4;
21159 }
21160 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
21161 // `get_tx_size_context`): a block wider than 64 still tops out at
21162 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
21163 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
21164 // never against its own 128 side (lane-sb128b r1).
21165 let max_tx = side.min(64);
21166 let ctx = tx_size_context_txfm(n, at_mi, max_tx);
21167 let depth = match max_tx {
21168 8 => {
21169 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
21170 }
21171 16 => {
21172 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
21173 }
21174 32 => {
21175 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
21176 }
21177 64 => {
21178 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
21179 }
21180 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
21181 };
21182 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
21183 let (rng, _) = dec.debug_state();
21184 let (mi_r, mi_c) = at_mi;
21185 eprintln!(
21186 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
21187 );
21188 }
21189 if depth != 0 {
21190 hit!(TX_DEPTH_HITS);
21191 }
21192 max_tx >> depth
21193}
21194
21195/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
21196/// `txfm_split` context -- a category from the block's own largest square
21197/// transform and whether this unit already sits below it, times three, plus
21198/// the two neighbour terms (whether the transform last written above/left of
21199/// this unit is narrower/shorter than the unit itself).
21200#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21201fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
21202 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
21203}
21204
21205/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
21206/// libaom's `txfm_partition_context` compares the above context against
21207/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
21208/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
21209/// side for a square transform, which is why the square form above is a
21210/// special case of this one.
21211pub(crate) fn txfm_partition_ctx_rect(
21212 above_px: u8,
21213 left_px: u8,
21214 blk_max_px: usize,
21215 tx_w: usize,
21216 tx_h: usize,
21217) -> usize {
21218 let above = usize::from(usize::from(above_px) < tx_w);
21219 let left = usize::from(usize::from(left_px) < tx_h);
21220 let tx_px = tx_w.max(tx_h);
21221 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
21222 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
21223 // `log2(px) - 2`.
21224 let max_tx = blk_max_px.min(64);
21225 let max_idx = max_tx.trailing_zeros() as usize - 2;
21226 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
21227 category * 3 + above + left
21228}
21229
21230/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
21231/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
21232/// resolved transform's own size.
21233#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21234fn txfm_partition_update(
21235 n: &mut Neighbours,
21236 at_mi: (usize, usize),
21237 tx_px: usize,
21238 txb_px: usize,
21239) {
21240 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
21241}
21242
21243/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
21244/// the left column records `tx_size_high` over the parent's own height and
21245/// the above row records `tx_size_wide` over its width.
21246/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
21247/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
21248/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
21249/// key frame writes neither (its readers use the deblock grid), so the
21250/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
21251/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
21252/// at the call site (the transform size comes back to them); the 1:4 arms
21253/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
21254/// so they call this where their own depth resolves. A no-op on a key frame
21255/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
21256///
21257/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
21258/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
21259/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
21260/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
21261/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
21262/// / early-return-skips-tail).
21263///
21264/// lane-av1-intrabc r3: an `allow_intrabc` KEY frame reads the same bands --
21265/// `read_intra_frame_mode_info` returns early for an intrabc block, so
21266/// [`read_block_tx_size_rect`]'s var-tx tree is the intra path's one
21267/// `txfm_partition_context` reader, and it reads whatever the block ABOVE and
21268/// the block LEFT published. [`decode_block`] has published on such a frame
21269/// since lane-t900 r32; the RECT strips did not, so the band still held the
21270/// value of an older, smaller neighbour -- measured on the 256x192 testsrc2
21271/// cq45 var-tx arm: the coded 16x8 intrabc strip at mi(38,48) read ctx 14
21272/// where libaom reads 13 (`left_ctx` 4 vs the 8 the 16x8 intra strip at
21273/// mi(38,44) should have published), desyncing the tile there.
21274fn publish_txfm_bands_if_in_inter(
21275 n: &mut Neighbours,
21276 at_mi: (usize, usize),
21277 (tx_w, tx_h): (usize, usize),
21278 (bw, bh): (usize, usize), fctx: &crate::decode::FrameCtx,
21279) {
21280 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none()
21281 && !allow_intrabc_frame(fctx)
21282 {
21283 return;
21284 }
21285 let (mi_r, mi_c) = at_mi;
21286 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
21287 for i in 0..bw / MI {
21288 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
21289 *cell = tx_w as u8;
21290 }
21291 }
21292 for i in 0..bh / MI {
21293 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
21294 *cell = tx_h as u8;
21295 }
21296 }
21297}
21298
21299fn txfm_partition_update_rect(
21300 n: &mut Neighbours,
21301 (mi_r, mi_c): (usize, usize),
21302 (tx_w, tx_h): (usize, usize),
21303 (txb_w, txb_h): (usize, usize),
21304) {
21305 if crate::envflags::env_flag!("EC_TXUPD") {
21306 eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c);
21307 }
21308 for i in 0..txb_h / MI {
21309 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
21310 *cell = tx_h as u8;
21311 }
21312 }
21313 for i in 0..txb_w / MI {
21314 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
21315 *cell = tx_w as u8;
21316 }
21317 }
21318}
21319
21320/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
21321/// same contexts -- a skipped *inter* block records its own block size rather
21322/// than its transform size.
21323fn set_txfm_ctxs(
21324 n: &mut Neighbours,
21325 (mi_r, mi_c): (usize, usize),
21326 tx_px: usize,
21327 w_mi: usize,
21328 h_mi: usize,
21329 skip_inter: bool,
21330) {
21331 if crate::envflags::env_flag!("EC_TXUPD") {
21332 eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}");
21333 }
21334 let bw = if skip_inter { w_mi * MI } else { tx_px };
21335 let bh = if skip_inter { h_mi * MI } else { tx_px };
21336 for i in 0..w_mi {
21337 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
21338 *cell = bw as u8;
21339 }
21340 }
21341 for i in 0..h_mi {
21342 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
21343 *cell = bh as u8;
21344 }
21345 }
21346}
21347
21348/// The value libaom initialises both transform contexts to -- NOT zero:
21349/// `av1_zero_above_context` memsets the txfm row to
21350/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
21351/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
21352/// pixels, so an unwritten neighbour reads as the *widest* possible
21353/// transform, not the narrowest.
21354pub(crate) const TXFM_CTX_INIT: u8 = 64;
21355
21356/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
21357/// twice below its own largest transform.
21358const MAX_VARTX_DEPTH: usize = 2;
21359
21360/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
21361/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
21362/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
21363/// small ones, square everywhere else.
21364fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
21365 match (tx_w, tx_h) {
21366 (4, 4) => (4, 4),
21367 (8, 8) => (4, 4),
21368 (16, 16) => (8, 8),
21369 (32, 32) => (16, 16),
21370 (64, 64) => (32, 32),
21371 (4, 8) | (8, 4) => (4, 4),
21372 (8, 16) | (16, 8) => (8, 8),
21373 (16, 32) | (32, 16) => (16, 16),
21374 (32, 64) | (64, 32) => (32, 32),
21375 (4, 16) => (4, 8),
21376 (16, 4) => (8, 4),
21377 (8, 32) => (8, 16),
21378 (32, 8) => (16, 8),
21379 (16, 64) => (16, 32),
21380 (64, 16) => (32, 16),
21381 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
21382 }
21383}
21384
21385#[test]
21386fn sub_tx_size_map_matches_libaom() {
21387 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
21388 const TABLE: [((usize, usize), (usize, usize)); 19] = [
21389 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
21390 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
21391 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
21392 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
21393 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
21394 ];
21395 for (tx, want) in TABLE {
21396 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
21397 }
21398}
21399
21400/// The domain of var-tx leaf sizes, enumerated against the two refusals that
21401/// name a leaf "larger than 32x32" / "larger than 64x64".
21402///
21403/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is
21404/// either the unit it was entered with or a `sub_tx_size_map` step below it:
21405/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early
21406/// return. So the leaf set reachable from an entry unit is that unit plus the
21407/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` --
21408/// which this test enumerates, and over which no leaf is ever larger than the
21409/// entry.
21410///
21411/// That closes both refusals:
21412///
21413/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit
21414/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than
21415/// 64x64" names a leaf the tree cannot produce;
21416/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32
21417/// below the 128 root. The only entry that exceeds that ceiling is 64x64,
21418/// reached only when `side == 64`, and then the block is ONE unit whose only
21419/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single`
21420/// case the refusal is guarded by.
21421#[test]
21422fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
21423 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
21424 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
21425 out.push((depth, entry.0, entry.1));
21426 if depth == MAX_VARTX_DEPTH {
21427 return;
21428 }
21429 let sub = sub_tx_size_map(entry.0, entry.1);
21430 if sub == (4, 4) {
21431 out.push((depth + 1, 4, 4));
21432 return;
21433 }
21434 reachable(sub, depth + 1, out);
21435 }
21436
21437 for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] {
21438 let mut leaves = Vec::new();
21439 reachable(entry, 0, &mut leaves);
21440 for (depth, w, h) in &leaves {
21441 assert!(
21442 w.max(h) <= &entry.0.max(entry.1),
21443 "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}",
21444 entry.0,
21445 entry.1
21446 );
21447 }
21448 // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0.
21449 if entry == (64, 64) {
21450 let above: Vec<&(usize, usize, usize)> =
21451 leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect();
21452 assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32");
21453 }
21454 }
21455
21456 // The entry size and ceiling each caller uses, over the block sides that
21457 // reach them (`read_block_tx_size`'s square path; the 128-root rect path
21458 // enters at a fixed 64).
21459 for side in [8usize, 16, 32, 64, 128] {
21460 let max_tx = side.min(64);
21461 let ceiling = if side > 64 { 64 } else { 32 };
21462 let units = (side / max_tx) * (side / max_tx);
21463 if max_tx <= ceiling {
21464 continue;
21465 }
21466 assert_eq!(
21467 (side, units),
21468 (64, 1),
21469 "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \
21470 {units} units -- an above-ceiling leaf there would NOT be the `single` case"
21471 );
21472 }
21473}
21474
21475/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
21476/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
21477/// max-transform-sized unit of an inter block, collecting the resolved leaf
21478/// transform units into `out` as `(row offset, col offset, side)` in mi units
21479/// -- exactly the order `decode_reconstruct_tx` later reads their
21480/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
21481/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
21482/// `max_block_high`).
21483#[allow(clippy::too_many_arguments)]
21484fn read_var_tx_size(
21485 dec: &mut SymbolDecoder,
21486 cdfs: &mut Cdfs,
21487 n: &mut Neighbours,
21488 at_mi: (usize, usize),
21489 blk_max_px: usize,
21490 (max_w_mi, max_h_mi): (usize, usize),
21491 (tx_w, tx_h): (usize, usize),
21492 depth: usize,
21493 blk_row: usize,
21494 blk_col: usize,
21495 out: &mut Vec<(usize, usize, usize, usize)>,
21496) {
21497 if blk_row >= max_h_mi || blk_col >= max_w_mi {
21498 return;
21499 }
21500 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
21501 if depth == MAX_VARTX_DEPTH {
21502 out.push((blk_row, blk_col, tx_w, tx_h));
21503 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
21504 return;
21505 }
21506 let ctx = txfm_partition_ctx_rect(
21507 n.above_txfm[unit.1],
21508 n.left_txfm[unit.0],
21509 blk_max_px,
21510 tx_w,
21511 tx_h,
21512 );
21513 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
21514 hit!(TXFM_SPLIT_READS);
21515 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
21516 let (rng, _) = dec.debug_state();
21517 eprintln!(
21518 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
21519 unit.0,
21520 unit.1,
21521 u8::from(split)
21522 );
21523 }
21524 if !split {
21525 out.push((blk_row, blk_col, tx_w, tx_h));
21526 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
21527 return;
21528 }
21529 hit!(TXFM_SPLIT_HITS);
21530 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
21531 if (sub_w, sub_h) == (4, 4) {
21532 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
21533 // unit is marked 4x4 (raster order) without recursing.
21534 for row in 0..tx_h / MI {
21535 for col in 0..tx_w / MI {
21536 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
21537 out.push((blk_row + row, blk_col + col, 4, 4));
21538 }
21539 }
21540 }
21541 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
21542 return;
21543 }
21544 for row in (0..tx_h / MI).step_by(sub_h / MI) {
21545 for col in (0..tx_w / MI).step_by(sub_w / MI) {
21546 read_var_tx_size(
21547 dec,
21548 cdfs,
21549 n,
21550 at_mi,
21551 blk_max_px,
21552 (max_w_mi, max_h_mi),
21553 (sub_w, sub_h),
21554 depth + 1,
21555 blk_row + row,
21556 blk_col + col,
21557 out,
21558 );
21559 }
21560 }
21561}
21562
21563/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
21564/// branch): every block of a `TxMode::Select` inter frame codes its transform
21565/// size right after its own mode info -- an inter non-skip block through the
21566/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
21567/// every other block through the intra `tx_depth` symbol (a skipped inter
21568/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
21569/// block's own resolved transform side and the leaf list, the latter only
21570/// when the tree resolved to more than one transform unit.
21571#[allow(clippy::too_many_arguments)]
21572fn read_block_tx_size(
21573 dec: &mut SymbolDecoder,
21574 cdfs: &mut Cdfs,
21575 n: &mut Neighbours,
21576 at_mi: (usize, usize),
21577 side: usize,
21578 (mi_cols, mi_rows): (usize, usize),
21579 is_inter: bool,
21580 skip: bool, fctx: &crate::decode::FrameCtx,
21581) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
21582 // lane-lossless: TX_4X4 over the whole block, and NO var-tx tree -- libaom
21583 // `read_block_tx_size` (`decodeframe.c`) sends a lossless block down the
21584 // `read_tx_size` arm, which returns TX_4X4 before it reads anything.
21585 if lossless(fctx) {
21586 let mut leaves = Vec::new();
21587 for row in 0..side / MI {
21588 for col in 0..side / MI {
21589 leaves.push((row, col, 4, 4));
21590 }
21591 }
21592 return Ok((4, Some(leaves)));
21593 }
21594 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
21595 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
21596 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
21597 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
21598 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
21599 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
21600 if side > 64 {
21601 let step = 64 / MI;
21602 let mut leaves = Vec::new();
21603 for row in (0..side / MI).step_by(step) {
21604 for col in (0..side / MI).step_by(step) {
21605 leaves.push((row, col, 64, 64));
21606 }
21607 }
21608 return Ok((64, Some(leaves)));
21609 }
21610 return Ok((side, None));
21611 }
21612 let side_mi = side / MI;
21613 if is_inter && !skip {
21614 let max_tx = side.min(64);
21615 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
21616 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
21617 let mut leaves = Vec::new();
21618 let step = max_tx / MI;
21619 for row in (0..side_mi).step_by(step) {
21620 for col in (0..side_mi).step_by(step) {
21621 read_var_tx_size(
21622 dec,
21623 cdfs,
21624 n,
21625 at_mi,
21626 side,
21627 (max_w_mi, max_h_mi),
21628 (max_tx, max_tx),
21629 0,
21630 row,
21631 col,
21632 &mut leaves,
21633 );
21634 }
21635 }
21636 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
21637 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
21638 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
21639 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
21640 // which the mu-chunk reader above codes as their 32x32 coded corner.
21641 let leaf_ceiling = if side > 64 { 64 } else { 32 };
21642 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
21643 // Only a block wider than a superblock's own 64x64 max transform
21644 // reaches here; this crate has no 64-point *inter* coefficient
21645 // table set ([`inter_txbset_for`] stops at 32).
21646 return Err(unsupported(
21647 "an inter var-tx tree with a leaf transform larger than 32x32",
21648 ));
21649 }
21650 let resolved = leaves.last().map_or(side, |l| l.2);
21651 return Ok((resolved, (!single).then_some(leaves)));
21652 }
21653 let tx = if is_inter {
21654 side.min(64)
21655 } else {
21656 read_tx_size(dec, cdfs, n, at_mi, side, fctx)
21657 };
21658 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
21659 if !is_inter && tx != side {
21660 // lane-intrainter r1: an intra block inside an inter frame whose
21661 // `tx_depth` split its luma transform codes exactly the key-frame
21662 // split path's transform units (`decode_block`'s multi-TU loop),
21663 // raster order over the block. Handed back in the same leaf shape the
21664 // inter var-tx tree uses, so the caller's per-TU luma loop, the
21665 // `record_split_luma` neighbour write-back and the per-TU deblock
21666 // edges are the ones it already runs for a var-tx inter block. A
21667 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
21668 // seeing `Some` here.
21669 let step = tx / MI;
21670 let mut leaves = Vec::new();
21671 for row in (0..side_mi).step_by(step) {
21672 for col in (0..side_mi).step_by(step) {
21673 leaves.push((row, col, tx, tx));
21674 }
21675 }
21676 hit_do! {
21677 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
21678 let mut h = c.get();
21679 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
21680 c.set(h);
21681 });
21682 }
21683 return Ok((tx, Some(leaves)));
21684 }
21685 Ok((tx, None))
21686}
21687
21688/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
21689/// decoder codes -- a 2:1 strip whose own max rect transform
21690/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
21691/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
21692/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
21693/// 64-point rect transform, and 16x8/8x16 needs
21694/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
21695/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
21696/// rect transform), neither of which exists yet -- both stay refused by name.
21697pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
21698 matches!(
21699 (w, h),
21700 // 2:1 strips whose transform is coded in full (lane-inter4).
21701 (32, 16) | (16, 32) | (16, 8) | (8, 16)
21702 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
21703 // codes all 64 of its positions, and its chroma pair is an 8x4 /
21704 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
21705 | (16, 4) | (4, 16)
21706 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
21707 // only the low 32 coefficients of a 64-length axis, so these read
21708 // exactly the truncated corner the INTRA superblock-strip path
21709 // already reads (`read_intra_mode_rect`), through
21710 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
21711 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
21712 // `tx_type` symbol is coded at all.
21713 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
21714 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
21715 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
21716 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
21717 // refused earlier ("an inter partition below 8x8").
21718 | (8, 4) | (4, 8)
21719 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
21720 // one rectangular transform -- `max_txsize_rect_lookup
21721 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
21722 // TX_64X64 units read through the mu-chunk loop, same as the
21723 // 128x128 NONE block's four.
21724 | (128, 64) | (64, 128)
21725 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
21726 // 10-bit film cuts and every measured 1080p offset stop on
21727 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
21728 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
21729 // positions, and its chroma pair is a 16x4 / 4x16 unit
21730 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
21731 | (32, 8) | (8, 32)
21732 )
21733}
21734
21735// lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path
21736// actually PRESENTS, as a thread-local bitmask -- the measured domain behind
21737// the "rectangular ... has no ... here" refusals. `side` is the square context
21738// a block reads its CDFs at and `write_w`/`write_h` its true footprint;
21739// `inter_piece!` derives `reject_residual` from exactly that inequality, so
21740// these triples are what decides whether those refusals can fire at all. Bit
21741// 31 is "a triple this table does not list", which is what makes the gate a
21742// census rather than a restatement of its own table.
21743pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
21744 (16, 16, 16),
21745 (32, 32, 32),
21746 (32, 16, 32),
21747 (32, 32, 16),
21748 (16, 8, 16),
21749 (16, 16, 8),
21750 (32, 8, 32),
21751 (64, 64, 64),
21752 (32, 32, 8),
21753 (64, 16, 64),
21754 (128, 128, 128),
21755 (64, 32, 64),
21756 (64, 64, 32),
21757 (16, 4, 16),
21758 (64, 64, 16),
21759 (16, 16, 4),
21760 (128, 128, 64),
21761 (128, 64, 128),
21762];
21763
21764/// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple
21765/// outside [`INTER_BLOCK_SHAPES`].
21766pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31;
21767
21768thread_local! {
21769 static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
21770}
21771
21772/// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a
21773/// gate reading it sees only the streams it decoded itself).
21774pub fn inter_block_shape_mask() -> u32 {
21775 INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get)
21776}
21777
21778/// Records one block's shape. The table is ordered by measured frequency over
21779/// the three witnesses the census gate decodes, so the common square shapes
21780/// leave the scan on their first comparison.
21781fn census_inter_block_shape(side: usize, w: usize, h: usize) {
21782 let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) {
21783 Some(i) => 1u32 << i,
21784 None => INTER_BLOCK_SHAPE_UNLISTED,
21785 };
21786 let seen = inter_block_shape_mask();
21787 if seen & bit == 0 {
21788 INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit));
21789 }
21790}
21791
21792/// The luma coefficient/`tx_type` table set of a whole-block rectangular
21793/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
21794/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
21795/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
21796/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
21797/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
21798/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
21799/// row (`txsize_sqr_map`), never the 16x16 one.
21800fn rect_inter_luma_set(w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> Result<TxbSet> {
21801 Ok(match (w, h) {
21802 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
21803 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
21804 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
21805 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
21806 // ALL16 otherwise -- both at the TX_4X4 row.
21807 (8, 4) | (4, 8) => {
21808 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
21809 TxbSet::LumaRect8x4Inter
21810 } else {
21811 TxbSet::LumaRect8x4InterSet1
21812 }
21813 }
21814 (16, 4) | (4, 16) => {
21815 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
21816 TxbSet::LumaRect16x4Inter
21817 } else {
21818 TxbSet::LumaRect16x4Inter1
21819 }
21820 }
21821 (16, 8) | (8, 16) => {
21822 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
21823 TxbSet::LumaRect16x8Inter
21824 } else {
21825 TxbSet::LumaRect16x8InterSet1
21826 }
21827 }
21828 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
21829 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
21830 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
21831 // adjusted size, so the existing sets are bit-exact. Neither carries a
21832 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
21833 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
21834 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
21835 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
21836 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
21837 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
21838 (64, 32) | (32, 64) => TxbSet::Luma64,
21839 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
21840 _ => {
21841 return Err(unsupported(
21842 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
21843 ));
21844 }
21845 })
21846}
21847
21848/// The chroma table set of the same block's single rectangular chroma unit
21849/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
21850/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
21851/// the luma unit's.
21852fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
21853 Ok(match (w, h) {
21854 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
21855 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
21856 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
21857 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
21858 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
21859 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
21860 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
21861 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
21862 (32, 8) | (8, 32) => TxbSet::Chroma16,
21863 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
21864 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
21865 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
21866 (16, 4) | (4, 16) => TxbSet::Chroma8,
21867 // lane-av1-444: one 32x32 unit of a 4:4:4 64x32/32x64 chroma plane
21868 // block (`av1_get_max_uv_txsize` adjusts `TX_64X32`/`TX_32X64` to
21869 // `TX_32X32`); `get_txsize_entropy_ctx(TX_32X32)` is the 32x32 set.
21870 (32, 32) => TxbSet::Chroma32,
21871 _ => {
21872 return Err(unsupported(
21873 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
21874 ));
21875 }
21876 })
21877}
21878
21879
21880/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
21881/// inter path reaches, from the block's TRUE footprint rather than the
21882/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
21883/// everything 32 and above -> 3.
21884fn size_group_wh(w: usize, h: usize) -> usize {
21885 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
21886 // `common_data.h:60`) is 0 for every block with a 4-px side
21887 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
21888 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
21889 match w.min(h) {
21890 0..=4 => 0,
21891 8 => 1,
21892 16 => 2,
21893 _ => 3,
21894 }
21895}
21896
21897#[test]
21898fn size_group_wh_matches_libaom_size_group_lookup() {
21899 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
21900 // transcribed values (common_data.h:60-62).
21901 const TABLE: [((usize, usize), usize); 22] = [
21902 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
21903 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
21904 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
21905 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
21906 ];
21907 for ((w, h), want) in TABLE {
21908 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
21909 }
21910}
21911
21912/// The default (2D) coefficient scan of a rectangular transform.
21913fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
21914 Ok(match (w, h) {
21915 (32, 16) => &SCAN_32X16,
21916 (16, 32) => &SCAN_16X32,
21917 (16, 8) => &SCAN_16X8,
21918 (8, 16) => &SCAN_8X16,
21919 (16, 4) => &SCAN_16X4,
21920 (4, 16) => &SCAN_4X16,
21921 (8, 4) => &SCAN_8X4,
21922 (4, 8) => &SCAN_4X8,
21923 (32, 8) => &SCAN_32X8,
21924 (8, 32) => &SCAN_8X32,
21925 _ => {
21926 return Err(unsupported(
21927 "a rectangular transform unit whose shape has no coefficient scan table here",
21928 ));
21929 }
21930 })
21931}
21932
21933/// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma
21934/// transform unit whose shape has no coefficient table set here" / "a
21935/// rectangular transform unit whose shape has no coefficient scan table here"
21936/// arms, enumerated against the MEASURED domain of the inter block path
21937/// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate
21938/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`).
21939///
21940/// What each helper is actually handed:
21941///
21942/// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the
21943/// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is
21944/// square for every rect transform except TX_16X4/TX_4X16, whose leaves are
21945/// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8.
21946/// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0
21947/// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8.
21948/// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect
21949/// unit, and only when that corner is not 32x32 (a square corner goes
21950/// through the square reader with `rect_shape = Some((w, h))`).
21951///
21952/// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is
21953/// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk
21954/// loop, which is why they are skipped below.
21955#[test]
21956fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
21957 let fctx = &crate::decode::FrameCtx::new();
21958 let corner_scan = |w: usize, h: usize| {
21959 let (cw, ch) = (w.min(32), h.min(32));
21960 if (cw, ch) == (32, 32) {
21961 return; // the square coefficient reader, not `rect_scan`
21962 }
21963 assert!(
21964 rect_scan(cw, ch).is_ok(),
21965 "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table"
21966 );
21967 };
21968 let mut checked = 0;
21969 for &(side, w, h) in &INTER_BLOCK_SHAPES {
21970 if (w, h) == (side, side) || w.max(h) > 64 {
21971 continue;
21972 }
21973 assert!(
21974 rect_inter_luma_set(w, h, fctx).is_ok(),
21975 "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one"
21976 );
21977 corner_scan(w, h);
21978 // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved
21979 // footprint for every other shape.
21980 let (cw, ch) = match (w, h) {
21981 (16, 4) => (8, 4),
21982 (4, 16) => (4, 8),
21983 _ => (w / 2, h / 2),
21984 };
21985 assert!(
21986 rect_inter_chroma_set(cw, ch).is_ok(),
21987 "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set"
21988 );
21989 corner_scan(cw, ch);
21990 checked += 1;
21991 }
21992 assert_eq!(
21993 checked, 12,
21994 "the block-shape census changed: {checked} rect shapes reach the rect transform \
21995 tables, not the 12 this claim was measured over"
21996 );
21997 // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf
21998 // shapes, which reach `rect_inter_luma_set` as `(tw, th)`.
21999 for (w, h) in [(8usize, 4usize), (4, 8)] {
22000 assert!(
22001 rect_inter_luma_set(w, h, fctx).is_ok(),
22002 "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set"
22003 );
22004 corner_scan(w, h);
22005 }
22006}
22007
22008/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
22009/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
22010/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
22011/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
22012/// own width/height; a `0` leaves one whole-block rect transform unit
22013/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
22014/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
22015/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
22016/// every leaf of a split rect block is square and the existing square leaf
22017/// loop reconstructs it unchanged.
22018#[allow(clippy::too_many_arguments)]
22019fn read_block_tx_size_rect(
22020 dec: &mut SymbolDecoder,
22021 cdfs: &mut Cdfs,
22022 n: &mut Neighbours,
22023 at_mi: (usize, usize),
22024 (bw, bh): (usize, usize),
22025 (mi_cols, mi_rows): (usize, usize),
22026 skip: bool, fctx: &crate::decode::FrameCtx,
22027) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
22028 if lossless(fctx) {
22029 let mut leaves = Vec::new();
22030 for row in 0..bh / MI {
22031 for col in 0..bw / MI {
22032 leaves.push((row, col, 4, 4));
22033 }
22034 }
22035 return Ok(Some(leaves));
22036 }
22037 if skip {
22038 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
22039 // its own BLOCK size -- width above, height left -- not a transform.
22040 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
22041 return Ok(None);
22042 }
22043 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
22044 // `rect_inter_residual_supported` has already excluded everything above 32.
22045 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
22046 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
22047 // is TWO square top-level transform units side by side and a 64x128 one is
22048 // two stacked -- exactly what libaom `read_block_tx_size`
22049 // (decodeframe.c:1140) codes with its `idy/idx` loop over
22050 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
22051 // own `txfm_partition` symbol at depth 0.
22052 if bw.max(bh) > 64 {
22053 let tx = 64usize;
22054 let (max_w_mi, max_h_mi) = (
22055 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
22056 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
22057 );
22058 let mut leaves = Vec::new();
22059 if !fctx.tx_select_frame.with(std::cell::Cell::get) {
22060 for row in (0..bh / MI).step_by(tx / MI) {
22061 for col in (0..bw / MI).step_by(tx / MI) {
22062 leaves.push((row, col, tx, tx));
22063 }
22064 }
22065 for &(row, col, tw, th) in &leaves {
22066 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
22067 }
22068 return Ok(Some(leaves));
22069 }
22070 for row in (0..bh / MI).step_by(tx / MI) {
22071 for col in (0..bw / MI).step_by(tx / MI) {
22072 read_var_tx_size(
22073 dec,
22074 cdfs,
22075 n,
22076 at_mi,
22077 bw.max(bh),
22078 (max_w_mi, max_h_mi),
22079 (tx, tx),
22080 0,
22081 row,
22082 col,
22083 &mut leaves,
22084 );
22085 }
22086 }
22087 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
22088 return Err(unsupported(
22089 "an inter var-tx tree with a leaf transform larger than 64x64",
22090 ));
22091 }
22092 return Ok(Some(leaves));
22093 }
22094 let (tx_w, tx_h) = (bw, bh);
22095 if !fctx.tx_select_frame.with(std::cell::Cell::get) {
22096 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
22097 // transform, and `set_txfm_ctxs` records exactly what
22098 // `txfm_partition_update` would for that same unit.
22099 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
22100 hit!(RECT_INTER_TU_HITS);
22101 return Ok(None);
22102 }
22103 let ctx = txfm_partition_ctx_rect(
22104 n.above_txfm[at_mi.1],
22105 n.left_txfm[at_mi.0],
22106 bw.max(bh),
22107 tx_w,
22108 tx_h,
22109 );
22110 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
22111 hit!(TXFM_SPLIT_READS);
22112 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
22113 let (rng, _) = dec.debug_state();
22114 eprintln!(
22115 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
22116 at_mi.0,
22117 at_mi.1,
22118 u8::from(split)
22119 );
22120 }
22121 if !split {
22122 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
22123 hit!(RECT_INTER_TU_HITS);
22124 return Ok(None);
22125 }
22126 hit!(TXFM_SPLIT_HITS);
22127 hit!(RECT_INTER_TXSPLIT_HITS);
22128 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
22129 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
22130 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
22131 // rect one and its leaves carry their own width and height.
22132 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
22133 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
22134 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
22135 let mut leaves = Vec::new();
22136 for row in (0..bh / MI).step_by(sub_h / MI) {
22137 for col in (0..bw / MI).step_by(sub_w / MI) {
22138 read_var_tx_size(
22139 dec,
22140 cdfs,
22141 n,
22142 at_mi,
22143 bw.max(bh),
22144 (max_w_mi, max_h_mi),
22145 (sub_w, sub_h),
22146 1,
22147 row,
22148 col,
22149 &mut leaves,
22150 );
22151 }
22152 }
22153 Ok(Some(leaves))
22154}
22155
22156/// The chroma half of a whole-block rectangular INTER transform unit (both
22157/// [`decode_inter_block`] rect readers): `av1_get_max_uv_txsize(bsize)` gives
22158/// the strip's own rect chroma size at 4:2:0 (one unit for the whole block),
22159/// but at 4:4:4 the chroma plane block keeps the luma block's 64-px axis,
22160/// which `av1_get_adjusted_tx_size` caps at 32 (`TX_64X16` -> `TX_32X16`),
22161/// so it codes TWO units plane-major (every U, then every V --
22162/// `decode_token_recon_block`'s inter branch loops `for plane` outside
22163/// `for blk_row/blk_col` inside the one mu chunk). No unit codes a `tx_type`
22164/// symbol: each inherits the block-wide luma one (`av1_get_tx_type`'s inter
22165/// UV lookup at ss 0 reads the tx_type_map at its own mi, which a single-TU
22166/// luma block fills uniformly).
22167#[allow(clippy::too_many_arguments)]
22168fn read_inter_rect_chroma(
22169 dec: &mut SymbolDecoder,
22170 cdfs: &mut Cdfs,
22171 neighbours: &mut Neighbours,
22172 around: [(bool, bool, i32); 3],
22173 u: &mut PlaneBuf<'static>,
22174 v: &mut PlaneBuf<'static>,
22175 su: Pred<'_>,
22176 sv: Pred<'_>,
22177 at_mi: (usize, usize),
22178 (cpx, cpy): (usize, usize),
22179 (write_chroma_w, write_chroma_h): (usize, usize),
22180 chroma_side: usize,
22181 mode_for_tx: usize,
22182 luma_tx_type: TxType,
22183 fctx: &crate::decode::FrameCtx,
22184) -> Result<(Grid, Grid, Vec<((usize, usize), usize, Grid, usize, usize)>)> {
22185 let (uw, uh) = (write_chroma_w.min(32), write_chroma_h.min(32));
22186 let (nx, ny) = (write_chroma_w / uw, write_chroma_h / uh);
22187 let multi = nx * ny > 1;
22188 let set = rect_inter_chroma_set(uw, uh)?;
22189 let mut assembled: [Vec<i32>; 2] = [Vec::new(), Vec::new()];
22190 // The multi-unit stamps below are rewritten by the caller's whole-block
22191 // record (`record_rect_mi`/`record_split_luma_rect_mi` write ONE
22192 // whole-block chroma state, class `override-slot-on-one-arm`). The
22193 // block tail's square-mu derivation cannot express a non-square strip's
22194 // units, so the TRUE units travel back for the tail's `mu_chroma_units`
22195 // replay (the c8 re-stamp, at the strip's own tiling).
22196 let mut units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
22197 if multi {
22198 hit!(CHROMA_SPLIT_TX_HITS);
22199 assembled = [
22200 vec![0i32; chroma_side * chroma_side],
22201 vec![0i32; chroma_side * chroma_side],
22202 ];
22203 }
22204 for plane_idx in 1..=2 {
22205 let (src, buf) = if plane_idx == 1 { (su, &mut *u) } else { (sv, &mut *v) };
22206 for cu_row in 0..ny {
22207 for cu_col in 0..nx {
22208 let (span_x, span_y) = (uw << ss_x(fctx), uh << ss_y(fctx));
22209 let cu_mi = (
22210 at_mi.0 + cu_row * (span_y / MI),
22211 at_mi.1 + cu_col * (span_x / MI),
22212 );
22213 let cu_around = if multi {
22214 neighbours.around_mi_rect(cu_mi, span_x, span_y)
22215 } else {
22216 around
22217 };
22218 let (cu_x, cu_y) = (cpx + cu_col * uw, cpy + cu_row * uh);
22219 let cu_pred = src.offset(cu_row * uh * chroma_side + cu_col * uw);
22220 let cu_grid = read_inter_plane_rect(
22221 dec,
22222 cdfs,
22223 set,
22224 (uw, uh),
22225 chroma_side,
22226 plane_idx,
22227 cu_around[plane_idx],
22228 mode_for_tx,
22229 buf,
22230 cu_x,
22231 cu_y,
22232 cu_pred,
22233 Some(luma_tx_type),
22234 multi.then_some(3), fctx,
22235 )?
22236 .0;
22237 if multi {
22238 // Immediately, so the next unit of this block reads this
22239 // one's coefficient context (libaom updates the chroma
22240 // above/left contexts per unit).
22241 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &cu_grid);
22242 let dst = &mut assembled[plane_idx - 1];
22243 for rr in 0..uh {
22244 let start = (cu_row * uh + rr) * chroma_side + cu_col * uw;
22245 dst[start..start + uw].copy_from_slice(&cu_grid[rr * uw..][..uw]);
22246 }
22247 units.push((cu_mi, plane_idx, cu_grid, span_x, span_y));
22248 } else {
22249 assembled[plane_idx - 1] = embed_rect_grid(&cu_grid, uw, uh, chroma_side);
22250 }
22251 }
22252 }
22253 }
22254 let [ug, vg] = assembled;
22255 Ok((Grid::Own(ug), Grid::Own(vg), units))
22256}
22257
22258/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
22259/// the coefficients are read with the rect coefficient machinery
22260/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
22261/// types), inverted with the rect inverse transform
22262/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
22263/// and added onto the top-left `w x h` of the block's own square-strided
22264/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
22265/// and the coded `tx_type`.
22266///
22267/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
22268/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
22269#[allow(clippy::too_many_arguments)]
22270fn read_inter_plane_rect(
22271 dec: &mut SymbolDecoder,
22272 cdfs: &mut Cdfs,
22273 set: TxbSet,
22274 (w, h): (usize, usize),
22275 stride: usize,
22276 plane_idx: usize,
22277 around: (bool, bool, i32),
22278 tx_mode: usize,
22279 // lane-wave1 step (i): unread -- this reader records its write
22280 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
22281 // stays in the signature so every call site still proves the plane is
22282 // exclusively held while its coefficients are parsed.
22283 _plane: &mut PlaneBuf<'static>,
22284 x: usize,
22285 y: usize,
22286 prediction: Pred<'_>,
22287 inherited_luma_tx_type: Option<TxType>,
22288 luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx,
22289) -> Result<(Grid, TxType)> {
22290 // lane-av1mono: as [`read_plane`] -- a monochrome frame codes no chroma
22291 // coefficients (`plane < av1_num_planes == 1`).
22292 if plane_idx > 0 && mono(fctx) {
22293 return Ok((Grid::Zero(w * h), TxType::DctDct));
22294 }
22295 let skip_ctx = if plane_idx == 0 {
22296 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
22297 // block; a var-tx leaf passes its own neighbour-table context.
22298 luma_skip_ctx.unwrap_or(0)
22299 } else {
22300 // libaom `get_txb_ctx`: a chroma unit's context is
22301 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
22302 // plane block is bigger than the transform. Our chroma tables hold the
22303 // offset-7 rows first, so a multi-unit caller adds 3 through
22304 // `luma_skip_ctx` (same convention as [`read_plane`]).
22305 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
22306 };
22307 let mut coding = cdfs.txb(set, tx_mode);
22308 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
22309 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
22310 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
22311 // plane of a lossless block (the residual then goes through the WHT, so
22312 // the type only picks the scan, which is the default one).
22313 if lossless(fctx) {
22314 coding.tx_type = None;
22315 }
22316 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
22317 // the *longer* side of this rect transform.
22318 let default_tx_type = match inherited_luma_tx_type {
22319 Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx),
22320 None => TxType::DctDct,
22321 };
22322 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
22323 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
22324 let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
22325 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
22326 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
22327 // corner, zero-extended into the true `w x h` grid before the inverse
22328 // transform -- exactly what the intra superblock-strip path does. A
22329 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
22330 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
22331 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
22332 // rectangular shape (lane-sbpart r8).
22333 let (cw, ch) = (w.min(32), h.min(32));
22334 if plane_idx == 0 && w.max(h) == 64 {
22335 hit!(RECT64_INTER_TU_HITS);
22336 }
22337 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
22338 hit_do! {
22339 RECT32X8_INTER_TU_HITS.with(|c| {
22340 let mut v = c.get();
22341 v[usize::from(w == 8)] += 1;
22342 c.set(v);
22343 });
22344 }
22345 }
22346 let (corner, tx_type) = if (cw, ch) == (32, 32) {
22347 let scan32 = default_scan(TX32);
22348 read_coeffs(
22349 dec,
22350 &mut coding,
22351 &scan32,
22352 skip_ctx,
22353 dc_sign_ctx(around.2),
22354 default_tx_type,
22355 Some((w, h)),
22356 )?
22357 } else {
22358 read_coeffs_rect(
22359 dec,
22360 &mut coding,
22361 rect_scan(cw, ch)?,
22362 cw,
22363 ch,
22364 skip_ctx,
22365 dc_sign_ctx(around.2),
22366 default_tx_type,
22367 )?
22368 };
22369 let grid = extend_corner(corner, cw, ch, w, h);
22370 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
22371 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
22372 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
22373 }
22374 // `reconstruct_mc_rect` reads both buffers at the square prediction
22375 // stride, so the dense `w x h` residual is re-laid at that stride
22376 // (`TxParams::stride`) after the inverse transform.
22377 let tx = TxParams {
22378 w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type,
22379 qm: block_iqmatrix(fctx, plane_idx, w, h, tx_type),
22380 stride, lossless: lossless(fctx),
22381 };
22382 push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx);
22383 Ok((grid, tx_type))
22384}
22385
22386/// The coded `cw x ch` corner of a transform zero-extended into its true
22387/// `w x h` grid (a 64-length axis codes only its low 32 coefficients). A
22388/// corner that coded nothing stays the shared zero grid -- no allocation
22389/// (lane-coefgrid).
22390fn extend_corner(corner: Grid, cw: usize, ch: usize, w: usize, h: usize) -> Grid {
22391 if (cw, ch) == (w, h) {
22392 return corner;
22393 }
22394 if let Grid::Zero(_) = corner {
22395 return Grid::Zero(w * h);
22396 }
22397 let mut full = vec![0i32; w * h];
22398 for row in 0..ch {
22399 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
22400 }
22401 Grid::Own(full)
22402}
22403
22404/// [`embed_rect_grid`] that keeps the shared zero marker zero: an all-zero
22405/// transform unit's grid IS `Grid::Zero` (whose deref is the shared
22406/// `ZERO_RESIDUAL`), so re-laying it would read a zero-length slice.
22407fn embed_grid_stride(grid: &Grid, w: usize, h: usize, stride: usize) -> Grid {
22408 if is_zero_grid(grid) {
22409 return Grid::Zero(stride * stride);
22410 }
22411 Grid::Own(embed_rect_grid(grid, w, h, stride))
22412}
22413
22414/// A rect coefficient grid re-laid into the square `stride x stride` grid the
22415/// neighbour/deblock stamps downstream of the residual expect.
22416fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
22417 let mut full = vec![0i32; stride * stride];
22418 for row in 0..h {
22419 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
22420 }
22421 full
22422}
22423
22424/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
22425/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
22426/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
22427/// raster order, each reading its own coefficient context off the units
22428/// already decoded before it. Returns the block's luma grid (all-zero in the
22429/// split case, whose reconstruction has already happened unit by unit) and
22430/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
22431/// which for a split block lands on the top-left unit.
22432#[allow(clippy::too_many_arguments)]
22433fn read_inter_luma8(
22434 dec: &mut SymbolDecoder,
22435 cdfs: &mut Cdfs,
22436 neighbours: &mut Neighbours,
22437 leaf_mi: (usize, usize),
22438 y: &mut PlaneBuf<'static>,
22439 px: usize,
22440 py: usize,
22441 pred_y: Pred<'_>,
22442 mode_for_tx: usize,
22443 base_q_idx: u8,
22444 scan8: &[u16],
22445 scan4: &[u16],
22446 reduced_tx_set: bool,
22447 split: bool, fctx: &crate::decode::FrameCtx,
22448) -> Result<(Grid, TxType)> {
22449 // lane-lossless: an 8x8 inter block is FOUR 4x4 units (libaom
22450 // `read_block_tx_size`'s lossless TX_4X4), tree or no tree.
22451 let split = split || lossless(fctx);
22452 if !split {
22453 return read_inter_plane(
22454 dec,
22455 cdfs,
22456 if reduced_tx_set {
22457 TxbSet::Luma8Inter
22458 } else {
22459 TxbSet::Luma8InterSet1
22460 },
22461 scan8,
22462 0,
22463 neighbours.around_mi(leaf_mi, 8)[0],
22464 mode_for_tx,
22465 y,
22466 px,
22467 py,
22468 8,
22469 base_q_idx,
22470 pred_y,
22471 None,
22472 None, fctx,
22473 );
22474 }
22475 let mut first = TxType::DctDct;
22476 for tu_row in 0..2 {
22477 for tu_col in 0..2 {
22478 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
22479 let tu_pred = pred_y.view(8).offset(tu_row * 4 * 8 + tu_col * 4);
22480 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
22481 let (tu_grid, tu_tx_type) = read_inter_plane(
22482 dec,
22483 cdfs,
22484 if reduced_tx_set {
22485 TxbSet::Luma4Inter
22486 } else {
22487 TxbSet::Luma4InterSet1
22488 },
22489 scan4,
22490 0,
22491 neighbours.around_mi(tu_mi, 4)[0],
22492 mode_for_tx,
22493 y,
22494 px + tu_col * 4,
22495 py + tu_row * 4,
22496 4,
22497 base_q_idx,
22498 tu_pred,
22499 None,
22500 Some(tu_skip_ctx), fctx,
22501 )?;
22502 if tu_row == 0 && tu_col == 0 {
22503 first = tu_tx_type;
22504 }
22505 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
22506 }
22507 }
22508 Ok((Grid::Zero(64), first))
22509}
22510
22511/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
22512/// coefficient tables from -- the inter counterpart of [`txbset_for`].
22513/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
22514/// an inter block's chroma transform inherits the *colocated luma* unit's
22515/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
22516/// of the extended set the CHROMA transform size selects
22517/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
22518/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
22519/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
22520/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
22521/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
22522/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
22523/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
22524/// sync and only corrupted the inverse transform (one 64x64 superblock of
22525/// high-frequency chroma noise, luma bit-exact).
22526pub(crate) fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> TxType {
22527 reduce_inherited_chroma_tx_type_flagged(t, w, h, fctx.reduced_tx_set_inter.with(std::cell::Cell::get))
22528}
22529
22530/// [`reduce_inherited_chroma_tx_type`] against an explicit `reduced_tx_set`
22531/// bit (lane-intertx): the WRITER calls this with the frame's own header bit
22532/// ([`crate::cdf_state::Cdfs::reduced_tx_set`]) to derive the type an inter
22533/// block's chroma transform is coded with, the same derivation its reader
22534/// makes -- it has no `FrameCtx` in reach and must not silently read one
22535/// whose value can lag the frame being written (class `stale-context-bit`).
22536pub(crate) fn reduce_inherited_chroma_tx_type_flagged(t: TxType, w: usize, h: usize, reduced: bool) -> TxType {
22537 use TxType::*;
22538 let sqr_up = w.max(h);
22539 let sqr = w.min(h);
22540 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
22541 let allowed: &[TxType] = if sqr_up > 32 {
22542 // EXT_TX_SET_DCTONLY
22543 &[DctDct]
22544 } else if sqr_up == 32 || reduced {
22545 // EXT_TX_SET_DCT_IDTX
22546 &[DctDct, Idtx]
22547 } else if sqr == 16 {
22548 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
22549 // the four 1D ADST/FLIPADST types.
22550 &[
22551 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
22552 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
22553 ]
22554 } else {
22555 // EXT_TX_SET_ALL16
22556 return t;
22557 };
22558 if allowed.contains(&t) { t } else { DctDct }
22559}
22560
22561/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
22562/// from for a block libaom's `is_inter_block` calls inter -- which an intrabc
22563/// block is (`blockd.h:373`), so its `tx_type` comes off the inter `ext_tx`
22564/// sets, never the mode-indexed intra ones ([`txbset_for`]).
22565///
22566/// 64 is only ever the 64x64-block, depth-0, corner-scanned case
22567/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
22568/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
22569/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
22570/// regardless of the flag (`av1_get_ext_tx_set_type`'s
22571/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
22572/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
22573/// second table ([`TxbSet::Luma8Inter`]/[`TxbSet::Luma4Inter`]).
22574///
22575/// lane-av1txr: the intrabc leaf sites used to call a near-duplicate
22576/// `txbset_for_inter` whose `4` fell through to `Luma64` -- 32x32-class tables
22577/// (a 1024-entry grid) handed to a 4x4 dequant, which panicked at
22578/// `transform.rs`'s `inverse_transform_2d_typed_wh` the first time an intrabc
22579/// 4x4 TU coded a non-zero coefficient (`allintra0`/cpu-used=0). The
22580/// duplicate is gone; every inter-table site goes through this one mapping.
22581fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
22582 match tx_px {
22583 // lane-sb128c r1: a 128x128 inter block's own luma unit
22584 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
22585 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
22586 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
22587 // coincide -- exactly the set the whole-64x64 inter block already uses.
22588 64 => TxbSet::Luma64,
22589 32 => TxbSet::Luma32Inter,
22590 16 if reduced_tx_set => TxbSet::Luma16Inter,
22591 16 => TxbSet::Luma16InterSet1,
22592 8 if reduced_tx_set => TxbSet::Luma8Inter,
22593 8 => TxbSet::Luma8InterSet1,
22594 4 if reduced_tx_set => TxbSet::Luma4Inter,
22595 4 => TxbSet::Luma4InterSet1,
22596 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
22597 }
22598}
22599
22600/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
22601/// the only four sizes a `TxMode::Select` block's coded coefficient grid
22602/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
22603fn scan_for<'a>(
22604 tx_px: usize,
22605 scan32: &'a [u16],
22606 scan16: &'a [u16],
22607 scan8: &'a [u16],
22608 scan4: &'a [u16],
22609) -> &'a [u16] {
22610 match tx_px {
22611 32 => scan32,
22612 16 => scan16,
22613 8 => scan8,
22614 4 => scan4,
22615 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
22616 }
22617}
22618
22619
22620fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
22621 match tx_px {
22622 64 => TxbSet::Luma64,
22623 32 => TxbSet::Luma32,
22624 16 => TxbSet::Luma16,
22625 8 if reduced_tx_set => TxbSet::Luma8,
22626 8 => TxbSet::Luma8Set1,
22627 4 if reduced_tx_set => TxbSet::Luma4,
22628 4 => TxbSet::Luma4Set1,
22629 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
22630 }
22631}
22632
22633/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
22634/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
22635fn unit_log2(px: u32) -> i32 {
22636 if px == 0 {
22637 0
22638 } else {
22639 px.trailing_zeros() as i32 - 2
22640 }
22641}
22642
22643/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
22644/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
22645/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
22646/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
22647/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
22648/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
22649/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
22650/// block anywhere aborted the whole stream's decode before comparison).
22651fn lf_level(
22652 lf: &LoopFilterParams,
22653 plane_idx: usize,
22654 dir: usize,
22655 ref_frame: i8,
22656 delta_lf: i32,
22657 segment_id: u8, fctx: &crate::decode::FrameCtx,
22658) -> i32 {
22659 let base = i32::from(if plane_idx == 0 {
22660 lf.level[dir]
22661 } else if plane_idx == 1 {
22662 lf.level[2]
22663 } else {
22664 lf.level[3]
22665 });
22666 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
22667 // ref/mode delta scaling below, and regardless of `delta_enabled`
22668 // (that flag only gates `ref_deltas`/`mode_deltas`).
22669 let base = (base + delta_lf).clamp(0, 63);
22670 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
22671 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
22672 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
22673 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
22674 // for chroma.
22675 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
22676 // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely
22677 // when the frame codes no segmentation (`seg_lf_active`), which is what
22678 // spares the deblock loop two thread-local reads per 4x4 edge.
22679 let base = match seg_feature(usize::from(segment_id), feature, fctx) {
22680 Some(data) => (base + data).clamp(0, 63),
22681 None => base,
22682 };
22683 if !lf.delta_enabled {
22684 return base;
22685 }
22686 let scale = 1i32 << (base >> 5);
22687 let is_inter = ref_frame != 0;
22688 let is_globalmv = ref_frame < 0;
22689 let ref_idx = ref_frame.unsigned_abs() as usize;
22690 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
22691 if is_inter {
22692 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
22693 }
22694 lvl.clamp(0, 63)
22695}
22696
22697thread_local! {
22698 /// lane-pipefilt: [`EdgeCtx`]'s level LUT, memoised per thread. The table
22699 /// is a pure function of the frame's [`LoopFilterParams`], the plane, the
22700 /// pass and segment 0's own `SEG_LVL_ALT_LF_*` datum (the only thing
22701 /// [`lf_level`] reads out of the `FrameCtx` at `segment_id = 0`), so one
22702 /// build per plane and pass serves the whole frame. The pipeline builds
22703 /// an `EdgeCtx` per superblock-row band rather than per frame, which
22704 /// turned 20 builds a frame into ~680 -- 960 `lf_level` calls each.
22705 static LVL_CACHE: std::cell::RefCell<
22706 Vec<((usize, usize, LoopFilterParams, Option<i32>), [[u8; 15]; 64])>,
22707 > = const { std::cell::RefCell::new(Vec::new()) };
22708}
22709
22710/// `lf_level` over the whole `(base level, ref frame)` domain -- see
22711/// [`LVL_CACHE`]. `lf_level`'s own first step is
22712/// `(base0 + delta_lf).clamp(0, 63)`, so passing `b - base0` pins its base at
22713/// `b` and the rest of the function is a pure function of `(b, ref_frame)`.
22714fn lvl_table(
22715 lf: &LoopFilterParams,
22716 plane_idx: usize,
22717 dir: usize,
22718 base0: i32,
22719 fctx: &crate::decode::FrameCtx,
22720) -> [[u8; 15]; 64] {
22721 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
22722 let key = (plane_idx, dir, *lf, seg_feature(0, feature, fctx));
22723 if let Some(t) = LVL_CACHE.with(|c| {
22724 c.borrow().iter().find(|(k, _)| *k == key).map(|(_, t)| *t)
22725 }) {
22726 return t;
22727 }
22728 let mut lvl = [[0u8; 15]; 64];
22729 for (b, row) in lvl.iter_mut().enumerate() {
22730 for (r, cell) in row.iter_mut().enumerate() {
22731 *cell =
22732 lf_level(lf, plane_idx, dir, (r as i32 - 7) as i8, b as i32 - base0, 0, fctx) as u8;
22733 }
22734 }
22735 LVL_CACHE.with(|c| {
22736 let mut c = c.borrow_mut();
22737 if c.len() >= 8 {
22738 c.remove(0);
22739 }
22740 c.push((key, lvl));
22741 });
22742 lvl
22743}
22744
22745/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
22746/// no-segmentation, no-delta-LF path and to this decoder's own invariant
22747/// that a coded block's transform is always its own full size -- so a TU
22748/// edge is always also a PU edge, and the "both sides skipped, not a PU
22749/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
22750/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
22751/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
22752/// One plane pass's worth of [`edge_params`] constants (lane-deblock2): the
22753/// seven values that used to be re-passed per 4-pixel edge group -- half of
22754/// them on the stack, into an `inline(never)` body -- plus libaom's
22755/// `lfi->lfthr` idea in level form: `av1_loop_filter_frame_init` builds the
22756/// filter level for every `(base level, ref frame)` pair once per frame
22757/// instead of running `av1_get_filter_level`'s delta arithmetic per edge.
22758struct EdgeCtx<'a> {
22759 lf: &'a LoopFilterParams,
22760 n: &'a Neighbours,
22761 fctx: &'a crate::decode::FrameCtx,
22762 plane_idx: usize,
22763 dir: usize,
22764 chroma: bool,
22765 seg_lf_active: bool,
22766 /// `delta_lf_grid`'s column for this plane and direction.
22767 delta_idx: usize,
22768 /// `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for
22769 /// chroma.
22770 step: usize,
22771 /// This pass's own `lf.level[..]`, the LUT's base.
22772 base0: i32,
22773 /// `lf_level` at `[base level][ref frame + 7]`, with no segment
22774 /// override -- the whole domain, since a level is `0..=63` and a ref
22775 /// frame `-7..=7` (`ref_deltas` holds `TOTAL_REFS_PER_FRAME` = 8
22776 /// entries and is indexed by the ref frame's magnitude).
22777 lvl: [[u8; 15]; 64],
22778}
22779
22780impl<'a> EdgeCtx<'a> {
22781 fn new(
22782 lf: &'a LoopFilterParams,
22783 n: &'a Neighbours,
22784 plane_idx: usize,
22785 dir: usize,
22786 chroma: bool,
22787 seg_lf_active: bool,
22788 fctx: &'a crate::decode::FrameCtx,
22789 ) -> Self {
22790 let base0 = i32::from(if plane_idx == 0 {
22791 lf.level[dir]
22792 } else if plane_idx == 1 {
22793 lf.level[2]
22794 } else {
22795 lf.level[3]
22796 });
22797 let lvl = lvl_table(lf, plane_idx, dir, base0, fctx);
22798 Self {
22799 lf,
22800 n,
22801 fctx,
22802 plane_idx,
22803 dir,
22804 chroma,
22805 seg_lf_active,
22806 delta_idx: if plane_idx == 0 { dir } else { plane_idx + 1 },
22807 step: if chroma { 1 << (if dir == 0 { ss_x(fctx) } else { ss_y(fctx) }) } else { 1 },
22808 base0,
22809 lvl,
22810 }
22811 }
22812
22813 /// Spec 7.14.4's `get_filter_level`, off the table when no segment can
22814 /// override it (which is every frame that codes no segmentation).
22815 #[inline(always)]
22816 fn level(&self, ref_frame: i8, delta_lf: i32, seg: u8) -> i32 {
22817 if self.seg_lf_active {
22818 return lf_level(self.lf, self.plane_idx, self.dir, ref_frame, delta_lf, seg, self.fctx);
22819 }
22820 let b = (self.base0 + delta_lf).clamp(0, 63) as usize;
22821 debug_assert!((-7..=7).contains(&ref_frame));
22822 let r = (i32::from(ref_frame) + 7).clamp(0, 14) as usize;
22823 i32::from(self.lvl[b][r])
22824 }
22825}
22826
22827/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
22828/// no-segmentation, no-delta-LF path and to this decoder's own invariant
22829/// that a coded block's transform is always its own full size -- so a TU
22830/// edge is always also a PU edge, and the "both sides skipped, not a PU
22831/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
22832/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
22833/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
22834#[inline(always)]
22835fn edge_params(c: &EdgeCtx, x0: usize, y0: usize) -> Option<(u8, i32)> {
22836 let (mi_r, mi_c) = (
22837 plane_to_mi(c.chroma, y0, if c.chroma { ss_y(c.fctx) } else { 0 }),
22838 plane_to_mi(c.chroma, x0, if c.chroma { ss_x(c.fctx) } else { 0 }),
22839 );
22840 let cur_tx = if c.dir == 0 {
22841 tx_px_at(c.n, c.chroma, mi_r, mi_c)
22842 } else {
22843 tx_h_px_at(c.n, c.chroma, mi_r, mi_c)
22844 };
22845 // lane-deblock: `cur_tx` is a power-of-two pixel size, so the alignment
22846 // test is a mask, not the hardware `divl` this used to emit (10.7% of
22847 // `edge_params`' own samples sat on that divide's result test).
22848 //
22849 // Most 4-pixel edge groups die right here (a 4-aligned coordinate that
22850 // the covering transform does not start at), so this head is inlined
22851 // into the deblock loops and only survivors pay the call and the
22852 // register-spilling prologue of the body below.
22853 if cur_tx == 0 || (if c.dir == 0 { x0 } else { y0 }) & (cur_tx as usize - 1) != 0 {
22854 return None;
22855 }
22856 edge_params_body(c, x0, y0, mi_r, mi_c, cur_tx)
22857}
22858
22859/// [`edge_params`] past its transform-alignment gate.
22860#[inline(never)]
22861fn edge_params_body(
22862 c: &EdgeCtx,
22863 x0: usize,
22864 y0: usize,
22865 mi_r: usize,
22866 mi_c: usize,
22867 cur_tx: u32,
22868) -> Option<(u8, i32)> {
22869 let n = c.n;
22870 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
22871 // The previous cell must keep the odd parity `plane_to_mi` just
22872 // established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma group,
22873 // not the other half of this one.
22874 let (pv_mi_r, pv_mi_c) = if c.dir == 0 {
22875 (mi_r, mi_c - c.step)
22876 } else {
22877 (mi_r - c.step, mi_c)
22878 };
22879 let pv_tx = if c.dir == 0 {
22880 tx_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
22881 } else {
22882 tx_h_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
22883 };
22884 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
22885 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][c.delta_idx]);
22886 let pv_delta_lf =
22887 i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][c.delta_idx]);
22888
22889 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
22890 // SKIPPED INTER blocks is filtered only when it is also a prediction
22891 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
22892 // omission of this term (on the stale invariant "a coded block's transform
22893 // is always its own full size", which var-tx broke) had us filtering an
22894 // interior 8-px lattice the reference never touches: on the pinned 192x68
22895 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
22896 // libaom prices `pu_edge` in the PLANE's own pixels against the plane's
22897 // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] -
22898 // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma
22899 // edge of a sub-8x8 group is a prediction edge, even though the group's
22900 // bottom/right mi does not start there. Comparing mi origins instead is
22901 // the same test only while the block's own origin is aligned to its
22902 // size, which a 4x4 luma block read at the `| 1` mi is not.
22903 let cur_cell = n.blk_grid[mi_r * n.skip_grid_cols_mi + mi_c];
22904 let (cur_org, cur_dim) = (cur_cell.org, cur_cell.dim);
22905 let (org_px, dim_mi) = if c.dir == 0 {
22906 (usize::from(cur_org[1]), usize::from(cur_dim[0]))
22907 } else {
22908 (usize::from(cur_org[0]), usize::from(cur_dim[1]))
22909 };
22910 let pu_edge = if c.chroma {
22911 let ss = if c.dir == 0 { ss_x(c.fctx) } else { ss_y(c.fctx) };
22912 let plane_dim = ((dim_mi * MI) >> ss).max(4);
22913 (if c.dir == 0 { x0 } else { y0 }) % plane_dim == 0
22914 } else {
22915 plane_to_mi(false, if c.dir == 0 { x0 } else { y0 }, 0) == org_px
22916 };
22917 if !pu_edge
22918 && cur_ref != 0
22919 && pv_ref != 0
22920 && n.skip_at(mi_r, mi_c)
22921 && n.skip_at(pv_mi_r, pv_mi_c)
22922 {
22923 return None;
22924 }
22925 let (cur_seg, pv_seg) = if c.seg_lf_active {
22926 (segment_id_at(mi_r, mi_c, c.fctx), segment_id_at(pv_mi_r, pv_mi_c, c.fctx))
22927 } else {
22928 (0, 0)
22929 };
22930 let cur_level = c.level(cur_ref, cur_delta_lf, cur_seg);
22931 let pv_level = c.level(pv_ref, pv_delta_lf, pv_seg);
22932 if cur_level == 0 && pv_level == 0 {
22933 return None;
22934 }
22935 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
22936 let len: u8 = if c.chroma {
22937 if dim == 0 { 4 } else { 6 }
22938 } else {
22939 [4, 8, 14, 14, 14][dim]
22940 };
22941 let level = if cur_level != 0 { cur_level } else { pv_level };
22942 hit!(DEBLOCK_HITS);
22943 Some((len, level))
22944}
22945
22946/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
22947fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
22948 let sharpness = i32::from(sharpness);
22949 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
22950 let mut lim = level >> shift;
22951 if sharpness > 0 {
22952 lim = lim.min(9 - sharpness);
22953 }
22954 lim = lim.max(1);
22955 (2 * (level + 2) + lim, lim, level >> 4)
22956}
22957
22958#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
22959fn sclamp(v: i32, fctx: &crate::decode::FrameCtx) -> i32 {
22960 // libaom's `signed_char_clamp_high`: the clamp range scales with
22961 // `128 << (bit_depth - 8)` alongside the centering constant below.
22962 let scale = 1i32 << (bit_depth(fctx) - 8);
22963 v.clamp(-128 * scale, 128 * scale - 1)
22964}
22965
22966fn round_pow2(v: i32, n: u32) -> i32 {
22967 (v + (1 << (n - 1))) >> n
22968}
22969
22970/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
22971/// fallback.
22972fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32, fctx: &crate::decode::FrameCtx) -> [i32; 4] {
22973 if !mask {
22974 return [p1, p0, q0, q1];
22975 }
22976 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
22977 // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of
22978 // this kernel's eight clamps, and this kernel runs per deblocked sample.
22979 // Same bound, resolved once.
22980 let scale = 1i32 << (bit_depth(fctx) - 8);
22981 let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1);
22982 let centre = 128i32 * scale;
22983 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
22984 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
22985 let filter = sclamp(outer + 3 * (qs0 - ps0));
22986 let filter1 = sclamp(filter + 4) >> 3;
22987 let filter2 = sclamp(filter + 3) >> 3;
22988 let oq0 = sclamp(qs0 - filter1) + centre;
22989 let op0 = sclamp(ps0 + filter2) + centre;
22990 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
22991 let oq1 = sclamp(qs1 - tap) + centre;
22992 let op1 = sclamp(ps1 + tap) + centre;
22993 [op1, op0, oq0, oq1]
22994}
22995
22996/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
22997/// `filter4`'s narrow taps.
22998#[allow(clippy::too_many_arguments)]
22999fn filter6(
23000 mask: bool,
23001 thresh: i32,
23002 flat: bool,
23003 p2: i32,
23004 p1: i32,
23005 p0: i32,
23006 q0: i32,
23007 q1: i32,
23008 q2: i32, fctx: &crate::decode::FrameCtx,
23009) -> [i32; 4] {
23010 if flat && mask {
23011 [
23012 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
23013 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
23014 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
23015 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
23016 ]
23017 } else {
23018 filter4(mask, thresh, p1, p0, q0, q1, fctx)
23019 }
23020}
23021
23022/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
23023#[allow(clippy::too_many_arguments)]
23024fn filter8(
23025 mask: bool,
23026 thresh: i32,
23027 flat: bool,
23028 p3: i32,
23029 p2: i32,
23030 p1: i32,
23031 p0: i32,
23032 q0: i32,
23033 q1: i32,
23034 q2: i32,
23035 q3: i32, fctx: &crate::decode::FrameCtx,
23036) -> [i32; 6] {
23037 if flat && mask {
23038 [
23039 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
23040 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
23041 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
23042 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
23043 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
23044 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
23045 ]
23046 } else {
23047 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1, fctx);
23048 [p2, op1, op0, oq0, oq1, q2]
23049 }
23050}
23051
23052/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
23053/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
23054/// way -- they are only ever taps here, never written).
23055#[allow(clippy::too_many_arguments)]
23056fn filter14(
23057 mask: bool,
23058 thresh: i32,
23059 flat: bool,
23060 flat2: bool,
23061 p6: i32,
23062 p5: i32,
23063 p4: i32,
23064 p3: i32,
23065 p2: i32,
23066 p1: i32,
23067 p0: i32,
23068 q0: i32,
23069 q1: i32,
23070 q2: i32,
23071 q3: i32,
23072 q4: i32,
23073 q5: i32,
23074 q6: i32, fctx: &crate::decode::FrameCtx,
23075) -> [i32; 12] {
23076 if flat2 && flat && mask {
23077 [
23078 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
23079 round_pow2(
23080 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
23081 4,
23082 ),
23083 round_pow2(
23084 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
23085 4,
23086 ),
23087 round_pow2(
23088 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
23089 4,
23090 ),
23091 round_pow2(
23092 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
23093 4,
23094 ),
23095 round_pow2(
23096 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
23097 4,
23098 ),
23099 round_pow2(
23100 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
23101 4,
23102 ),
23103 round_pow2(
23104 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
23105 4,
23106 ),
23107 round_pow2(
23108 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
23109 4,
23110 ),
23111 round_pow2(
23112 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
23113 4,
23114 ),
23115 round_pow2(
23116 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
23117 4,
23118 ),
23119 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
23120 ]
23121 } else {
23122 let [op2, op1, op0, oq0, oq1, oq2] =
23123 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
23124 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
23125 }
23126}
23127
23128/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
23129/// the first (`q0`) sample past the edge, `outer_stride` advances to the
23130/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
23131/// the next along the edge's own filtering direction.
23132#[allow(clippy::too_many_arguments)]
23133fn filter_edge(
23134 data: &mut [u16],
23135 base: usize,
23136 outer_stride: isize,
23137 tap_stride: isize,
23138 len: u8,
23139 level: i32,
23140 sharpness: u8, fctx: &crate::decode::FrameCtx,
23141) {
23142 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
23143 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
23144 // every 8-bit threshold (including the flat masks' fixed `1`) is
23145 // compared against a raw pixel difference on the stream's own bit-depth
23146 // scale, so each is shifted left by `bit_depth - 8` before use.
23147 let shift = bit_depth(fctx) - 8;
23148 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
23149 let flat_thresh = 1i32 << shift;
23150 let smax = sample_max(fctx);
23151 for i in 0..4isize {
23152 let center = (base as isize + i * outer_stride) as usize;
23153 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
23154 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
23155 match len {
23156 4 => {
23157 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
23158 let mask = (p1 - p0).abs() <= limit
23159 && (q1 - q0).abs() <= limit
23160 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
23161 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1, fctx);
23162 data[idx(-2)] = op1.clamp(0, smax) as u16;
23163 data[idx(-1)] = op0.clamp(0, smax) as u16;
23164 data[idx(0)] = oq0.clamp(0, smax) as u16;
23165 data[idx(1)] = oq1.clamp(0, smax) as u16;
23166 }
23167 6 => {
23168 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
23169 let mask = (p2 - p1).abs() <= limit
23170 && (p1 - p0).abs() <= limit
23171 && (q1 - q0).abs() <= limit
23172 && (q2 - q1).abs() <= limit
23173 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
23174 let flat = (p1 - p0).abs() <= flat_thresh
23175 && (q1 - q0).abs() <= flat_thresh
23176 && (p2 - p0).abs() <= flat_thresh
23177 && (q2 - q0).abs() <= flat_thresh;
23178 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2, fctx);
23179 data[idx(-2)] = op1.clamp(0, smax) as u16;
23180 data[idx(-1)] = op0.clamp(0, smax) as u16;
23181 data[idx(0)] = oq0.clamp(0, smax) as u16;
23182 data[idx(1)] = oq1.clamp(0, smax) as u16;
23183 }
23184 8 => {
23185 let (p3, p2, p1, p0, q0, q1, q2, q3) =
23186 (px(-4), px(-3), px(-2), px(-1), px(0), px(1)

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