forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mod.rs3797 lines, 153.8 KiBHistoryRawDownload
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
44mod counters;
45pub use counters::*;
46
47mod frame_tile;
48
49mod inter_block8;
50mod inter_intra_arm;
51use inter_block8::*;
52use inter_intra_arm::*;
53
54mod inter_block;
55use inter_block::*;
56
57mod post_filter;
58use post_filter::*;
59
60mod coeffs;
61pub(crate) use coeffs::*;
62
63#[cfg(target_arch = "x86_64")]
64mod cdef_simd;
65
66mod rect;
67pub(crate) use rect::*;
68
69mod rect4;
70use rect4::*;
71
72mod block;
73mod wave;
74pub use block::*;
75
76mod leaf8;
77use leaf8::*;
78
79mod leaf_sub8;
80use leaf_sub8::*;
81
82mod cdef;
83use cdef::*;
84
85mod inter_shapes;
86pub use inter_shapes::*;
87
88mod deblock;
89pub(crate) use deblock::*;
90
91#[cfg(target_arch = "x86_64")]
92mod deblock_simd;
93
94mod replay;
95pub(crate) use replay::*;
96
97mod key_tile;
98pub use key_tile::*;
99
100mod inter_ctx;
101pub(crate) use inter_ctx::*;
102
103#[cfg(test)]
104mod obmc_skip_chroma_tests;
105
106mod sub8_inter;
107pub(crate) use frame_tile::*;
108use sub8_inter::*;
109
110/// Per-frame decode state, one instance per decoded stream (lane-thread1).
111///
112/// Every field here used to be a `thread_local!` static, which made a decode a
113/// function of the calling THREAD's history rather than of the bitstream alone
114/// -- and made frame-parallel decoding impossible, since a worker thread sees
115/// empty state. The cells keep exactly the interior mutability the statics
116/// had, so every read/write site is byte-identical; what changes is WHERE the
117/// state lives: `stream.rs` owns one `FrameCtx` and threads `&FrameCtx` down
118/// the decode call graph.
119///
120/// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to
121/// exactly one thread's decode, and is never shared between workers.
122/// One frame's in-loop filter intermediates, as [`FrameCtx::capture_stages`]
123/// asks for them: each plane's post-deblock (pre-CDEF) and post-CDEF
124/// (pre-restoration) samples, at the decoder's own plane stride.
125pub(crate) struct FilterStages {
126 /// Post-deblock, pre-CDEF planes (Y, U, V).
127 pub(crate) deblocked: [Vec<u16>; 3],
128 /// Post-CDEF, pre-restoration planes (Y, U, V).
129 pub(crate) cdefed: [Vec<u16>; 3],
130 /// Each plane's stride (and so its width in the buffers above).
131 pub(crate) stride: [usize; 3],
132}
133
134/// Takes whatever the last capturing decode left (see
135/// [`FrameCtx::capture_stages`]).
136#[allow(dead_code)] // read from the encoder's loop restoration search
137pub(crate) fn take_filter_stages(fctx: &FrameCtx) -> Option<FilterStages> {
138 fctx.stages.borrow_mut().take()
139}
140
141pub(crate) struct FrameCtx {
142 /// lane-av1lr: when set, the frame filter chain leaves its post-deblock
143 /// and post-CDEF planes in [`FrameCtx::stages`] for the ENCODER's loop
144 /// restoration search (spec 7.17 reads both: the stripe interior from
145 /// the post-CDEF plane, its 3-row border from the post-deblock one).
146 /// Off for every decode but that search, and off it costs one bool read
147 /// per frame and not a single copy.
148 pub(crate) capture_stages: std::cell::Cell<bool>,
149 pub(crate) stages: std::cell::RefCell<Option<FilterStages>>,
150 pub(crate) sb128_flag: std::cell::Cell<bool>,
151 /// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every
152 /// motion compensation of THIS frame runs, already resolved to a kernel.
153 /// `mc::predict` used to hardwire `Regular`, so the encoder's search,
154 /// trial and recon could only ever build a REGULAR prediction whatever
155 /// the frame header said; it lives here (and is copied by
156 /// [`filter_ctx_copy`]) so a tile-search worker thread reads the same
157 /// kernel the frame header wrote instead of the default.
158 pub(crate) interp_filter: std::cell::Cell<crate::mc::InterpFilterKind>,
159 /// lane-lossless: this frame's per-segment lossless table -- libaom's
160 /// `xd->lossless[MAX_SEGMENTS]`, computed ONCE per frame in the header
161 /// (spec 5.9.12 `CodedLossless`: each segment at `qindex == 0` with zero
162 /// plane deltas, `get_qindex` applying that segment's own `SEG_LVL_ALT_Q`).
163 /// Every block-decoder rule that reads [`decode::lossless`] resolves it
164 /// through the BLOCK's own `segment_id`: TX_4X4 with the Walsh-Hadamard
165 /// transform on every plane, the dropped `tx_type` symbol and the narrowed
166 /// `is_cfl_allowed` (libaom `read_tx_size` (`decodeframe.c`),
167 /// `read_tx_type` (`decodetxb.c`), `is_cfl_allowed` (`blockd.h`)) follow
168 /// the SEGMENT, so a frame whose segments disagree codes lossless and
169 /// lossy blocks side by side.
170 pub(crate) lossless_per_seg: std::cell::Cell<[bool; MAX_SEGMENTS]>,
171 /// lane-av1txr: this frame header's `disable_cdf_update` (spec 5.9.2).
172 /// When set, the tile reader must not adapt any CDF it reads, or its
173 /// tables drift away from the encoder's and the frame desyncs mid-tile
174 /// (libaom: `allow_update_cdf = allow_update_cdf &&
175 /// !cm->features.disable_cdf_update`, `decodeframe.c:2909`).
176 pub(crate) disable_cdf_update: std::cell::Cell<bool>,
177 pub(crate) cdef_bits: std::cell::Cell<u8>,
178 pub(crate) bit_depth: std::cell::Cell<u8>,
179 /// lane-av1mono: the sequence header's `color_config.mono_chrome` (spec
180 /// 5.5.2), i.e. `NumPlanes == 1`. libaom threads this as
181 /// `av1_num_planes(cm)` and every chroma read site is guarded by
182 /// `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`,
183 /// `:1208`) or bounded by `plane < num_planes`; a monochrome frame codes
184 /// NO `uv_mode`/`cfl`/`angle_delta_uv`/`palette_uv` symbol and NO chroma
185 /// coefficients on any block. Set once per frame from the sequence header
186 /// (like [`FrameCtx::bit_depth`]), so a mono frame decoded on a thread
187 /// that last saw a 4:2:0 one never inherits the wrong plane count.
188 pub(crate) mono_chrome: std::cell::Cell<bool>,
189 /// lane-av1-444: sequence subsampling_x/y. 1,1 is 4:2:0; 0,0 is 4:4:4.
190 pub(crate) subsampling_x: std::cell::Cell<u8>,
191 pub(crate) subsampling_y: std::cell::Cell<u8>,
192 pub(crate) superres: std::cell::Cell<(u32, u32)>,
193 pub(crate) cdef_transmitted: std::cell::Cell<bool>,
194 pub(crate) cdef_sb_cols: std::cell::Cell<usize>,
195 pub(crate) cdef_idx_grid: std::cell::RefCell<Vec<u8>>,
196 pub(crate) delta_q_present: std::cell::Cell<bool>,
197 pub(crate) delta_q_res: std::cell::Cell<i32>,
198 pub(crate) current_q_idx: std::cell::Cell<i32>,
199 pub(crate) quant_deltas: std::cell::Cell<crate::quant::QuantDeltas>,
200 /// lane-av1-qmatrix: this frame's quantisation-matrix LEVEL per plane,
201 /// straight from spec 5.9.12's `qm_y`/`qm_u`/`qm_v` (the parsed 4-bit
202 /// value IS the table level -- libaom `quant_params->qmatrix_level_y/u/v`,
203 /// decodeframe.c:1902-1917; the `aom_get_qmlevel` formula that maps
204 /// base_q_idx onto a level is encoder-side only). 15 is libaom's flat
205 /// sentinel (`NUM_QM_LEVELS - 1`, stored as NULL tables) and the default
206 /// every `using_qmatrix == 0` frame keeps, so a matrix-free stream
207 /// selects no matrix.
208 pub(crate) qm_levels: std::cell::Cell<[u8; 3]>,
209 pub(crate) delta_lf_present: std::cell::Cell<bool>,
210 pub(crate) delta_lf_res: std::cell::Cell<i32>,
211 pub(crate) delta_lf_multi: std::cell::Cell<bool>,
212 pub(crate) current_delta_lf: std::cell::Cell<[i32; 4]>,
213 pub(crate) seg: std::cell::RefCell<SegmentationParams>,
214 pub(crate) seg_ids: std::cell::RefCell<Vec<u8>>,
215 pub(crate) prev_seg_ids: std::cell::RefCell<Vec<u8>>,
216 pub(crate) seg_mi_dims: std::cell::Cell<(usize, usize)>,
217 pub(crate) above_seg_pred: std::cell::RefCell<Vec<u8>>,
218 pub(crate) left_seg_pred: std::cell::RefCell<Vec<u8>>,
219 pub(crate) cur_segment_id: std::cell::Cell<u8>,
220 pub(crate) seg_tile_origin: std::cell::Cell<(usize, usize)>,
221 pub(crate) tx_select_inter: std::cell::Cell<bool>,
222 /// Whether the tile being decoded is an INTRA-ONLY frame's (key/intra-only
223 /// frame). libaom runs `set_txfm_ctxs` for EVERY block of EVERY frame
224 /// (`decodeframe.c` `parse_decode_block`), so an intra-only frame
225 /// maintains the `TXFM_CONTEXT` bands exactly like an inter one; only this
226 /// decoder's inter-side publishing was wired. See
227 /// [`Neighbours::fill_lf_grid_rect`]'s band publish.
228 pub(crate) intra_only: std::cell::Cell<bool>,
229 /// This FRAME's own `tx_mode == TxMode::Select`, set for EVERY frame
230 /// (intra included). [`Self::tx_select_inter`] cannot stand in for it:
231 /// an intrabc block rides an INTRA frame, but libaom still reads its
232 /// var-tx `txfm_partition` tree under the frame's `TxMode::Select`.
233 pub(crate) tx_select_frame: std::cell::Cell<bool>,
234 pub(crate) reduced_tx_set_inter: std::cell::Cell<bool>,
235 pub(crate) enable_filter_intra_inter: std::cell::Cell<bool>,
236 pub(crate) palette_pred: std::cell::RefCell<Option<Vec<u16>>>,
237 /// Set when a reconstruction input is inconsistent with its block: a
238 /// palette/intrabc override or a CfL AC signal whose size is not the
239 /// transform block's. A conforming stream cannot produce one, so the
240 /// frame is refused with `Error::Corrupt` once its tiles are decoded.
241 pub(crate) corrupt: std::cell::Cell<Option<&'static str>>,
242 pub(crate) intrabc_mi_grid: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>>,
243 pub(crate) intrabc_dv: std::cell::Cell<Option<(i32, i32)>>,
244 pub(crate) luma_tx_type: std::cell::Cell<TxType>,
245 pub(crate) intrabc_chroma_tx: std::cell::Cell<Option<TxType>>,
246 pub(crate) intra_in_inter_mode: std::cell::Cell<Option<(usize, bool)>>,
247 pub(crate) inter_strip_chroma: std::cell::Cell<Option<InterStripChroma>>,
248 pub(crate) inter_last_mc:
249 std::cell::Cell<Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>>,
250 pub(crate) enable_edge_filter: std::cell::Cell<bool>,
251 pub(crate) last_frame_wide_margin: std::cell::RefCell<Option<Picture>>,
252 pub(crate) reach_sb_px: std::cell::Cell<usize>,
253 pub(crate) grain_bit_depth: std::cell::Cell<u32>,
254}
255
256impl std::fmt::Debug for FrameCtx {
257 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258 f.write_str("FrameCtx")
259 }
260}
261
262impl FrameCtx {
263 /// Records the first inconsistency this frame hit; the frame is then refused.
264 pub(crate) fn flag_corrupt(&self, why: &'static str) {
265 if self.corrupt.get().is_none() {
266 self.corrupt.set(Some(why));
267 }
268 }
269
270 /// A fresh context, every field at the default its thread-local
271 /// predecessor was born with.
272 pub(crate) fn new() -> Self {
273 Self {
274 // A DECODER context is seeded from the stream alone: every real
275 // decode overwrites this from the parsed sequence header
276 // (`set_sb128`, stream.rs). The encoder's own contexts start at
277 // the size this process encodes -- see [`FrameCtx::for_encoder`].
278 sb128_flag: std::cell::Cell::new(false),
279 interp_filter: std::cell::Cell::new(crate::mc::InterpFilterKind::Regular),
280 lossless_per_seg: std::cell::Cell::new([false; MAX_SEGMENTS]),
281 disable_cdf_update: std::cell::Cell::new(false),
282 cdef_bits: std::cell::Cell::new(0),
283 bit_depth: std::cell::Cell::new(8),
284 mono_chrome: std::cell::Cell::new(false),
285 subsampling_x: std::cell::Cell::new(1),
286 subsampling_y: std::cell::Cell::new(1),
287 superres: std::cell::Cell::new((0, 8)),
288 cdef_transmitted: std::cell::Cell::new(false),
289 cdef_sb_cols: std::cell::Cell::new(0),
290 capture_stages: std::cell::Cell::new(false),
291 stages: std::cell::RefCell::new(None),
292 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
293 delta_q_present: std::cell::Cell::new(false),
294 delta_q_res: std::cell::Cell::new(1),
295 current_q_idx: std::cell::Cell::new(0),
296 quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas {
297 y_dc: 0,
298 u_dc: 0,
299 u_ac: 0,
300 v_dc: 0,
301 v_ac: 0,
302 }),
303 qm_levels: std::cell::Cell::new([crate::qm::NUM_QM_LEVELS as u8 - 1; 3]),
304 delta_lf_present: std::cell::Cell::new(false),
305 delta_lf_res: std::cell::Cell::new(1),
306 delta_lf_multi: std::cell::Cell::new(false),
307 current_delta_lf: std::cell::Cell::new([0; 4]),
308 seg: std::cell::RefCell::new(SegmentationParams::default()),
309 seg_ids: std::cell::RefCell::new(Vec::new()),
310 prev_seg_ids: std::cell::RefCell::new(Vec::new()),
311 seg_mi_dims: std::cell::Cell::new((0, 0)),
312 above_seg_pred: std::cell::RefCell::new(Vec::new()),
313 left_seg_pred: std::cell::RefCell::new(Vec::new()),
314 cur_segment_id: std::cell::Cell::new(0),
315 seg_tile_origin: std::cell::Cell::new((0, 0)),
316 tx_select_inter: std::cell::Cell::new(false),
317 tx_select_frame: std::cell::Cell::new(false),
318 intra_only: std::cell::Cell::new(false),
319 reduced_tx_set_inter: std::cell::Cell::new(false),
320 enable_filter_intra_inter: std::cell::Cell::new(false),
321 palette_pred: std::cell::RefCell::new(None),
322 corrupt: std::cell::Cell::new(None),
323 intrabc_mi_grid: std::cell::RefCell::new(None),
324 intrabc_dv: std::cell::Cell::new(None),
325 luma_tx_type: std::cell::Cell::new(TxType::DctDct),
326 intrabc_chroma_tx: std::cell::Cell::new(None),
327 intra_in_inter_mode: std::cell::Cell::new(None),
328 inter_strip_chroma: std::cell::Cell::new(None),
329 inter_last_mc: std::cell::Cell::new(None),
330 enable_edge_filter: std::cell::Cell::new(false),
331 last_frame_wide_margin: std::cell::RefCell::new(None),
332 reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK),
333 grain_bit_depth: std::cell::Cell::new(8),
334 }
335 }
336
337 /// A context for the ENCODER's own trial decodes: it starts at the
338 /// superblock size this process encodes (`crate::encode::sb128_on`) so
339 /// the mode search's `Reach` and the filter search's internal decodes
340 /// agree with the tile writer. A decoder never reads that knob -- doing
341 /// so coupled every decode to the encoder's process-global and raced the
342 /// 128-superblock decode gates against the encoder witness.
343 pub(crate) fn for_encoder() -> Self {
344 let ctx = Self::new();
345 let on = crate::encode::sb128_on();
346 ctx.sb128_flag.set(on);
347 ctx.reach_sb_px
348 .set(if on { 128 } else { crate::encode::SUPERBLOCK });
349 ctx
350 }
351}
352
353/// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)`
354/// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent
355/// `with` still wins for the scratch pools and gate counters that stay
356/// thread-local.
357pub(crate) trait WithRef {
358 fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
359 f(self)
360 }
361}
362impl<T: ?Sized> WithRef for T {}
363
364/// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads.
365///
366/// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread),
367/// and the post-decode filter chain reads exactly these fields: the bit depth
368/// (every kernel's clamp and threshold shift), the segmentation table
369/// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state
370/// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s
371/// default -- a field that turns out to be read after all shows up as a hash
372/// mismatch in
373/// `a_real_stream_filters_identically_with_one_and_four_filter_threads`.
374pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
375 let out = FrameCtx::new();
376 out.bit_depth.set(fctx.bit_depth.get());
377 out.mono_chrome.set(fctx.mono_chrome.get());
378 out.subsampling_x.set(fctx.subsampling_x.get());
379 out.subsampling_y.set(fctx.subsampling_y.get());
380 out.interp_filter.set(fctx.interp_filter.get());
381 out.grain_bit_depth.set(fctx.grain_bit_depth.get());
382 out.superres.set(fctx.superres.get());
383 out.seg_mi_dims.set(fctx.seg_mi_dims.get());
384 out.seg.replace(*fctx.seg.borrow());
385 out.seg_ids.replace(fctx.seg_ids.borrow().clone());
386 // lane-b128m: the superblock size travels with the copy. A tile SEARCH
387 // worker (`encode::search_tiles`) gets its context from here, so dropping
388 // it made every worker search at 64 while the calling thread searched at
389 // 128 -- the bytes a frame came out as then depended on the tile thread
390 // count under `EC_AV1_SB128`.
391 out.sb128_flag.set(fctx.sb128_flag.get());
392 out.reach_sb_px.set(fctx.reach_sb_px.get());
393 out
394}
395
396use crate::cdf;
397use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
398use crate::encode::{Picture, Reach};
399use crate::intra::predict;
400use crate::mc;
401use crate::msac::SymbolDecoder;
402use crate::mvstack::{
403 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
404 MiGrid, MiInfo, NO_REF1, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
405 find_mv_stack_with_sign_bias, mv16, mv32, reference_mode_ctx, single_ref_p1_ctx,
406 single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
407 uni_comp_ref_p1_ctx,
408};
409use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
410use crate::transform::{TxType, dequant_and_inverse_typed_wh};
411
412const PARTITION_NONE: usize = 0;
413const PARTITION_HORZ: usize = 1;
414const PARTITION_VERT: usize = 2;
415const PARTITION_SPLIT: usize = 3;
416const PARTITION_HORZ_A: usize = 4;
417const PARTITION_HORZ_B: usize = 5;
418const PARTITION_VERT_A: usize = 6;
419const PARTITION_VERT_B: usize = 7;
420const PARTITION_HORZ_4: usize = 8;
421const PARTITION_VERT_4: usize = 9;
422const SB_MI: u32 = 16;
423const BLOCK_MI: u32 = 8;
424
425// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
426// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
427// superblock's own top-left mi?", the loop-restoration read's unit span, the
428// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
429// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
430// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
431// inside a 128 superblock).
432thread_local! {
433 /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the
434 /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream
435 /// prints gigabytes otherwise). Unset = every frame, as before.
436 static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
437 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
438}
439
440/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
441/// that frame's DECODE-order index.
442pub fn set_coeff_trace_frame(idx: usize) {
443 COEFF_TRACE_FRAME.with(|c| {
444 if c.get().is_none() {
445 let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
446 Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
447 // unset: keep tracing every frame, as before this rung existed
448 Err(_) => usize::MAX - 1,
449 };
450 c.set(Some(want));
451 }
452 });
453 COEFF_TRACE_CUR.with(|c| c.set(idx));
454 if crate::envflags::env_flag!("EC_TRACE_COEFF") {
455 eprintln!("EC_COEFF_FRAME decode_idx={idx}");
456 }
457}
458
459pub(crate) fn coeff_trace_on() -> bool {
460 if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
461 return false;
462 }
463 match COEFF_TRACE_FRAME.with(|c| c.get()) {
464 // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
465 // env var unset: trace every frame.
466 None => true,
467 Some(w) if w >= usize::MAX - 1 => true,
468 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
469 }
470}
471
472/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
473pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
474 fctx.sb128_flag.with(|c| c.set(v));
475 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
476}
477
478/// lane-av1mixloss: sets [`FrameCtx::lossless_per_seg`] (called once per frame
479/// from `stream.rs`).
480pub(crate) fn set_lossless_per_seg(table: [bool; MAX_SEGMENTS], fctx: &crate::decode::FrameCtx) {
481 fctx.lossless_per_seg.with(|c| c.set(table));
482}
483
484/// The BLOCK's own lossless bit: libaom's `xd->lossless[mbmi->segment_id]`.
485/// The table is computed once per frame (libaom `decodeframe.c:5205`:
486/// `qindex == 0` with every plane delta 0, `av1_get_qindex` applying the
487/// segment's `SEG_LVL_ALT_Q`), but the frame never carries ONE lossless rule
488/// -- `read_tx_size`, `read_tx_type` and `is_cfl_allowed` all index it by the
489/// BLOCK's own segment id, which the spec-order `segment_id` read sets before
490/// any mode/transform symbol of the block. A frame whose segments disagree
491/// codes TX_4X4/WHT blocks and normal blocks side by side.
492pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool {
493 let seg_id = usize::from(fctx.cur_segment_id.with(|c| c.get()));
494 fctx.lossless_per_seg.with(|c| c.get())[seg_id]
495}
496
497/// Sets [`FrameCtx::disable_cdf_update`] (called once per frame from
498/// `stream.rs`).
499pub(crate) fn set_disable_cdf_update(v: bool, fctx: &crate::decode::FrameCtx) {
500 fctx.disable_cdf_update.with(|c| c.set(v));
501}
502
503/// This frame's `disable_cdf_update`, for the tile readers --
504/// [`msac::SymbolDecoder::set_cdf_update`](crate::msac::SymbolDecoder::set_cdf_update).
505pub(crate) fn cdf_update_disabled(fctx: &crate::decode::FrameCtx) -> bool {
506 fctx.disable_cdf_update.with(|c| c.get())
507}
508
509/// The transform side a block of `side` pixels codes: its own (capped at the
510/// caller's own largest) normally, 4 on a lossless BLOCK, where libaom's
511/// `read_tx_size` returns TX_4X4 before it looks at anything else
512/// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return
513/// TX_4X4;`).
514pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize {
515 if lossless(fctx) { 4 } else { px }
516}
517
518/// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to
519/// 32x32 -- but on a LOSSLESS BLOCK only when the block's CHROMA plane block
520/// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller.
521/// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom
522/// picks the 13-symbol one (class `wrong-alphabet-same-value`).
523pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool {
524 if lossless(fctx) {
525 // `is_cfl_allowed`: at lossless CfL is available only when the
526 // partition size equals the transform size -- the CHROMA plane block
527 // must be a single TX_4X4. True for an 8x8 partition at 4:2:0 (its
528 // plane block is 4x4) and for 4x4 partitions; FALSE for an 8x8
529 // partition at 4:4:4, whose plane block is 8x8 -- that partition
530 // reads the 13-symbol uv_mode CDF, and reading the CFL alphabet
531 // there desynced the tile from the leaf's own uv_mode symbol (class
532 // `wrong-alphabet-same-value`).
533 (bw >> ss_x(fctx)).max(4) == 4 && (bh >> ss_y(fctx)).max(4) == 4
534 } else {
535 bw <= 32 && bh <= 32
536 }
537}
538
539fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
540 fctx.sb128_flag.with(|c| c.get())
541}
542
543/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
544pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
545 if sb128(fctx) { SB_MI * 2 } else { SB_MI }
546}
547
548thread_local! {
549 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
550 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
551}
552
553/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
554/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
555/// 5.11.4), which this decoder used to read and throw away.
556#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
557pub(crate) fn part128_gathered_symbols() -> usize {
558 PART128_GATHERED_SYMBOLS.with(|c| c.get())
559}
560
561/// Current value of [`PART128_SYMBOLS`].
562#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
563pub(crate) fn part128_symbols() -> usize {
564 PART128_SYMBOLS.with(|c| c.get())
565}
566
567/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
568/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
569/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
570/// the 64/32 levels sum 6.
571pub(crate) fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
572 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
573 [32768 - split, 32768, 0]
574}
575
576/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
577pub(crate) const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
578pub(crate) const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
579
580// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
581// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
582// frame-level flag through the recursive block decode -- `0` (the default)
583// makes every call a true no-op, matching every existing gate stream's
584// `cdef_bits == 0` behaviour exactly.
585// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
586// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
587// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
588// blocks every non-8-bit stream from reaching a decode call, so this is `8`
589// on every path that runs today -- threading it now (rather than the literal
590// `8`) is stage 1 of widening past that refusal without re-deriving every
591// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
592// depth (this decoder's own internal choice, matches dav1d/libaom).
593/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
594/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
595pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
596 (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
597}
598/// The current stream's bit depth, for callers (e.g. dequant) that need the
599/// raw value rather than the derived clamp bound.
600pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
601 fctx.bit_depth.with(std::cell::Cell::get)
602}
603/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
604/// [`crate::stream`]'s decode loop.
605pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
606 fctx.bit_depth.with(|c| c.set(bit_depth));
607}
608
609/// This stream's `mono_chrome` (see [`FrameCtx::mono_chrome`]): a
610/// monochrome frame has `NumPlanes == 1`, so no block codes any chroma
611/// symbol or chroma coefficient and the output picture is luma only.
612pub(crate) fn mono(fctx: &crate::decode::FrameCtx) -> bool {
613 fctx.mono_chrome.with(std::cell::Cell::get)
614}
615
616/// Sets [`mono`] for the current thread, called once per frame from
617/// [`crate::stream`]'s decode loop like [`set_bit_depth`].
618pub(crate) fn set_mono(mono_chrome: bool, fctx: &crate::decode::FrameCtx) {
619 fctx.mono_chrome.with(|c| c.set(mono_chrome));
620}
621
622/// Sequence subsampling. Set once per frame from stream.rs, like set_mono.
623pub(crate) fn set_subsampling(ss_x: u8, ss_y: u8, fctx: &crate::decode::FrameCtx) {
624 fctx.subsampling_x.set(ss_x);
625 fctx.subsampling_y.set(ss_y);
626}
627
628#[inline]
629pub(crate) fn ss_x(fctx: &crate::decode::FrameCtx) -> usize {
630 fctx.subsampling_x.get() as usize
631}
632
633#[inline]
634pub(crate) fn ss_y(fctx: &crate::decode::FrameCtx) -> usize {
635 fctx.subsampling_y.get() as usize
636}
637
638/// libaom ROUND_POWER_OF_TWO. At ss=1 equals div_ceil(dim, 2); at ss=0 is dim.
639#[inline]
640pub(crate) fn round_ss(dim: usize, ss: usize) -> usize {
641 (dim + ((1usize << ss) >> 1)) >> ss
642}
643
644/// This frame's superres state: `(upscaled_width, superres_denom)`, or
645/// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
646/// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
647/// `read_lr`'s unit corners and the pixel filters themselves -- works in
648/// UPSCALED coordinates while deblock and CDEF work in downscaled ones
649/// (libaom `av1_superres_upscale` in `decodeframe.c`, and
650/// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x`
651/// superres arms). Set once per frame from [`crate::stream`]'s decode
652/// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
653/// so a later frame never inherits it.
654/// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
655/// `denom` 8) for a frame that is not superres-scaled.
656pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
657 fctx.superres.with(|c| c.set((upscaled_width, denom)));
658}
659
660/// `(upscaled_width, superres_denom)` when this frame is superres-scaled
661/// (libaom `av1_superres_scaled`), else `None`.
662pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
663 let (w, d) = fctx.superres.with(std::cell::Cell::get);
664 (w > 0 && d != 8).then_some((w, d))
665}
666
667/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
668/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
669/// block dimensions decide it -- never the square `side`/`chroma_side`, which
670/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
671/// bigger than the real block in one axis.
672pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool {
673 if w >= 8 && h >= 8 {
674 return true;
675 }
676 hit!(WARP_PLANE_SUPPRESS_HITS);
677 false
678}
679
680/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
681/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
682/// one), so it is always `0` here.
683fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
684 let d = fctx.quant_deltas.with(|c| c.get());
685 match plane_idx {
686 0 => (d.y_dc, 0),
687 1 => (d.u_dc, d.u_ac),
688 _ => (d.v_dc, d.v_ac),
689 }
690}
691
692/// lane-av1-qmatrix: records this FRAME's quantisation-matrix levels
693/// ([`crate::decode::FrameCtx::qm_levels`]) from the parsed
694/// `quantization_params`. Called from `stream.rs` at the frame header, where
695/// the refusal this lane lifted used to sit.
696pub(crate) fn set_qm_levels(levels: [u8; 3], fctx: &crate::decode::FrameCtx) {
697 fctx.qm_levels.with(|c| c.set(levels));
698}
699
700/// This block's inverse quantisation matrix -- libaom `av1_get_iqmatrix`
701/// (`av1/common/quant_common.c:243`) plus `setup_segmentation_dequant`'s
702/// `av1_use_qmatrix` gate, evaluated per dequantisation call site the same
703/// way the site already evaluates its quantizer index. `None` dequantises
704/// flat (the only behaviour before lane-av1-qmatrix):
705/// - a level of 15, which is both libaom's flat sentinel and what every
706/// `using_qmatrix == 0` frame's levels are parked at;
707/// - a 1D/identity transform (`is_2d_transform` false: libaom's
708/// `av1_get_iqmatrix` reads the NULL slot for those);
709/// - a LOSSLESS block (libaom `av1_use_qmatrix`'s `!xd->lossless[seg]`: the
710/// segment-adjusted quantizer index clamped to 0 with all five plane
711/// deltas zero -- the same `block_q_idx` every other dequant site reads).
712fn block_iqmatrix(
713 fctx: &crate::decode::FrameCtx,
714 plane_idx: usize,
715 w: usize,
716 h: usize,
717 tx_type: TxType,
718) -> Option<crate::qm::Iqm> {
719 let levels = fctx.qm_levels.with(|c| c.get());
720 let level = levels[plane_idx.min(2)];
721 if usize::from(level) >= crate::qm::NUM_QM_LEVELS - 1 {
722 return None;
723 }
724 if !tx_type.is_2d_transform() {
725 return None;
726 }
727 let d = fctx.quant_deltas.with(|c| c.get());
728 if block_q_idx(fctx) == 0
729 && d.y_dc == 0
730 && d.u_dc == 0
731 && d.u_ac == 0
732 && d.v_dc == 0
733 && d.v_ac == 0
734 {
735 return None;
736 }
737 crate::qm::iwt_matrix(usize::from(level), plane_idx != 0, w, h)
738}
739
740/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
741/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
742/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
743/// A no-op when `delta_q_present` is unset, or when this block is not at the
744/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
745/// libaom, collapsed here to a position check since a partition tree's
746/// top-left leaf is the only block that can ever land there), or when that
747/// leaf both *is* the whole superblock and is `skip` (the one case libaom
748/// itself skips the read, state carrying over unchanged).
749fn maybe_read_delta_q(
750 dec: &mut SymbolDecoder,
751 cdfs: &mut Cdfs,
752 mi_r: usize,
753 mi_c: usize,
754 is_whole_sb: bool,
755 skip: bool,
756 fctx: &crate::decode::FrameCtx,
757) {
758 if !fctx.delta_q_present.with(|c| c.get()) {
759 return;
760 }
761 let sb_mi = sb_mi_cur(fctx) as usize;
762 if !mi_r.is_multiple_of(sb_mi) || !mi_c.is_multiple_of(sb_mi) {
763 return;
764 }
765 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
766 // computed against the sequence's own superblock size (lane-sb128b r1:
767 // it used to be hardcoded against 64 and disabled under `sb128`, which a
768 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
769 // wrong).
770 if is_whole_sb && skip {
771 return;
772 }
773 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
774 const DELTA_Q_SMALL: i32 = 3;
775 if abs >= DELTA_Q_SMALL {
776 let rem_bits = dec.literal(3) + 1;
777 let thr = (1i32 << rem_bits) + 1;
778 abs = dec.literal(rem_bits) as i32 + thr;
779 }
780 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
781 let reduced = if sign_negative { -abs } else { abs };
782 hit!(DELTA_Q_HITS);
783 let res = fctx.delta_q_res.with(|c| c.get());
784 fctx.current_q_idx
785 .with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
786}
787
788/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
789/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
790/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
791/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
792/// read once into index 0 otherwise.
793fn maybe_read_delta_lf(
794 dec: &mut SymbolDecoder,
795 cdfs: &mut Cdfs,
796 mi_r: usize,
797 mi_c: usize,
798 is_whole_sb: bool,
799 skip: bool,
800 fctx: &crate::decode::FrameCtx,
801) {
802 if !fctx.delta_lf_present.with(|c| c.get()) {
803 return;
804 }
805 let sb_mi = sb_mi_cur(fctx) as usize;
806 if !mi_r.is_multiple_of(sb_mi) || !mi_c.is_multiple_of(sb_mi) {
807 return;
808 }
809 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
810 // computed against the sequence's own superblock size (lane-sb128b r1:
811 // it used to be hardcoded against 64 and disabled under `sb128`, which a
812 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
813 // wrong).
814 if is_whole_sb && skip {
815 return;
816 }
817 let multi = fctx.delta_lf_multi.with(|c| c.get());
818 let res = fctx.delta_lf_res.with(|c| c.get());
819 let count = if multi { 4 } else { 1 };
820 let mut cur = fctx.current_delta_lf.with(|c| c.get());
821 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
822 #[allow(clippy::needless_range_loop)]
823 for i in 0..count {
824 let mut abs = if multi {
825 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
826 } else {
827 dec.symbol(&mut cdfs.delta_lf) as i32
828 };
829 const DELTA_LF_SMALL: i32 = 3;
830 if abs >= DELTA_LF_SMALL {
831 let rem_bits = dec.literal(3) + 1;
832 let thr = (1i32 << rem_bits) + 1;
833 abs = dec.literal(rem_bits) as i32 + thr;
834 }
835 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
836 let reduced = if sign_negative { -abs } else { abs };
837 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
838 hit!(DELTA_LF_HITS);
839 }
840 fctx.current_delta_lf.with(|c| c.set(cur));
841}
842
843/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
844/// after `skip` is known at every block-decode call site. A no-op at
845/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
846/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
847/// `allow_intrabc`, so neither needs a separate check here. Reads once per
848/// superblock, at the first non-skip block.
849fn maybe_read_cdef_idx(
850 dec: &mut SymbolDecoder,
851 mi_r: usize,
852 mi_c: usize,
853 // The reading BLOCK's own span in 4x4 mode-info units: a block wider or
854 // taller than one 64x64 CDEF unit is the first non-skip block of EVERY
855 // unit it covers, so its one literal drives all of them (lane-b128r).
856 (w_mi, h_mi): (usize, usize),
857 skip: bool,
858 fctx: &crate::decode::FrameCtx,
859) {
860 let bits = fctx.cdef_bits.with(|c| c.get());
861 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
862 return;
863 }
864 let idx = dec.literal(u32::from(bits)) as u8;
865 fctx.cdef_transmitted.with(|c| c.set(true));
866 hit!(CDEF_IDX_HITS);
867 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
868 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
869 if sb_cols > 0 {
870 // lane-b128r: libaom's four CDEF units of a 128 superblock all read
871 // their strength off the MB_MODE_INFO of the first non-skip block in
872 // their own unit -- and a block that COVERS several units (the 128
873 // root's own 128x128 block, the only one there is) is that block for
874 // every unit it covers, so one literal drives all four. This grid is
875 // per 64x64 unit, so the read stamps every unit the block covers; one
876 // that is smaller than a unit stamps exactly the cell it always did.
877 let (rows, cols) = (
878 (h_mi / SB_MI as usize).max(1),
879 (w_mi / SB_MI as usize).max(1),
880 );
881 fctx.cdef_idx_grid.with(|g| {
882 let mut g = g.borrow_mut();
883 for dr in 0..rows {
884 for dc in 0..cols {
885 let i = (sb_r + dr) * sb_cols + sb_c + dc;
886 if sb_c + dc < sb_cols && i < g.len() {
887 g[i] = idx;
888 }
889 }
890 }
891 });
892 }
893}
894
895thread_local! {
896 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
897 /// lane-golomb2: the (lowest, highest) quantizer index any block has been
898 /// dequantized with, i.e. `block_q_idx`'s own span. A gate that means to
899 /// exercise `SEG_LVL_ALT_Q` needs a stream where this span is WIDER than
900 /// zero (class `gate-blind-to-feature`): segmentation being enabled says
901 /// nothing about the segments carrying distinct quantizers.
902 static BLOCK_Q_SPAN: std::cell::Cell<(i32, i32)> = const { std::cell::Cell::new((i32::MAX, i32::MIN)) };
903}
904
905/// Installs this frame's segmentation parameters and allocates its map, with
906/// `prev` the primary reference frame's saved map (spec
907/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
908/// slot). Called once per frame, whether or not segmentation is enabled.
909pub(crate) fn set_segmentation(
910 seg: SegmentationParams,
911 mi_rows: usize,
912 mi_cols: usize,
913 prev: Option<&[u8]>,
914 fctx: &crate::decode::FrameCtx,
915) {
916 if crate::envflags::env_flag!("EC_HDR") {
917 eprintln!(
918 "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}",
919 seg.enabled,
920 seg.update_map,
921 seg.temporal_update,
922 seg.seg_id_pre_skip,
923 seg.last_active_seg_id,
924 seg.feature_data
925 );
926 }
927 fctx.seg.with(|s| *s.borrow_mut() = seg);
928 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
929 fctx.seg_ids
930 .with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
931 fctx.prev_seg_ids.with(|m| {
932 let mut m = m.borrow_mut();
933 m.clear();
934 if let Some(p) = prev
935 && p.len() == mi_rows * mi_cols
936 {
937 m.extend_from_slice(p);
938 }
939 });
940 fctx.above_seg_pred
941 .with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
942 fctx.left_seg_pred
943 .with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
944 fctx.cur_segment_id.with(|c| c.set(0));
945}
946
947/// This frame's decoded segment map, to be stored into whichever reference
948/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
949pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
950 fctx.seg_ids.with(|m| m.borrow().clone())
951}
952
953/// How many distinct segment ids any decoded block has carried.
954#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
955pub(crate) fn segment_ids_seen() -> usize {
956 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
957}
958
959/// The lowest and highest quantizer index any decoded block was dequantized
960/// with (`(i32::MAX, i32::MIN)` when nothing decoded).
961#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
962pub(crate) fn block_q_span() -> (i32, i32) {
963 BLOCK_Q_SPAN.with(|c| c.get())
964}
965
966/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
967/// being decoded, with its `FeatureData` value.
968fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
969 fctx.seg.with(|s| {
970 let s = s.borrow();
971 s.feature_active(segment_id, feature)
972 .then(|| i32::from(s.feature_data[segment_id][feature]))
973 })
974}
975
976/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
977/// `av1_get_qindex`) for the block currently being decoded: the running
978/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
979/// Every dequant call site reads the block's quantizer through here.
980fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
981 let base = fctx.current_q_idx.with(|c| c.get());
982 let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
983 let q = match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
984 Some(data) => (base + data).clamp(0, 255),
985 None => base,
986 };
987 // lane-d792: which SEGMENT a block's quantizer came out of, beside the
988 // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels
989 // already proven equal is a segment-id defect, not a quantizer one.
990 if crate::envflags::env_flag!("EC_DQCOEFF") {
991 eprintln!("OUR_Q base={base} seg={seg_id} q={q}");
992 }
993 hit_do!(BLOCK_Q_SPAN.with(|c| {
994 let (lo, hi) = c.get();
995 c.set((lo.min(q), hi.max(q)));
996 }););
997 q
998}
999
1000/// The segment id recorded for one mi cell of the current frame's map.
1001fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
1002 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1003 if mi_r >= mi_rows || mi_c >= mi_cols {
1004 return 0;
1005 }
1006 fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
1007}
1008
1009/// `set_segment_id`: stamps `id` over every mi cell this block covers.
1010fn write_segment_id(
1011 mi_r: usize,
1012 mi_c: usize,
1013 w_mi: usize,
1014 h_mi: usize,
1015 id: u8,
1016 fctx: &crate::decode::FrameCtx,
1017) {
1018 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1019 let (x_mis, y_mis) = (
1020 w_mi.min(mi_cols.saturating_sub(mi_c)),
1021 h_mi.min(mi_rows.saturating_sub(mi_r)),
1022 );
1023 fctx.seg_ids.with(|m| {
1024 let mut m = m.borrow_mut();
1025 for y in 0..y_mis {
1026 for x in 0..x_mis {
1027 m[(mi_r + y) * mi_cols + mi_c + x] = id;
1028 }
1029 }
1030 });
1031 fctx.cur_segment_id.with(|c| c.set(id));
1032 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1033}
1034
1035/// `copy_segment_id` (libaom `decodemv.c:342`): the previous frame's map is
1036/// inherited VERBATIM over this block's own mi footprint -- per-cell copies,
1037/// not the minified id [`predicted_segment_id`] hands the block. Without a
1038/// previous map the footprint is zeroed, exactly as the C NULL branch does.
1039fn copy_segment_ids(
1040 mi_r: usize,
1041 mi_c: usize,
1042 w_mi: usize,
1043 h_mi: usize,
1044 fctx: &crate::decode::FrameCtx,
1045) {
1046 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1047 let (x_mis, y_mis) = (
1048 w_mi.min(mi_cols.saturating_sub(mi_c)),
1049 h_mi.min(mi_rows.saturating_sub(mi_r)),
1050 );
1051 fctx.seg_ids.with(|m| {
1052 let mut m = m.borrow_mut();
1053 fctx.prev_seg_ids.with(|p| {
1054 let p = p.borrow();
1055 for y in 0..y_mis {
1056 for x in 0..x_mis {
1057 let idx = (mi_r + y) * mi_cols + mi_c + x;
1058 m[idx] = p.get(idx).copied().unwrap_or(0);
1059 }
1060 }
1061 });
1062 });
1063}
1064
1065/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
1066/// `last_frame_seg_map`): the minimum previous-frame segment id over the
1067/// block's own mi footprint. `0` when there is no previous map.
1068fn predicted_segment_id(
1069 mi_r: usize,
1070 mi_c: usize,
1071 w_mi: usize,
1072 h_mi: usize,
1073 fctx: &crate::decode::FrameCtx,
1074) -> u8 {
1075 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1076 fctx.prev_seg_ids.with(|m| {
1077 let m = m.borrow();
1078 if m.is_empty() {
1079 return 0;
1080 }
1081 let (x_mis, y_mis) = (
1082 w_mi.min(mi_cols.saturating_sub(mi_c)),
1083 h_mi.min(mi_rows.saturating_sub(mi_r)),
1084 );
1085 let mut id = u8::MAX;
1086 for y in 0..y_mis {
1087 for x in 0..x_mis {
1088 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
1089 }
1090 }
1091 if id == u8::MAX { 0 } else { id }
1092 })
1093}
1094
1095/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
1096fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
1097 if reference == 0 {
1098 return diff;
1099 }
1100 if reference >= max - 1 {
1101 return max - diff - 1;
1102 }
1103 let half = if 2 * reference < max {
1104 diff <= 2 * reference
1105 } else {
1106 diff <= 2 * (max - reference - 1)
1107 };
1108 if half {
1109 return if diff & 1 != 0 {
1110 reference + ((diff + 1) >> 1)
1111 } else {
1112 reference - (diff >> 1)
1113 };
1114 }
1115 if 2 * reference < max {
1116 diff
1117 } else {
1118 max - (diff + 1)
1119 }
1120}
1121
1122/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
1123/// frame's already-decoded above/left/above-left neighbours.
1124fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
1125 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1126 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
1127 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
1128 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
1129 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
1130 let ctx = match prev_ul {
1131 None => 0,
1132 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
1133 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
1134 Some(_) => 0,
1135 };
1136 let pred = match (prev_u, prev_l) {
1137 (None, l) => l.unwrap_or(0),
1138 (Some(u), None) => u,
1139 (Some(u), Some(l)) => {
1140 if prev_ul == Some(u) {
1141 u
1142 } else {
1143 l
1144 }
1145 }
1146 };
1147 (pred, ctx)
1148}
1149
1150/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
1151/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
1152/// that prediction. Does NOT write the map -- callers do.
1153fn read_segment_id(
1154 dec: &mut SymbolDecoder,
1155 cdfs: &mut Cdfs,
1156 mi_r: usize,
1157 mi_c: usize,
1158 skip: bool,
1159 fctx: &crate::decode::FrameCtx,
1160) -> u8 {
1161 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
1162 if skip {
1163 return pred as u8;
1164 }
1165 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
1166 hit!(SEG_ID_HITS);
1167 let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
1168 let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active);
1169 // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..`
1170 // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff.
1171 if crate::envflags::env_flag!("EC_TRACE_SEG") {
1172 eprintln!(
1173 "EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}",
1174 dec.debug_state().0
1175 );
1176 }
1177 id as u8
1178}
1179
1180/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
1181/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
1182/// caller decides which by passing `pre_skip`).
1183// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1184#[allow(clippy::too_many_arguments)]
1185fn intra_segment_id(
1186 dec: &mut SymbolDecoder,
1187 cdfs: &mut Cdfs,
1188 mi_r: usize,
1189 mi_c: usize,
1190 w_mi: usize,
1191 h_mi: usize,
1192 skip: bool,
1193 fctx: &crate::decode::FrameCtx,
1194) {
1195 if !fctx.seg.with(|s| s.borrow().enabled) {
1196 return;
1197 }
1198 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
1199 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1200}
1201
1202/// Whether this frame's intra blocks read their `segment_id` before `skip`
1203/// (`SegIdPreSkip`); `false` also when segmentation is off.
1204fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
1205 fctx.seg.with(|s| {
1206 let s = s.borrow();
1207 s.enabled && s.seg_id_pre_skip
1208 })
1209}
1210
1211/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
1212/// Called at both spec positions of an inter frame's block: `pre_skip = true`
1213/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
1214// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1215#[allow(clippy::too_many_arguments)]
1216fn inter_segment_id(
1217 dec: &mut SymbolDecoder,
1218 cdfs: &mut Cdfs,
1219 mi_r: usize,
1220 mi_c: usize,
1221 w_mi: usize,
1222 h_mi: usize,
1223 skip: bool,
1224 pre_skip: bool,
1225 fctx: &crate::decode::FrameCtx,
1226) {
1227 let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
1228 let s = s.borrow();
1229 (
1230 s.enabled,
1231 s.update_map,
1232 s.temporal_update,
1233 s.seg_id_pre_skip,
1234 )
1235 });
1236 if !enabled {
1237 return;
1238 }
1239 if !update_map {
1240 // The map is inherited from the previous frame, and libaom's
1241 // `copy_segment_id` (decodemv.c:342) does that VERBATIM -- a memcpy of
1242 // the previous map over the block's own footprint, mixed ids intact --
1243 // while the id the BLOCK itself carries is the min over that footprint
1244 // (`get_predicted_segment_id`). Stamping the min here flattened mixed
1245 // footprints into the saved map, and every later frame whose
1246 // `update_map == 0` copy or temporal prediction read that position
1247 // dequantized with the wrong segment's `SEG_LVL_ALT_Q` (class
1248 // `simplified-inheritance`).
1249 copy_segment_ids(mi_r, mi_c, w_mi, h_mi, fctx);
1250 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
1251 fctx.cur_segment_id.with(|c| c.set(id));
1252 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1253 return;
1254 }
1255 if pre_skip && !pre_skip_frame {
1256 return;
1257 }
1258 if !pre_skip && skip {
1259 // libaom: a skipped block never codes `seg_id_predicted`, and its
1260 // segment id is the spatial prediction.
1261 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
1262 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
1263 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1264 return;
1265 }
1266 let id = if temporal_update {
1267 let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
1268 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
1269 hit!(SEG_PRED_HITS);
1270 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
1271 if predicted {
1272 predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
1273 } else {
1274 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1275 }
1276 } else {
1277 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1278 };
1279 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1280}
1281
1282/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
1283fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
1284 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
1285 // so contribute 0) outside the tile -- the availability check here is
1286 // what keeps a previous tile's stamps out of this tile's context.
1287 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1288 let above = if mi_r > row0 {
1289 fctx.above_seg_pred
1290 .with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
1291 } else {
1292 0
1293 };
1294 let left = if mi_c > col0 {
1295 fctx.left_seg_pred
1296 .with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
1297 } else {
1298 0
1299 };
1300 usize::from(above + left)
1301}
1302
1303/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
1304fn stamp_seg_pred(
1305 mi_r: usize,
1306 mi_c: usize,
1307 w_mi: usize,
1308 h_mi: usize,
1309 value: u8,
1310 fctx: &crate::decode::FrameCtx,
1311) {
1312 fctx.above_seg_pred.with(|m| {
1313 let mut m = m.borrow_mut();
1314 for i in 0..w_mi {
1315 if let Some(cell) = m.get_mut(mi_c + i) {
1316 *cell = value;
1317 }
1318 }
1319 });
1320 fctx.left_seg_pred.with(|m| {
1321 let mut m = m.borrow_mut();
1322 for i in 0..h_mi {
1323 if let Some(cell) = m.get_mut(mi_r + i) {
1324 *cell = value;
1325 }
1326 }
1327 });
1328}
1329
1330/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
1331/// answer differs from the standalone-block answer the call sites used before
1332/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
1333/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
1334/// block's top-left `(px, py)`.
1335#[allow(clippy::too_many_arguments)]
1336fn tu_reach(
1337 bw: usize,
1338 bh: usize,
1339 col_off: usize,
1340 row_off: usize,
1341 tx: usize,
1342 block: Reach,
1343 px: usize,
1344 py: usize,
1345 width: usize,
1346 height: usize,
1347 fctx: &crate::decode::FrameCtx,
1348) -> Reach {
1349 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
1350 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
1351 if fixed != standalone {
1352 hit!(SPLIT_TU_REACH_FIX_HITS);
1353 }
1354 fixed
1355}
1356
1357/// [`tu_reach`] for a unit whose LUMA footprint is a `tx_w` x `tx_h` rect
1358/// (lane-av1-422b: a 4:2:2 chroma unit is square in chroma pixels, but its
1359/// luma anchor is `(chroma_tx << ss_x, chroma_tx << ss_y)` -- at ss (1,0)
1360/// twice as wide as it is tall). Same predicate as [`tu_reach`]; the
1361/// square mismatch counter only means anything when the footprint actually
1362/// is square.
1363// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1364#[allow(clippy::too_many_arguments)]
1365fn tu_reach_rect(
1366 bw: usize,
1367 bh: usize,
1368 col_off: usize,
1369 row_off: usize,
1370 tx_w: usize,
1371 tx_h: usize,
1372 block: Reach,
1373 px: usize,
1374 py: usize,
1375 width: usize,
1376 height: usize,
1377 fctx: &crate::decode::FrameCtx,
1378) -> Reach {
1379 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block);
1380 if tx_w == tx_h {
1381 let standalone = Reach::of(tx_w, px + col_off, py + row_off, width, height, fctx);
1382 if fixed != standalone {
1383 hit!(SPLIT_TU_REACH_FIX_HITS);
1384 }
1385 }
1386 fixed
1387}
1388
1389/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1390/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1391/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1392static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1393
1394/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1395pub(crate) fn note_fwd_kf() {
1396 hit!(FWD_KF_HITS);
1397}
1398
1399thread_local! {
1400 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1401}
1402
1403/// Current value of [`TXFM_SPLIT_READS`].
1404#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1405pub(crate) fn txfm_split_reads() -> usize {
1406 TXFM_SPLIT_READS.with(|c| c.get())
1407}
1408
1409/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1410/// [`ENABLE_FILTER_INTRA_INTER`].
1411pub(crate) fn set_inter_tx_mode(
1412 tx_select: bool,
1413 reduced_tx_set: bool,
1414 enable_filter_intra: bool,
1415 fctx: &crate::decode::FrameCtx,
1416) {
1417 fctx.tx_select_inter.with(|c| c.set(tx_select));
1418 fctx.intra_only.with(|c| c.set(false));
1419 fctx.tx_select_frame.with(|c| c.set(tx_select));
1420 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1421 fctx.enable_filter_intra_inter
1422 .with(|c| c.set(enable_filter_intra));
1423}
1424
1425fn bump_ab16(arm: usize) {
1426 hit_do! {
1427 AB16_HITS.with(|c| {
1428 let mut v = c.get();
1429 v[arm] += 1;
1430 c.set(v);
1431 });
1432 }
1433}
1434
1435/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1436pub(crate) fn bump_inter_edge_strip(idx: usize) {
1437 hit_do! {
1438 INTER_EDGE_STRIP_HITS.with(|c| {
1439 let mut v = c.get();
1440 v[idx] += 1;
1441 c.set(v);
1442 });
1443 }
1444}
1445
1446fn bump_edge_both_cut(level: usize) {
1447 hit_do! {
1448 EDGE_BOTH_CUT_HITS.with(|c| {
1449 let mut v = c.get();
1450 v[level] += 1;
1451 c.set(v);
1452 });
1453 }
1454}
1455
1456// lane-av1muchroma site 1: the total number of samples by which
1457// `decode_block`'s SKIP arm chroma bookkeeping grids fell SHORT of their own
1458// plane block, summed over every skipped block decoded. It reads the
1459// allocation's real length, so it measures the shape rather than proxying a
1460// condition: the square form this lane removed is `side >> ss_x` squared,
1461// which at 4:2:2 (ss (1,0)) is exactly HALF the `side >> ss_x` x `side >> ss_y`
1462// plane block, and restoring it drives this counter strictly positive on
1463// every 4:2:2 skip block. Zero on 4:2:0 and 4:4:4, where the two forms are
1464// the same number.
1465thread_local! {
1466 static SKIP_ARM_CHROMA_SHORT_SAMPLES: std::cell::Cell<usize> =
1467 const { std::cell::Cell::new(0) };
1468}
1469
1470/// Current value of [`SKIP_ARM_CHROMA_SHORT_SAMPLES`].
1471#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1472pub(crate) fn skip_arm_chroma_short_samples() -> usize {
1473 SKIP_ARM_CHROMA_SHORT_SAMPLES.with(|c| c.get())
1474}
1475
1476// Number of times `decode_block`'s SKIP arm ran at a shape where the
1477// per-axis and square chroma allocations DIFFER -- i.e. at 4:2:2, where
1478// the square is half the plane block. Zero on 4:2:0 and 4:4:4, where the
1479// two forms are the same number, so a gate that wants to prove it actually
1480// exercised the shape under test (rather than passing vacuously) asserts
1481// this moved.
1482thread_local! {
1483 static SKIP_ARM_CHROMA_RECT_SHAPES: std::cell::Cell<usize> =
1484 const { std::cell::Cell::new(0) };
1485}
1486
1487/// Current value of [`SKIP_ARM_CHROMA_RECT_SHAPES`].
1488#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1489pub(crate) fn skip_arm_chroma_rect_shapes() -> usize {
1490 SKIP_ARM_CHROMA_RECT_SHAPES.with(|c| c.get())
1491}
1492
1493// lane-av1floorshift: the two FRAME chroma plane allocators
1494// (`decode_key_frame_tile_with_cdfs` and `decode_inter_tile`'s `PlaneBuf` trio)
1495// size U and V as `(width >> ss_x) x (height >> ss_y)` with `width`/`height`
1496// the 32-aligned coded size and `true_width`/`true_height` its `mi_cols * 4`
1497// counterpart. `lanes/av1subsizesweep.report.md` named these "floor-`>>`
1498// chroma plane allocators -- shape assumption at frame edges; not probed":
1499// the `>>` FLOORS where libaom's own producer CROPS (`round_ss`), so the
1500// question was whether an odd frame dimension makes the allocation one sample
1501// short of the extent every chroma walk inside the tile indexes.
1502//
1503// `FRAME_CHROMA_ALLOC_SHORT_SAMPLES` is the measured answer: the number of
1504// samples by which the allocated `cw * ch` fell SHORT of the `round_ss`
1505// extent the tile's chroma walks may address, summed over every frame. It
1506// reads the allocation's real length against a recomputed `round_ss` bound, so
1507// it measures the shape rather than proxying a condition. Restoring a bare
1508// `>> 1` on either axis drives it strictly positive at an odd dimension.
1509thread_local! {
1510 static FRAME_CHROMA_ALLOC_SHORT_SAMPLES: std::cell::Cell<usize> =
1511 const { std::cell::Cell::new(0) };
1512}
1513
1514// lane-av1floorshift: frames whose coded luma dimension made `>>` and
1515// `round_ss` DISAGREE on a chroma axis -- i.e. the only frames on which the
1516// floor-vs-crop question is even decidable. Zero on every even dimension,
1517// which is why a gate asserting `FRAME_CHROMA_ALLOC_SHORT_SAMPLES == 0` is
1518// vacuous without this: on an even frame the two forms are the same number
1519// and the shortfall cannot move.
1520thread_local! {
1521 static FRAME_CHROMA_ALLOC_CROP_SHAPES: std::cell::Cell<usize> =
1522 const { std::cell::Cell::new(0) };
1523}
1524
1525// How many times a frame chroma plane allocator ran at all -- one per frame,
1526// from either the key-frame or the inter call site. The non-vacuity arm: the
1527// other two counters are ZERO on every input that exists (see
1528// [`note_frame_chroma_alloc`]), so a gate that only asserted them would pass
1529// with the instrument removed entirely.
1530thread_local! {
1531 static FRAME_CHROMA_ALLOC_CALLS: std::cell::Cell<usize> =
1532 const { std::cell::Cell::new(0) };
1533}
1534
1535/// Current value of [`FRAME_CHROMA_ALLOC_CALLS`].
1536#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1537pub(crate) fn frame_chroma_alloc_calls() -> usize {
1538 FRAME_CHROMA_ALLOC_CALLS.with(|c| c.get())
1539}
1540
1541/// Current value of [`FRAME_CHROMA_ALLOC_SHORT_SAMPLES`].
1542#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1543pub(crate) fn frame_chroma_alloc_short_samples() -> usize {
1544 FRAME_CHROMA_ALLOC_SHORT_SAMPLES.with(|c| c.get())
1545}
1546
1547/// Current value of [`FRAME_CHROMA_ALLOC_CROP_SHAPES`].
1548#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1549pub(crate) fn frame_chroma_alloc_crop_shapes() -> usize {
1550 FRAME_CHROMA_ALLOC_CROP_SHAPES.with(|c| c.get())
1551}
1552
1553/// The census both frame chroma plane allocators share. `shape` is the frame's
1554/// own 32-aligned coded `(width, height)`, `ss` its `(ss_x, ss_y)`.
1555///
1556/// `round_ss` is libaom's chroma CROP (`av1_round_shift`), the extent the
1557/// committed reference planes are stored at and the bound every chroma walk
1558/// inside the tile is clamped against.
1559///
1560/// `alloc` is the allocator's OWN `(cw, ch)` -- the numbers that size the
1561/// `PlaneBuf` -- not a recomputation of them. That is what makes the gate
1562/// bite: the shortfall is a difference between what was allocated and what the
1563/// tile may address, so replacing the shift with a bare `>> 1` (the 4:2:0-only
1564/// form this lane's target class is made of) moves it on the 4:2:2 and 4:4:4
1565/// witnesses, where the correct shift and the hardcoded one are different
1566/// numbers. A counter that recomputed `shape >> ss` beside the allocation
1567/// would have read the same value either way and proved nothing.
1568fn note_frame_chroma_alloc(shape: (usize, usize), alloc: (usize, usize), ss: (usize, usize)) {
1569 hit!(FRAME_CHROMA_ALLOC_CALLS);
1570 let (need_w, need_h) = (round_ss(shape.0, ss.0), round_ss(shape.1, ss.1));
1571 // Decidability: the floor and the crop are the same number on this frame,
1572 // so the shortfall below is the same number the two forms would have given.
1573 if (need_w, need_h) != (shape.0 >> ss.0, shape.1 >> ss.1) {
1574 hit!(FRAME_CHROMA_ALLOC_CROP_SHAPES);
1575 if crate::envflags::env_flag!("EC_AV1_CHROMA_ALLOC_SWEEP") {
1576 eprintln!(
1577 "CHROMA_ALLOC luma={}x{} ss={:?} floor={}x{} round_ss={}x{} alloc={}x{}",
1578 shape.0,
1579 shape.1,
1580 ss,
1581 shape.0 >> ss.0,
1582 shape.1 >> ss.1,
1583 need_w,
1584 need_h,
1585 alloc.0,
1586 alloc.1,
1587 );
1588 }
1589 }
1590 let want = need_w * need_h;
1591 let got = alloc.0 * alloc.1;
1592 if want > got {
1593 hit_do!(FRAME_CHROMA_ALLOC_SHORT_SAMPLES.with(|c| c.set(c.get() + want - got)));
1594 }
1595}
1596
1597/// lane-av1ibcfork: this decoder's half of the per-unit BIT INTERVAL -- the
1598/// exact mirror of the oracle's `EC_ECDUMP_IN` / `EC_ECDUMP_OUT` /
1599/// `EC_ECDUMP_END` triple (`aom-oracle2/src/av1/decoder/decodetxb.c`: one
1600/// print in `read_coeffs_txb` before and after its `aom_read_symbol`, one in
1601/// the single caller `av1_read_coeffs_txb` after the whole unit).
1602///
1603/// Why three prints and not one `EC_CENSUS_UNIT`: a COUNT is not a key. The
1604/// two sides can walk a different NUMBER of units and still be paired, because
1605/// the interval is what a unit CONSUMED. Entry position alone drifts the moment
1606/// one side consumes a different number of bits, and list index is invalid the
1607/// moment one side misses a unit -- both were measured here and both
1608/// mis-attribute. `post_bit` after the `txb_skip` read is the same
1609/// `aom_reader_tell` the oracle prints there; `end_bit` is the end of the whole
1610/// unit including the optional luma `tx_type`, the eob, the base/BR passes and
1611/// the sign/Golomb loop, so a unit that reads the right symbols in the wrong
1612/// ORDER is caught too.
1613///
1614/// `bit` counts the bits this decoder has pulled out of its window, so it sits
1615/// at a CONSTANT offset from the oracle's tell (the OBU header libaom counts
1616/// before `aom_reader_init`). The offset is measured per fixture, never
1617/// assumed: +14 on `444_intrabc_rect4_witness.obu`.
1618#[inline]
1619fn unit_iv_on() -> bool {
1620 crate::envflags::env_flag!("EC_UNITIV")
1621}
1622
1623/// The unit's ENTRY position. Returns it so the caller can pass the same value
1624/// to [`unit_iv_skip`] and [`unit_iv_end`] without reading the decoder again.
1625#[inline]
1626#[track_caller]
1627fn unit_iv_in(plane: usize, w: usize, h: usize, ctx: usize, dec: &SymbolDecoder) -> usize {
1628 if !unit_iv_on() {
1629 return 0;
1630 }
1631 let bit = dec.debug_bitpos();
1632 let (mi_r, mi_c) = SymbolDecoder::symr_mi();
1633 eprintln!(
1634 "EC_UNITIV_IN side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} bit={bit} at {}",
1635 std::panic::Location::caller()
1636 );
1637 bit
1638}
1639
1640/// The position immediately after this unit's `txb_skip` read. `bit_in ==
1641/// post_bit` means the read consumed ZERO bits (a CDF row already at a
1642/// boundary), so this is also the real-read filter: the reader logs a step
1643/// either way, and counting raw lines overstates the symbol count ~2x (measured
1644/// on `444_intrabc_rect4_witness.obu`: 2395 lines, 512 real reads, against the
1645/// oracle's 513 -- not the "~1069 fewer" an earlier round reported).
1646#[inline]
1647fn unit_iv_skip(
1648 dec: &SymbolDecoder,
1649 bit_in: usize,
1650 plane: usize,
1651 w: usize,
1652 h: usize,
1653 ctx: usize,
1654 all_zero: bool,
1655) {
1656 if !unit_iv_on() {
1657 return;
1658 }
1659 let (mi_r, mi_c) = SymbolDecoder::symr_mi();
1660 eprintln!(
1661 "EC_UNITIV_SKIP side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} az={} bit={bit_in} post_bit={}",
1662 all_zero as i32,
1663 dec.debug_bitpos()
1664 );
1665}
1666
1667/// The position after the WHOLE unit. One call per successful read, on both
1668/// the all-zero early return and the full coefficient walk.
1669#[inline]
1670fn unit_iv_end(dec: &SymbolDecoder, plane: usize, w: usize, h: usize, ctx: usize) {
1671 if !unit_iv_on() {
1672 return;
1673 }
1674 let (mi_r, mi_c) = SymbolDecoder::symr_mi();
1675 eprintln!(
1676 "EC_UNITIV_END side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} end_bit={}",
1677 dec.debug_bitpos()
1678 );
1679}
1680
1681/// A just-decoded palette-Y block's own predicted pixels
1682/// (`side*side`, row-major, `colors[map[i]]`), consumed by
1683/// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
1684/// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
1685/// per-block override through `read_plane`'s two dozen call sites is the
1686/// alternative this avoids). Always empty again once that call consumes
1687/// it (`.take()`), so a non-palette block's own `reconstruct` call never
1688/// sees stale state.
1689/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
1690/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
1691/// site whose reconstruct never runs would be picked up by the NEXT block's
1692/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
1693/// lane-lossless2: one transform unit's window on a block-sized palette
1694/// prediction buffer. A unit reads its prediction at ITS OWN stride, so
1695/// handing it the whole-block buffer makes every unit reconstruct the block's
1696/// top-left corner (the luma split-transform paths already window; the chroma
1697/// ones did not, which is invisible until a lossless frame codes a palette
1698/// block as 4x4 chroma units).
1699fn palette_window(
1700 buf: &[u16],
1701 stride: usize,
1702 ox: usize,
1703 oy: usize,
1704 w: usize,
1705 h: usize,
1706) -> Vec<u16> {
1707 // `stride` is the BLOCK's own chroma width, so a caller that handed over a
1708 // mismatched stride could read in-bounds GARBAGE instead of panicking --
1709 // a silent misread, which is the one failure mode this walk must not have.
1710 // The refutation pass (`lanes/refute-av1444d10.report.md`, risk (e)) named
1711 // that as the only thing keeping the tiled walk safe, so the invariant is
1712 // closed loudly here instead of resting on an `unsupported` return
1713 // elsewhere that a future shape could remove.
1714 assert!(
1715 w <= stride && ox + w <= stride && (oy + h) * stride <= buf.len(),
1716 "palette window {w}x{h} at ({ox},{oy}) does not fit a {}-entry buffer at stride {stride}",
1717 buf.len()
1718 );
1719 (0..h)
1720 .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied())
1721 .collect()
1722}
1723
1724/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1725#[track_caller]
1726fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
1727 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
1728 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
1729 eprintln!(
1730 "PALSET len={} stale={stale} at {}",
1731 buf.len(),
1732 std::panic::Location::caller()
1733 );
1734 }
1735 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
1736}
1737
1738#[track_caller]
1739fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
1740 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
1741 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
1742 eprintln!(
1743 "PALTAKE len={:?} at {}",
1744 got.as_ref().map(Vec::len),
1745 std::panic::Location::caller()
1746 );
1747 }
1748 got
1749}
1750
1751/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over.
1752#[derive(Clone, Copy, Debug)]
1753pub(crate) struct CflSrc {
1754 px: usize,
1755 py: usize,
1756 bw: usize,
1757 bh: usize,
1758}
1759
1760fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
1761 CflSrc {
1762 px,
1763 py,
1764 bw: side,
1765 bh: side,
1766 }
1767}
1768
1769fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
1770 CflSrc { px, py, bw, bh }
1771}
1772
1773/// The dequantization + inverse transform of one transform unit, kept as its
1774/// INPUTS so the transform runs where the unit is written. `stride == 0` means
1775/// the dense `w x h` residual; otherwise it is re-laid into the
1776/// `stride x stride` grid `reconstruct_mc_rect` reads both of its buffers at.
1777#[derive(Clone, Copy)]
1778pub(crate) struct TxParams {
1779 /// The plane this unit belongs to (0 luma, 1 U, 2 V), carried from the
1780 /// reader that OWNS the unit. `dequant_and_inverse_wht4x4`'s `EC_DQCOEFF`
1781 /// twin prints it so its ladder pairs with the oracle's: the per-unit
1782 /// census plane could not, because the callers that route a lossless 4x4
1783 /// unit into the WHT are not all the ones that stamp the census plane
1784 /// (measured on `ll444-lossless-key.obu`: 1663 of 1663 chroma units paired
1785 /// by count, 1660 of them against an empty grid).
1786 pub(crate) plane: usize,
1787 pub(crate) w: usize,
1788 pub(crate) h: usize,
1789 pub(crate) bit_depth: u8,
1790 pub(crate) q_idx: i32,
1791 pub(crate) dc_delta: i32,
1792 pub(crate) ac_delta: i32,
1793 pub(crate) tx_type: TxType,
1794 /// lane-av1-qmatrix: this unit's inverse quantisation matrix, selected
1795 /// on the parse thread by [`block_iqmatrix`] and captured here so the
1796 /// transform scales identically without touching frame state.
1797 pub(crate) qm: Option<crate::qm::Iqm>,
1798 pub(crate) stride: usize,
1799 /// lane-lossless: this transform unit belongs to a lossless BLOCK (its
1800 /// segment's `xd->lossless[segment_id]` bit), so the residual comes off
1801 /// the 4x4 Walsh-Hadamard
1802 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
1803 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
1804 pub(crate) lossless: bool,
1805}
1806
1807/// lane-av1mixloss: Walsh-Hadamard transform units actually reconstructed.
1808/// The mixed-lossless witness's proof the per-segment lossless path really
1809/// ran on a frame that is NOT `CodedLossless`.
1810static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1811
1812/// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after
1813/// delta around one decode.
1814#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1815pub(crate) fn lossless_wht_units() -> usize {
1816 LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
1817}
1818
1819/// lane-whtshape: 4x4 Walsh-Hadamard units reconstructed as part of a LOSSLESS
1820/// transform unit that was itself NOT 4x4 -- a shape libaom cannot code.
1821/// `read_tx_mode` (`av1/decoder/decodeframe.c:140`) returns `ONLY_4X4` for a
1822/// `coded_lossless` frame before it looks at the `tx_mode` symbol,
1823/// `read_tx_size` (`:1117`) returns `TX_4X4` before it looks at a tree,
1824/// `get_vartx_max_txsize` (`av1/common/blockd.h:1447`) returns `TX_4X4` for
1825/// EVERY plane of a lossless block, and of `av1/common/idct.c`'s
1826/// `highbd_inv_txfm_add_*_c` only `highbd_inv_txfm_add_4x4_c` carries a
1827/// `lossless` branch -- every other size falls through to the IDCT, because
1828/// there is no non-4x4 lossless inverse transform to dispatch to. So one of
1829/// these is a CALLER sizing a lossless unit wrongly, not a bitstream shape;
1830/// read as a before/after delta around one decode it names the caller. Must
1831/// read 0 on a stream whose lossless unit geometry is right.
1832static LOSSLESS_WHT_SPLIT_UNITS: std::sync::atomic::AtomicUsize =
1833 std::sync::atomic::AtomicUsize::new(0);
1834
1835/// [`LOSSLESS_WHT_SPLIT_UNITS`] -- total over the process, read as a
1836/// before/after delta around one decode.
1837#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1838pub(crate) fn lossless_wht_split_units() -> usize {
1839 LOSSLESS_WHT_SPLIT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
1840}
1841
1842impl TxParams {
1843 /// The one copy of the produce-the-residual code.
1844 fn run(self, grid: &[i32]) -> Vec<i32> {
1845 let residual = if self.lossless {
1846 LOSSLESS_WHT_UNITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1847 // lane-whtshape: a non-4x4 unit here is this decoder's own
1848 // transform-unit geometry being wrong (see
1849 // [`LOSSLESS_WHT_SPLIT_UNITS`] for the libaom evidence). It used
1850 // to be stopped by a `debug_assert_eq!` that RELEASE never ran:
1851 // the 4x4 WHT returned 16 values for a `w * h` block and the
1852 // release build died one frame later in the strided copy with an
1853 // opaque `range end index 8 out of range for slice of length 0`
1854 // that never named lossless or the transform. Counted, and
1855 // reconstructed as the raster of 4x4 WHT units
1856 // ([`crate::transform::dequant_and_inverse_wht`]) instead: total,
1857 // the same in both profiles, and the 4x4 fast path is the same
1858 // single call it always was. The old
1859 // `debug_assert_eq!(self.tx_type, TxType::DctDct)` is gone with
1860 // it: the WHT takes no tx_type (libaom's `av1_iwht4x4_add` does
1861 // not either), and `av1_get_tx_type` already answers `DCT_DCT` on
1862 // every plane of a lossless block, so asserting an argument
1863 // nothing reads was a debug-only panic on a value release
1864 // ignores.
1865 if self.w != 4 || self.h != 4 {
1866 LOSSLESS_WHT_SPLIT_UNITS.fetch_add(
1867 self.w.div_ceil(4) * self.h.div_ceil(4),
1868 std::sync::atomic::Ordering::Relaxed,
1869 );
1870 }
1871 crate::transform::dequant_and_inverse_wht(
1872 grid,
1873 self.plane,
1874 self.w,
1875 self.h,
1876 self.bit_depth,
1877 self.q_idx,
1878 self.dc_delta,
1879 self.ac_delta,
1880 )
1881 } else {
1882 dequant_and_inverse_typed_wh(
1883 grid,
1884 self.w,
1885 self.h,
1886 self.bit_depth,
1887 self.q_idx,
1888 self.dc_delta,
1889 self.ac_delta,
1890 self.tx_type,
1891 self.qm,
1892 )
1893 };
1894 // An all-zero grid transforms to the empty marker, and a strided copy
1895 // of zeros is still zeros: the marker passes straight through.
1896 if residual.is_empty() {
1897 return residual;
1898 }
1899 if self.stride == 0 {
1900 return residual;
1901 }
1902 // lane-av1-422sub8rect: `h` rows of `stride` -- a rect unit whose
1903 // height exceeds its (narrow) prediction stride needs the full
1904 // stride * h; every square caller has h == stride and is unchanged.
1905 let mut strided = vec![0i32; self.stride * self.h];
1906 for row in 0..self.h {
1907 strided[row * self.stride..][..self.w]
1908 .copy_from_slice(&residual[row * self.w..][..self.w]);
1909 }
1910 strided
1911 }
1912}
1913
1914/// An all-zero residual, for the transform units that code no coefficient:
1915/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
1916/// and the reconstruction loops below read this instead of a per-unit
1917/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
1918/// (a 128-wide inter block's prediction stride).
1919pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
1920
1921/// lane-blockscratch: one plane's coefficient levels as the block-tail
1922/// neighbour writes want them. A plane that coded nothing (a skipped block, a
1923/// strip with no chroma, luma under a var-tx split whose units already wrote
1924/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
1925/// zeroing up to 64 KB of its own per block.
1926#[derive(Clone)]
1927enum Grid {
1928 Zero(usize),
1929 Own(Vec<i32>),
1930}
1931
1932/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
1933/// unit that writes into it. Only a block wider or taller than 64 px codes its
1934/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
1935/// collectors per block and then drop them untouched.
1936fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
1937 if v.is_empty() {
1938 *v = vec![0i32; n];
1939 }
1940 v
1941}
1942
1943impl std::ops::Deref for Grid {
1944 type Target = [i32];
1945 fn deref(&self) -> &[i32] {
1946 match self {
1947 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
1948 Grid::Own(v) => v,
1949 }
1950 }
1951}
1952
1953/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
1954/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
1955/// transform units that code no coefficient without the scan (lane-coefgrid).
1956pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
1957 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
1958}
1959
1960/// `residual`, or `n` zeros when it is the empty all-zero marker.
1961fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
1962 if residual.is_empty() {
1963 &ZERO_RESIDUAL[..n]
1964 } else {
1965 residual
1966 }
1967}
1968
1969/// Where a motion-compensated write reads its prediction from.
1970#[derive(Clone, Copy)]
1971pub(crate) enum Pred<'a> {
1972 /// A prediction the parse thread already built, at its own stride
1973 /// (`stride == 0` means "the reader's own `stride` argument").
1974 Inline(&'a [u16], usize),
1975 /// The current block's deferred prediction (see [`wave::ReconOp::Pred`]):
1976 /// plane, its stride, and this unit's offset into it.
1977 Cur {
1978 plane: usize,
1979 stride: usize,
1980 off: usize,
1981 },
1982}
1983
1984impl<'a> Pred<'a> {
1985 /// The same prediction read at an explicit stride.
1986 fn view(self, stride: usize) -> Self {
1987 match self {
1988 Self::Inline(b, _) => Self::Inline(b, stride),
1989 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
1990 }
1991 }
1992
1993 /// The buffer and the stride to read it at (`stride` is the reader's own
1994 /// when this prediction was built dense); `None` for a deferred
1995 /// prediction, which only a recorded op can carry.
1996 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
1997 match self {
1998 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
1999 Self::Cur { .. } => None,
2000 }
2001 }
2002
2003 /// This prediction's window starting `n` samples in.
2004 fn offset(self, n: usize) -> Self {
2005 match self {
2006 Self::Inline(b, s) => Self::Inline(&b[n..], s),
2007 Self::Cur { plane, stride, off } => Self::Cur {
2008 plane,
2009 stride,
2010 off: off + n,
2011 },
2012 }
2013 }
2014}
2015
2016/// Whether a block's prediction may be built by a recon worker: a wavefront
2017/// is running and this frame's references can be handed to it.
2018fn pred_deferred(refpix: &RefPix<'_>) -> bool {
2019 wave::active() && refpix.is_shared()
2020}
2021
2022/// Records one block's prediction build for the worker that reconstructs it.
2023fn push_pred<F>(f: F)
2024where
2025 F: FnOnce(
2026 &mut PlaneBuf<'static>,
2027 &mut PlaneBuf<'static>,
2028 &mut PlaneBuf<'static>,
2029 &RefPix<'_>,
2030 &crate::decode::FrameCtx,
2031 &mut [Vec<u16>; 3],
2032 ) + Send
2033 + 'static,
2034{
2035 wave::push(wave::ReconOp::Pred(Box::new(f)));
2036}
2037
2038/// The previous block's prediction buffer, cleared and zero-filled to `n`
2039/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
2040/// without the per-block allocation and free.
2041fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
2042 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
2043 // than resized element by element -- which is every block on the inline
2044 // path, where there is no previous buffer to reuse.
2045 if v.capacity() < n {
2046 return vec![0u16; n];
2047 }
2048 v.clear();
2049 v.resize(n, 0);
2050 v
2051}
2052
2053/// [`PlaneBuf::reconstruct`] at its push site: the intra transform block is
2054/// written into the tile's planes as soon as it is parsed.
2055#[allow(clippy::too_many_arguments)]
2056fn push_intra(
2057 y: &mut PlaneBuf<'static>,
2058 u: &mut PlaneBuf<'static>,
2059 v: &mut PlaneBuf<'static>,
2060 plane: usize,
2061 x: usize,
2062 cy: usize,
2063 side: usize,
2064 mode: usize,
2065 angle_delta: i32,
2066 reach: Reach,
2067 residual: &[i32],
2068 cfl: Option<(i32, CflSrc)>,
2069 filter_intra: Option<usize>,
2070 smooth_neighbor: bool,
2071 fctx: &crate::decode::FrameCtx,
2072) {
2073 let pred = take_palette_pred(fctx);
2074 exec_intra(
2075 y,
2076 u,
2077 v,
2078 plane,
2079 x,
2080 cy,
2081 side,
2082 side,
2083 false,
2084 mode,
2085 angle_delta,
2086 reach,
2087 residual,
2088 cfl,
2089 filter_intra,
2090 smooth_neighbor,
2091 pred,
2092 fctx,
2093 );
2094}
2095
2096/// [`PlaneBuf::reconstruct_rect`] at its push site.
2097#[allow(clippy::too_many_arguments)]
2098fn push_intra_rect(
2099 y: &mut PlaneBuf<'static>,
2100 u: &mut PlaneBuf<'static>,
2101 v: &mut PlaneBuf<'static>,
2102 plane: usize,
2103 x: usize,
2104 cy: usize,
2105 bw: usize,
2106 bh: usize,
2107 mode: usize,
2108 angle_delta: i32,
2109 reach: Reach,
2110 residual: &[i32],
2111 cfl: Option<(i32, CflSrc)>,
2112 filter_intra: Option<usize>,
2113 smooth_neighbor: bool,
2114 fctx: &crate::decode::FrameCtx,
2115) {
2116 let pred = take_palette_pred(fctx);
2117 exec_intra(
2118 y,
2119 u,
2120 v,
2121 plane,
2122 x,
2123 cy,
2124 bw,
2125 bh,
2126 true,
2127 mode,
2128 angle_delta,
2129 reach,
2130 residual,
2131 cfl,
2132 filter_intra,
2133 smooth_neighbor,
2134 pred,
2135 fctx,
2136 );
2137}
2138
2139/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`.
2140#[allow(clippy::too_many_arguments)]
2141fn push_mc(
2142 y: &mut PlaneBuf<'static>,
2143 u: &mut PlaneBuf<'static>,
2144 v: &mut PlaneBuf<'static>,
2145 plane: usize,
2146 x: usize,
2147 cy: usize,
2148 side: usize,
2149 prediction: Pred<'_>,
2150 residual: &[i32],
2151 fctx: &crate::decode::FrameCtx,
2152) {
2153 push_mc_rect(
2154 y, u, v, plane, x, cy, side, side, side, prediction, residual, fctx,
2155 );
2156}
2157
2158/// [`PlaneBuf::reconstruct_mc_rect`] at its push site.
2159#[allow(clippy::too_many_arguments)]
2160#[track_caller]
2161fn push_mc_rect(
2162 y: &mut PlaneBuf<'static>,
2163 u: &mut PlaneBuf<'static>,
2164 v: &mut PlaneBuf<'static>,
2165 plane: usize,
2166 x: usize,
2167 cy: usize,
2168 stride: usize,
2169 w: usize,
2170 h: usize,
2171 prediction: Pred<'_>,
2172 residual: &[i32],
2173 fctx: &crate::decode::FrameCtx,
2174) {
2175 // lane-av1ibcfork: the PUSH site of an MC/inter write. The executed rung
2176 // (`EC_MCWR`, in `reconstruct_mc_rect`) can only name the dispatch, so
2177 // this is what names the block decoder that asked for the write -- the
2178 // only thing that distinguishes two writes of the same shape. It is what
2179 // localized a 4:4:4 intra-BC SKIP block committing its chroma plane block
2180 // at `(px/2, py/2)` instead of the ss origin, clobbering a neighbouring
2181 // block's reconstruction (lanes/av1ibcfork.report.md).
2182 if crate::envflags::env_flag!("EC_MCPUSH") {
2183 eprintln!(
2184 "EC_MCPUSH plane={plane} x={x} y={cy} stride={stride} w={w} h={h} \
2185 res_len={} at {}",
2186 residual.len(),
2187 std::panic::Location::caller()
2188 );
2189 }
2190 let Some((src, stride)) = prediction.inline(stride) else {
2191 let Pred::Cur {
2192 plane: sp,
2193 stride: ss,
2194 off,
2195 } = prediction
2196 else {
2197 unreachable!("only a deferred prediction has no inline buffer")
2198 };
2199 wave::push(wave::ReconOp::Mc {
2200 plane,
2201 x,
2202 oy: cy,
2203 stride: ss,
2204 w,
2205 h,
2206 prediction: wave::PredSrc::Cur {
2207 plane: sp,
2208 off,
2209 src: ss,
2210 },
2211 residual: wave::Residual::ready(residual),
2212 });
2213 return;
2214 };
2215 exec_mc(y, u, v, plane, x, cy, stride, w, h, src, residual, fctx);
2216}
2217
2218/// [`push_intra_rect`] carrying the transform's INPUTS: the dequantization
2219/// and inverse transform run here, at the push site.
2220#[allow(clippy::too_many_arguments)]
2221fn push_intra_tx(
2222 y: &mut PlaneBuf<'static>,
2223 u: &mut PlaneBuf<'static>,
2224 v: &mut PlaneBuf<'static>,
2225 plane: usize,
2226 x: usize,
2227 cy: usize,
2228 bw: usize,
2229 bh: usize,
2230 rect: bool,
2231 mode: usize,
2232 angle_delta: i32,
2233 reach: Reach,
2234 tx: TxParams,
2235 grid: &[i32],
2236 cfl: Option<(i32, CflSrc)>,
2237 filter_intra: Option<usize>,
2238 smooth_neighbor: bool,
2239 fctx: &crate::decode::FrameCtx,
2240) {
2241 if wave::active() {
2242 let pred = take_palette_pred(fctx);
2243 wave::push(wave::ReconOp::Intra {
2244 plane,
2245 x,
2246 oy: cy,
2247 bw,
2248 bh,
2249 rect,
2250 mode,
2251 angle_delta,
2252 reach,
2253 residual: wave::Residual::tx(tx, grid),
2254 cfl,
2255 filter_intra,
2256 smooth_neighbor,
2257 pred,
2258 });
2259 return;
2260 }
2261 let residual = tx.run(grid);
2262 let pred = take_palette_pred(fctx);
2263 exec_intra(
2264 y,
2265 u,
2266 v,
2267 plane,
2268 x,
2269 cy,
2270 bw,
2271 bh,
2272 rect,
2273 mode,
2274 angle_delta,
2275 reach,
2276 &residual,
2277 cfl,
2278 filter_intra,
2279 smooth_neighbor,
2280 pred,
2281 fctx,
2282 );
2283}
2284
2285/// [`push_mc_rect`] carrying the transform's INPUTS (see [`push_intra_tx`]).
2286#[allow(clippy::too_many_arguments)]
2287fn push_mc_rect_tx(
2288 y: &mut PlaneBuf<'static>,
2289 u: &mut PlaneBuf<'static>,
2290 v: &mut PlaneBuf<'static>,
2291 plane: usize,
2292 x: usize,
2293 cy: usize,
2294 stride: usize,
2295 w: usize,
2296 h: usize,
2297 prediction: Pred<'_>,
2298 tx: TxParams,
2299 grid: &[i32],
2300 fctx: &crate::decode::FrameCtx,
2301) {
2302 let Some((prediction, stride)) = prediction.inline(stride) else {
2303 // A deferred prediction is not there to be windowed: the op carries its
2304 // offset into the block's prediction, and the residual is laid out dense.
2305 let Pred::Cur {
2306 plane: sp,
2307 stride: ss,
2308 off,
2309 } = prediction
2310 else {
2311 unreachable!("only a deferred prediction has no inline buffer")
2312 };
2313 let mut tx = tx;
2314 tx.stride = 0;
2315 wave::push(wave::ReconOp::Mc {
2316 plane,
2317 x,
2318 oy: cy,
2319 stride: w,
2320 w,
2321 h,
2322 prediction: wave::PredSrc::Cur {
2323 plane: sp,
2324 off,
2325 src: ss,
2326 },
2327 residual: wave::Residual::tx(tx, grid),
2328 });
2329 return;
2330 };
2331 let res_stride = if tx.stride == 0 { w } else { tx.stride };
2332 let window;
2333 let prediction = if stride == res_stride {
2334 prediction
2335 } else {
2336 debug_assert_eq!(res_stride, w);
2337 let mut win = Vec::with_capacity(w * h);
2338 for row in 0..h {
2339 win.extend_from_slice(&prediction[row * stride..][..w]);
2340 }
2341 window = win;
2342 &window[..]
2343 };
2344 if wave::active() {
2345 wave::push(wave::ReconOp::Mc {
2346 plane,
2347 x,
2348 oy: cy,
2349 stride: res_stride,
2350 w,
2351 h,
2352 prediction: wave::PredSrc::Owned(prediction.to_vec()),
2353 residual: wave::Residual::tx(tx, grid),
2354 });
2355 return;
2356 }
2357 let residual = tx.run(grid);
2358 exec_mc(
2359 y, u, v, plane, x, cy, res_stride, w, h, prediction, &residual, fctx,
2360 );
2361}
2362
2363/// Performs one intra transform block's write into the tile's planes.
2364#[allow(clippy::too_many_arguments)]
2365fn exec_intra(
2366 y: &mut PlaneBuf<'static>,
2367 u: &mut PlaneBuf<'static>,
2368 v: &mut PlaneBuf<'static>,
2369 plane: usize,
2370 x: usize,
2371 oy: usize,
2372 bw: usize,
2373 bh: usize,
2374 rect: bool,
2375 mode: usize,
2376 angle_delta: i32,
2377 reach: Reach,
2378 residual: &[i32],
2379 cfl: Option<(i32, CflSrc)>,
2380 filter_intra: Option<usize>,
2381 smooth_neighbor: bool,
2382 pred: Option<Vec<u16>>,
2383 fctx: &crate::decode::FrameCtx,
2384) {
2385 if wave::active() {
2386 wave::push(wave::ReconOp::Intra {
2387 plane,
2388 x,
2389 oy,
2390 bw,
2391 bh,
2392 rect,
2393 mode,
2394 angle_delta,
2395 reach,
2396 residual: wave::Residual::ready(residual),
2397 cfl,
2398 filter_intra,
2399 smooth_neighbor,
2400 pred,
2401 });
2402 return;
2403 }
2404 // The CfL AC signal is read HERE, off the luma that has already been
2405 // written for this block -- at parse time it would have been the previous
2406 // frame's samples.
2407 let ac = cfl.map(|(alpha, src)| {
2408 let sig = cfl_ac_ss(&*y, src.px, src.py, src.bw, src.bh, ss_x(fctx), ss_y(fctx));
2409 (alpha, sig)
2410 });
2411 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
2412 // Both replays below index their inputs by the transform block's area. A
2413 // size mismatch is a corrupt stream (the override or the CfL source window
2414 // does not belong to this transform block): flag it, and let the
2415 // reconstruction fall back to edge prediction without indexing past it.
2416 let area = bw * bh;
2417 if pred.as_ref().is_some_and(|p| p.len() != area) {
2418 fctx.flag_corrupt(
2419 "palette or intrabc prediction override is not the transform block's size",
2420 );
2421 }
2422 if cfl.is_some_and(|(_, sig)| sig.len() != area) {
2423 fctx.flag_corrupt("CfL AC signal is not the transform block's size");
2424 }
2425 let target: &mut PlaneBuf<'static> = match plane {
2426 0 => &mut *y,
2427 1 => &mut *u,
2428 _ => &mut *v,
2429 };
2430 // lane-av1cmpaudit: label the in-flight reconstruction's plane for the
2431 // `EC_PRED` rung (aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`).
2432 // Saved and restored so the rung reports THIS call's plane even under
2433 // nesting, and so both of exec_intra's return paths need no cleanup.
2434 let prev_plane = RECON_PLANE.with(|c| c.replace(plane));
2435 let _plane_guard = PlaneGuard(prev_plane);
2436 if rect {
2437 target.reconstruct_rect(
2438 x,
2439 oy,
2440 bw,
2441 bh,
2442 mode,
2443 angle_delta,
2444 reach,
2445 residual,
2446 cfl,
2447 filter_intra,
2448 smooth_neighbor,
2449 pred,
2450 fctx,
2451 );
2452 } else {
2453 target.reconstruct(
2454 x,
2455 oy,
2456 bw,
2457 mode,
2458 angle_delta,
2459 reach,
2460 residual,
2461 cfl,
2462 filter_intra,
2463 smooth_neighbor,
2464 pred,
2465 fctx,
2466 );
2467 }
2468}
2469
2470/// Performs one motion-compensated transform block's write (see [`exec_intra`]).
2471#[allow(clippy::too_many_arguments)]
2472fn exec_mc(
2473 y: &mut PlaneBuf<'static>,
2474 u: &mut PlaneBuf<'static>,
2475 v: &mut PlaneBuf<'static>,
2476 plane: usize,
2477 x: usize,
2478 oy: usize,
2479 stride: usize,
2480 w: usize,
2481 h: usize,
2482 prediction: &[u16],
2483 residual: &[i32],
2484 fctx: &crate::decode::FrameCtx,
2485) {
2486 if wave::active() {
2487 wave::push(wave::ReconOp::Mc {
2488 plane,
2489 x,
2490 oy,
2491 stride,
2492 w,
2493 h,
2494 prediction: wave::PredSrc::Owned(prediction.to_vec()),
2495 residual: wave::Residual::ready(residual),
2496 });
2497 return;
2498 }
2499 let target: &mut PlaneBuf<'static> = match plane {
2500 0 => &mut *y,
2501 1 => &mut *u,
2502 _ => &mut *v,
2503 };
2504 target.reconstruct_mc_rect(x, oy, plane, stride, w, h, prediction, residual, fctx);
2505}
2506
2507// The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
2508// an intrabc block's chroma reads can inherit it (see
2509// [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
2510// through that one arming site.
2511// libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
2512// branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
2513// satisfies (`blockd.h:373`) -- and takes the *colocated luma
2514// transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
2515// `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
2516// intrabc block's two chroma [`read_plane`] calls; the type decides the
2517// `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
2518// -- getting it wrong desyncs the chroma coefficients, it is not a
2519// reconstruction-only detail.
2520
2521/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
2522/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
2523/// needs no separate plumbing to reach the rect-strip mode reader.
2524fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
2525 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
2526}
2527
2528thread_local! {
2529 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
2530 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
2531 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
2532 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2533}
2534
2535/// Current value of [`RECT_INTRABC_READS`].
2536pub(crate) fn rect_intrabc_reads() -> usize {
2537 RECT_INTRABC_READS.with(|c| c.get())
2538}
2539
2540thread_local! {
2541 /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as
2542 /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the
2543 /// per-axis walk used. A 4:2:2 run and a 4:2:0 run of the same block
2544 /// differ here (32|64 vs 32|32), which is what the de-square-cut fixes.
2545 static INTRABC_128RECT_CHUNK_SHAPE: std::cell::Cell<usize> =
2546 const { std::cell::Cell::new(0) };
2547}
2548
2549/// Current value of [`INTRABC_128RECT_CHUNK_SHAPE`].
2550#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2551pub fn intrabc_128rect_chunk_shape() -> usize {
2552 INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.get())
2553}
2554
2555/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
2556/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
2557/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
2558/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
2559fn record_intrabc_mi(
2560 mi_r: usize,
2561 mi_c: usize,
2562 n4: usize,
2563 dv: Option<(i32, i32)>,
2564 n: &mut Neighbours,
2565 fctx: &crate::decode::FrameCtx,
2566) {
2567 record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx);
2568}
2569
2570/// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs`
2571/// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4`
2572/// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr).
2573///
2574/// Also stamps libaom's `is_inter_block` verdict for this block into the
2575/// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override
2576/// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] >
2577/// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and
2578/// `get_tx_size_context` reads its BLOCK size rather than its transform band.
2579/// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which
2580/// every block runs; this runs after it (class leaked-band otherwise).
2581fn record_intrabc_mi_rect(
2582 mi_r: usize,
2583 mi_c: usize,
2584 n4_w: usize,
2585 n4_h: usize,
2586 dv: Option<(i32, i32)>,
2587 n: &mut Neighbours,
2588 fctx: &crate::decode::FrameCtx,
2589) {
2590 if dv.is_some() {
2591 for i in 0..n4_w {
2592 if let Some(cell) = n.above_inter.get_mut(mi_c + i) {
2593 *cell = true;
2594 }
2595 }
2596 for i in 0..n4_h {
2597 if let Some(cell) = n.left_inter.get_mut(mi_r + i) {
2598 *cell = true;
2599 }
2600 }
2601 // lane-av1txctxband: the per-CELL `is_inter_block` an INTRABC block
2602 // publishes (`blockd.h:372-374` counts it), at the granularity
2603 // `get_tx_size_context` reads it. The band above is one slot per
2604 // column and so survives every later block in that column.
2605 n.mark_inter_grid_rect((mi_r, mi_c), n4_w, n4_h, true);
2606 }
2607 fctx.intrabc_mi_grid.with(|g| {
2608 let mut g = g.borrow_mut();
2609 let Some((grid, _, _)) = g.as_mut() else {
2610 return;
2611 };
2612 let info = crate::mvstack::MiInfo {
2613 is_inter: dv.is_some(),
2614 ref_frame: 0,
2615 ref_frame1: NO_REF1,
2616 mv: mv16(dv.unwrap_or((0, 0))),
2617 mv1: (0, 0),
2618 is_new_mv: dv.is_some(),
2619 is_global_mv0: false,
2620 is_global_mv1: false,
2621 size: n4_w as u8,
2622 size_h: n4_h as u8,
2623 };
2624 for r in mi_r..mi_r + n4_h {
2625 for c in mi_c..mi_c + n4_w {
2626 grid.set(r, c, info);
2627 }
2628 }
2629 });
2630}
2631
2632/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
2633/// `force_integer_mv` bit is set.
2634pub fn note_force_integer_mv_frame() {
2635 hit!(FIMV_FRAME_HITS);
2636}
2637
2638// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
2639// off the neighbour band -- the positive half of the proof for "an OBMC
2640// neighbour whose switchable interp filter was never recorded". A
2641// fixed-filter frame returns before this point (its neighbours legitimately
2642// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
2643// `interp_filter` symbols were published by `record_inter_rect_mi`.
2644thread_local! {
2645 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2646}
2647
2648/// Current value of [`OBMC_FILTER_BAND_READS`].
2649#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2650pub(crate) fn obmc_filter_band_reads() -> usize {
2651 OBMC_FILTER_BAND_READS.with(|c| c.get())
2652}
2653
2654/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
2655/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
2656pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
2657 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
2658
2659fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
2660 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
2661}
2662
2663// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
2664// through one of the key-frame rect readers ([`decode_block_rect4`],
2665// [`decode_block_rect64`]). `Some((size_group, skip))` tells
2666// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
2667// already read by [`decode_inter_block`] and (b) the luma mode comes off
2668// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
2669// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
2670
2671// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
2672// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
2673// mode from the previous tile, where libaom's `up_available`/`left_available`
2674// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
2675// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
2676// per superblock row in `start_row`, so the luma fallback cannot leak the way
2677// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
2678// the invariant that makes the coarse fallback safe.
2679thread_local! {
2680 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
2681 const { std::cell::Cell::new(0) };
2682}
2683
2684/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
2685#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2686pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
2687 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
2688}
2689
2690thread_local! {
2691 static UV_LEFT_SS_Y_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2692}
2693
2694/// Current value of [`UV_LEFT_SS_Y_READS`].
2695pub fn uv_left_ss_y_reads() -> usize {
2696 UV_LEFT_SS_Y_READS.with(|c| c.get())
2697}
2698
2699// lane-av1leftwit: the per-tile epoch `uv_owner` cells are stamped with.
2700// Bumped in `Neighbours::start_tile`; never read by decode logic.
2701thread_local! {
2702 static UV_OWNER_EPOCH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
2703}
2704
2705fn bump_edge_part(slot: usize) {
2706 hit_do! {
2707 EDGE_PART_HITS.with(|c| {
2708 let mut h = c.get();
2709 h[slot] += 1;
2710 c.set(h);
2711 });
2712 }
2713}
2714
2715/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
2716/// reads are `if`-conditions, so the counter has to ride the expression.
2717fn bump_edge32_bit(base: usize, bit: usize) -> usize {
2718 bump_edge32(base + bit.min(1));
2719 bit
2720}
2721
2722fn bump_edge32(slot: usize) {
2723 hit_do! {
2724 EDGE32_HITS.with(|c| {
2725 let mut h = c.get();
2726 h[slot] += 1;
2727 c.set(h)
2728 });
2729 }
2730}
2731
2732/// One 16x4 / 4x16 inter strip's chroma situation, handed to
2733/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
2734/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
2735/// that all mean "an ordinary block, chroma of its own".
2736#[derive(Clone, Copy)]
2737pub(crate) struct InterStripChroma {
2738 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
2739 /// read and reconstruct NO chroma at all.
2740 has_chroma: bool,
2741 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
2742 horz: bool,
2743 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
2744 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
2745 /// i.e. the origin of the 8x4 (4x8) chroma transform.
2746 pair_mi: (usize, usize),
2747 /// The previous (even) strip's single-reference MC parameters, `None`
2748 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
2749 /// and the whole chroma block is predicted from THIS strip's mv.
2750 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
2751}
2752
2753/// The single-reference MC parameters of the inter block that decoded
2754/// last -- read by the next 1:4 strip to build its pair's chroma.
2755fn bump_ab16_inter(arm: usize) {
2756 hit_do! {
2757 AB16_INTER_HITS.with(|c| {
2758 let mut v = c.get();
2759 v[arm] += 1;
2760 c.set(v);
2761 });
2762 }
2763}
2764
2765/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
2766/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
2767/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
2768/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
2769/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
2770/// needs to turn a query block's own resolved `ref_frame` into
2771/// `TplArgs::cur_offset_0` (spec 7.9.3).
2772pub(crate) struct TplFrameArgs<'a> {
2773 pub field: &'a crate::motion_field::TplField,
2774 pub order_hint_bits: u32,
2775 pub order_hint: u32,
2776 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
2777 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
2778 /// frame's own `ref_frame_idx` names for each single reference.
2779 pub ref_order_hints: [u32; 7],
2780}
2781
2782/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
2783/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
2784/// decoded `grid`: every 4x4 unit an inter block covers reads the same
2785/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
2786/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
2787/// exact — every block this crate ever codes is at least 8x8, so no 8x8
2788/// cell straddles two different blocks' values.
2789pub(crate) fn build_motion_field(
2790 grid: &MiGrid,
2791 mi_cols: usize,
2792 mi_rows: usize,
2793 order_hint: u32,
2794 order_hint_bits: u32,
2795 ref_order_hints: [u32; 7],
2796 fctx: &FrameCtx,
2797) -> crate::motion_field::MotionField {
2798 let mut field =
2799 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
2800 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
2801 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
2802 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
2803 // referencing one stores only its OTHER side's mv. With
2804 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
2805 // nothing is skipped.
2806 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
2807 // only on the reference frame, so it is 7 table lookups per frame instead
2808 // of two per inter unit.
2809 let other_side: [bool; 8] = std::array::from_fn(|rf| {
2810 let i = rf.wrapping_sub(LAST_FRAME as usize);
2811 order_hint_bits != 0
2812 && i < 7
2813 && (crate::motion_field::get_relative_dist(
2814 order_hint_bits,
2815 ref_order_hints[i],
2816 order_hint,
2817 ) > 0
2818 || ref_order_hints[i] == order_hint)
2819 });
2820 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
2821 // capped at 12 bits per component; a longer one is not stored at all.
2822 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
2823 let (cols, rows, cells) = field.cells_mut();
2824 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
2825 // never touch each other (an 8x8 cell lives in one cell row, and mi row
2826 // `row` writes cell row `row / 2`).
2827 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
2828 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
2829 let out = &mut out[(row / 2 - r0) * cols..][..cols];
2830 for col in 0..mi_cols {
2831 let Some(info) = grid.get_frame(row, col) else {
2832 continue;
2833 };
2834 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
2835 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
2836 // so an intra block -- or an inter block whose every slot is on the
2837 // other side / over the limit -- wipes what an earlier block wrote
2838 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
2839 // share a cell).
2840 if !info.is_inter {
2841 out[col / 2] = None;
2842 continue;
2843 }
2844 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
2845 // qualifying one wins -- a compound block stores its second
2846 // reference's mv, never its first (unless the second is on the
2847 // other side or over the limit). Storing slot 0 unconditionally
2848 // put the wrong (mv, ref_frame_offset) pair in every compound
2849 // block's cell, which a later frame's temporal candidate then
2850 // projected with the wrong reference distance.
2851 let mut saved: Option<crate::motion_field::SavedMv> = None;
2852 for (rf, mv) in [
2853 (info.ref_frame, Some(mv32(info.mv))),
2854 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
2855 ] {
2856 let (Some(mv), true) = (mv, rf > 0) else {
2857 continue;
2858 };
2859 if other_side[rf as usize] {
2860 continue;
2861 }
2862 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
2863 continue;
2864 }
2865 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
2866 }
2867 out[col / 2] = saved;
2868 }
2869 }
2870 };
2871 // lane-mf: the whole-frame pass split over the filter pool in cell-row
2872 // bands, each band owning its own disjoint slice of `cells`.
2873 let bands = crate::par::bands(rows, crate::par::filter_threads());
2874 crate::par::run_bands_mut(&bands, cols, fctx, cells, |r0, r1, mine, _| {
2875 fill(r0, r1, mine);
2876 });
2877 if crate::envflags::env_flag!("EC_TRACE_TPL") {
2878 eprintln!("EC_TPL_SAVED oh={order_hint}");
2879 for (r, row) in field.occupancy().iter().enumerate() {
2880 eprintln!("EC_TPL_SAVED r{r} {row}");
2881 }
2882 }
2883 field
2884}
2885
2886/// The sequence header's `enable_intra_edge_filter`, set once per
2887/// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
2888/// own read of it, kept off the call stack (see that function's own doc
2889/// comment for why) rather than threaded through every `read_plane`/
2890/// `decode_block`/`decode_leaf8` call between here and there.
2891/// Set [`ENABLE_EDGE_FILTER`] for this thread.
2892///
2893/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
2894/// never did -- so an inter frame's intra blocks read whatever value the last
2895/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
2896/// harmless (its own key frame sets it first), but a caller that decodes an
2897/// inter frame directly, or a test harness running several streams on one
2898/// thread, inherits a foreign sequence's bit: decode stops being a pure
2899/// function of the bitstream. `decode_stream` now calls this once per stream
2900/// from the sequence header, which covers every frame including inter ones.
2901pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
2902 fctx.enable_edge_filter.with(|f| f.set(value));
2903}
2904
2905thread_local! {
2906 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2907 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
2908 // crosses the cropped frame edge -- the only units for which "clamp at
2909 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
2910 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
2911 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
2912 // whose width or height is not a multiple of 8 is the only shape that
2913 // produces one; the straddling-band gate arms assert it grew.
2914 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2915 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
2916 // (see `Neighbours::skip_written`).
2917 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2918 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2919}
2920
2921/// Current value of `CDEF_MIXED_SKIP_UNITS`.
2922pub fn cdef_mixed_skip_units() -> usize {
2923 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
2924}
2925
2926/// Current value of `CDEF_SKIPPED_UNITS`.
2927#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2928pub(crate) fn cdef_skipped_units() -> usize {
2929 CDEF_SKIPPED_UNITS.with(|c| c.get())
2930}
2931
2932/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
2933/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
2934pub fn cdef_unwritten_skip_units() -> usize {
2935 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
2936}
2937
2938/// Current value of `CDEF_STRADDLE_UNITS`.
2939#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2940pub(crate) fn cdef_straddle_units() -> usize {
2941 CDEF_STRADDLE_UNITS.with(|c| c.get())
2942}
2943
2944fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
2945 if coeffs && first_sub != chroma_ref {
2946 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
2947 }
2948}
2949
2950/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
2951/// `tx_type` put this block's `eob_pt` on the class-1 row.
2952fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
2953 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
2954 hit!(CHROMA_EOB_CLASS1_HITS);
2955 }
2956}
2957
2958// Which plane the in-flight INTRA reconstruction is writing (0=Y, 1=U, 2=V).
2959// lane-av1cmpaudit: aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`, and
2960// without the same field on our side an `EC_PREDOUT8` vs `OUR_PRED` diff of a
2961// per-plane prediction cannot be read off ours -- a luma/chroma disagreement
2962// looked identical to a same-plane disagreement. Set by `exec_intra` (the
2963// single place a `PlaneBuf::reconstruct{,_rect}` is reached from) and read only
2964// by the `EC_PRED` rung, so it cannot change a decode.
2965thread_local! {
2966 static RECON_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2967}
2968
2969/// The plane index the `EC_PRED` rung prints as `plane=`.
2970fn recon_plane() -> usize {
2971 RECON_PLANE.with(std::cell::Cell::get)
2972}
2973
2974/// Restores [`RECON_PLANE`] on drop, so `exec_intra` needs no cleanup path on
2975/// either of its two early returns.
2976struct PlaneGuard(usize);
2977impl Drop for PlaneGuard {
2978 fn drop(&mut self) {
2979 RECON_PLANE.with(|c| c.set(self.0));
2980 }
2981}
2982
2983const SUB_MI: u32 = 4;
2984const MI: usize = 4;
2985const SB: usize = 64;
2986/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
2987/// (tile start, superblock-row start).
2988///
2989/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
2990/// `av1_get_partition_plane_context` reads its own zero-initialised
2991/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
2992/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
2993/// (64), which reads identically at every level up to 64x64 but sets the bit
2994/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
2995/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
2996/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
2997const NO_NEIGHBOUR_SIDE: usize = 128;
2998const BLOCK: usize = 32;
2999const SUB: usize = 16;
3000const TX32: usize = 32;
3001const TX16: usize = 16;
3002const TX8: usize = 8;
3003const TX4: usize = 4;
3004const DC_PRED: usize = 0;
3005/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
3006/// carries an angle delta — [`crate::tile`]'s own private copy of the same
3007/// constant.
3008const V_PRED: usize = 1;
3009const H_PRED: usize = 2;
3010/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
3011/// `Fimode_To_Intradir`, libaom `blockd.h`).
3012const D157_PRED: usize = 6;
3013/// The last directional mode, `D67_PRED`.
3014const D67_PRED: usize = 8;
3015/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
3016/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
3017/// codes anything else, so this decoder never reads anything else either.
3018const ANGLE_DELTA_ZERO: usize = 3;
3019const NUM_BASE_LEVELS: i32 = 2;
3020const COEFF_BASE_RANGE: i32 = 12;
3021const BR_STEP: i32 = 3;
3022const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
3023
3024/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
3025/// whose probability mass a superblock or block half outside the frame
3026/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
3027/// duplicated here (that module is another lane's territory this round) and
3028/// kept in step with it by the byte-exact round-trip tests below rather than
3029/// by sharing code.
3030const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
3031const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
3032
3033fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
3034 if crate::envflags::env_flag!("EC_AV1_TRACE") {
3035 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
3036 }
3037}
3038
3039fn element_prob(cdf: &[u16], element: usize) -> u16 {
3040 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
3041}
3042
3043/// The two-symbol CDF a partial superblock/block's forced-split flag is read
3044/// with: the mass of `elements` becomes the probability of the one partition
3045/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
3046/// (the encoder's non-adapting counterpart to this read).
3047fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
3048 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
3049 [32768 - split, 32768, 0]
3050}
3051
3052fn unsupported(what: impl Into<String>) -> Error {
3053 Error::unsupported("AV1 tile", what.into())
3054}
3055
3056/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
3057/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
3058/// same rule.
3059pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
3060 match base_q_idx {
3061 0..=20 => 0,
3062 21..=60 => 1,
3063 61..=120 => 2,
3064 _ => 3,
3065 }
3066}
3067
3068/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
3069/// [`crate::tile`]'s writer generates its scan tables with.
3070fn default_scan(side: usize) -> &'static [u16] {
3071 // One table per transform side (4/8/16/32), built once: this used to be a
3072 // fresh heap allocation plus the whole anti-diagonal walk on every
3073 // transform block read.
3074 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
3075 [
3076 default_scan_gen(4),
3077 default_scan_gen(8),
3078 default_scan_gen(16),
3079 default_scan_gen(32),
3080 ]
3081 });
3082 assert!(
3083 matches!(side, 4 | 8 | 16 | 32),
3084 "no default scan for a {side}-point transform"
3085 );
3086 &SCANS[side.trailing_zeros() as usize - 2]
3087}
3088
3089fn default_scan_gen(side: usize) -> Vec<u16> {
3090 let mut scan = Vec::with_capacity(side * side);
3091 for d in 0..(2 * side - 1) {
3092 let lo = d.saturating_sub(side - 1);
3093 let hi = d.min(side - 1);
3094 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
3095 if d % 2 == 0 {
3096 scan.extend(diagonal.rev());
3097 } else {
3098 scan.extend(diagonal);
3099 }
3100 }
3101 scan
3102}
3103
3104/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
3105/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
3106/// in, instead of the default zigzag. libaom's own tables are keyed by a
3107/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
3108/// physically column-major level buffer, but they decompose to the exact
3109/// same (row, col) walk as a flat row-major traversal of *our* row-major
3110/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
3111/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
3112/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
3113/// transposed (column 0 down every row, then column 1, ...).
3114pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
3115 class_scan_table_wh(side, side, class)
3116}
3117
3118/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
3119/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
3120/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
3121/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
3122/// transcribed with -- `mrow` is the plain row-major raster in our indexing
3123/// and `mcol` its transpose, at rect sizes exactly as at square ones.
3124fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
3125 match class {
3126 TxClass::Vert => (0..(w * h) as u16).collect(),
3127 TxClass::Horiz => (0..w)
3128 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
3129 .collect(),
3130 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
3131 }
3132}
3133
3134fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
3135 match scan_idx {
3136 0 => 0,
3137 i if i <= area / 8 => 1,
3138 i if i <= area / 4 => 2,
3139 _ => 3,
3140 }
3141}
3142
3143/// One cell of [`read_coeffs`]'s level buffer.
3144///
3145/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
3146/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
3147/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
3148/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
3149/// zero cells instead of needing the `row >= side || col >= side` edge test
3150/// this used to run five times per coefficient. Nothing writes a padding
3151/// cell, so the values are the same zeros the test returned.
3152#[inline]
3153fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
3154 grid[row * stride + col] as i32
3155}
3156
3157/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
3158/// `txb_common.h`): everything but the two lone-axis-identity types this
3159/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
3160#[derive(Clone, Copy, PartialEq, Eq)]
3161pub(crate) enum TxClass {
3162 TwoD,
3163 Horiz,
3164 Vert,
3165}
3166
3167impl TxClass {
3168 pub(crate) fn of(tx_type: TxType) -> Self {
3169 match tx_type {
3170 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
3171 // key on axis alone -- FLIPADST is still ADST for this purpose.
3172 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
3173 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
3174 _ => Self::TwoD,
3175 }
3176 }
3177}
3178
3179/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
3180/// table (indexed by the position along the transform's *coded* axis --
3181/// `col` for horiz, `row` for vert) that places their contexts past the 2D
3182/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
3183/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
3184pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
3185 match i {
3186 0 => 26,
3187 1 => 31,
3188 _ => 36,
3189 }
3190}
3191
3192fn base_ctx(
3193 grid: &[u8],
3194 stride: usize,
3195 row: usize,
3196 col: usize,
3197 class: TxClass,
3198 rect_shape: Option<(usize, usize)>,
3199) -> usize {
3200 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
3201 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
3202 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
3203 // position through the full 1D neighbour sum and offset table. Skipping
3204 // that for every class desynced the last (DC) coefficient of a
3205 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
3206 // 0, which then read one extra `BR` symbol at the max and forced a
3207 // spurious third Golomb call).
3208 if class == TxClass::TwoD && row == 0 && col == 0 {
3209 return 0;
3210 }
3211 let offsets: [(usize, usize); 5] = match class {
3212 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
3213 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
3214 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
3215 };
3216 let mag: i32 = offsets
3217 .iter()
3218 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
3219 .sum();
3220 let ctx = ((mag + 1) >> 1).min(4) as usize;
3221 match class {
3222 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
3223 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
3224 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
3225 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
3226 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
3227 // strip, which own a genuinely different table from the square one
3228 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
3229 // square table vs the real ctx 13 the rect table gives).
3230 TxClass::TwoD => {
3231 // lane-rectsplit r4: apply libaom's GENERATING RULE
3232 // (`txb_common.h:199-209`) directly instead of indexing the
3233 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
3234 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
3235 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
3236 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
3237 // so 32 consecutive entries are one COLUMN: the [`cdf`]
3238 // transcriptions are `[col][row]` and this read had them as
3239 // `[row][col]` -- the transpose, i.e. the other shape's rule with
3240 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
3241 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
3242 // pins the rule against the tables over their whole 5x5 domain.
3243 if let Some((w, h)) = rect_shape {
3244 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
3245 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
3246 }
3247 if w < h && row < 2 {
3248 return ctx + 11;
3249 }
3250 if w > h && col < 2 {
3251 return ctx + 16;
3252 }
3253 }
3254 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
3255 }
3256 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
3257 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
3258 }
3259}
3260
3261/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
3262/// offsets into the padded level frame (lane-coefread): the tap pattern is a
3263/// function of the tx class alone, which is fixed for a whole transform unit,
3264/// so resolving it once per unit takes the class match and the `(dr, dc)`
3265/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
3266/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
3267/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
3268/// original `(dr, dc)` form.
3269fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
3270 match class {
3271 TxClass::TwoD => (
3272 [stride, 1, stride + 1, 2 * stride, 2],
3273 [stride, 1, stride + 1],
3274 ),
3275 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
3276 TxClass::Vert => (
3277 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
3278 [stride, 1, 2 * stride],
3279 ),
3280 }
3281}
3282
3283/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
3284/// neighbours) + 1) >> 1`, clamped to 4.
3285#[inline(always)]
3286fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
3287 let mut mag = 0u32;
3288 for &t in taps {
3289 mag += u32::from(grid[idx + t]).min(3);
3290 }
3291 (((mag + 1) >> 1) as usize).min(4)
3292}
3293
3294/// [`br_ctx`]'s neighbour sum, off flat taps.
3295#[inline(always)]
3296fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
3297 let mut mag = 0u32;
3298 for &t in taps {
3299 mag += u32::from(grid[idx + t]);
3300 }
3301 (((mag + 1) >> 1) as usize).min(6)
3302}
3303
3304/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
3305/// origin-offset tail the two coefficient readers state inline; kept as the
3306/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
3307/// flat one against.
3308#[cfg(test)]
3309fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
3310 let extra = match class {
3311 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
3312 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
3313 TxClass::Vert => neighbour(grid, stride, row + 2, col),
3314 };
3315 let mag = neighbour(grid, stride, row + 1, col) + neighbour(grid, stride, row, col + 1) + extra;
3316 let mag = (((mag + 1) >> 1).min(6)) as usize;
3317 if row == 0 && col == 0 {
3318 return mag;
3319 }
3320 let near_origin = match class {
3321 TxClass::TwoD => row < 2 && col < 2,
3322 TxClass::Horiz => col == 0,
3323 TxClass::Vert => row == 0,
3324 };
3325 if near_origin { mag + 7 } else { mag + 14 }
3326}
3327
3328/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
3329/// transposed from libaom's column-major buffer into this decoder's row-major
3330/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
3331/// against the real table). Not the square zigzag formula generalized to
3332/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
3333const SCAN_32X16: [u16; 512] = [
3334 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
3335 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39, 8,
3336 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72, 41,
3337 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229, 198,
3338 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, 13,
3339 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418, 387,
3340 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326, 295,
3341 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234, 203,
3342 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142, 111, 80,
3343 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19, 485, 454,
3344 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424, 393, 362,
3345 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332, 301, 270,
3346 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178,
3347 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148, 117, 86, 55,
3348 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, 491, 460, 429,
3349 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430, 399, 368, 337,
3350 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338, 307, 276, 245,
3351 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246, 215, 184, 153,
3352 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154, 123, 92, 61, 30,
3353 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 497, 466, 435,
3354 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405, 374, 343, 312,
3355 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251, 220, 189, 158,
3356 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439, 408, 377, 346,
3357 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503, 472, 441, 410,
3358 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443, 412, 381, 350,
3359 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415, 509, 478, 447,
3360 510, 479, 511,
3361];
3362
3363/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
3364/// [`SCAN_32X16`]'s doc comment).
3365const SCAN_16X32: [u16; 512] = [
3366 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,
3367 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
3368 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
3369 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
3370 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
3371 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
3372 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
3373 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
3374 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
3375 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
3376 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
3377 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
3378 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
3379 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
3380 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
3381 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
3382 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
3383 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
3384 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
3385 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
3386 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
3387 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
3388 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
3389 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
3390 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
3391 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
3392];
3393
3394/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
3395/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
3396/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
3397/// the same source).
3398const SCAN_4X8: [u16; 32] = [
3399 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,
3400 23, 26, 29, 27, 30, 31,
3401];
3402
3403/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
3404const SCAN_8X4: [u16; 32] = [
3405 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,
3406 29, 22, 15, 30, 23, 31,
3407];
3408
3409/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
3410/// [`SCAN_32X16`]'s doc comment).
3411const SCAN_16X8: [u16; 128] = [
3412 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,
3413 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
3414 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
3415 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
3416 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
3417 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
3418];
3419
3420/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
3421/// [`SCAN_32X16`]'s doc comment).
3422const SCAN_8X16: [u16; 128] = [
3423 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,
3424 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
3425 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
3426 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
3427 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
3428 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
3429];
3430
3431/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
3432/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
3433/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
3434/// scans column-major (`p = col * height + row`), so a naive copy of
3435/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
3436/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
3437/// are byte-identical to this decoder's [`SCAN_8X16`].
3438const SCAN_32X8: [u16; 256] = [
3439 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
3440 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226,
3441 195, 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104,
3442 73, 42, 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200,
3443 169, 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78,
3444 47, 16, 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205,
3445 174, 143, 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83,
3446 52, 21, 239, 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210,
3447 179, 148, 117, 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88,
3448 57, 26, 244, 213, 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215,
3449 184, 153, 122, 91, 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93,
3450 62, 31, 249, 218, 187, 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127,
3451 252, 221, 190, 159, 253, 222, 191, 254, 223, 255,
3452];
3453/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
3454/// 16x64 `PARTITION_VERT_4` strip).
3455const SCAN_8X32: [u16; 256] = [
3456 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,
3457 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
3458 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
3459 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
3460 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
3461 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
3462 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
3463 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
3464 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
3465 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
3466 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
3467 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
3468 239, 246, 253, 247, 254, 255,
3469];
3470/// `Default_Scan_16x4`, this decoder's own row-major transcription of
3471/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
3472/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
3473/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
3474/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
3475/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
3476/// were emitted -- a naive copy installs the transpose (class
3477/// reference-layout-not-spec).
3478const SCAN_16X4: [u16; 64] = [
3479 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,
3480 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
3481 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
3482];
3483/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
3484/// 8x32 `PARTITION_VERT_4` strip).
3485const SCAN_4X16: [u16; 64] = [
3486 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,
3487 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
3488 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
3489];
3490
3491/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
3492/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
3493/// padding already holds.
3494#[inline]
3495fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
3496 grid[row * stride + col] as i32
3497}
3498
3499/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
3500/// the rect generalization is libaom's own comment in
3501/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
3502/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
3503/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
3504/// [`decode_block_rect`] codes (see that function's own doc comment).
3505fn base_ctx_rect(
3506 grid: &[u8],
3507 stride: usize,
3508 w: usize,
3509 h: usize,
3510 row: usize,
3511 col: usize,
3512 class: TxClass,
3513) -> usize {
3514 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
3515 // the 2D class short-circuits the DC position.
3516 if class == TxClass::TwoD && row == 0 && col == 0 {
3517 return 0;
3518 }
3519 let offsets: [(usize, usize); 5] = match class {
3520 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
3521 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
3522 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
3523 };
3524 let mag: i32 = offsets
3525 .iter()
3526 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
3527 .sum();
3528 let ctx = ((mag + 1) >> 1).min(4) as usize;
3529 match class {
3530 TxClass::TwoD => {
3531 if w < h && row < 2 {
3532 return ctx + 11;
3533 }
3534 if w > h && col < 2 {
3535 return ctx + 16;
3536 }
3537 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
3538 }
3539 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
3540 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
3541 // position along one axis only).
3542 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
3543 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
3544 }
3545}
3546
3547/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
3548/// neighbour-offset math itself is shape-independent, only the boundary
3549/// clamp needs the real bound in each axis.
3550/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
3551/// its body was character-for-character [`br_ctx`]'s, which
3552/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
3553#[cfg(test)]
3554fn br_ctx_rect(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
3555 let extra = match class {
3556 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
3557 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
3558 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
3559 };
3560 let mag = neighbour_rect(grid, stride, row + 1, col)
3561 + neighbour_rect(grid, stride, row, col + 1)
3562 + extra;
3563 let mag = (((mag + 1) >> 1).min(6)) as usize;
3564 if row == 0 && col == 0 {
3565 return mag;
3566 }
3567 let near_origin = match class {
3568 TxClass::TwoD => row < 2 && col < 2,
3569 TxClass::Horiz => col == 0,
3570 TxClass::Vert => row == 0,
3571 };
3572 if near_origin { mag + 7 } else { mag + 14 }
3573}
3574
3575fn dc_vote(dc: Option<bool>) -> i32 {
3576 match dc {
3577 None => 0,
3578 Some(true) => -1,
3579 Some(false) => 1,
3580 }
3581}
3582
3583fn dc_sign_ctx(vote: i32) -> usize {
3584 match vote.signum() {
3585 0 => 0,
3586 -1 => 1,
3587 _ => 2,
3588 }
3589}
3590
3591/// The `tx_type` a CDF symbol names, given the width of the row it was read
3592/// from.
3593///
3594/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
3595/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
3596/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
3597/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
3598/// members are a prefix of the five.
3599///
3600/// One function rather than a `match` at each reader, so
3601/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
3602/// tests the mapping the readers actually use.
3603pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
3604 match cdf_len {
3605 17 => TxType::from_symbol_all16(t),
3606 13 => TxType::from_symbol_set2_12(t),
3607 8 => TxType::from_symbol_set1(t),
3608 _ => TxType::from_symbol(t),
3609 }
3610}
3611
3612/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
3613/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
3614/// (class `table-and-reader-move-together` -- the writer picks its symbol
3615/// through the reader's own map, so the two cannot drift).
3616pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
3617 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
3618}
3619
3620/// The remainder of a level the base and base-range syntax could not reach
3621/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
3622/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
3623pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
3624 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
3625 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
3626 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
3627 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
3628 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
3629 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
3630 // stream_can_carry` enumerates that whole value domain.
3631 //
3632 // So this refusal never names a reader gap: it is always the SYMPTOM of an
3633 // earlier desync (class `refusal-hides-a-defect`), and every historical
3634 // instance was closed by fixing that desync -- lane-dgolomb's
3635 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
3636 // Raising the cap only trades a clean refusal for silent corruption:
3637 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
3638 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
3639 // from a refusal into a frame-0 LUMA MISMATCH.
3640 let mut length = 1u32;
3641 while dec.literal(1) == 0 {
3642 length += 1;
3643 if length > 20 {
3644 return Err(unsupported("a Golomb tail longer than this decoder reads"));
3645 }
3646 }
3647 let mut x = 1u32;
3648 for _ in 1..length {
3649 x = (x << 1) | dec.literal(1);
3650 }
3651 Ok(x - 1)
3652}
3653
3654/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
3655/// [`crate::tile`]'s `write_eob`.
3656fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
3657 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
3658 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
3659
3660 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
3661 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
3662 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
3663 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
3664 // `eob_multi_ctx`). Missing that split desynced the very first
3665 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
3666 // against a real aomdec trace).
3667 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
3668 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
3669 (_, Some(class1)) => class1,
3670 };
3671 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
3672 let (range, value) = dec.debug_state();
3673 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
3674 }
3675 crate::msac::SymbolDecoder::set_symr_cdf("eob_pt");
3676 let group = dec.symbol(eob_pt) + 1;
3677 if trace {
3678 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
3679 }
3680 let bits = OFFSET_BITS[group];
3681 let mut offset = 0u32;
3682 if bits > 0 {
3683 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
3684 if trace {
3685 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
3686 }
3687 offset = top << (bits - 1);
3688 if bits > 1 {
3689 offset |= dec.literal(bits - 1);
3690 }
3691 }
3692 GROUP_START[group] + offset as usize
3693}
3694
3695/// One transform block's levels, the inverse of [`crate::tile`]'s
3696/// `write_coeffs`, returned as a `side * side` grid in raster order, along
3697/// with the transform type that grid was coded under (`DCT_DCT` when the
3698/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
3699/// 64-point transforms, which never code anything else).
3700///
3701/// # Errors
3702/// Returns an error if the `tx_type` symbol decodes to a value outside its
3703/// CDF's own set (a corrupt or unsupported bitstream) — every value the
3704/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
3705/// produce dispatches to a real inverse transform.
3706/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
3707/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
3708/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
3709/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
3710/// the plane's own predicted mode instead. Every entry this table can
3711/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
3712/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
3713/// table ever names), so unlike the CDF-coded luma path there is no
3714/// ext-tx-set membership check to fall back from here.
3715pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
3716 use crate::intra::{
3717 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
3718 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
3719 };
3720 match mode {
3721 DC_PRED | D45_PRED => TxType::DctDct,
3722 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
3723 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
3724 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
3725 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
3726 }
3727}
3728
3729/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
3730/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
3731/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
3732fn is_smooth_mode(mode: usize) -> bool {
3733 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
3734}
3735
3736/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
3737/// returning the picture it reconstructs to.
3738///
3739/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
3740/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
3741/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
3742/// `compute_image_size` derives one from the other, but not losslessly: a
3743/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
3744/// what the reconstruction is cropped to on the way out, mirroring
3745/// [`crate::encode::crop_encoded`].
3746///
3747/// # Errors
3748/// Returns an error when a block's partition, mode, skip flag or transform
3749/// type is anything this decoder does not reconstruct (round 2: inter, tx
3750/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
3751/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
3752/// or when the tile payload runs out of the symbols this decode expects (a
3753/// genuinely foreign stream).
3754#[allow(dead_code)]
3755// read only from the `#[cfg(test)]` gates
3756// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
3757#[allow(clippy::too_many_arguments)]
3758pub(crate) fn decode_key_frame_tile(
3759 data: &[u8],
3760 mi_cols: u32,
3761 mi_rows: u32,
3762 base_q_idx: u8,
3763 frame_width: u32,
3764 frame_height: u32,
3765 enable_filter_intra: bool,
3766 cdef: &CdefParams,
3767 loop_filter: &LoopFilterParams,
3768 tx_select: bool,
3769 reduced_tx_set: bool,
3770 allow_screen_content_tools: bool,
3771 allow_intrabc: bool,
3772 fctx: &crate::decode::FrameCtx,
3773) -> Result<Picture> {
3774 decode_key_frame_tile_lr(
3775 data,
3776 mi_cols,
3777 mi_rows,
3778 base_q_idx,
3779 frame_width,
3780 frame_height,
3781 enable_filter_intra,
3782 cdef,
3783 loop_filter,
3784 tx_select,
3785 reduced_tx_set,
3786 allow_screen_content_tools,
3787 allow_intrabc,
3788 &LoopRestorationParams::default(),
3789 fctx,
3790 )
3791}
3792
3793#[cfg(test)]
3794mod tests;
3795
3796#[cfg(test)]
3797mod tx4x8_table_tests;