forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

inter_shapes.rs1721 lines, 73.9 KiBHistoryRawDownload
1//! Inter block shape helpers: the block tx-size readers for rect and inter blocks, the rect residual scan tables and the edge-parameter body. Moved out of `decode/mod.rs` (av1split D13); the items are unchanged apart from visibility.
2
3use super::*;
4
5/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
6/// branch): every block of a `TxMode::Select` inter frame codes its transform
7/// size right after its own mode info -- an inter non-skip block through the
8/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
9/// every other block through the intra `tx_depth` symbol (a skipped inter
10/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
11/// block's own resolved transform side and the leaf list, the latter only
12/// when the tree resolved to more than one transform unit.
13#[allow(clippy::too_many_arguments)]
14pub(super) fn read_block_tx_size(
15 dec: &mut SymbolDecoder,
16 cdfs: &mut Cdfs,
17 n: &mut Neighbours,
18 at_mi: (usize, usize),
19 side: usize,
20 (mi_cols, mi_rows): (usize, usize),
21 is_inter: bool,
22 skip: bool,
23 fctx: &crate::decode::FrameCtx,
24) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
25 // lane-lossless: TX_4X4 over the whole block, and NO var-tx tree -- libaom
26 // `read_block_tx_size` (`decodeframe.c`) sends a lossless block down the
27 // `read_tx_size` arm, which returns TX_4X4 before it reads anything.
28 if lossless(fctx) {
29 // lane-av1lm444loss: libaom CLIPS the transform-unit grid at the frame
30 // edge -- `max_block_high`/`max_block_wide` (`av1_common_int.h:1565`,
31 // `:1579`) fold `mb_to_bottom_edge`/`mb_to_right_edge` into
32 // `block_size_high/wide` before `>> MI_SIZE_LOG2`, so a block that
33 // hangs off the bottom/right codes only the units INSIDE the frame.
34 // `decode_token_recon_block`'s mu walk then bounds every chunk with
35 // `unit_height = ROUND_POWER_OF_TWO(AOMMIN(mu_blocks_high + row,
36 // max_blocks_high), ss_y)`, so the out-of-frame units are never read.
37 //
38 // The unclipped `side / MI` grid is correct arithmetic for a block that
39 // FITS, which is every block of a frame whose height and width are
40 // multiples of the superblock -- so this reads identically on all of
41 // those, and only differs on the partial edge block. Measured on the
42 // 128x96 4:4:4 lossless pin (one 128 root per inter frame, frame 32
43 // mi = 24 tx rows tall): the unclipped grid read 32 rows where the
44 // oracle read 24 -- 256 extra luma units per inter frame (1024 vs
45 // the oracle's 768), the `EC_SYMR` ladder's first fork landing exactly
46 // at that row-24 boundary (`plane=0` luma where the oracle had moved
47 // to `plane=1`), and the pixel diff growing 5596 -> 33561 wrong
48 // samples over the six frames.
49 let side_mi = side / MI;
50 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
51 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
52 if max_w_mi != side_mi || max_h_mi != side_mi {
53 LOSSLESS_EDGE_CLIPPED.with(|c| c.set(c.get() + 1));
54 LOSSLESS_EDGE_CLIP_UNITS
55 .with(|c| c.set(c.get() + (side_mi * side_mi - max_w_mi * max_h_mi)));
56 }
57 let mut leaves = Vec::with_capacity(max_w_mi * max_h_mi);
58 for row in 0..max_h_mi {
59 for col in 0..max_w_mi {
60 leaves.push((row, col, 4, 4));
61 }
62 }
63 // lane-av1txctxband2: a lossless block still runs libaom's
64 // `set_txfm_ctxs` at the tail of `parse_decode_block`
65 // (decodeframe.c:1260). Its `read_tx_size` returned `TX_4X4` on the
66 // FIRST line (decodeframe.c:1214) -- the early return skips the symbol
67 // read, not the PUBLISH -- so `tx_size_wide[TX_4X4] == 4` goes over the
68 // block's own width/height, and a SKIPPED inter block instead records
69 // its block size (the `skip && is_inter` term).
70 //
71 // This early return published nothing, so on a MIXED frame every
72 // lossless square block left the band holding whatever an earlier,
73 // lossy block wrote. Measured on the 640x480 mixed-lossless+altref
74 // cell (`420_mixll_altref_640x480_5f.obu`, 87 537 B): the abutting
75 // 8x8 INTRA lossless block at mi(78,110) left `above_txfm[110]` at
76 // the 16 a skipped 16-px inter block at mi(36,108) had written 43 mi
77 // rows earlier, and the 8x4 intra leaf with `use_filter_intra` at
78 // mi(80,110) then read `tx_size_cat0[2]` where libaom reads row 1
79 // (oracle `EC_TXCTXB` `abv=4 lft=8 above=0 left=1 ctx=1`). The tile
80 // desynced there and the frame refused.
81 //
82 // The RECT twin [`read_block_tx_size_rect`] has published on this arm
83 // since lane-av1lm444loss; only the square arm had the hole.
84 let pub_above: u8 = if skip && is_inter {
85 (side_mi * MI) as u8
86 } else {
87 4
88 };
89 // The gate's non-vacuity arm, on the DECISION, sampled BEFORE the
90 // write: this publish CHANGES at least one of the above-band cells it
91 // covers -- the cell did not already hold `pub_above`, so a later
92 // `get_tx_size_context` / `txfm_partition_context` reader in the same
93 // tile column reads a value the publish produced.
94 //
95 // CORRECTED 2026-09-30 (refutation pass `lanes/refute-av1txctxband2`):
96 // an earlier version of this comment, and of the static's doc, claimed
97 // the write counts only when it OVERWRITES "a size some earlier block
98 // had left", and that a wholly-lossless all-non-skip stream leaves it
99 // at zero. MEASURED FALSE: 420_lossless_tallinter_8x16.obu fires 48,
100 // ALL with every covered column still at `TXFM_CTX_INIT` -- a first
101 // write into a fresh tile column counts here too, because the test is
102 // "the cell did not already hold this value", not "some block wrote a
103 // different value earlier". Of the pin's 944 fires, 183 are that
104 // first-touch case. The count is still a decision (no reader, no
105 // intra-only frame, no unchanged column), so the gate keeps its teeth;
106 // only the doc's stronger reading was wrong.
107 let overwrote = !fctx.intra_only.with(std::cell::Cell::get)
108 && (0..side_mi).any(|i| n.above_txfm.get(at_mi.1 + i) != Some(&pub_above));
109 set_txfm_ctxs(n, at_mi, 4, side_mi, side_mi, skip && is_inter);
110 if overwrote {
111 hit!(LOSSLESS_SQ_TXFM_BAND_OVERWRITE_HITS);
112 }
113 return Ok((4, Some(leaves)));
114 }
115 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
116 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
117 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
118 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
119 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
120 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
121 if side > 64 {
122 let step = 64 / MI;
123 let mut leaves = Vec::new();
124 for row in (0..side / MI).step_by(step) {
125 for col in (0..side / MI).step_by(step) {
126 leaves.push((row, col, 64, 64));
127 }
128 }
129 return Ok((64, Some(leaves)));
130 }
131 return Ok((side, None));
132 }
133 let side_mi = side / MI;
134 if is_inter && !skip {
135 let max_tx = side.min(64);
136 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
137 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
138 let mut leaves = Vec::new();
139 let step = max_tx / MI;
140 for row in (0..side_mi).step_by(step) {
141 for col in (0..side_mi).step_by(step) {
142 read_var_tx_size(
143 dec,
144 cdfs,
145 n,
146 at_mi,
147 side,
148 (max_w_mi, max_h_mi),
149 (max_tx, max_tx),
150 0,
151 row,
152 col,
153 &mut leaves,
154 );
155 }
156 }
157 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
158 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
159 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
160 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
161 // which the mu-chunk reader above codes as their 32x32 coded corner.
162 let leaf_ceiling = if side > 64 { 64 } else { 32 };
163 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
164 // Only a block wider than a superblock's own 64x64 max transform
165 // reaches here; this crate has no 64-point *inter* coefficient
166 // table set ([`inter_txbset_for`] stops at 32).
167 return Err(unsupported(
168 "an inter var-tx tree with a leaf transform larger than 32x32",
169 ));
170 }
171 let resolved = leaves.last().map_or(side, |l| l.2);
172 return Ok((resolved, (!single).then_some(leaves)));
173 }
174 let tx = if is_inter {
175 side.min(64)
176 } else {
177 read_tx_size(dec, cdfs, n, at_mi, side, fctx)
178 };
179 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
180 if !is_inter && tx != side {
181 // lane-intrainter r1: an intra block inside an inter frame whose
182 // `tx_depth` split its luma transform codes exactly the key-frame
183 // split path's transform units (`decode_block`'s multi-TU loop),
184 // raster order over the block. Handed back in the same leaf shape the
185 // inter var-tx tree uses, so the caller's per-TU luma loop, the
186 // `record_split_luma` neighbour write-back and the per-TU deblock
187 // edges are the ones it already runs for a var-tx inter block. A
188 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
189 // seeing `Some` here.
190 let step = tx / MI;
191 let mut leaves = Vec::new();
192 for row in (0..side_mi).step_by(step) {
193 for col in (0..side_mi).step_by(step) {
194 leaves.push((row, col, tx, tx));
195 }
196 }
197 hit_do! {
198 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
199 let mut h = c.get();
200 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
201 c.set(h);
202 });
203 }
204 return Ok((tx, Some(leaves)));
205 }
206 Ok((tx, None))
207}
208
209/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
210/// decoder codes -- a 2:1 strip whose own max rect transform
211/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
212/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
213/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
214/// 64-point rect transform, and 16x8/8x16 needs
215/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
216/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
217/// rect transform), neither of which exists yet -- both stay refused by name.
218pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
219 matches!(
220 (w, h),
221 // 2:1 strips whose transform is coded in full (lane-inter4).
222 (32, 16) | (16, 32) | (16, 8) | (8, 16)
223 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
224 // codes all 64 of its positions, and its chroma pair is an 8x4 /
225 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
226 | (16, 4) | (4, 16)
227 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
228 // only the low 32 coefficients of a 64-length axis, so these read
229 // exactly the truncated corner the INTRA superblock-strip path
230 // already reads (`read_intra_mode_rect`), through
231 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
232 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
233 // `tx_type` symbol is coded at all.
234 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
235 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
236 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
237 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
238 // refused earlier ("an inter partition below 8x8").
239 | (8, 4) | (4, 8)
240 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
241 // one rectangular transform -- `max_txsize_rect_lookup
242 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
243 // TX_64X64 units read through the mu-chunk loop, same as the
244 // 128x128 NONE block's four.
245 | (128, 64) | (64, 128)
246 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
247 // 10-bit film cuts and every measured 1080p offset stop on
248 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
249 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
250 // positions, and its chroma pair is a 16x4 / 4x16 unit
251 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
252 | (32, 8) | (8, 32)
253 )
254}
255
256// lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path
257// actually PRESENTS, as a thread-local bitmask -- the measured domain behind
258// the "rectangular ... has no ... here" refusals. `side` is the square context
259// a block reads its CDFs at and `write_w`/`write_h` its true footprint;
260// `inter_piece!` derives `reject_residual` from exactly that inequality, so
261// these triples are what decides whether those refusals can fire at all. Bit
262// 31 is "a triple this table does not list", which is what makes the gate a
263// census rather than a restatement of its own table.
264pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
265 (16, 16, 16),
266 (32, 32, 32),
267 (32, 16, 32),
268 (32, 32, 16),
269 (16, 8, 16),
270 (16, 16, 8),
271 (32, 8, 32),
272 (64, 64, 64),
273 (32, 32, 8),
274 (64, 16, 64),
275 (128, 128, 128),
276 (64, 32, 64),
277 (64, 64, 32),
278 (16, 4, 16),
279 (64, 64, 16),
280 (16, 16, 4),
281 (128, 128, 64),
282 (128, 64, 128),
283];
284
285/// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple
286/// outside [`INTER_BLOCK_SHAPES`].
287pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31;
288
289thread_local! {
290 pub(super) static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
291}
292
293/// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a
294/// gate reading it sees only the streams it decoded itself).
295pub fn inter_block_shape_mask() -> u32 {
296 INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get)
297}
298
299/// The luma coefficient/`tx_type` table set of a whole-block rectangular
300/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
301/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
302/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
303/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
304/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
305/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
306/// row (`txsize_sqr_map`), never the 16x16 one.
307pub(super) fn rect_inter_luma_set(
308 w: usize,
309 h: usize,
310 fctx: &crate::decode::FrameCtx,
311) -> Result<TxbSet> {
312 Ok(match (w, h) {
313 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
314 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
315 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
316 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
317 // ALL16 otherwise -- both at the TX_4X4 row.
318 (8, 4) | (4, 8) => {
319 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
320 TxbSet::LumaRect8x4Inter
321 } else {
322 TxbSet::LumaRect8x4InterSet1
323 }
324 }
325 (16, 4) | (4, 16) => {
326 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
327 TxbSet::LumaRect16x4Inter
328 } else {
329 TxbSet::LumaRect16x4Inter1
330 }
331 }
332 (16, 8) | (8, 16) => {
333 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
334 TxbSet::LumaRect16x8Inter
335 } else {
336 TxbSet::LumaRect16x8InterSet1
337 }
338 }
339 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
340 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
341 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
342 // adjusted size, so the existing sets are bit-exact. Neither carries a
343 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
344 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
345 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
346 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
347 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
348 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
349 (64, 32) | (32, 64) => TxbSet::Luma64,
350 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
351 _ => {
352 return Err(unsupported(
353 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
354 ));
355 }
356 })
357}
358
359/// The chroma table set of the same block's single rectangular chroma unit
360/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
361/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
362/// the luma unit's.
363pub(super) fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
364 Ok(match (w, h) {
365 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
366 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
367 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
368 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
369 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
370 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
371 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
372 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
373 (32, 8) | (8, 32) => TxbSet::Chroma16,
374 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
375 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
376 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
377 (16, 4) | (4, 16) => TxbSet::Chroma8,
378 // lane-av1-444: one 32x32 unit of a 4:4:4 64x32/32x64 chroma plane
379 // block (`av1_get_max_uv_txsize` adjusts `TX_64X32`/`TX_32X64` to
380 // `TX_32X32`); `get_txsize_entropy_ctx(TX_32X32)` is the 32x32 set.
381 (32, 32) => TxbSet::Chroma32,
382 // lane-av1-422j: square chroma units of a 4:2:2 strip -- a 16x8
383 // (8x16) luma strip's chroma plane block is 8x8 (16x16) square, and
384 // the square-block routing above sends it here. The sets are the
385 // exact `get_txsize_entropy_ctx` tables the square arms use.
386 (16, 16) => TxbSet::Chroma16,
387 (8, 8) => TxbSet::Chroma8,
388 (4, 4) => TxbSet::Chroma4,
389 _ => {
390 // lane-av1-422l: the refusing (w, h) for the owning lane -- the
391 // 4:2:2 frontier stops here at (4, 32), the plane residual of an
392 // 8x32 luma block, which libaom itself marks BLOCK_INVALID
393 // (`av1_ss_size_lookup[BLOCK_8X32][1][0]`, common_data.c:38) and
394 // for which no TX_4X32 exists -- that chroma is coded as a
395 // TX_8X32-chunked merge, not a 4-px unit.
396 if crate::envflags::env_flag!("EC_AV1_TRACE_422") {
397 eprintln!("EC_422 rect_inter_chroma_set missing (w,h)=({w},{h})");
398 }
399 return Err(unsupported(
400 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
401 ));
402 }
403 })
404}
405
406/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
407/// inter path reaches, from the block's TRUE footprint rather than the
408/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
409/// everything 32 and above -> 3.
410pub(super) fn size_group_wh(w: usize, h: usize) -> usize {
411 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
412 // `common_data.h:60`) is 0 for every block with a 4-px side
413 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
414 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
415 match w.min(h) {
416 0..=4 => 0,
417 8 => 1,
418 16 => 2,
419 _ => 3,
420 }
421}
422
423#[test]
424fn size_group_wh_matches_libaom_size_group_lookup() {
425 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
426 // transcribed values (common_data.h:60-62).
427 const TABLE: [((usize, usize), usize); 22] = [
428 ((4, 4), 0),
429 ((4, 8), 0),
430 ((8, 4), 0),
431 ((8, 8), 1),
432 ((8, 16), 1),
433 ((16, 8), 1),
434 ((16, 16), 2),
435 ((16, 32), 2),
436 ((32, 16), 2),
437 ((32, 32), 3),
438 ((32, 64), 3),
439 ((64, 32), 3),
440 ((64, 64), 3),
441 ((64, 128), 3),
442 ((128, 64), 3),
443 ((128, 128), 3),
444 ((4, 16), 0),
445 ((16, 4), 0),
446 ((8, 32), 1),
447 ((32, 8), 1),
448 ((16, 64), 2),
449 ((64, 16), 2),
450 ];
451 for ((w, h), want) in TABLE {
452 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
453 }
454}
455
456/// The default (2D) coefficient scan of a rectangular transform.
457pub(super) fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
458 Ok(match (w, h) {
459 (32, 16) => &SCAN_32X16,
460 (16, 32) => &SCAN_16X32,
461 (16, 8) => &SCAN_16X8,
462 (8, 16) => &SCAN_8X16,
463 (16, 4) => &SCAN_16X4,
464 (4, 16) => &SCAN_4X16,
465 (8, 4) => &SCAN_8X4,
466 (4, 8) => &SCAN_4X8,
467 (32, 8) => &SCAN_32X8,
468 (8, 32) => &SCAN_8X32,
469 // lane-av1-422j: square units routed through the rect reader -- a
470 // 4:2:2 strip's square chroma plane block (8x8 under a 16x8 strip,
471 // 16x16 under an 8x16 one). The default 2D scan is exactly what the
472 // square reader uses for the same side.
473 (w, h) if w == h => default_scan(w),
474 _ => {
475 return Err(unsupported(
476 "a rectangular transform unit whose shape has no coefficient scan table here",
477 ));
478 }
479 })
480}
481
482/// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma
483/// transform unit whose shape has no coefficient table set here" / "a
484/// rectangular transform unit whose shape has no coefficient scan table here"
485/// arms, enumerated against the MEASURED domain of the inter block path
486/// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate
487/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`).
488///
489/// What each helper is actually handed:
490///
491/// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the
492/// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is
493/// square for every rect transform except TX_16X4/TX_4X16, whose leaves are
494/// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8.
495/// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0
496/// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8.
497/// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect
498/// unit, and only when that corner is not 32x32 (a square corner goes
499/// through the square reader with `rect_shape = Some((w, h))`).
500///
501/// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is
502/// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk
503/// loop, which is why they are skipped below.
504#[test]
505fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
506 // lane-av1refusalspan: this gate is the PROOF for THREE refusals, so it
507 // names all three and pins all three guard sites. The census below proves
508 // the shape domain and, on its own, named NONE of the strings that domain
509 // was about -- under a real function boundary rather than a window that
510 // ran into the next test, all three rows read as unanchored.
511 for refusal in [
512 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
513 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
514 "a rectangular transform unit whose shape has no coefficient scan table here",
515 ] {
516 assert!(
517 crate::test_source::module_source("decode").contains(refusal),
518 "this gate proves {refusal:?}, but that string is no longer in decode.rs"
519 );
520 }
521 let fctx = &crate::decode::FrameCtx::new();
522 let corner_scan = |w: usize, h: usize| {
523 let (cw, ch) = (w.min(32), h.min(32));
524 if (cw, ch) == (32, 32) {
525 return; // the square coefficient reader, not `rect_scan`
526 }
527 assert!(
528 rect_scan(cw, ch).is_ok(),
529 "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table"
530 );
531 };
532 let mut checked = 0;
533 for &(side, w, h) in &INTER_BLOCK_SHAPES {
534 if (w, h) == (side, side) || w.max(h) > 64 {
535 continue;
536 }
537 assert!(
538 rect_inter_luma_set(w, h, fctx).is_ok(),
539 "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one"
540 );
541 corner_scan(w, h);
542 // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved
543 // footprint for every other shape.
544 let (cw, ch) = match (w, h) {
545 (16, 4) => (8, 4),
546 (4, 16) => (4, 8),
547 _ => (w / 2, h / 2),
548 };
549 assert!(
550 rect_inter_chroma_set(cw, ch).is_ok(),
551 "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set"
552 );
553 corner_scan(cw, ch);
554 checked += 1;
555 }
556 assert_eq!(
557 checked, 12,
558 "the block-shape census changed: {checked} rect shapes reach the rect transform \
559 tables, not the 12 this claim was measured over"
560 );
561 // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf
562 // shapes, which reach `rect_inter_luma_set` as `(tw, th)`.
563 for (w, h) in [(8usize, 4usize), (4, 8)] {
564 assert!(
565 rect_inter_luma_set(w, h, fctx).is_ok(),
566 "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set"
567 );
568 corner_scan(w, h);
569 }
570}
571
572/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
573/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
574/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
575/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
576/// own width/height; a `0` leaves one whole-block rect transform unit
577/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
578/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
579/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
580/// every leaf of a split rect block is square and the existing square leaf
581/// loop reconstructs it unchanged.
582#[allow(clippy::too_many_arguments)]
583pub(super) fn read_block_tx_size_rect(
584 dec: &mut SymbolDecoder,
585 cdfs: &mut Cdfs,
586 n: &mut Neighbours,
587 at_mi: (usize, usize),
588 (bw, bh): (usize, usize),
589 (mi_cols, mi_rows): (usize, usize),
590 skip: bool,
591 fctx: &crate::decode::FrameCtx,
592) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
593 if lossless(fctx) {
594 // lane-av1lm444loss: the same frame-edge clip as the square builder
595 // above -- `max_block_high`/`max_block_wide` bound a rect block's
596 // transform grid by the part of it inside the frame, so a 1:4 strip
597 // hanging off the bottom codes only its in-frame rows. Identical
598 // arithmetic for a block that fits.
599 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
600 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
601 let full_w_mi = bw / MI;
602 let full_h_mi = bh / MI;
603 if max_w_mi != full_w_mi || max_h_mi != full_h_mi {
604 LOSSLESS_EDGE_CLIPPED.with(|c| c.set(c.get() + 1));
605 LOSSLESS_EDGE_CLIP_UNITS
606 .with(|c| c.set(c.get() + (full_w_mi * full_h_mi - max_w_mi * max_h_mi)));
607 }
608 let mut leaves = Vec::with_capacity(max_w_mi * max_h_mi);
609 for row in 0..max_h_mi {
610 for col in 0..max_w_mi {
611 leaves.push((row, col, 4, 4));
612 }
613 }
614 // A lossless segment takes libaom's `else` branch (the var-tx
615 // condition carries `!xd->lossless[mbmi->segment_id]`), so
616 // `read_tx_size` returns `TX_4X4` and `set_txfm_ctxs` publishes it
617 // over the block's own width/height. The grid's own values (4x4) are
618 // identical either way, so this write is only what keeps the
619 // caller's `fill_lf_grid_rect_after_vartx` suppression sound: a
620 // mixed frame's lossy neighbour reads this block's bands.
621 txfm_partition_update_rect(n, at_mi, (4, 4), (bw, bh));
622 return Ok(Some(leaves));
623 }
624 if skip {
625 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
626 // its own BLOCK size -- width above, height left -- not a transform.
627 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
628 return Ok(None);
629 }
630 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
631 // `rect_inter_residual_supported` has already excluded everything above 32.
632 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
633 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
634 // is TWO square top-level transform units side by side and a 64x128 one is
635 // two stacked -- exactly what libaom `read_block_tx_size`
636 // (decodeframe.c:1140) codes with its `idy/idx` loop over
637 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
638 // own `txfm_partition` symbol at depth 0.
639 if bw.max(bh) > 64 {
640 let tx = 64usize;
641 let (max_w_mi, max_h_mi) = (
642 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
643 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
644 );
645 let mut leaves = Vec::new();
646 if !fctx.tx_select_frame.with(std::cell::Cell::get) {
647 for row in (0..bh / MI).step_by(tx / MI) {
648 for col in (0..bw / MI).step_by(tx / MI) {
649 leaves.push((row, col, tx, tx));
650 }
651 }
652 for &(row, col, tw, th) in &leaves {
653 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
654 }
655 return Ok(Some(leaves));
656 }
657 for row in (0..bh / MI).step_by(tx / MI) {
658 for col in (0..bw / MI).step_by(tx / MI) {
659 read_var_tx_size(
660 dec,
661 cdfs,
662 n,
663 at_mi,
664 bw.max(bh),
665 (max_w_mi, max_h_mi),
666 (tx, tx),
667 0,
668 row,
669 col,
670 &mut leaves,
671 );
672 }
673 }
674 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
675 return Err(unsupported(
676 "an inter var-tx tree with a leaf transform larger than 64x64",
677 ));
678 }
679 return Ok(Some(leaves));
680 }
681 let (tx_w, tx_h) = (bw, bh);
682 if !fctx.tx_select_frame.with(std::cell::Cell::get) {
683 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
684 // transform, and `set_txfm_ctxs` records exactly what
685 // `txfm_partition_update` would for that same unit.
686 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
687 hit!(RECT_INTER_TU_HITS);
688 return Ok(None);
689 }
690 // lane-av1oddheightfork2: `above_px` / `left_px` are the two
691 // `TXFM_CONTEXT` inputs of `txfm_partition_ctx_rect`, i.e. the exact
692 // operands of libaom's `*above_ctx < txw` / `*left_ctx < txh`
693 // (av1_common_int.h:1750-1753). They are printed so a ctx disagreement
694 // with aomdec's `EC_VARTX` rung names WHICH neighbour is wrong instead of
695 // only the arithmetic difference. Trace-only; reads no bits.
696 let (above_px, left_px) = (n.above_txfm[at_mi.1], n.left_txfm[at_mi.0]);
697 let ctx = txfm_partition_ctx_rect(above_px, left_px, bw.max(bh), tx_w, tx_h);
698 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
699 hit!(TXFM_SPLIT_READS);
700 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
701 let (rng, _) = dec.debug_state();
702 eprintln!(
703 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} above={above_px} left={left_px} maxblk={} tx={tx_w}x{tx_h} rng={rng}",
704 at_mi.0,
705 at_mi.1,
706 u8::from(split),
707 bw.max(bh),
708 );
709 }
710 if !split {
711 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
712 hit!(RECT_INTER_TU_HITS);
713 return Ok(None);
714 }
715 hit!(TXFM_SPLIT_HITS);
716 hit!(RECT_INTER_TXSPLIT_HITS);
717 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
718 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
719 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
720 // rect one and its leaves carry their own width and height.
721 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
722 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
723 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
724 let mut leaves = Vec::new();
725 for row in (0..bh / MI).step_by(sub_h / MI) {
726 for col in (0..bw / MI).step_by(sub_w / MI) {
727 read_var_tx_size(
728 dec,
729 cdfs,
730 n,
731 at_mi,
732 bw.max(bh),
733 (max_w_mi, max_h_mi),
734 (sub_w, sub_h),
735 1,
736 row,
737 col,
738 &mut leaves,
739 );
740 }
741 }
742 Ok(Some(leaves))
743}
744
745/// The chroma half of a whole-block rectangular INTER transform unit (both
746/// [`decode_inter_block`] rect readers): `av1_get_max_uv_txsize(bsize)` gives
747/// the strip's own rect chroma size at 4:2:0 (one unit for the whole block),
748/// but at 4:4:4 the chroma plane block keeps the luma block's 64-px axis,
749/// which `av1_get_adjusted_tx_size` caps at 32 (`TX_64X16` -> `TX_32X16`),
750/// so it codes TWO units plane-major (every U, then every V --
751/// `decode_token_recon_block`'s inter branch loops `for plane` outside
752/// `for blk_row/blk_col` inside the one mu chunk). No unit codes a `tx_type`
753/// symbol: each inherits the block-wide luma one (`av1_get_tx_type`'s inter
754/// UV lookup at ss 0 reads the tx_type_map at its own mi, which a single-TU
755/// luma block fills uniformly).
756#[allow(clippy::too_many_arguments)]
757pub(super) fn read_inter_rect_chroma(
758 y: &mut PlaneBuf<'static>,
759 u: &mut PlaneBuf<'static>,
760 v: &mut PlaneBuf<'static>,
761 dec: &mut SymbolDecoder,
762 cdfs: &mut Cdfs,
763 neighbours: &mut Neighbours,
764 around: [(bool, bool, i32); 3],
765 su: Pred<'_>,
766 sv: Pred<'_>,
767 at_mi: (usize, usize),
768 (cpx, cpy): (usize, usize),
769 (write_chroma_w, write_chroma_h): (usize, usize),
770 chroma_side: usize,
771 mode_for_tx: usize,
772 // lane-av1chrtx: this block's coded luma transform leaves, `(row, col,
773 // tw, th, tx_type)` -- the same list the 4:4:4 four-unit arms resolve
774 // through `covering_leaf_tx_type`. This sibling used to hand EVERY unit
775 // the block-level `luma_tx_type` (the top-left leaf's type), so a rect
776 // inter block whose chroma plane splits (`nx*ny > 1`) over MIXED var-tx
777 // leaves read the wrong type per unit.
778 leaf_tx_types: &[(usize, usize, usize, usize, TxType)],
779 luma_tx_type: TxType,
780 fctx: &crate::decode::FrameCtx,
781) -> Result<(Grid, Grid, Vec<((usize, usize), usize, Grid, usize, usize)>)> {
782 let (uw, uh) = (write_chroma_w.min(32), write_chroma_h.min(32));
783 // lane-av1-422m, CORRECTED lane-av1-422n: an 8x32 luma block HAS no
784 // 4:2:2 plane residual block -- `av1_ss_size_lookup[BLOCK_8X32][1][0]`
785 // is BLOCK_INVALID (= 255, blockd.h) -- so libaom never codes its chroma
786 // as a (4, 32) unit, and no such coefficient set exists (no TX_4X32
787 // either). The plane is still coded, CHUNKED: `decode_token_recon_block`
788 // (`decodeframe.c:1022`) steps the plane in `get_vartx_max_txsize`
789 // units, where the `BLOCK_INVALID` plane size indexes
790 // `max_txsize_rect_lookup` OUT OF BOUNDS and the byte read there in the
791 // pinned Release oracle build is TX_4X8 -- the committed
792 // "adjacent `vtx_tab[0]` = TX_4X4" reading was wrong (reviewer FAIL on
793 // e24dc84b). `decode_reconstruct_tx`'s
794 // `if (tx_size == plane_tx_size || plane)` never recurses for chroma, so
795 // every unit reads at TX_4X8: FOUR stacked 4x8 units per plane over the
796 // 4x32 chroma plane. The units KEEP a tx type: `av1_get_tx_type`
797 // (blockd.h) has no TX_4X4 early-out -- it derives from the block's
798 // inherited luma type reduced into the TX_4X8 ext-tx set
799 // (`reduce_inherited_chroma_tx_type`), exactly like every other rect
800 // unit here, so the 4:2:2 drop-the-type special case is gone.
801 let invalid_ss_plane =
802 ss_x(fctx) == 1 && ss_y(fctx) == 0 && (write_chroma_w, write_chroma_h) == (4, 32);
803 let (uw, uh) = if invalid_ss_plane { (4, 8) } else { (uw, uh) };
804 // lane-av1chrtx: `inherit_tx_type` is resolved PER UNIT below, not once
805 // for the block -- `av1_get_tx_type` (blockd.h:1287-1297) reads
806 // `xd->tx_type_map` at the chroma unit's own position scaled back to
807 // luma, so a unit sitting over a luma leaf that coded NOTHING takes that
808 // leaf's `DCT_DCT` stamp (`decodetxb.c:199-203`), not the block-level
809 // (top-left leaf) type.
810 let (nx, ny) = (write_chroma_w / uw, write_chroma_h / uh);
811 let multi = nx * ny > 1;
812 let set = rect_inter_chroma_set(uw, uh)?;
813 // lane-av1-422blockhalf: the assembled block grid is the PRED stride x
814 // the plane's true height -- at 4:2:2 a square block's plane is
815 // (side/2, side), so the old `chroma_side`-square sizing under-allocated
816 // every row past `chroma_stride` once the caller began passing the
817 // per-axis stride.
818 let assembled_h = write_chroma_h.max(chroma_side);
819 let mut assembled: [Vec<i32>; 2] = [Vec::new(), Vec::new()];
820 // The multi-unit stamps below are rewritten by the caller's whole-block
821 // record (`record_rect_mi`/`record_split_luma_rect_mi` write ONE
822 // whole-block chroma state, class `override-slot-on-one-arm`). The
823 // block tail's square-mu derivation cannot express a non-square strip's
824 // units, so the TRUE units travel back for the tail's `mu_chroma_units`
825 // replay (the c8 re-stamp, at the strip's own tiling).
826 let mut units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
827 if multi {
828 hit!(CHROMA_SPLIT_TX_HITS);
829 assembled = [
830 vec![0i32; chroma_side * assembled_h],
831 vec![0i32; chroma_side * assembled_h],
832 ];
833 }
834 for plane_idx in 1..=2 {
835 let src = if plane_idx == 1 { su } else { sv };
836 for cu_row in 0..ny {
837 for cu_col in 0..nx {
838 let (span_x, span_y) = (uw << ss_x(fctx), uh << ss_y(fctx));
839 let cu_mi = (
840 at_mi.0 + cu_row * (span_y / MI),
841 at_mi.1 + cu_col * (span_x / MI),
842 );
843 let unit_rel_mi = (cu_mi.0 - at_mi.0, cu_mi.1 - at_mi.1);
844 let cu_around = if multi {
845 // lane-av1422ctxgather: at ss (1,0) the unit's above
846 // span covers `uw` chroma px = `2*uw` luma mi columns,
847 // so the plain per-mi gather counts every chroma
848 // column's whole-unit dc sign twice
849 // ([`Neighbours::around_mi_422_chroma`]; the left
850 // extent is 1:1 at ss_y 0). 4:2:0 keeps the per-mi
851 // gather (both extents duplicated there, measured
852 // elsewhere).
853 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
854 neighbours.around_mi_422_chroma(cu_mi, span_x, span_y)
855 } else {
856 neighbours.around_mi_rect(cu_mi, span_x, span_y)
857 }
858 } else {
859 around
860 };
861 let (cu_x, cu_y) = (cpx + cu_col * uw, cpy + cu_row * uh);
862 let cu_pred = src.offset(cu_row * uh * chroma_side + cu_col * uw);
863 let inherit_tx_type =
864 if let Some(t) = covering_leaf_tx_type(leaf_tx_types, unit_rel_mi) {
865 hit!(CHROMA_RECT_LEAF_TX_HITS);
866 if Some(t) != Some(luma_tx_type) {
867 hit!(CHROMA_RECT_LEAF_TX_DIFF_HITS);
868 }
869 Some(t)
870 } else {
871 // lane-av1ichromatx: the ONE remaining site in
872 // `decode_inter_block` that can hand a chroma unit a
873 // BLOCK-level type on a split plane. `covering_leaf_tx_
874 // type` found nothing, i.e. no luma leaf covers this
875 // unit's own MI cell -- which is exactly the shape a
876 // block that coded a SINGLE luma transform has (its
877 // leaf list is empty, so every lookup misses). For
878 // that block `luma_tx_type` IS the type of the one
879 // luma unit whose stamp covers the whole plane, so the
880 // fallback is correct there.
881 //
882 // What is NOT correct is a fallback on a plane with
883 // `leaves` NON-empty: then some luma leaf does exist,
884 // it simply does not cover this unit's cell, and the
885 // block-level value is a DIFFERENT leaf's type. The
886 // assertion below is what closes that shape, so the
887 // fallback can never again be a silent mistype: the
888 // class is "block-level where the unit's own cell
889 // says otherwise", and this is its last site.
890 hit!(CHROMA_RECT_BLOCK_TX_FALLBACK);
891 if multi {
892 hit!(CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI);
893 }
894 debug_assert!(
895 leaf_tx_types.is_empty(),
896 "lane-av1ichromatx: a multi-unit rect chroma plane fell back to the \
897 block-level tx_type while {} luma leaves were coded -- the unit's own \
898 av1_get_tx_type cell is then some other leaf's stamp, not \
899 luma_tx_type",
900 leaf_tx_types.len()
901 );
902 Some(luma_tx_type)
903 };
904 let cu_grid = read_inter_plane_rect(
905 dec,
906 cdfs,
907 set,
908 (uw, uh),
909 chroma_side,
910 plane_idx,
911 cu_around[plane_idx],
912 mode_for_tx,
913 y,
914 u,
915 v,
916 cu_x,
917 cu_y,
918 cu_pred,
919 inherit_tx_type,
920 multi.then_some(3),
921 fctx,
922 )?
923 .0;
924 if invalid_ss_plane {
925 hit!(CHROMA422_CHUNK_HITS);
926 }
927 if multi {
928 // Immediately, so the next unit of this block reads this
929 // one's coefficient context (libaom updates the chroma
930 // above/left contexts per unit).
931 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &cu_grid);
932 let dst = &mut assembled[plane_idx - 1];
933 for rr in 0..uh {
934 let start = (cu_row * uh + rr) * chroma_side + cu_col * uw;
935 dst[start..start + uw].copy_from_slice(&cu_grid[rr * uw..][..uw]);
936 }
937 units.push((cu_mi, plane_idx, cu_grid, span_x, span_y));
938 } else {
939 let mut full = vec![0i32; chroma_side * assembled_h];
940 for rr in 0..uh {
941 full[rr * chroma_side..][..uw].copy_from_slice(&cu_grid[rr * uw..][..uw]);
942 }
943 assembled[plane_idx - 1] = full;
944 }
945 }
946 }
947 }
948 let [ug, vg] = assembled;
949 Ok((Grid::Own(ug), Grid::Own(vg), units))
950}
951
952/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
953/// the coefficients are read with the rect coefficient machinery
954/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
955/// types), inverted with the rect inverse transform
956/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
957/// and added onto the top-left `w x h` of the block's own square-strided
958/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
959/// and the coded `tx_type`.
960///
961/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
962/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
963#[allow(clippy::too_many_arguments)]
964pub(super) fn read_inter_plane_rect(
965 dec: &mut SymbolDecoder,
966 cdfs: &mut Cdfs,
967 set: TxbSet,
968 (w, h): (usize, usize),
969 stride: usize,
970 plane_idx: usize,
971 around: (bool, bool, i32),
972 tx_mode: usize,
973 y: &mut PlaneBuf<'static>,
974 u: &mut PlaneBuf<'static>,
975 v: &mut PlaneBuf<'static>,
976 x: usize,
977 cy: usize,
978 prediction: Pred<'_>,
979 inherited_luma_tx_type: Option<TxType>,
980 luma_skip_ctx: Option<usize>,
981 fctx: &crate::decode::FrameCtx,
982) -> Result<(Grid, TxType)> {
983 // lane-av1mono: as [`read_plane`] -- a monochrome frame codes no chroma
984 // coefficients (`plane < av1_num_planes == 1`).
985 if plane_idx > 0 && mono(fctx) {
986 return Ok((Grid::Zero(w * h), TxType::DctDct));
987 }
988 // lane-av1readcensus: the units read from here on are this plane's.
989 set_census_plane(plane_idx);
990 let skip_ctx = if plane_idx == 0 {
991 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
992 // block; a var-tx leaf passes its own neighbour-table context.
993 luma_skip_ctx.unwrap_or(0)
994 } else {
995 // libaom `get_txb_ctx`: a chroma unit's context is
996 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
997 // plane block is bigger than the transform. Our chroma tables hold the
998 // offset-7 rows first, so a multi-unit caller adds 3 through
999 // `luma_skip_ctx` (same convention as [`read_plane`]).
1000 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
1001 };
1002 let mut coding = cdfs.txb(set, tx_mode);
1003 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
1004 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
1005 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
1006 // plane of a lossless block (the residual then goes through the WHT, so
1007 // the type only picks the scan, which is the default one).
1008 if lossless(fctx) {
1009 coding.tx_type = None;
1010 }
1011 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
1012 // the *longer* side of this rect transform.
1013 let default_tx_type = match inherited_luma_tx_type {
1014 Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx),
1015 None => TxType::DctDct,
1016 };
1017 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
1018 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
1019 let default_tx_type = if lossless(fctx) {
1020 TxType::DctDct
1021 } else {
1022 default_tx_type
1023 };
1024 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
1025 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
1026 // corner, zero-extended into the true `w x h` grid before the inverse
1027 // transform -- exactly what the intra superblock-strip path does. A
1028 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
1029 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
1030 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
1031 // rectangular shape (lane-sbpart r8).
1032 let (cw, ch) = (w.min(32), h.min(32));
1033 if plane_idx == 0 && w.max(h) == 64 {
1034 hit!(RECT64_INTER_TU_HITS);
1035 }
1036 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
1037 hit_do! {
1038 RECT32X8_INTER_TU_HITS.with(|c| {
1039 let mut v = c.get();
1040 v[usize::from(w == 8)] += 1;
1041 c.set(v);
1042 });
1043 }
1044 }
1045 let (corner, tx_type) = if (cw, ch) == (32, 32) {
1046 let scan32 = default_scan(TX32);
1047 read_coeffs(
1048 dec,
1049 &mut coding,
1050 scan32,
1051 skip_ctx,
1052 dc_sign_ctx(around.2),
1053 default_tx_type,
1054 Some((w, h)),
1055 )?
1056 } else {
1057 read_coeffs_rect(
1058 dec,
1059 &mut coding,
1060 rect_scan(cw, ch)?,
1061 cw,
1062 ch,
1063 skip_ctx,
1064 dc_sign_ctx(around.2),
1065 default_tx_type,
1066 plane_idx,
1067 )?
1068 };
1069 let grid = extend_corner(corner, cw, ch, w, h);
1070 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
1071 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
1072 eprintln!(
1073 "OUR_TXTYPE plane={plane_idx} x={x} y={cy} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}"
1074 );
1075 }
1076 // `reconstruct_mc_rect` reads both buffers at the square prediction
1077 // stride, so the dense `w x h` residual is re-laid at that stride
1078 // (`TxParams::stride`) after the inverse transform.
1079 let tx = TxParams {
1080 plane: plane_idx,
1081 w,
1082 h,
1083 bit_depth: bit_depth(fctx),
1084 q_idx: block_q_idx(fctx),
1085 dc_delta,
1086 ac_delta,
1087 tx_type,
1088 qm: block_iqmatrix(fctx, plane_idx, w, h, tx_type),
1089 stride,
1090 lossless: lossless(fctx),
1091 };
1092 push_mc_rect_tx(
1093 y, u, v, plane_idx, x, cy, stride, w, h, prediction, tx, &grid, fctx,
1094 );
1095 Ok((grid, tx_type))
1096}
1097
1098/// The coded `cw x ch` corner of a transform zero-extended into its true
1099/// `w x h` grid (a 64-length axis codes only its low 32 coefficients). A
1100/// corner that coded nothing stays the shared zero grid -- no allocation
1101/// (lane-coefgrid).
1102pub(super) fn extend_corner(corner: Grid, cw: usize, ch: usize, w: usize, h: usize) -> Grid {
1103 if (cw, ch) == (w, h) {
1104 return corner;
1105 }
1106 if let Grid::Zero(_) = corner {
1107 return Grid::Zero(w * h);
1108 }
1109 let mut full = vec![0i32; w * h];
1110 for row in 0..ch {
1111 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
1112 }
1113 Grid::Own(full)
1114}
1115
1116/// [`embed_rect_grid`] that keeps the shared zero marker zero: an all-zero
1117/// transform unit's grid IS `Grid::Zero` (whose deref is the shared
1118/// `ZERO_RESIDUAL`), so re-laying it would read a zero-length slice.
1119pub(super) fn embed_grid_stride(grid: &Grid, w: usize, h: usize, stride: usize) -> Grid {
1120 if is_zero_grid(grid) {
1121 return Grid::Zero(stride * stride);
1122 }
1123 Grid::Own(embed_rect_grid(grid, w, h, stride))
1124}
1125
1126/// A rect coefficient grid re-laid into the square `stride x stride` grid the
1127/// neighbour/deblock stamps downstream of the residual expect.
1128pub(super) fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
1129 let mut full = vec![0i32; stride * stride];
1130 for row in 0..h {
1131 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
1132 }
1133 full
1134}
1135
1136/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
1137/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
1138/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
1139/// raster order, each reading its own coefficient context off the units
1140/// already decoded before it. Returns the block's luma grid (all-zero in the
1141/// split case, whose reconstruction has already happened unit by unit) and
1142/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
1143/// which for a split block lands on the top-left unit.
1144#[allow(clippy::too_many_arguments)]
1145pub(super) fn read_inter_luma8(
1146 y: &mut PlaneBuf<'static>,
1147 u: &mut PlaneBuf<'static>,
1148 v: &mut PlaneBuf<'static>,
1149 dec: &mut SymbolDecoder,
1150 cdfs: &mut Cdfs,
1151 neighbours: &mut Neighbours,
1152 leaf_mi: (usize, usize),
1153 px: usize,
1154 py: usize,
1155 pred_y: Pred<'_>,
1156 mode_for_tx: usize,
1157 base_q_idx: u8,
1158 scan8: &[u16],
1159 scan4: &[u16],
1160 reduced_tx_set: bool,
1161 split: bool,
1162 fctx: &crate::decode::FrameCtx,
1163) -> Result<(Grid, TxType)> {
1164 // lane-lossless: an 8x8 inter block is FOUR 4x4 units (libaom
1165 // `read_block_tx_size`'s lossless TX_4X4), tree or no tree.
1166 let split = split || lossless(fctx);
1167 if !split {
1168 return read_inter_plane(
1169 dec,
1170 cdfs,
1171 if reduced_tx_set {
1172 TxbSet::Luma8Inter
1173 } else {
1174 TxbSet::Luma8InterSet1
1175 },
1176 scan8,
1177 0,
1178 neighbours.around_mi(leaf_mi, 8)[0],
1179 mode_for_tx,
1180 y,
1181 u,
1182 v,
1183 px,
1184 py,
1185 8,
1186 base_q_idx,
1187 pred_y,
1188 None,
1189 None,
1190 fctx,
1191 );
1192 }
1193 let mut first = TxType::DctDct;
1194 for tu_row in 0..2 {
1195 for tu_col in 0..2 {
1196 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
1197 let tu_pred = pred_y.view(8).offset(tu_row * 4 * 8 + tu_col * 4);
1198 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
1199 let (tu_grid, tu_tx_type) = read_inter_plane(
1200 dec,
1201 cdfs,
1202 if reduced_tx_set {
1203 TxbSet::Luma4Inter
1204 } else {
1205 TxbSet::Luma4InterSet1
1206 },
1207 scan4,
1208 0,
1209 neighbours.around_mi(tu_mi, 4)[0],
1210 mode_for_tx,
1211 y,
1212 u,
1213 v,
1214 px + tu_col * 4,
1215 py + tu_row * 4,
1216 4,
1217 base_q_idx,
1218 tu_pred,
1219 None,
1220 Some(tu_skip_ctx),
1221 fctx,
1222 )?;
1223 if tu_row == 0 && tu_col == 0 {
1224 first = tu_tx_type;
1225 }
1226 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
1227 }
1228 }
1229 Ok((Grid::Zero(64), first))
1230}
1231
1232/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
1233/// coefficient tables from -- the inter counterpart of [`txbset_for`].
1234/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
1235/// an inter block's chroma transform inherits the *colocated luma* unit's
1236/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
1237/// of the extended set the CHROMA transform size selects
1238/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
1239/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
1240/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
1241/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
1242/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
1243/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
1244/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
1245/// sync and only corrupted the inverse transform (one 64x64 superblock of
1246/// high-frequency chroma noise, luma bit-exact).
1247pub(crate) fn reduce_inherited_chroma_tx_type(
1248 t: TxType,
1249 w: usize,
1250 h: usize,
1251 fctx: &crate::decode::FrameCtx,
1252) -> TxType {
1253 reduce_inherited_chroma_tx_type_flagged(
1254 t,
1255 w,
1256 h,
1257 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
1258 )
1259}
1260
1261/// [`reduce_inherited_chroma_tx_type`] against an explicit `reduced_tx_set`
1262/// bit (lane-intertx): the WRITER calls this with the frame's own header bit
1263/// ([`crate::cdf_state::Cdfs::reduced_tx_set`]) to derive the type an inter
1264/// block's chroma transform is coded with, the same derivation its reader
1265/// makes -- it has no `FrameCtx` in reach and must not silently read one
1266/// whose value can lag the frame being written (class `stale-context-bit`).
1267pub(crate) fn reduce_inherited_chroma_tx_type_flagged(
1268 t: TxType,
1269 w: usize,
1270 h: usize,
1271 reduced: bool,
1272) -> TxType {
1273 use TxType::*;
1274 let sqr_up = w.max(h);
1275 let sqr = w.min(h);
1276 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
1277 let allowed: &[TxType] = if sqr_up > 32 {
1278 // EXT_TX_SET_DCTONLY
1279 &[DctDct]
1280 } else if sqr_up == 32 || reduced {
1281 // EXT_TX_SET_DCT_IDTX
1282 &[DctDct, Idtx]
1283 } else if sqr == 16 {
1284 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
1285 // the four 1D ADST/FLIPADST types.
1286 &[
1287 DctDct,
1288 AdstDct,
1289 DctAdst,
1290 AdstAdst,
1291 FlipAdstDct,
1292 DctFlipAdst,
1293 FlipAdstFlipAdst,
1294 AdstFlipAdst,
1295 FlipAdstAdst,
1296 Idtx,
1297 VDct,
1298 HDct,
1299 ]
1300 } else {
1301 // EXT_TX_SET_ALL16
1302 return t;
1303 };
1304 if allowed.contains(&t) { t } else { DctDct }
1305}
1306
1307/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
1308/// from for a block libaom's `is_inter_block` calls inter -- which an intrabc
1309/// block is (`blockd.h:373`), so its `tx_type` comes off the inter `ext_tx`
1310/// sets, never the mode-indexed intra ones ([`txbset_for`]).
1311///
1312/// 64 is only ever the 64x64-block, depth-0, corner-scanned case
1313/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
1314/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
1315/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
1316/// regardless of the flag (`av1_get_ext_tx_set_type`'s
1317/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
1318/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
1319/// second table ([`TxbSet::Luma8Inter`]/[`TxbSet::Luma4Inter`]).
1320///
1321/// lane-av1txr: the intrabc leaf sites used to call a near-duplicate
1322/// `txbset_for_inter` whose `4` fell through to `Luma64` -- 32x32-class tables
1323/// (a 1024-entry grid) handed to a 4x4 dequant, which panicked at
1324/// `transform.rs`'s `inverse_transform_2d_typed_wh` the first time an intrabc
1325/// 4x4 TU coded a non-zero coefficient (`allintra0`/cpu-used=0). The
1326/// duplicate is gone; every inter-table site goes through this one mapping.
1327pub(super) fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
1328 match tx_px {
1329 // lane-sb128c r1: a 128x128 inter block's own luma unit
1330 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
1331 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
1332 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
1333 // coincide -- exactly the set the whole-64x64 inter block already uses.
1334 64 => TxbSet::Luma64,
1335 32 => TxbSet::Luma32Inter,
1336 16 if reduced_tx_set => TxbSet::Luma16Inter,
1337 16 => TxbSet::Luma16InterSet1,
1338 8 if reduced_tx_set => TxbSet::Luma8Inter,
1339 8 => TxbSet::Luma8InterSet1,
1340 4 if reduced_tx_set => TxbSet::Luma4Inter,
1341 4 => TxbSet::Luma4InterSet1,
1342 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
1343 }
1344}
1345
1346/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
1347/// the only four sizes a `TxMode::Select` block's coded coefficient grid
1348/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
1349pub(super) fn scan_for<'a>(
1350 tx_px: usize,
1351 scan32: &'a [u16],
1352 scan16: &'a [u16],
1353 scan8: &'a [u16],
1354 scan4: &'a [u16],
1355) -> &'a [u16] {
1356 match tx_px {
1357 32 => scan32,
1358 16 => scan16,
1359 8 => scan8,
1360 4 => scan4,
1361 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
1362 }
1363}
1364
1365pub(super) fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
1366 match tx_px {
1367 64 => TxbSet::Luma64,
1368 32 => TxbSet::Luma32,
1369 16 => TxbSet::Luma16,
1370 8 if reduced_tx_set => TxbSet::Luma8,
1371 8 => TxbSet::Luma8Set1,
1372 4 if reduced_tx_set => TxbSet::Luma4,
1373 4 => TxbSet::Luma4Set1,
1374 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
1375 }
1376}
1377
1378/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
1379/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
1380fn unit_log2(px: u32) -> i32 {
1381 if px == 0 {
1382 0
1383 } else {
1384 px.trailing_zeros() as i32 - 2
1385 }
1386}
1387
1388/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
1389/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
1390/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
1391/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
1392/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
1393/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
1394/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
1395/// block anywhere aborted the whole stream's decode before comparison).
1396pub(super) fn lf_level(
1397 lf: &LoopFilterParams,
1398 plane_idx: usize,
1399 dir: usize,
1400 ref_frame: i8,
1401 delta_lf: i32,
1402 segment_id: u8,
1403 fctx: &crate::decode::FrameCtx,
1404) -> i32 {
1405 let base = i32::from(if plane_idx == 0 {
1406 lf.level[dir]
1407 } else if plane_idx == 1 {
1408 lf.level[2]
1409 } else {
1410 lf.level[3]
1411 });
1412 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
1413 // ref/mode delta scaling below, and regardless of `delta_enabled`
1414 // (that flag only gates `ref_deltas`/`mode_deltas`).
1415 let base = (base + delta_lf).clamp(0, 63);
1416 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
1417 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
1418 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
1419 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
1420 // for chroma.
1421 let feature = if plane_idx == 0 {
1422 SEG_LVL_ALT_LF_Y_V + dir
1423 } else {
1424 plane_idx + 2
1425 };
1426 // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely
1427 // when the frame codes no segmentation (`seg_lf_active`), which is what
1428 // spares the deblock loop two thread-local reads per 4x4 edge.
1429 let base = match seg_feature(usize::from(segment_id), feature, fctx) {
1430 Some(data) => (base + data).clamp(0, 63),
1431 None => base,
1432 };
1433 if !lf.delta_enabled {
1434 return base;
1435 }
1436 let scale = 1i32 << (base >> 5);
1437 let is_inter = ref_frame != 0;
1438 let is_globalmv = ref_frame < 0;
1439 let ref_idx = ref_frame.unsigned_abs() as usize;
1440 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
1441 if is_inter {
1442 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
1443 }
1444 lvl.clamp(0, 63)
1445}
1446
1447thread_local! {
1448 /// [`EdgeCtx`]'s level LUT, memoised per thread. The table
1449 /// is a pure function of the frame's [`LoopFilterParams`], the plane, the
1450 /// pass and segment 0's own `SEG_LVL_ALT_LF_*` datum (the only thing
1451 /// [`lf_level`] reads out of the `FrameCtx` at `segment_id = 0`), so one
1452 /// build per plane and pass serves the whole frame.
1453 static LVL_CACHE: std::cell::RefCell<
1454 Vec<((usize, usize, LoopFilterParams, Option<i32>), [[u8; 15]; 64])>,
1455 > = const { std::cell::RefCell::new(Vec::new()) };
1456}
1457
1458/// `lf_level` over the whole `(base level, ref frame)` domain -- see
1459/// [`LVL_CACHE`]. `lf_level`'s own first step is
1460/// `(base0 + delta_lf).clamp(0, 63)`, so passing `b - base0` pins its base at
1461/// `b` and the rest of the function is a pure function of `(b, ref_frame)`.
1462fn lvl_table(
1463 lf: &LoopFilterParams,
1464 plane_idx: usize,
1465 dir: usize,
1466 base0: i32,
1467 fctx: &crate::decode::FrameCtx,
1468) -> [[u8; 15]; 64] {
1469 let feature = if plane_idx == 0 {
1470 SEG_LVL_ALT_LF_Y_V + dir
1471 } else {
1472 plane_idx + 2
1473 };
1474 let key = (plane_idx, dir, *lf, seg_feature(0, feature, fctx));
1475 if let Some(t) = LVL_CACHE.with(|c| c.borrow().iter().find(|(k, _)| *k == key).map(|(_, t)| *t))
1476 {
1477 return t;
1478 }
1479 let mut lvl = [[0u8; 15]; 64];
1480 for (b, row) in lvl.iter_mut().enumerate() {
1481 for (r, cell) in row.iter_mut().enumerate() {
1482 *cell = lf_level(
1483 lf,
1484 plane_idx,
1485 dir,
1486 (r as i32 - 7) as i8,
1487 b as i32 - base0,
1488 0,
1489 fctx,
1490 ) as u8;
1491 }
1492 }
1493 LVL_CACHE.with(|c| {
1494 let mut c = c.borrow_mut();
1495 if c.len() >= 8 {
1496 c.remove(0);
1497 }
1498 c.push((key, lvl));
1499 });
1500 lvl
1501}
1502
1503/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
1504/// no-segmentation, no-delta-LF path and to this decoder's own invariant
1505/// that a coded block's transform is always its own full size -- so a TU
1506/// edge is always also a PU edge, and the "both sides skipped, not a PU
1507/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
1508/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
1509/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
1510/// One plane pass's worth of [`edge_params`] constants (lane-deblock2): the
1511/// seven values that used to be re-passed per 4-pixel edge group -- half of
1512/// them on the stack, into an `inline(never)` body -- plus libaom's
1513/// `lfi->lfthr` idea in level form: `av1_loop_filter_frame_init` builds the
1514/// filter level for every `(base level, ref frame)` pair once per frame
1515/// instead of running `av1_get_filter_level`'s delta arithmetic per edge.
1516pub(super) struct EdgeCtx<'a> {
1517 pub(super) lf: &'a LoopFilterParams,
1518 pub(super) n: &'a Neighbours,
1519 pub(super) fctx: &'a crate::decode::FrameCtx,
1520 pub(super) plane_idx: usize,
1521 pub(super) dir: usize,
1522 pub(super) chroma: bool,
1523 pub(super) seg_lf_active: bool,
1524 /// `delta_lf_grid`'s column for this plane and direction.
1525 pub(super) delta_idx: usize,
1526 /// `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for
1527 /// chroma.
1528 pub(super) step: usize,
1529 /// This pass's own `lf.level[..]`, the LUT's base.
1530 pub(super) base0: i32,
1531 /// `lf_level` at `[base level][ref frame + 7]`, with no segment
1532 /// override -- the whole domain, since a level is `0..=63` and a ref
1533 /// frame `-7..=7` (`ref_deltas` holds `TOTAL_REFS_PER_FRAME` = 8
1534 /// entries and is indexed by the ref frame's magnitude).
1535 pub(super) lvl: [[u8; 15]; 64],
1536}
1537
1538impl<'a> EdgeCtx<'a> {
1539 pub(super) fn new(
1540 lf: &'a LoopFilterParams,
1541 n: &'a Neighbours,
1542 plane_idx: usize,
1543 dir: usize,
1544 chroma: bool,
1545 seg_lf_active: bool,
1546 fctx: &'a crate::decode::FrameCtx,
1547 ) -> Self {
1548 let base0 = i32::from(if plane_idx == 0 {
1549 lf.level[dir]
1550 } else if plane_idx == 1 {
1551 lf.level[2]
1552 } else {
1553 lf.level[3]
1554 });
1555 let lvl = lvl_table(lf, plane_idx, dir, base0, fctx);
1556 Self {
1557 lf,
1558 n,
1559 fctx,
1560 plane_idx,
1561 dir,
1562 chroma,
1563 seg_lf_active,
1564 delta_idx: if plane_idx == 0 { dir } else { plane_idx + 1 },
1565 step: if chroma {
1566 1 << (if dir == 0 { ss_x(fctx) } else { ss_y(fctx) })
1567 } else {
1568 1
1569 },
1570 base0,
1571 lvl,
1572 }
1573 }
1574
1575 /// Spec 7.14.4's `get_filter_level`, off the table when no segment can
1576 /// override it (which is every frame that codes no segmentation).
1577 #[inline(always)]
1578 pub(super) fn level(&self, ref_frame: i8, delta_lf: i32, seg: u8) -> i32 {
1579 if self.seg_lf_active {
1580 return lf_level(
1581 self.lf,
1582 self.plane_idx,
1583 self.dir,
1584 ref_frame,
1585 delta_lf,
1586 seg,
1587 self.fctx,
1588 );
1589 }
1590 let b = (self.base0 + delta_lf).clamp(0, 63) as usize;
1591 debug_assert!((-7..=7).contains(&ref_frame));
1592 let r = (i32::from(ref_frame) + 7).clamp(0, 14) as usize;
1593 i32::from(self.lvl[b][r])
1594 }
1595}
1596
1597/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
1598/// no-segmentation, no-delta-LF path and to this decoder's own invariant
1599/// that a coded block's transform is always its own full size -- so a TU
1600/// edge is always also a PU edge, and the "both sides skipped, not a PU
1601/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
1602/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
1603/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
1604#[inline(always)]
1605pub(super) fn edge_params(c: &EdgeCtx, x0: usize, y0: usize) -> Option<(u8, i32)> {
1606 let (mi_r, mi_c) = (
1607 plane_to_mi(c.chroma, y0, if c.chroma { ss_y(c.fctx) } else { 0 }),
1608 plane_to_mi(c.chroma, x0, if c.chroma { ss_x(c.fctx) } else { 0 }),
1609 );
1610 let cur_tx = if c.dir == 0 {
1611 tx_px_at(c.n, c.chroma, mi_r, mi_c)
1612 } else {
1613 tx_h_px_at(c.n, c.chroma, mi_r, mi_c)
1614 };
1615 // lane-deblock: `cur_tx` is a power-of-two pixel size, so the alignment
1616 // test is a mask, not the hardware `divl` this used to emit (10.7% of
1617 // `edge_params`' own samples sat on that divide's result test).
1618 //
1619 // Most 4-pixel edge groups die right here (a 4-aligned coordinate that
1620 // the covering transform does not start at), so this head is inlined
1621 // into the deblock loops and only survivors pay the call and the
1622 // register-spilling prologue of the body below.
1623 if cur_tx == 0 || (if c.dir == 0 { x0 } else { y0 }) & (cur_tx as usize - 1) != 0 {
1624 return None;
1625 }
1626 edge_params_body(c, x0, y0, mi_r, mi_c, cur_tx)
1627}
1628
1629/// [`edge_params`] past its transform-alignment gate.
1630#[inline(never)]
1631pub(super) fn edge_params_body(
1632 c: &EdgeCtx,
1633 x0: usize,
1634 y0: usize,
1635 mi_r: usize,
1636 mi_c: usize,
1637 cur_tx: u32,
1638) -> Option<(u8, i32)> {
1639 let n = c.n;
1640 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
1641 // The previous cell must keep the odd parity `plane_to_mi` just
1642 // established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma group,
1643 // not the other half of this one.
1644 let (pv_mi_r, pv_mi_c) = if c.dir == 0 {
1645 (mi_r, mi_c - c.step)
1646 } else {
1647 (mi_r - c.step, mi_c)
1648 };
1649 let pv_tx = if c.dir == 0 {
1650 tx_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
1651 } else {
1652 tx_h_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
1653 };
1654 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
1655 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][c.delta_idx]);
1656 let pv_delta_lf =
1657 i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][c.delta_idx]);
1658
1659 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
1660 // SKIPPED INTER blocks is filtered only when it is also a prediction
1661 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
1662 // omission of this term (on the stale invariant "a coded block's transform
1663 // is always its own full size", which var-tx broke) had us filtering an
1664 // interior 8-px lattice the reference never touches: on the pinned 192x68
1665 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
1666 // libaom prices `pu_edge` in the PLANE's own pixels against the plane's
1667 // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] -
1668 // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma
1669 // edge of a sub-8x8 group is a prediction edge, even though the group's
1670 // bottom/right mi does not start there. Comparing mi origins instead is
1671 // the same test only while the block's own origin is aligned to its
1672 // size, which a 4x4 luma block read at the `| 1` mi is not.
1673 let cur_cell = n.blk_grid[mi_r * n.skip_grid_cols_mi + mi_c];
1674 let (cur_org, cur_dim) = (cur_cell.org, cur_cell.dim);
1675 let (org_px, dim_mi) = if c.dir == 0 {
1676 (usize::from(cur_org[1]), usize::from(cur_dim[0]))
1677 } else {
1678 (usize::from(cur_org[0]), usize::from(cur_dim[1]))
1679 };
1680 let pu_edge = if c.chroma {
1681 let ss = if c.dir == 0 {
1682 ss_x(c.fctx)
1683 } else {
1684 ss_y(c.fctx)
1685 };
1686 let plane_dim = ((dim_mi * MI) >> ss).max(4);
1687 (if c.dir == 0 { x0 } else { y0 }) % plane_dim == 0
1688 } else {
1689 plane_to_mi(false, if c.dir == 0 { x0 } else { y0 }, 0) == org_px
1690 };
1691 if !pu_edge
1692 && cur_ref != 0
1693 && pv_ref != 0
1694 && n.skip_at(mi_r, mi_c)
1695 && n.skip_at(pv_mi_r, pv_mi_c)
1696 {
1697 return None;
1698 }
1699 let (cur_seg, pv_seg) = if c.seg_lf_active {
1700 (
1701 segment_id_at(mi_r, mi_c, c.fctx),
1702 segment_id_at(pv_mi_r, pv_mi_c, c.fctx),
1703 )
1704 } else {
1705 (0, 0)
1706 };
1707 let cur_level = c.level(cur_ref, cur_delta_lf, cur_seg);
1708 let pv_level = c.level(pv_ref, pv_delta_lf, pv_seg);
1709 if cur_level == 0 && pv_level == 0 {
1710 return None;
1711 }
1712 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
1713 let len: u8 = if c.chroma {
1714 if dim == 0 { 4 } else { 6 }
1715 } else {
1716 [4, 8, 14, 14, 14][dim]
1717 };
1718 let level = if cur_level != 0 { cur_level } else { pv_level };
1719 hit!(DEBLOCK_HITS);
1720 Some((len, level))
1721}