forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBcdccbc2Tahinli10 hours ago4263 commits

rect.rs4946 lines, 212.1 KiBHistoryRawDownload
1//! Rect block decoders: intra mode for rects, rect split, the intrabc rects and decode_leaf_rect. //! av1split: moved out of `decode/mod.rs`; the items are unchanged apart from visibility. (D19)
2
3use super::*;
4
5/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
6/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
7/// size class comes from [`filter_intra_size_class_rect`] instead of the
8/// square-only [`filter_intra_size_class`], and the palette read (when
9/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
10/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
11/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
12/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
13#[allow(clippy::too_many_arguments)]
14pub(super) fn read_intra_mode_rect(
15 dec: &mut SymbolDecoder,
16 cdfs: &mut Cdfs,
17 above_mode: usize,
18 left_mode: usize,
19 cfl: bool,
20 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
21 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
22 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
23 // chroma is coded once, on the closing strip). Every other caller is a
24 // block big enough to own its chroma and passes `true`.
25 has_chroma: bool,
26 bw: usize,
27 bh: usize,
28 enable_filter_intra: bool,
29 skip_ctx: usize,
30 allow_screen_content_tools: bool,
31 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
32 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
33 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
34 palette: Option<(usize, &[u16])>,
35 palette_uv_cache: &[u16],
36 mi_r: usize,
37 mi_c: usize,
38 fctx: &crate::decode::FrameCtx,
39) -> Result<(
40 bool,
41 usize,
42 i32,
43 usize,
44 i32,
45 Option<(i32, i32)>,
46 Option<usize>,
47 Option<PaletteY>,
48 Option<PaletteUv>,
49 // lane-av1-intrabc: the block vector, `Some` exactly when this block's
50 // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns
51 // straight out of `read_intra_frame_mode_info` then, so every later field
52 // of the tuple is at its default (mode/uv_mode DC, no angle, no palette,
53 // no filter intra). A caller that can reconstruct intrabc at its shape
54 // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by
55 // name with the same string it always did.
56 Option<(i32, i32)>,
57)> {
58 // lane-av1mono: libaom guards every chroma symbol read with
59 // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
60 // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
61 // `palette_uv` even on a chroma-reference strip. Fold the plane count
62 // into the same `has_chroma` this reader already gates on.
63 let has_chroma = has_chroma && !mono(fctx);
64 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
65 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
66 if ec_istep {
67 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
68 // (decodemv.c:818), printed at the same point: before the first
69 // mode-info symbol of the block, so a cross-decoder range ladder can
70 // be keyed on the BLOCK, not just on the symbol sequence.
71 eprintln!(
72 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}",
73 enable_filter_intra as i32,
74 filter_intra_size_class_rect(bw, bh),
75 dec.debug_state().0
76 );
77 }
78 macro_rules! istep {
79 ($name:literal, $val:expr) => {
80 if ec_istep {
81 let (rng, _) = dec.debug_state();
82 eprintln!(
83 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
84 $name, $val
85 );
86 }
87 };
88 }
89 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
90 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
91 // the one point every rect caller routes through, so no call site can
92 // offer the 14-symbol CFL alphabet on a 64-axis block (class
93 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
94 let cfl = if cfl && bw.max(bh) > 32 {
95 hit!(NOCFL_UV_MODE_HITS);
96 false
97 } else {
98 cfl
99 };
100 // lane-intra14 r1: on the INTER block path everything up to and including
101 // `is_inter` was already read by [`decode_inter_block`], so this reader
102 // starts at the mode syntax with the `skip` that caller read.
103 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
104 let skip = if let Some((_, skip)) = inter {
105 skip
106 } else {
107 // Same `intra_segment_id` placement as the square reader above.
108 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
109 if seg_id_pre_skip(fctx) {
110 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
111 }
112 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
113 istep!("skip", skip as i32);
114 if !seg_id_pre_skip(fctx) {
115 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
116 }
117 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
118 istep!("cdef", 0);
119 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
120 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
121 // `false`.
122 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
123 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
124 istep!("dq", 0);
125 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
126 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
127 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
128 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
129 // rect strips read it exactly like square leaves ([`read_intra_mode`],
130 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
131 // decoder at the FIRST symbol of the first rect block of every
132 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
133 // block at this shape is out of scope, so the flag is consumed and
134 // refused by name when it fires.
135 if allow_intrabc_frame(fctx) {
136 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
137 hit!(RECT_INTRABC_READS);
138 istep!("intrabc", use_intrabc as i32);
139 if use_intrabc {
140 hit!(INTRABC_HITS);
141 // libaom `read_intrabc_info`: the DV read, then an immediate
142 // return out of the mode-info read -- no `y_mode`, no `uv_mode`,
143 // no angle deltas, no palette, no filter intra. The caller owns
144 // the reconstruction at its own shape.
145 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx);
146 return Ok((
147 skip,
148 DC_PRED,
149 0,
150 DC_PRED,
151 0,
152 None,
153 None,
154 None,
155 None,
156 Some(dv),
157 ));
158 }
159 }
160 skip
161 };
162 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
163 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
164 // off `kf_y_mode_cdf[above][left]`).
165 let mode = if let Some((size_group, _)) = inter {
166 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
167 dec.symbol(&mut cdfs.y_mode[size_group])
168 } else {
169 let above_ctx = INTRA_MODE_CTX[above_mode];
170 let left_ctx = INTRA_MODE_CTX[left_mode];
171 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
172 };
173 istep!("mode", mode as i32);
174 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
175 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
176 } else {
177 0
178 };
179 istep!("angle_y", angle_delta_y);
180 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
181 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
182 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
183 // here, from the block's own size, is the single point every caller routes
184 // through -- a caller passing `true` for a >32 strip used to pick the
185 // 14-symbol CFL CDF, same value but a different range (class
186 // wrong-alphabet-same-value).
187 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
188 let uv_mode = if !has_chroma {
189 DC_PRED
190 } else if cfl {
191 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
192 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
193 } else {
194 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
195 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
196 };
197 istep!("uv_mode", uv_mode as i32);
198 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
199 Some(read_cfl_alphas(dec, cdfs))
200 } else {
201 None
202 };
203 if has_chroma && (9..=12).contains(&uv_mode) {
204 hit!(SMOOTH_UV_HITS);
205 }
206 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
207 hit!(DIRECTIONAL_UV_HITS);
208 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
209 } else {
210 0
211 };
212 istep!("angle_uv", angle_delta_uv);
213 if angle_delta_uv != 0 {
214 hit!(UV_ANGLE_DELTA_HITS);
215 }
216 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
217 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
218 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
219 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
220 // colours only here, the colour-index maps deferred past `filter_intra`
221 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
222 // runs from the caller, after the whole mode-info read).
223 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
224 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
225 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
226 // r6: this is the exact site the removed blanket refusal used to
227 // guard -- reached for EVERY rect strip in a screen-content frame,
228 // independent of whether the block ends up using a palette.
229 hit!(RECT_SCREEN_CONTENT_HITS);
230 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
231 let use_palette_y =
232 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
233 if use_palette_y {
234 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
235 let colors = read_palette_colors_y(dec, n, cache, fctx);
236 palette_y_pending = Some((n, colors));
237 }
238 let palette_uv_mode_ctx = usize::from(use_palette_y);
239 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
240 if has_chroma
241 && uv_mode == DC_PRED
242 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
243 {
244 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
245 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
246 palette_uv_pending = Some((n, u_colors, v_colors));
247 }
248 }
249 let mut filter_intra = None;
250 if crate::envflags::env_flag!("EC_AV1_TRACE") {
251 let (rng, _) = dec.debug_state();
252 eprintln!(
253 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
254 class={:?} rng={rng}",
255 enable_filter_intra as i32,
256 filter_intra_size_class_rect(bw, bh)
257 );
258 }
259 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
260 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
261 if mode == DC_PRED
262 && enable_filter_intra
263 && palette_y_pending.is_none()
264 && let Some(class) = filter_intra_size_class_rect(bw, bh)
265 {
266 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
267 if crate::envflags::env_flag!("EC_AV1_TRACE") {
268 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
269 }
270 istep!("use_filter_intra", use_filter_intra as i32);
271 if use_filter_intra {
272 hit!(FILTER_INTRA_HITS);
273 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
274 istep!("filter_intra_mode", fi_mode as i32);
275 filter_intra = Some(fi_mode);
276 }
277 }
278 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
279 // same order as [`read_intra_mode`]'s own square path.
280 let palette_y = palette_y_pending.map(|(n, colors)| {
281 let map = decode_color_index_map_wh(
282 dec,
283 cdfs,
284 n,
285 bw,
286 bh,
287 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
288 false,
289 );
290 hit!(PALETTE_HITS);
291 hit!(PALETTE_RECT_HITS);
292 PaletteY {
293 size: n,
294 colors,
295 map,
296 }
297 });
298 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
299 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
300 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
301 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
302 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
303 // chroma palette and desynced the tile from there.
304 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
305 let on = palette_onscreen_uv(
306 (bw, bh),
307 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
308 (cw, ch),
309 (ss_x(fctx), ss_y(fctx)),
310 );
311 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
312 hit!(PALETTE_UV_HITS);
313 PaletteUv {
314 size: n,
315 u_colors,
316 v_colors,
317 map,
318 }
319 });
320 Ok((
321 skip,
322 mode,
323 angle_delta_y,
324 uv_mode,
325 angle_delta_uv,
326 alpha,
327 filter_intra,
328 palette_y,
329 palette_uv,
330 None,
331 ))
332}
333
334/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
335/// at the strip's REAL mi position. `av1_get_palette_cache` reads
336/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
337/// block, so each strip owns its own rows and columns and no aliasing rule
338/// is needed (lane-kf900 r6).
339#[allow(clippy::too_many_arguments)]
340pub(super) fn record_strip_palette(
341 n: &mut Neighbours,
342 mi: (usize, usize),
343 bw: usize,
344 bh: usize,
345 y_size: usize,
346 y_colors: [u16; 8],
347 uv_size: usize,
348 uv_colors: [u16; 8],
349) {
350 let (r, c) = mi;
351 // lane-t900 r23 rung: every publication of a block's palette state into
352 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
353 // path left a stale `left_palette_size` behind when
354 // `av1_get_palette_mode_ctx` disagrees with libaom's.
355 if crate::envflags::env_flag!("EC_PALPUB") {
356 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
357 }
358 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
359 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
360 // existed because the 16px [`SUB`] cell held one slot for all the strips
361 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
362 // real neighbour leaf 1 reads.
363 {
364 for cell in 0..(bw / MI).max(1) {
365 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
366 *e = y_size as u8;
367 n.above_palette_uv_size[c + cell] = uv_size as u8;
368 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
369 // colours of a size-0 neighbour are never read.
370 if y_size > 0 {
371 n.above_palette_colors[c + cell] = y_colors;
372 }
373 if uv_size > 0 {
374 n.above_palette_uv_colors[c + cell] = uv_colors;
375 }
376 }
377 }
378 }
379 {
380 for cell in 0..(bh / MI).max(1) {
381 if n.left_palette_size.get(r + cell).is_none() {
382 break;
383 }
384 n.left_palette_size[r + cell] = y_size as u8;
385 n.left_palette_uv_size[r + cell] = uv_size as u8;
386 if y_size > 0 {
387 n.left_palette_colors[r + cell] = y_colors;
388 }
389 if uv_size > 0 {
390 n.left_palette_uv_colors[r + cell] = uv_colors;
391 }
392 }
393 }
394}
395
396/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
397pub(super) fn cfl_ac_q3_rect(
398 y: &PlaneBuf<'_>,
399 px: usize,
400 py: usize,
401 bw: usize,
402 bh: usize,
403) -> Vec<i32> {
404 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| {
405 i32::from(y.data[ly * y.width + lx])
406 })
407}
408
409/// Everything a rect strip already read out of the stream before its luma
410/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
411/// (nine values that would otherwise be nine more parameters).
412pub(super) struct RectStripModes {
413 pub(super) skip: bool,
414 pub(super) mode: usize,
415 pub(super) angle_delta_y: i32,
416 pub(super) uv_predict_mode: usize,
417 pub(super) angle_delta_uv: i32,
418 pub(super) alpha: Option<(i32, i32)>,
419 pub(super) filter_intra: Option<usize>,
420 pub(super) smooth_neighbor: bool,
421 pub(super) smooth_neighbor_uv: bool,
422 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
423 /// mapped through the colour table), sliced per transform unit below --
424 /// palette prediction reads no edge pixels, so a unit's slice of the
425 /// whole-block map IS its prediction. Without this a palette strip whose
426 /// transform splits predicted DC and came out flat grey while the entropy
427 /// stream stayed in sync (the coefficients are read either way).
428 pub(super) palette_y: Option<Vec<u16>>,
429 /// As `palette_y`, for the un-split chroma transform (U, V).
430 pub(super) palette_uv: Option<(Vec<u16>, Vec<u16>)>,
431}
432
433/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
434/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
435/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
436/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
437/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
438/// TX_32X16`) and only the second reaches a square -- the reason
439/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
440/// already square) mis-tiled 1:4 strips.
441pub(super) fn depth_to_tx_wh(
442 bw: usize,
443 bh: usize,
444 depth: usize,
445 fctx: &crate::decode::FrameCtx,
446) -> (usize, usize) {
447 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
448 // `read_tx_size`: the lossless early return comes before
449 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
450 if lossless(fctx) {
451 return (4, 4);
452 }
453 let (mut w, mut h) = (bw.min(64), bh.min(64));
454 for _ in 0..depth {
455 match w.cmp(&h) {
456 std::cmp::Ordering::Greater => w /= 2,
457 std::cmp::Ordering::Less => h /= 2,
458 std::cmp::Ordering::Equal => {
459 w /= 2;
460 h /= 2;
461 }
462 }
463 }
464 (w, h)
465}
466
467/// lane-av1-422stripanchor: [`decode_rect_split`]'s 4-wide-strip port of the
468/// split4 floored-pair anchor ([`sub8_leaf_chroma422`]'s rule). A 1-mi-wide
469/// strip (luma `(4, 16)` / `(4, 8)`) has NO chroma plane block of its own at
470/// ss (1, 0) -- `av1_ss_size_lookup[BLOCK_4X16][1][0]` and
471/// `[BLOCK_4X8][1][0]` are both BLOCK_INVALID (`common_data.c`), and a
472/// 2-px-wide area is not a transform shape. The strip pairs with its
473/// even-column sibling (`is_chroma_reference`'s `mi_col & 1` column clause,
474/// the rule [`decode_rect4_16_strip`] implements one partition level up), and
475/// the ODD-column strip codes the PAIR's `(4, bh)` plane anchored at
476/// `av1_setup_dst_planes`' mi-exact floor `(mi_col & !1) * MI >> ss_x`, with
477/// the entropy context on the floored cell. Returns
478/// `(pair block width, pair block height, write anchor x, entropy mi column)`
479/// for that pair, or `None` when the strip keeps its own plane block at its
480/// own origin -- which is every 4:2:0 and 4:4:4 cell (their chroma is never
481/// 2 px wide) and every 4:2:2 strip of 8 px or more.
482fn chroma422_pair_plane(
483 ss_x: bool,
484 ss_y: bool,
485 mi_col: usize,
486 bw: usize,
487 bh: usize,
488) -> Option<(usize, usize, usize, usize)> {
489 if ss_x && !ss_y && (bw >> 1) == 2 {
490 Some((4, bh, ((mi_col & !1) * MI) >> 1, mi_col & !1))
491 } else {
492 None
493 }
494}
495
496/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
497/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
498/// rect path here refused by name until now ("per-unit rect prediction is not
499/// ported").
500///
501/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
502/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
503/// strip the very first step already lands on a SQUARE transform
504/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
505/// every further step halves a square) -- so each unit is square and reads
506/// through the ordinary square [`read_plane`]. What is genuinely rectangular
507/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
508/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
509/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
510/// split by luma's depth.
511///
512/// Each unit predicts off whatever the earlier units of this same block
513/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
514/// inside `av1_foreach_transformed_block`, raster order), which is exactly
515/// what predicting the whole strip in one shot got wrong.
516#[allow(clippy::too_many_arguments)]
517pub(super) fn decode_rect_split(
518 dec: &mut SymbolDecoder,
519 cdfs: &mut Cdfs,
520 neighbours: &mut Neighbours,
521 at_mi: (usize, usize),
522 bw: usize,
523 bh: usize,
524 // The transform unit's own width and height in pixels. Square for every
525 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
526 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
527 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
528 tx_w: usize,
529 tx_h: usize,
530 m: &RectStripModes,
531 y: &mut PlaneBuf<'static>,
532 u: &mut PlaneBuf<'static>,
533 v: &mut PlaneBuf<'static>,
534 base_q_idx: u8,
535 reduced_tx_set: bool,
536 fctx: &crate::decode::FrameCtx,
537) -> Result<()> {
538 let (mi_r, mi_c) = at_mi;
539 let (px, py) = (mi_c * MI, mi_r * MI);
540 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
541 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
542 // lane-av1-422blockhalf: at ss (1,0) the tall/wide 1:2 and 1:4 strips'
543 // chroma plane block is BLOCK_INVALID (`av1_ss_size_lookup[...][1][0]`,
544 // blockd.h -- the 4:2:2 column maps BLOCK_8X16/16X32/32X64/64X128 and
545 // BLOCK_8X32/16X64, plus 4-wide BLOCK_4X16, to BLOCK_INVALID), so
546 // `av1_get_max_uv_txsize` indexes `max_txsize_rect_lookup` OUT OF BOUNDS
547 // and the pinned Release oracle byte there is TX_4X8 (the lane-av1-422m
548 // measurement). The plane is still coded -- `decode_token_recon_block`
549 // steps it in that (4, 8) unit shape -- so the strip's chroma tiles into
550 // 4x8 rect units, plane-major.
551 let chroma_422_oob = ss_x(fctx) == 1
552 && ss_y(fctx) == 0
553 && matches!(
554 (bw, bh),
555 (8, 16) | (16, 32) | (32, 64) | (64, 128) | (8, 32) | (16, 64)
556 );
557 // lane-av1-422stripanchor: the 4-wide strips' PAIR chroma -- the ported
558 // floored-pair anchor. `chroma422_pair_plane` is `Some` exactly when this
559 // strip's own chroma block would be 2 px wide at ss (1, 0); the pair's
560 // plane is then `(4, chroma_h)` written at the FLOORED cell
561 // (`chroma_x`), and the skip/tiled chroma arms below tile it in (4, 8)
562 // units (the OOB `max_txsize_rect_lookup[BLOCK_INVALID]` byte, TX_4X8 --
563 // the same walk the (8, 32) class takes). The lossless raster arm keeps
564 // the strip's own geometry: no caller of this function can present a
565 // 4-wide strip yet (the enumeration test pins the five callers at
566 // `8 <= min`), and the skip/tiled arms are the routes a future caller
567 // needs.
568 let chroma422_pair = chroma422_pair_plane(ss_x(fctx) == 1, ss_y(fctx) == 0, mi_c, bw, bh);
569 let chroma_422_pair_wide = chroma422_pair.is_some();
570 let (chroma_block_w, chroma_block_h, chroma_x) =
571 chroma422_pair.map_or((chroma_w, chroma_h, cpx), |(w, h, x, _)| (w, h, x));
572 // The chroma transform is picked before any symbol is read, so an
573 // unsupported chroma shape refuses before this strip desyncs the tile.
574 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
575 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
576 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
577 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
578 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
579 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
580 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
581 // squares a rect transform down to a CDF set by
582 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
583 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
584 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
585 // paths already prove for these same shapes.
586 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
587 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
588 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
589 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
590 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
591 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
592 _ => None,
593 };
594 // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted
595 // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled
596 // below; everything else still needs a single-unit table.
597 // lane-av1-422: a 4:2:2 strip's chroma plane keeps the strip's HEIGHT and
598 // halves only the width, so a rect luma strip codes a SQUARE chroma block
599 // (16x8 luma -> 8x8 chroma) -- the square rows below. At 4:2:0 and 4:4:4 a
600 // rect strip's chroma is itself rect, so the square rows are unreachable
601 // there and cannot change their results.
602 // lane-av1-422blockhalf: the tiled arms below handle every shape this
603 // strip can carry (including the 4:2:2 BLOCK_INVALID planes), so the
604 // diagnostic names only the shapes that would actually refuse -- it used
605 // to fire for every tiled square too (the parent lane's `chroma=8x8`
606 // rows) and sent the next lane chasing handled shapes.
607 let chroma_tiled = chroma_422_pair_wide
608 || chroma_422_oob
609 || matches!(
610 (chroma_w, chroma_h),
611 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)
612 );
613 if !m.skip {
614 if let Some(i) = match (chroma_w, chroma_h) {
615 (32, 8) => Some(0),
616 (8, 32) => Some(1),
617 (8, 4) => Some(2),
618 (4, 8) => Some(3),
619 _ => None,
620 } {
621 hit_do! {
622 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
623 let mut hits = c.get();
624 hits[i] += 1;
625 c.set(hits);
626 });
627 }
628 }
629 if !m.skip && chroma.is_none() && !chroma_tiled {
630 // Diagnostic for the next caller that lands here (class
631 // refusal-names-a-correlate: the message names the tool, not the
632 // shape); the refusal below keeps its inventory-pinned wording.
633 eprintln!(
634 "EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} \
635 chroma={chroma_w}x{chroma_h}"
636 );
637 }
638 }
639 // lane-rectsplit r2 (verifier finding): with both callers wired
640 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
641 // 64x32/32x64) every shape that reaches here has a table above, so this
642 // arm is UNREACHABLE today. It stays as the shape guard for the next
643 // caller -- a new strip size would otherwise hit the `expect` below and
644 // panic instead of refusing by name -- and so stays in
645 // `refusal_inventory::REFUSALS`.
646 if !m.skip && chroma.is_none() && !chroma_tiled {
647 return Err(unsupported(
648 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
649 ));
650 }
651 hit!(RECT_SPLIT_TX_HITS);
652 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
653 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
654 }
655 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
656 // A square unit reads through the ordinary square [`read_plane`]; a rect
657 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
658 // the very tables the unsplit 16x8/32x16 paths use.
659 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
660 (w, h) if w == h => None,
661 (16, 8) | (8, 16) => Some((
662 if reduced_tx_set {
663 TxbSet::LumaRect16x8
664 } else {
665 TxbSet::LumaRect16x8Set1
666 },
667 if tx_w == 16 {
668 &SCAN_16X8[..]
669 } else {
670 &SCAN_8X16[..]
671 },
672 )),
673 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
674 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
675 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
676 // strip, read through the `luma_64corner` arm below instead of a rect
677 // table -- a 64-length axis codes only its low 32 coefficients
678 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
679 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
680 // depth-0 arm already reads on the key-frame path.
681 //
682 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
683 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
684 // sub-8x8 intra leaves still refused: with those lifted (r2) the
685 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
686 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
687 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
688 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
689 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
690 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
691 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
692 (64, 32) | (32, 64) => None,
693 _ => {
694 return Err(unsupported(format!(
695 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
696 coefficient tables for that shape here)"
697 )));
698 }
699 };
700 // The `None` above that is NOT the square arm.
701 let luma_64corner = tx_w != tx_h;
702 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
703 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
704 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
705 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
706 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
707 // per-unit rect walk stay wired above/below; the round that finds that
708 // defect deletes this refusal and nothing else.
709 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
710 let luma_scan = default_scan(tx_w.min(tx_h));
711 let zero_tu = vec![0i32; tx_w * tx_h];
712 // The strip's OWN edge availability, the fallback for a transform unit
713 // whose top-right/bottom-left pixels fall outside the strip.
714 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
715 for tu_row in 0..bh / tx_h {
716 for tu_col in 0..bw / tx_w {
717 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
718 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
719 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
720 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
721 // libaom clips `av1_foreach_transformed_block_in_plane` to
722 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
723 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
724 // TOP-LEFT sample falls outside the frame is never coded. We read
725 // coefficients for those phantom units and desynced the stream at
726 // the very next symbol.
727 if tu_px >= y.true_width || tu_py >= y.true_height {
728 continue;
729 }
730 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
731 // transform unit INSIDE a block, which is a different rule from
732 // the standalone-block table [`Reach::of`] applies -- and the
733 // reason a depth-2 superblock strip came out one sample off
734 // before this: `Reach::of(tx, ..)` answered as if the unit were
735 // its own block at that superblock position.
736 // * top-right: if the unit's right neighbour is still inside the
737 // strip the pixels are already reconstructed (`col_off +
738 // tx_wide < plane_bw`); otherwise only the strip's own top row
739 // of units can reach past it, through the block-level answer.
740 // * bottom-left: a unit that is not in the strip's left column
741 // has none (`col_off > 0` returns 0); inside the strip
742 // (`row_off + tx_high < plane_bh`) they are the left
743 // neighbour's, already reconstructed; the last row falls back
744 // to the block-level answer.
745 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
746 // The unit's own window on the block's palette prediction.
747 if let Some(buf) = &m.palette_y {
748 let tu_buf: Vec<u16> = (0..tx_h)
749 .flat_map(|i| {
750 let base = (row_off + i) * bw + col_off;
751 buf[base..base + tx_w].iter().copied()
752 })
753 .collect();
754 set_palette_pred(tu_buf, fctx);
755 }
756 if m.skip {
757 push_intra_rect(
758 y,
759 u,
760 v,
761 0,
762 tu_px,
763 tu_py,
764 tx_w,
765 tx_h,
766 m.mode,
767 m.angle_delta_y,
768 tu_reach,
769 &zero_tu,
770 None,
771 m.filter_intra,
772 m.smooth_neighbor,
773 fctx,
774 );
775 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
776 } else if luma_64corner && luma_rect.is_none() {
777 // The un-split 64-level luma transform: `read_coeffs` on the
778 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
779 // and the real rect shape passed through for
780 // `av1_nz_map_ctx_offset` -- byte for byte
781 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
782 // 64-level strip gate already proves. `tx_type` is not coded
783 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
784 // the square-up size is TX_64X64), and this unit covers its
785 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
786 if crate::envflags::env_flag!("EC_RECT64TU") {
787 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
788 }
789 hit_do! {
790 RECT64_CORNER_TU_HITS.with(|c| {
791 let mut v = c.get();
792 v[usize::from(tx_h > tx_w)] += 1;
793 c.set(v);
794 });
795 }
796 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
797 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
798 let (corner, tu_tx_type) = read_coeffs(
799 dec,
800 &mut coding,
801 default_scan(TX32),
802 0,
803 dc_sign_ctx(tu_around.2),
804 TxType::DctDct,
805 Some((tx_w, tx_h)),
806 )?;
807 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
808 let mut tu_grid = vec![0i32; tx_w * tx_h];
809 for row in 0..ch {
810 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
811 }
812 let residual = dequant_and_inverse_typed_wh(
813 &tu_grid,
814 tx_w,
815 tx_h,
816 crate::decode::bit_depth(fctx),
817 block_q_idx(fctx),
818 plane_q_delta(0, fctx).0,
819 plane_q_delta(0, fctx).1,
820 tu_tx_type,
821 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
822 );
823 push_intra_rect(
824 y,
825 u,
826 v,
827 0,
828 tu_px,
829 tu_py,
830 tx_w,
831 tx_h,
832 m.mode,
833 m.angle_delta_y,
834 tu_reach,
835 &residual,
836 None,
837 m.filter_intra,
838 m.smooth_neighbor,
839 fctx,
840 );
841 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
842 } else if let Some((rect_set, rect_scan)) = luma_rect {
843 // The rect-unit twin of the square arm below: same contexts,
844 // same order, through the rect coefficient reader. The
845 // `tx_type` CDF row of a filter-intra block is
846 // `fimode_to_intradir[filter_intra_mode]`, never the block's
847 // own (always DC_PRED) mode -- [`read_plane`] applies that
848 // for the square arm, so this one must too.
849 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
850 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
851 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
852 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
853 // neighbour-magnitude table is for a unit SMALLER than its
854 // block. [`decode_block_rect`]'s own unsplit read passes a
855 // literal 0 for the same reason; this arm applied the table
856 // unconditionally and desynced every depth-0 rect strip that
857 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
858 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
859 0
860 } else {
861 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
862 };
863 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
864 let (tu_grid, tu_tx_type) = read_coeffs_rect(
865 dec,
866 &mut coding,
867 rect_scan,
868 tx_w,
869 tx_h,
870 tu_skip_ctx,
871 dc_sign_ctx(tu_around.2),
872 TxType::DctDct,
873 0,
874 )?;
875 let residual = dequant_and_inverse_typed_wh(
876 &tu_grid,
877 tx_w,
878 tx_h,
879 crate::decode::bit_depth(fctx),
880 block_q_idx(fctx),
881 plane_q_delta(0, fctx).0,
882 plane_q_delta(0, fctx).1,
883 tu_tx_type,
884 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
885 );
886 push_intra_rect(
887 y,
888 u,
889 v,
890 0,
891 tu_px,
892 tu_py,
893 tx_w,
894 tx_h,
895 m.mode,
896 m.angle_delta_y,
897 tu_reach,
898 &residual,
899 None,
900 m.filter_intra,
901 m.smooth_neighbor,
902 fctx,
903 );
904 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
905 } else {
906 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
907 // This unit is smaller than the block it sits in, so
908 // `txb_skip_ctx` is the neighbour-magnitude table, not the
909 // lone-TU 0 (spec `get_txb_ctx_general`).
910 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
911 let tu_grid = read_plane(
912 dec,
913 cdfs,
914 luma_set,
915 luma_scan,
916 0,
917 tu_around,
918 m.mode,
919 m.mode,
920 m.angle_delta_y,
921 tu_reach,
922 y,
923 u,
924 v,
925 tu_px,
926 tu_py,
927 tx_w,
928 tx_w,
929 base_q_idx,
930 None,
931 m.filter_intra,
932 Some(tu_skip_ctx),
933 m.smooth_neighbor,
934 fctx,
935 )?;
936 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
937 }
938 }
939 }
940 // CHROMA: one un-split rect transform for the whole strip.
941 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
942 // units -- each stamps its own neighbour context as it is read, and the
943 // whole-block `record_split_luma_rect_mi` below would overwrite all of
944 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
945 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
946 // collected here and replayed after that record.
947 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
948 // The chroma_tiled arm below stamps each unit's coefficient context
949 // immediately (so the NEXT unit reads it), then the whole-strip
950 // `record_split_luma_rect_mi` rewrites every chroma cell with ONE
951 // whole-strip state and the per-unit DC signs and levels are lost
952 // (class `override-slot-on-one-arm`). The units are collected here and
953 // replayed after that record, the way the lossless arm's
954 // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail
955 // already do.
956 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
957 let ac = m.alpha.map(|_| {
958 // lane-av1-422stripanchor: the pair unit's CfL source is the PAIR's
959 // luma -- the 8-px-wide region the floored 4-px chroma block covers
960 // (`av1_setup_dst_planes`' floor), never the odd strip's own 4 px.
961 if chroma_422_pair_wide {
962 cfl_src_rect((mi_c & !1) * MI, py, 8, bh)
963 } else {
964 cfl_src_rect(px, py, bw, bh)
965 }
966 });
967 let reach = if chroma_422_pair_wide {
968 // The chroma units predict off the PAIR block's edges: an odd-column
969 // strip's pair starts 4 luma px to the strip's left, so the strip's
970 // own answer names the wrong above/right samples (the pair16 arm's
971 // `pair_reach`, one partition level up).
972 Reach::of_rect(8, bh, (mi_c & !1) * MI, py, y.width, y.height, fctx)
973 } else {
974 block_reach
975 };
976 let (u_grid, v_grid) = if mono(fctx) {
977 // lane-av1mono: a monochrome frame codes no chroma coefficients on
978 // any block (`plane < av1_num_planes == 1`), so the whole chroma
979 // section -- the skipped-strip pushes, the lossless raster and the
980 // un-split `read_coeffs_rect` below -- is bypassed.
981 let zero = Grid::Zero(chroma_w * chroma_h);
982 (zero.clone(), zero)
983 } else if m.skip {
984 let zero = Grid::Zero(chroma_block_w * chroma_block_h);
985 if chroma_422_pair_wide || chroma_422_oob {
986 // lane-av1-422blockhalf: libaom predicts an INTRA strip's chroma
987 // per transform unit even when the strip is skipped
988 // (`decode_token_recon_block`'s per-TU plane walk runs before the
989 // skip guard), so the BLOCK_INVALID plane predicts as (4, 8)
990 // units -- one whole-plane push here would ask the intra
991 // predictor for a 1:8 rect it never needs.
992 // lane-av1-422stripanchor: the 4-wide strip's PAIR plane does the
993 // same, over the pair's own `(chroma_block_w, chroma_block_h)`
994 // grid at the floored anchor `chroma_x`.
995 let (uw, uh) = (4usize, 8usize);
996 for plane_idx in 1..=2 {
997 if let Some((ub, vb)) = &m.palette_uv {
998 let buf = if plane_idx == 1 { ub } else { vb };
999 set_palette_pred(buf.clone(), fctx);
1000 }
1001 for cu_row in 0..chroma_block_h / uh {
1002 for cu_col in 0..chroma_block_w / uw {
1003 push_intra_rect(
1004 y,
1005 u,
1006 v,
1007 plane_idx,
1008 chroma_x + cu_col * uw,
1009 cpy + cu_row * uh,
1010 uw,
1011 uh,
1012 m.uv_predict_mode,
1013 m.angle_delta_uv,
1014 reach,
1015 &ZERO_RESIDUAL[..uw * uh],
1016 m.alpha
1017 .zip(ac)
1018 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
1019 None,
1020 m.smooth_neighbor_uv,
1021 fctx,
1022 );
1023 }
1024 }
1025 }
1026 } else {
1027 if let Some((ub, _)) = &m.palette_uv {
1028 set_palette_pred(ub.clone(), fctx);
1029 }
1030 push_intra_rect(
1031 y,
1032 u,
1033 v,
1034 1,
1035 cpx,
1036 cpy,
1037 chroma_w,
1038 chroma_h,
1039 m.uv_predict_mode,
1040 m.angle_delta_uv,
1041 reach,
1042 &zero,
1043 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
1044 None,
1045 m.smooth_neighbor_uv,
1046 fctx,
1047 );
1048 if let Some((_, vb)) = &m.palette_uv {
1049 set_palette_pred(vb.clone(), fctx);
1050 }
1051 push_intra_rect(
1052 y,
1053 u,
1054 v,
1055 2,
1056 cpx,
1057 cpy,
1058 chroma_w,
1059 chroma_h,
1060 m.uv_predict_mode,
1061 m.angle_delta_uv,
1062 reach,
1063 &zero,
1064 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
1065 None,
1066 m.smooth_neighbor_uv,
1067 fctx,
1068 );
1069 }
1070 (zero.clone(), zero)
1071 } else if lossless(fctx) {
1072 // lane-lossless: the strip's chroma plane block is coded as 4x4
1073 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
1074 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
1075 // (`decode_token_recon_block`'s mu-chunk loop, measured against
1076 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
1077 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
1078 // offset (our `+3` row base) whenever the plane block is bigger than
1079 // the transform.
1080 let scan4 = default_scan(4);
1081 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
1082 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
1083 // lane-av1-llband: one 4x4 chroma unit's extent in LUMA pixels -- 4
1084 // chroma px scaled by the plane's own subsampling. The hardcoded 8
1085 // was the 4:2:0 unit's span; at 4:4:4 a unit is 4x4 LUMA px (one mi
1086 // cell), and the 8-px step made every unit past the first column/row
1087 // read its `txb_skip` context at the WRONG mi (two cells over) and
1088 // stamp a 2-cell span with one unit's state -- the polluted above-band
1089 // cell behind a 16x8 leaf's U bc=2 unit of the 444 lossless key frame
1090 // (measured: oracle `EC_DBGCTX` reads 1-cell spans at 1-mi steps;
1091 // ours read `above[28..29]` where the oracle read `above[26]`).
1092 let span_x = 4 << ss_x(fctx);
1093 let span_y = 4 << ss_y(fctx);
1094 let mut last = [Grid::Zero(16), Grid::Zero(16)];
1095 for plane_idx in 1..=2 {
1096 for cu_row in 0..ch_n {
1097 for cu_col in 0..cw_n {
1098 // lane-av1offtile: the CHROMA twin of the luma walk's
1099 // `max_blocks_wide/high` clip (decode.rs:12516, lane-hgkf
1100 // r1). libaom computes those bounds per PLANE
1101 // (`max_block_wide(xd, plane_bsize, plane)`,
1102 // av1_common_int.h:1565 -- `mb_to_right_edge >>
1103 // (3 + pd->subsampling_x)`, then `>> MI_SIZE_LOG2`), so a
1104 // chroma unit whose top-left sample falls outside the
1105 // CHROMA plane is never coded. This walk counted
1106 // `chroma_w / 4` x `chroma_h / 4` units off the BLOCK's
1107 // own extent instead.
1108 //
1109 // MEASURED on `mix_176x144_6.obu` (4:2:0 8-bit,
1110 // --cq-level=0 --aq-mode=1 altref; the 48x16 bottom-right
1111 // sliver, block mi=(32,32) px=(128,128) bw=64 bh=32):
1112 // the chroma plane is 88x72, so `cw_n` must be
1113 // `(88 - 64) / 4 = 6` and `ch_n` `(72 - 64) / 4 = 2` --
1114 // the oracle's own `EC_ECDUMP_IN` for that block is
1115 // exactly 12 units per plane (bc 0..5 x br 0..1). Ours
1116 // walked 8 x 4 = 32 per plane: 20 phantom units x 2
1117 // planes = the 40 extra `txb_skip` reads after SYMR
1118 // 25791, all at `mi=(32,32)`, all `all_zero`, all with
1119 // the bit position FROZEN at 36288 -- reads out of a
1120 // tile already exhausted, which is what turned the
1121 // desync 11 970 reads later into a hard
1122 // `REFUSED: unsupported: AV1 tile (a Golomb tail longer
1123 // than this decoder reads)`.
1124 if cpx + cu_col * 4 >= u.true_width || cpy + cu_row * 4 >= u.true_height {
1125 hit!(RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS);
1126 continue;
1127 }
1128 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
1129 // lane-av1422llintra: at ss (1, 0) one chroma column
1130 // spans TWO luma mi columns, so the plain rect walk sums
1131 // its whole-unit dc sign TWICE where libaom's
1132 // `get_txb_ctx_general` reads `txb_w_unit` chroma cells
1133 // -- one per column. `dc_sign_ctx` only sees the vote's
1134 // SIGNUM, so a doubled above vote flips the row exactly
1135 // when above and left cancel (a+l = 0 -> ctx 0 becomes
1136 // 2a+l = +a). Measured on the pinned 4:2:2 all-intra
1137 // lossless control `ll422_allintra.obu`: the V 4x4 unit
1138 // at chroma (24, 8) of the BLOCK_32X8 at mi(2,8) --
1139 // oracle `EC_DBGCTX above0=23 left0=13` sums to dc 0 and
1140 // reads `dc_sign_cdf[0]`; ours summed the above column
1141 // twice, got vote +1, and read `dc_sign_cdf[2]`, so the
1142 // DC sign symbol came out inverted and the whole tile
1143 // desynced from there. Identical to the guard one arm up
1144 // at 12865.
1145 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
1146 neighbours.around_mi_422_chroma(cu_mi, span_x, span_y)
1147 } else {
1148 neighbours.around_mi_rect(cu_mi, span_x, span_y)
1149 };
1150 let cu_reach = tu_reach(
1151 bw,
1152 bh,
1153 cu_col * span_x,
1154 cu_row * span_y,
1155 span_x,
1156 block_reach,
1157 px,
1158 py,
1159 y.width,
1160 y.height,
1161 fctx,
1162 );
1163 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
1164 if let Some((ub, vb)) = &m.palette_uv {
1165 let pbuf = if plane_idx == 1 { ub } else { vb };
1166 set_palette_pred(
1167 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
1168 fctx,
1169 );
1170 }
1171 let grid = read_plane(
1172 dec,
1173 cdfs,
1174 TxbSet::Chroma4,
1175 scan4,
1176 plane_idx,
1177 cu_around[plane_idx],
1178 m.mode,
1179 m.uv_predict_mode,
1180 m.angle_delta_uv,
1181 cu_reach,
1182 y,
1183 u,
1184 v,
1185 cu_x,
1186 cu_y,
1187 4,
1188 4,
1189 base_q_idx,
1190 m.alpha
1191 .zip(ac)
1192 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
1193 None,
1194 offset,
1195 m.smooth_neighbor_uv,
1196 fctx,
1197 )?;
1198 if span_x == 4 && span_y == 4 {
1199 hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS);
1200 }
1201 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid);
1202 ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y));
1203 last[plane_idx - 1] = grid;
1204 }
1205 }
1206 }
1207 let [ug, vg] = last;
1208 (ug, vg)
1209 } else if chroma_tiled {
1210 let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) =
1211 if chroma_422_pair_wide || chroma_422_oob {
1212 // lane-av1-422blockhalf / lane-av1-422stripanchor: the
1213 // BLOCK_INVALID-plane chroma's (4, 8) units -- the Release
1214 // oracle's out-of-bounds `max_txsize_rect_lookup` byte (TX_4X8,
1215 // see above). For the 4-wide strip the units tile the PAIR's
1216 // plane, stepping from the floored anchor.
1217 (4, 8, TxbSet::ChromaRect8x4, &SCAN_4X8)
1218 } else {
1219 match (chroma_w, chroma_h) {
1220 (64, 32) | (32, 64) | (32, 32) => (32, 32, TxbSet::Chroma32, default_scan(32)),
1221 (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16),
1222 (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32),
1223 // lane-av1-422: the 4:2:2 square chroma planes (height unhalved),
1224 // through the square reader like every other square chroma unit.
1225 (16, 16) => (16, 16, TxbSet::Chroma16, default_scan(16)),
1226 (8, 8) => (8, 8, TxbSet::Chroma8, default_scan(8)),
1227 _ => unreachable!("chroma_tiled"),
1228 }
1229 };
1230 // lane-av1-422: the witness counter, keyed to ss (1,0) so only a 4:2:2
1231 // frame's square chroma units count it.
1232 if uw == uh && ss_x(fctx) == 1 && ss_y(fctx) == 0 {
1233 hit!(CHROMA422_SQUARE_HITS);
1234 }
1235 if chroma_422_pair_wide {
1236 hit!(CHROMA422_PAIR_WIDE_HITS);
1237 }
1238 let (nw, nh) = (chroma_block_w / uw, chroma_block_h / uh);
1239 // lane-av1-422stripanchor: the pair's plane block is BLOCK_INVALID
1240 // whatever the pair size (`num_pels_log2_lookup[255]` reads 0xff in
1241 // the pinned Release oracle), so its txb_skip rows always carry the
1242 // bigger-plane +3 (the av1422q rule the pair16 arm measures).
1243 let bigger = chroma_422_pair_wide || chroma_w * chroma_h > uw * uh;
1244 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
1245 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra;
1246 // smaller rect units (the 4:2:2 BLOCK_INVALID-plane (4, 8)s) take the
1247 // mode-indexed default, the same rule the unsplit arm below applies.
1248 let default_tx = if uw.max(uh) >= 32 {
1249 TxType::DctDct
1250 } else {
1251 default_intra_tx_type(m.uv_predict_mode as u8)
1252 };
1253 let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)];
1254 for plane_idx in 1..=2 {
1255 for cu_row in 0..nh {
1256 for cu_col in 0..nw {
1257 let luma_span_x = uw << ss_x(fctx);
1258 let luma_span_y = uh << ss_y(fctx);
1259 let cu_mi = (
1260 mi_r + cu_row * (luma_span_y / MI),
1261 if chroma_422_pair_wide {
1262 mi_c & !1
1263 } else {
1264 mi_c
1265 } + cu_col * (luma_span_x / MI),
1266 );
1267 // lane-av1-422blockhalf: the 4:2:2 (4, 8) units read their
1268 // chroma context per chroma cell
1269 // ([`Neighbours::around_mi_422_chroma`], the block-8
1270 // rule) -- the plain rect walk samples one chroma cell
1271 // twice at ss_x 1. Every pre-existing shape keeps its own
1272 // walk.
1273 // lane-av1422mi24: the plain rect walk's double-count
1274 // hits EVERY unit shape at ss (1,0), not just the (4, 8)
1275 // one -- the (8, 8) unit of a 16x8 intra-in-inter strip
1276 // read its above dc votes twice and its U dc_sign one
1277 // ctx row high (t422 frame 1). Route every ss (1,0)
1278 // unit through the every-second-above-cell sampling;
1279 // 4:2:0/4:4:4 keep the plain walk verbatim.
1280 let cu_around = if chroma_422_oob || (ss_x(fctx) == 1 && ss_y(fctx) == 0) {
1281 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
1282 } else {
1283 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
1284 };
1285 let (cu_x, cu_y) = (chroma_x + cu_col * uw, cpy + cu_row * uh);
1286 let cfl = m.alpha.map(|(au, av)| {
1287 let alpha = if plane_idx == 1 { au } else { av };
1288 (
1289 alpha,
1290 if chroma_422_pair_wide {
1291 // The unit's co-located luma is the PAIR's
1292 // 8-px-wide band at the floored mi column.
1293 cfl_src_rect(
1294 (mi_c & !1) * MI + cu_col * luma_span_x,
1295 py + cu_row * luma_span_y,
1296 luma_span_x,
1297 luma_span_y,
1298 )
1299 } else {
1300 cfl_src_rect(
1301 px + cu_col * luma_span_x,
1302 py + cu_row * luma_span_y,
1303 luma_span_x,
1304 luma_span_y,
1305 )
1306 },
1307 )
1308 });
1309 // lane-av1-422kf: the palette colour map is consumed per
1310 // unit here like every other chroma arm (`av1_visit_palette`
1311 // feeds the whole plane block; window it to this unit).
1312 // Without this the square chroma rows decoded a uv-palette
1313 // strip's chroma as plain DC (class same-symbols-silent-
1314 // prediction: the rng stayed in sync, only the prediction
1315 // was dropped).
1316 if let Some((ub, vb)) = &m.palette_uv {
1317 let buf = if plane_idx == 1 { ub } else { vb };
1318 set_palette_pred(
1319 palette_window(buf, chroma_block_w, cu_col * uw, cu_row * uh, uw, uh),
1320 fctx,
1321 );
1322 }
1323 // libaom computes `has_top_right` PER TRANSFORM UNIT (defined
1324 // reconintra.c:196, called from `av1_build_intra_predictors` at
1325 // reconintra.c:1847 with the txb walk's own
1326 // `blk_col`/`blk_row`), never per block: the
1327 // `row_off == 0` arm asks `col_off + top_right_count_unit
1328 // < plane_bw_unit`, so the FIRST unit of a 2-wide chroma
1329 // grid reads its above-right out of the already-reconstructed
1330 // block ABOVE even when the block's own right edge is the
1331 // frame's. Passing this walk's block-level `reach` gave
1332 // every unit the same answer, and `PlaneBuf::edges`
1333 // (decode.rs:20840) truncates the above row at
1334 // `own_across` when `above_right` is false -- so a
1335 // directional unit whose angle is below 90
1336 // (`need_right`, intra.rs:546) predicted with a 32-sample
1337 // above row where libaom used 64.
1338 // MEASURED on `fixtures/r512_rect2x1_1x2_444.obu`
1339 // (4:4:4 8-bit 256x256, one frame): frame 0 plane U 130
1340 // samples and plane V 30 samples wrong, every one of them
1341 // in the right 6 columns of the `cu=(0,0)` unit at
1342 // `mi=(48,48)` `px=(192,192)` -- the unit whose above-right
1343 // the block reach denied. Row0 and col0 of the prediction
1344 // matched the oracle exactly and the prediction SUM did
1345 // not (172662 vs 171512 on U, 125978 vs 126008 on V), so
1346 // the residual read is bit-identical and the divergence is
1347 // prediction-side, not entropy. Gate:
1348 // `a_444_rect_strip_chroma_tiled_2x1_and_1x2_units_take_their_own_above_right_reach`.
1349 let cu_reach = tu_reach_rect(
1350 bw,
1351 bh,
1352 (cu_col * uw) << ss_x(fctx),
1353 (cu_row * uh) << ss_y(fctx),
1354 uw << ss_x(fctx),
1355 uh << ss_y(fctx),
1356 reach,
1357 px,
1358 py,
1359 y.width,
1360 y.height,
1361 fctx,
1362 );
1363 if cu_reach.above_right != reach.above_right
1364 || cu_reach.below_left != reach.below_left
1365 {
1366 hit!(RECT_TILED_CHROMA_UNIT_REACH_HITS);
1367 }
1368 if nw * nh > 1 {
1369 match (nw, nh) {
1370 (2, 1) => hit!(RECT_TILED_CHROMA_2X1_HITS),
1371 (1, 2) => hit!(RECT_TILED_CHROMA_1X2_HITS),
1372 _ => hit!(RECT_TILED_CHROMA_NXN_HITS),
1373 }
1374 }
1375 // 32x32 does not fit read_coeffs_rect's scratch (768). The
1376 // square reader is the path every other 32x32 chroma unit uses.
1377 let levels = if uw == uh {
1378 read_plane(
1379 dec,
1380 cdfs,
1381 set,
1382 scan,
1383 plane_idx,
1384 cu_around[plane_idx],
1385 m.mode,
1386 m.uv_predict_mode,
1387 m.angle_delta_uv,
1388 cu_reach,
1389 y,
1390 u,
1391 v,
1392 cu_x,
1393 cu_y,
1394 uw,
1395 uw,
1396 base_q_idx,
1397 cfl,
1398 None,
1399 bigger.then_some(3),
1400 m.smooth_neighbor_uv,
1401 fctx,
1402 )?
1403 } else {
1404 let skip_ctx = usize::from(cu_around[plane_idx].0)
1405 + usize::from(cu_around[plane_idx].1)
1406 + usize::from(bigger) * 3;
1407 let mut coding = cdfs.txb(set, m.uv_predict_mode);
1408 let (levels, tx_type) = read_coeffs_rect(
1409 dec,
1410 &mut coding,
1411 scan,
1412 uw,
1413 uh,
1414 skip_ctx,
1415 dc_sign_ctx(cu_around[plane_idx].2),
1416 default_tx,
1417 plane_idx,
1418 )?;
1419 let residual = dequant_and_inverse_typed_wh(
1420 &levels,
1421 uw,
1422 uh,
1423 crate::decode::bit_depth(fctx),
1424 block_q_idx(fctx),
1425 plane_q_delta(plane_idx, fctx).0,
1426 plane_q_delta(plane_idx, fctx).1,
1427 tx_type,
1428 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
1429 );
1430 push_intra_rect(
1431 y,
1432 u,
1433 v,
1434 plane_idx,
1435 cu_x,
1436 cu_y,
1437 uw,
1438 uh,
1439 m.uv_predict_mode,
1440 m.angle_delta_uv,
1441 cu_reach,
1442 &residual,
1443 cfl,
1444 None,
1445 m.smooth_neighbor_uv,
1446 fctx,
1447 );
1448 levels
1449 };
1450 neighbours.record_mi_chroma(
1451 cu_mi,
1452 luma_span_x,
1453 luma_span_y,
1454 plane_idx,
1455 &levels,
1456 );
1457 tiled_chroma_units.push((
1458 cu_mi,
1459 plane_idx,
1460 levels.clone(),
1461 luma_span_x,
1462 luma_span_y,
1463 ));
1464 last[plane_idx - 1] = levels;
1465 }
1466 }
1467 }
1468 (last[0].clone(), last[1].clone())
1469 } else {
1470 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
1471 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
1472 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
1473 // so only the 16x8/8x16 pair takes the mode-indexed default.
1474 let default_tx = if chroma_w.max(chroma_h) >= 32 {
1475 TxType::DctDct
1476 } else {
1477 default_intra_tx_type(m.uv_predict_mode as u8)
1478 };
1479 // lane-av1422mi24: at ss (1,0) the chroma above span is `bw >> 1`
1480 // chroma cells spread over `bw` luma mi columns -- the per-mi gather
1481 // counts every chroma column's whole-unit dc sign twice (the t422
1482 // frame-1 mi(26,60) intra-in-inter strip's U dc_sign read one ctx
1483 // row high). Luma keeps the per-mi gather; the two chroma planes
1484 // take [`Neighbours::around_mi_422_chroma`]'s every-second
1485 // above-cell sampling, like every other 4:2:2 chroma gather.
1486 let mut around = neighbours.around_mi_rect(at_mi, bw, bh);
1487 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
1488 let c = neighbours.around_mi_422_chroma(at_mi, bw, bh);
1489 around[1] = c[1];
1490 around[2] = c[2];
1491 }
1492 let mut grids: Vec<Grid> = Vec::with_capacity(2);
1493 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
1494 #[allow(clippy::needless_range_loop)]
1495 for plane_idx in 1..=2 {
1496 let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
1497 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
1498 let (levels, tx_type) = read_coeffs_rect(
1499 dec,
1500 &mut coding,
1501 chroma_scan,
1502 chroma_w,
1503 chroma_h,
1504 skip_ctx,
1505 dc_sign_ctx(around[plane_idx].2),
1506 default_tx,
1507 plane_idx,
1508 )?;
1509 // The same delta_q proof the unsplit rect64 path records
1510 // (lane-rectsplit r4: lifting the split-transform refusal moved
1511 // superblock strips onto this path, so only counting there would
1512 // leave the delta_q gate's counter silent for them).
1513 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
1514 hit!(RECT64_QIDX_DRIFT_HITS);
1515 }
1516 let residual = dequant_and_inverse_typed_wh(
1517 &levels,
1518 chroma_w,
1519 chroma_h,
1520 crate::decode::bit_depth(fctx),
1521 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
1522 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
1523 // reading `current_q_idx` here dropped the segment feature
1524 // that every other dequant site applies (class
1525 // `parsed-then-discarded`).
1526 block_q_idx(fctx),
1527 plane_q_delta(plane_idx, fctx).0,
1528 plane_q_delta(plane_idx, fctx).1,
1529 tx_type,
1530 block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, tx_type),
1531 );
1532 let cfl = m
1533 .alpha
1534 .zip(ac)
1535 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
1536 if let Some((ub, vb)) = &m.palette_uv {
1537 let buf = if plane_idx == 1 { ub } else { vb };
1538 set_palette_pred(buf.clone(), fctx);
1539 }
1540 push_intra_rect(
1541 y,
1542 u,
1543 v,
1544 plane_idx,
1545 cpx,
1546 cpy,
1547 chroma_w,
1548 chroma_h,
1549 m.uv_predict_mode,
1550 m.angle_delta_uv,
1551 reach,
1552 &residual,
1553 cfl,
1554 None,
1555 m.smooth_neighbor_uv,
1556 fctx,
1557 );
1558 grids.push(levels);
1559 }
1560 let mut it = grids.into_iter();
1561 (it.next().unwrap(), it.next().unwrap())
1562 };
1563 neighbours.record_split_luma_rect_mi(
1564 at_mi,
1565 bw,
1566 bh,
1567 m.mode,
1568 m.uv_predict_mode,
1569 [&u_grid, &v_grid],
1570 );
1571 for (cu_mi, plane, unit, span_w, span_h) in &ll_chroma_units {
1572 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
1573 }
1574 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
1575 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
1576 }
1577 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
1578 neighbours.fill_lf_grid_rect(
1579 (mi_r, mi_c),
1580 bw / MI,
1581 bh / MI,
1582 tx_w as u8,
1583 tx_h as u8,
1584 0,
1585 fctx,
1586 );
1587 if crate::envflags::env_flag!("EC_AV1_TRACE") {
1588 let (rng, _) = dec.debug_state();
1589 eprintln!(
1590 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
1591 tx={tx_w}x{tx_h} rng={rng}"
1592 );
1593 }
1594 Ok(())
1595}
1596
1597/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
1598/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
1599/// because it predicts squares only. Every pixel here goes through the rect
1600/// machinery the key-frame paths already prove: [`decode_rect_split`], which
1601/// at `depth == 0` is the unsplit strip as a single transform unit and
1602/// beyond it the per-unit walk of [`depth_to_tx_wh`].
1603///
1604/// What is genuinely different from [`decode_block_rect`] is the mode
1605/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
1606/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
1607/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
1608/// intra-in-inter arm's own reads at the rect footprint, including its
1609/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
1610/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
1611/// square and this arm) and a nonzero luma angle delta refused by name.
1612///
1613/// The strip's own neighbour records (luma per transform unit, chroma, skip
1614/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
1615/// inter-side bands and the mi map.
1616#[allow(clippy::too_many_arguments)]
1617/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
1618/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
1619/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
1620/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
1621/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
1622/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
1623/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
1624/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
1625/// table here rather than a shift of `bw.min(bh)`.
1626fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
1627 Some(match (bw.min(bh), bw.max(bh)) {
1628 (8, 16) => (1usize, 1usize),
1629 (16, 32) => (2, 2),
1630 (32, 64) => (3, 3),
1631 (8, 32) => (1, 2),
1632 (16, 64) => (2, 3),
1633 _ => return None,
1634 })
1635}
1636
1637/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
1638/// block path"): the shapes that can reach that arm, enumerated against the
1639/// MEASURED domain of the inter block path
1640/// ([`INTER_BLOCK_SHAPES`], the census the gate
1641/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
1642/// fills from three real streams).
1643///
1644/// [`decode_intra_rect_in_inter`] is called from one site, under
1645/// `write_w != side || write_h != side`, and only after two earlier arms have
1646/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
1647/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
1648/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
1649/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
1650/// and each of those has a row, so the refusal names a shape no measured
1651/// stream can present.
1652#[test]
1653fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
1654 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
1655 // names that string exactly (placeholders included) and pins its guard
1656 // site. The enumeration below establishes the shape domain; on its own it
1657 // never said WHICH string the domain was about, so under a real function
1658 // boundary -- rather than a window that ran into the next test -- the row
1659 // read as unanchored.
1660 const REFUSAL: &str = "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)";
1661 assert!(
1662 crate::test_source::module_source("decode").contains(REFUSAL),
1663 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
1664 );
1665 let mut checked = 0;
1666 for &(side, w, h) in &INTER_BLOCK_SHAPES {
1667 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
1668 continue;
1669 }
1670 assert!(
1671 intra_in_inter_size_row(w, h).is_some(),
1672 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
1673 the \"no size-group/tx-category row\" refusal"
1674 );
1675 checked += 1;
1676 }
1677 assert_eq!(
1678 checked, 10,
1679 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
1680 lookup, not the 10 this claim was measured over"
1681 );
1682}
1683
1684/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
1685/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
1686/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
1687/// matched before the square arm's `log2` shortcut).
1688///
1689/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
1690/// row here"; the enumeration below is what proves no conformant block can
1691/// reach it.
1692pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
1693 Some(match (write_w, write_h) {
1694 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
1695 // below maps 128 to row 4 (BLOCK_16X32).
1696 (64, 128) => 14,
1697 (128, 64) => 15,
1698 (128, 128) => 16,
1699 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
1700 (16, 32) => 4,
1701 (32, 16) => 5,
1702 (32, 64) => 6,
1703 (64, 32) => 7,
1704 (8, 32) => 8,
1705 (32, 8) => 9,
1706 (16, 64) => 10,
1707 (64, 16) => 11,
1708 // lane-inter4 r3: the 16x16-level rect inter leaves.
1709 (8, 16) => 12,
1710 (16, 8) => 13,
1711 _ => return None,
1712 })
1713}
1714
1715/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
1716/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
1717/// `block_size_wide`/`block_size_high`).
1718#[cfg(test)]
1719pub(super) const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
1720 (4, 4),
1721 (4, 8),
1722 (8, 4),
1723 (8, 8),
1724 (8, 16),
1725 (16, 8),
1726 (16, 16),
1727 (16, 32),
1728 (32, 16),
1729 (32, 32),
1730 (32, 64),
1731 (64, 32),
1732 (64, 64),
1733 (64, 128),
1734 (128, 64),
1735 (128, 128),
1736 (4, 16),
1737 (16, 4),
1738 (8, 32),
1739 (32, 8),
1740 (16, 64),
1741 (64, 16),
1742];
1743
1744/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
1745/// shape with no CDF row here" names a shape no conformant stream can present.
1746///
1747/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
1748/// whose `write_w.min(write_h) >= 8` clause is libaom's
1749/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
1750/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
1751/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
1752/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
1753/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
1754/// clause rejects before the lookup.
1755#[test]
1756fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
1757 let mut rows = std::collections::BTreeSet::new();
1758 let mut excluded = 0;
1759 for (w, h) in BLOCK_SIZES_ALL_WH {
1760 if w.min(h) < 8 {
1761 excluded += 1;
1762 assert!(
1763 w == 4 || h == 4,
1764 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
1765 );
1766 continue;
1767 }
1768 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
1769 panic!(
1770 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
1771 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
1772 )
1773 });
1774 assert!(
1775 row < 17,
1776 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
1777 );
1778 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
1779 }
1780 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
1781 assert_eq!(
1782 rows.len(),
1783 17,
1784 "17 eligible footprints must fill all 17 rows of the motion_mode table"
1785 );
1786}
1787
1788/// lane-av1-422stripanchor, format-cell census for the 4-wide-strip pair port
1789/// ([`chroma422_pair_plane`], [`decode_rect_split`]'s chroma routing): over
1790/// every `BLOCK_SIZES_ALL` footprint at every subsampling cell, the pair arm
1791/// fires exactly when libaom's own `av1_ss_size_lookup[..][1][0]` column
1792/// (`common_data.c`) marks the plane block BLOCK_INVALID AND the plane would
1793/// be 2 px wide -- the 4-wide footprints. The tall/wide BLOCK_INVALID shapes
1794/// stay on the pre-existing `chroma_422_oob` (4, 8) tiling, and 4:2:0 /
1795/// 4:4:4 never enter either arm (the byte-identical claim, checked per cell).
1796#[test]
1797fn chroma422_pair_plane_matches_the_ss_size_lookup_cells() {
1798 // The `av1_ss_size_lookup[..][1][0]` column verbatim (pinned oracle,
1799 // `common_data.c`), keyed by footprint: `true` = BLOCK_INVALID.
1800 let ss10_invalid: &[(&str, bool)] = &[
1801 ("4x4", false),
1802 ("4x8", true),
1803 ("8x4", false),
1804 ("8x8", false),
1805 ("8x16", true),
1806 ("16x8", false),
1807 ("16x16", false),
1808 ("16x32", true),
1809 ("32x16", false),
1810 ("32x32", false),
1811 ("32x64", true),
1812 ("64x32", false),
1813 ("64x64", false),
1814 ("64x128", true),
1815 ("128x64", false),
1816 ("128x128", false),
1817 ("4x16", true),
1818 ("16x4", false),
1819 ("8x32", true),
1820 ("32x8", false),
1821 ("16x64", true),
1822 ("64x16", false),
1823 ];
1824 for (footprint, invalid10) in ss10_invalid {
1825 let (w, h) = footprint.split_once('x').unwrap();
1826 let (bw, bh) = (w.parse::<usize>().unwrap(), h.parse::<usize>().unwrap());
1827 // BLOCK_4X4 is the SQUARE path's leaf, never a strip: its ss cell is
1828 // valid because a (2, 4) plane area rounds UP to the 4x4 read
1829 // (`sub8_leaf_chroma422`'s own rule), and it never reaches
1830 // [`decode_rect_split`] at all.
1831 if (bw, bh) == (4, 4) {
1832 continue;
1833 }
1834 // 4:2:0 and 4:4:4: the port never fires, whatever the footprint.
1835 for (ss_x, ss_y) in [(false, false), (true, true)] {
1836 assert!(
1837 chroma422_pair_plane(ss_x, ss_y, 7, bw, bh).is_none(),
1838 "{bw}x{bh} at ss ({ss_x}, {ss_y}) must keep its own plane block"
1839 );
1840 }
1841 // 4:2:2: the pair arm is exactly the 2-px-wide (4-wide) slice of the
1842 // BLOCK_INVALID column, anchored at the floored mi column.
1843 let pair = chroma422_pair_plane(true, false, 7, bw, bh);
1844 assert_eq!(
1845 pair.is_some(),
1846 *invalid10 && bw == 4,
1847 "{bw}x{bh} at ss (1, 0): pair routing disagrees with ss_size_lookup"
1848 );
1849 if let Some((block_w, block_h, x, ctx_col)) = pair {
1850 assert_eq!((block_w, block_h), (4, bh), "{bw}x{bh} pair plane shape");
1851 assert_eq!(x, ((7 & !1) * MI) >> 1, "{bw}x{bh} floored write anchor");
1852 assert_eq!(ctx_col, 6, "{bw}x{bh} entropy cell is the floored column");
1853 // An even-column strip anchors at its own cell.
1854 let (x_even, col_even) = match chroma422_pair_plane(true, false, 6, bw, bh) {
1855 Some((_, _, x, c)) => (x, c),
1856 None => panic!("{bw}x{bh} lost its pair arm at an even mi_col"),
1857 };
1858 assert_eq!(
1859 (x_even, col_even),
1860 (12, 6),
1861 "even column keeps its own cell"
1862 );
1863 }
1864 }
1865 // The tall/wide BLOCK_INVALID shapes (8 px wide or more) are the
1866 // `chroma_422_oob` tiling's residents, not the pair arm's: both are
1867 // 4:2:2-only, so the two arms partition the BLOCK_INVALID column.
1868 for (bw, bh) in [
1869 (8usize, 16),
1870 (16, 32),
1871 (32, 64),
1872 (64, 128),
1873 (8, 32),
1874 (16, 64),
1875 ] {
1876 assert!(chroma422_pair_plane(true, false, 7, bw, bh).is_none());
1877 }
1878}
1879
1880// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1881#[allow(clippy::too_many_arguments)]
1882pub(super) fn decode_intra_rect_in_inter(
1883 dec: &mut SymbolDecoder,
1884 cdfs: &mut Cdfs,
1885 neighbours: &mut Neighbours,
1886 at: (usize, usize),
1887 bw: usize,
1888 bh: usize,
1889 skip: bool,
1890 allow_screen_content_tools: bool,
1891 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
1892 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
1893 strip16: Option<(bool, bool)>,
1894 y: &mut PlaneBuf<'static>,
1895 u: &mut PlaneBuf<'static>,
1896 v: &mut PlaneBuf<'static>,
1897 base_q_idx: u8,
1898 fctx: &crate::decode::FrameCtx,
1899) -> Result<()> {
1900 // `at` is in MI units (the inter path's own unit since lane-inter4);
1901 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
1902 // below are still keyed by.
1903 let (mi_r, mi_c) = at;
1904 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
1905 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
1906 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
1907 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
1908 // finding -- the category is NOT the same for every strip size).
1909 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
1910 // it is refused by name rather than read from the wrong CDF row.
1911 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
1912 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
1913 // tx-depth category is 1 -- but nothing here has to know either, because
1914 // the strip decodes through the very body the KEY FRAME path proves for
1915 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
1916 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
1917 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
1918 // inter-frame difference is the mode-info read, which
1919 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
1920 // `y_mode[0]` plus the `skip` this caller already read.
1921 if let Some((horz, has_chroma)) = strip16 {
1922 // lane-t900 r22: the screen-content refusal here was STALE (class
1923 // stale-premise): [`decode_rect4_16_strip`] takes
1924 // `allow_screen_content_tools` and reads the whole palette syntax
1925 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
1926 // pair) -- the key frame proves that body. Lifted with the 10-bit
1927 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
1928 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
1929 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
1930 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
1931 let res = decode_rect4_16_strip(
1932 dec,
1933 cdfs,
1934 neighbours,
1935 (mi_r, mi_c),
1936 horz,
1937 has_chroma,
1938 // The inter strips of the same partition publish their own
1939 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
1940 // has nothing to add here.
1941 None,
1942 y,
1943 u,
1944 v,
1945 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
1946 allow_screen_content_tools,
1947 base_q_idx,
1948 fctx.tx_select_inter.with(std::cell::Cell::get),
1949 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
1950 fctx,
1951 );
1952 fctx.intra_in_inter_mode.with(|c| c.set(None));
1953 let (mode, uv, (tx_w, tx_h)) = res?;
1954 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
1955 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
1956 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
1957 // block of an inter frame, intra ones included, and
1958 // `txfm_partition_update` for the var-tx context. The key-frame body
1959 // writes neither (a key frame has no var-tx tree and its own readers
1960 // use the deblock grid), so the block AFTER this strip read a stale
1961 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
1962 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
1963 // 16x16 row.
1964 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
1965 for i in 0..bw / MI {
1966 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
1967 *cell = tx_w as u8;
1968 }
1969 }
1970 for i in 0..bh / MI {
1971 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
1972 *cell = tx_h as u8;
1973 }
1974 }
1975 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
1976 // coarse 16-px cell holds one entry for the whole 16x16 and the last
1977 // block to write it wins).
1978 neighbours.above_mode[c] = mode;
1979 neighbours.left_mode[r] = mode;
1980 if let Some(uvm) = uv {
1981 neighbours.above_uv_mode[c] = uvm;
1982 neighbours.left_uv_mode[r] = uvm;
1983 }
1984 neighbours.above_side[c] = bw;
1985 neighbours.left_side[r] = bh;
1986 if crate::envflags::env_flag!("EC_INTRA16X4") {
1987 eprintln!(
1988 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
1989 mi_c * MI,
1990 mi_r * MI
1991 );
1992 }
1993 hit_do! {
1994 INTRA16X4_IN_INTER_HITS.with(|h| {
1995 let mut v = h.get();
1996 v[usize::from(!horz)] += 1;
1997 v[2] += usize::from(has_chroma);
1998 h.set(v);
1999 });
2000 }
2001 return Ok(());
2002 }
2003 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
2004 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
2005 // puts BLOCK_128X64/64X128/128X128 in group 3 and
2006 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
2007 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
2008 // block decodes through the very body the KEY FRAME path proves for this
2009 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
2010 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
2011 // `Reach` rule and the frame-edge write clip). The only inter-frame
2012 // differences live inside that body: the mode-info read
2013 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
2014 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
2015 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
2016 // palette (>64) do not exist at this size and are refused by name there.
2017 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
2018 // `intra128_in_inter_witness2.obu` (gate
2019 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
2020 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
2021 // all 15 frames, so the hits are counted out of exact frames (class
2022 // `counter-from-refused-stream`). What r16/r17 could not find, and what
2023 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
2024 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
2025 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
2026 // where the frame EDGE forces it: a partial last superblock row has
2027 // `has_rows128 == false`, so the 128x64 top half is implied, and a
2028 // partial last column implies the 64x128 left half. Put content no
2029 // reference holds (a fresh smooth ramp) in exactly those two bands of an
2030 // inter frame and the encoder codes those forced halves INTRA.
2031 if bw.max(bh) == 128 {
2032 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
2033 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
2034 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
2035 // palette_syntax`), so a 128-root half consumes no palette syntax and
2036 // a screen-content frame's half is syntactically identical to the
2037 // non-screen one this arm already decodes byte-exact.
2038 if coeff_trace_on() {
2039 // lane-t900 r16: which decode-order frame this arm fires in --
2040 // interleaved with the `EC_COEFF_FRAME` markers, this is what
2041 // proves the hit is counted out of a frame that compares exact
2042 // (class `counter-from-refused-stream`).
2043 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
2044 }
2045 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
2046 let res = decode_block_128rect(
2047 dec,
2048 cdfs,
2049 neighbours,
2050 (r, c),
2051 bw,
2052 bh,
2053 y,
2054 u,
2055 v,
2056 base_q_idx,
2057 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
2058 allow_screen_content_tools,
2059 fctx.tx_select_inter.with(std::cell::Cell::get),
2060 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
2061 fctx,
2062 );
2063 fctx.intra_in_inter_mode.with(|c| c.set(None));
2064 return res;
2065 }
2066 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
2067 if crate::envflags::env_flag!("EC_OBMCREC") {
2068 eprintln!(
2069 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
2070 );
2071 }
2072 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
2073 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
2074 // can arrive here are enumerated against the measured block-shape
2075 // census ([`INTER_BLOCK_SHAPES`]) by
2076 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
2077 // -- every one of them has a row, so this arm names a shape no stream
2078 // has been able to present.
2079 return Err(unsupported(format!(
2080 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
2081 )));
2082 };
2083 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
2084 // screen-content frame ("palette syntax is consumed for square blocks
2085 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
2086 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
2087 // it, while the 2:1 reader inlined further down now codes the same syntax
2088 // itself. A real `--tune-content=screen` inter stream reached this refusal
2089 // on 8x16 / 16x8 strips (gate
2090 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
2091 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
2092 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
2093 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
2094 // luma/chroma transform tables, the per-unit split walk and the strip's
2095 // own neighbour records). The ONLY difference on an inter frame is the
2096 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
2097 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
2098 // this caller already read. `tx_cat` above is the same category those
2099 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
2100 // `decode_block_rect64`), asserted here so a future shape cannot drift.
2101 if bw.max(bh) == 4 * bw.min(bh) {
2102 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
2103 fctx.intra_in_inter_mode
2104 .with(|c| c.set(Some((size_group, skip))));
2105 let res = if bw.max(bh) == 64 {
2106 decode_block_rect64(
2107 dec,
2108 cdfs,
2109 neighbours,
2110 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
2111 bw,
2112 bh,
2113 y,
2114 u,
2115 v,
2116 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
2117 allow_screen_content_tools,
2118 base_q_idx,
2119 fctx.tx_select_inter.with(std::cell::Cell::get),
2120 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
2121 fctx,
2122 )
2123 } else {
2124 decode_block_rect4(
2125 dec,
2126 cdfs,
2127 neighbours,
2128 (mi_r, mi_c),
2129 bw,
2130 bh,
2131 None,
2132 y,
2133 u,
2134 v,
2135 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
2136 allow_screen_content_tools,
2137 base_q_idx,
2138 fctx.tx_select_inter.with(std::cell::Cell::get),
2139 fctx,
2140 )
2141 .map(|_| ())
2142 };
2143 fctx.intra_in_inter_mode.with(|c| c.set(None));
2144 res?;
2145 let shape = match (bw, bh) {
2146 (64, 16) => 0,
2147 (16, 64) => 1,
2148 (32, 8) => 2,
2149 _ => 3,
2150 };
2151 hit_do! {
2152 INTRA_RECT4_IN_INTER_HITS.with(|h| {
2153 let mut v = h.get();
2154 v[shape] += 1;
2155 h.set(v);
2156 });
2157 }
2158 return Ok(());
2159 }
2160 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
2161 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
2162 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
2163 // own, so a cross-decoder bisection could only see the block's first
2164 // coefficient. Same names/format as [`read_tx_size`]'s rung.
2165 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
2166 if step_trace {
2167 eprintln!(
2168 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
2169 dec.debug_state().0
2170 );
2171 }
2172 if mode >= 13 {
2173 return Err(unsupported(
2174 "an intra mode this decoder does not code (round 2)",
2175 ));
2176 }
2177 // lane-angleinter (merged on main for the square intra-in-inter arm):
2178 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
2179 // directional predictor; this arm refused a nonzero one before the merge.
2180 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
2181 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
2182 } else {
2183 0
2184 };
2185 if angle_delta_y != 0 {
2186 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
2187 }
2188 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
2189 // superblock-level strip reads the no-CFL alphabet -- the same split
2190 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
2191 //
2192 // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
2193 // (libaom `decodemv.c:933`).
2194 let has_chroma = !mono(fctx);
2195 let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
2196 let uv_mode = if !has_chroma {
2197 DC_PRED
2198 } else if cfl_allowed {
2199 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
2200 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2201 } else {
2202 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
2203 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
2204 };
2205 if step_trace {
2206 eprintln!(
2207 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
2208 u8::from(cfl_allowed),
2209 dec.debug_state().0
2210 );
2211 }
2212 if (9..=12).contains(&uv_mode) {
2213 hit!(SMOOTH_UV_HITS);
2214 }
2215 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
2216 Some(read_cfl_alphas(dec, cdfs))
2217 } else {
2218 None
2219 };
2220 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
2221 DC_PRED
2222 } else {
2223 uv_mode
2224 };
2225 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
2226 hit!(DIRECTIONAL_UV_HITS);
2227 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
2228 } else {
2229 0
2230 };
2231 if angle_delta_uv != 0 {
2232 hit!(UV_ANGLE_DELTA_HITS);
2233 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
2234 }
2235 // `read_palette_mode_info` (spec 5.11.13), in the position
2236 // `read_intra_block_mode_info` writes it: after the chroma mode and
2237 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
2238 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
2239 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
2240 // skipping the syntax here desynced the tile at the strip's own symbol.
2241 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
2242 // context and colour cache at its own mi position, and the two
2243 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
2244 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
2245 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
2246 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
2247 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
2248 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
2249 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
2250 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
2251 let use_palette_y =
2252 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
2253 if use_palette_y {
2254 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
2255 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
2256 }
2257 // A 2:1 strip of at least 8x8 is always a chroma reference, so
2258 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
2259 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
2260 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
2261 let use_palette_uv = has_chroma
2262 && uv_mode == DC_PRED
2263 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
2264 if crate::envflags::env_flag!("EC_PALSYN") {
2265 eprintln!(
2266 "EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
2267 use_palette_y as i32,
2268 use_palette_uv as i32,
2269 dec.debug_state().0
2270 );
2271 }
2272 if use_palette_uv {
2273 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
2274 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
2275 palette_uv_pending = Some((n, u_colors, v_colors));
2276 }
2277 }
2278 // lane-fiinter (merged on main for the square intra-in-inter arm):
2279 // `read_filter_intra_mode_info` is the tail of
2280 // `read_intra_block_mode_info`, after the palette syntax (refused whole
2281 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
2282 // 2:1 strips with both sides <= 32 -- their own CDF rows
2283 // ([`filter_intra_size_class_rect`]).
2284 let mut filter_intra = None;
2285 if mode == DC_PRED
2286 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
2287 // `av1_filter_intra_allowed` excludes a palette-Y block.
2288 && palette_y_pending.is_none()
2289 && let Some(class) = filter_intra_size_class_rect(bw, bh)
2290 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
2291 {
2292 hit!(FILTER_INTRA_HITS);
2293 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
2294 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
2295 }
2296 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
2297 let palette_y = palette_y_pending.map(|(n, colors)| {
2298 let map = decode_color_index_map_wh(
2299 dec,
2300 cdfs,
2301 n,
2302 bw,
2303 bh,
2304 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
2305 false,
2306 );
2307 hit!(PALETTE_HITS);
2308 hit!(PALETTE_RECT_HITS);
2309 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
2310 PaletteY {
2311 size: n,
2312 colors,
2313 map,
2314 }
2315 });
2316 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
2317 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
2318 let on = palette_onscreen_uv(
2319 (bw, bh),
2320 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
2321 (cw, ch),
2322 (ss_x(fctx), ss_y(fctx)),
2323 );
2324 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
2325 hit!(PALETTE_UV_HITS);
2326 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
2327 PaletteUv {
2328 size: n,
2329 u_colors,
2330 v_colors,
2331 map,
2332 }
2333 });
2334 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
2335 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
2336 // chroma ones -- [`decode_block_rect`]'s own pair.
2337 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
2338 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
2339 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
2340 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
2341 // one exactly as [`decode_leaf8`] already does (class
2342 // context-read-from-one-cell).
2343 let coarse_pair = neighbours.modes_above_left(r, c);
2344 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
2345 if (nb_above_mode, nb_left_mode) != coarse_pair {
2346 hit!(EDGE_FILTER_MI_FIX_HITS);
2347 }
2348 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
2349 if smooth_neighbor {
2350 hit!(SMOOTH_LUMA_HITS);
2351 }
2352 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
2353 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
2354 // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside
2355 // an inter frame codes no depth symbol either (`xd->lossless` is per
2356 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
2357 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
2358 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
2359 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
2360 let d = match tx_cat {
2361 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
2362 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
2363 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
2364 };
2365 if step_trace {
2366 eprintln!(
2367 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
2368 dec.debug_state().0
2369 );
2370 }
2371 d
2372 } else {
2373 0
2374 };
2375 if depth != 0 || lossless(fctx) {
2376 hit!(TX_DEPTH_HITS);
2377 // lane-intrasplit r1: a split intra strip in an inter frame walks the
2378 // key frame's own per-TU path ([`decode_rect_split`] below); what was
2379 // wrong when this refusal was written was the depth SYMBOL, not the walk.
2380 hit_do! {
2381 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
2382 let mut v = h.get();
2383 v[depth.min(2)] += 1;
2384 h.set(v);
2385 });
2386 }
2387 }
2388 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
2389 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
2390 // the two are indistinguishable when the diagnostic fires on splits alone.
2391 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
2392 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
2393 }
2394 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
2395 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
2396 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
2397 // of an inter frame, intra ones included -- with the skip term 0 it
2398 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
2399 // and `left_txfm_context` to `tx_size_high` over its height. This strip
2400 // wrote neither, so the next block's var-tx `txfm_partition` context read
2401 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
2402 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
2403 // mi(16,0) and desyncing the tile at that symbol.
2404 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
2405 let modes = RectStripModes {
2406 skip,
2407 mode,
2408 angle_delta_y,
2409 uv_predict_mode,
2410 angle_delta_uv,
2411 alpha,
2412 filter_intra,
2413 smooth_neighbor,
2414 smooth_neighbor_uv,
2415 palette_y: palette_y
2416 .as_ref()
2417 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
2418 palette_uv: palette_uv.as_ref().map(|p| {
2419 (
2420 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
2421 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
2422 )
2423 }),
2424 };
2425 decode_rect_split(
2426 dec,
2427 cdfs,
2428 neighbours,
2429 (mi_r, mi_c),
2430 bw,
2431 bh,
2432 tx_w,
2433 tx_h,
2434 &modes,
2435 y,
2436 u,
2437 v,
2438 base_q_idx,
2439 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
2440 fctx,
2441 )?;
2442 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
2443 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
2444 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
2445 // left column over its height. This arm wrote neither before lane-intrasplit
2446 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
2447 // context across the strip's footprint.
2448 for i in 0..bw / MI {
2449 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
2450 *cell = tx_w as u8;
2451 }
2452 }
2453 for i in 0..bh / MI {
2454 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
2455 *cell = tx_h as u8;
2456 }
2457 }
2458 // The strip's own palette state into the mi-granular neighbour bands, so
2459 // the next block's colour cache and `palette_y_mode` context are libaom's.
2460 record_strip_palette(
2461 neighbours,
2462 (mi_r, mi_c),
2463 bw,
2464 bh,
2465 palette_y.as_ref().map_or(0, |p| p.size),
2466 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
2467 palette_uv.as_ref().map_or(0, |p| p.size),
2468 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
2469 );
2470 let class = match bw.max(bh) {
2471 64 => 0,
2472 32 => 1,
2473 _ => 2,
2474 };
2475 hit_do! {
2476 INTRA_RECT_IN_INTER_HITS.with(|h| {
2477 let mut v = h.get();
2478 v[class] += 1;
2479 h.set(v);
2480 });
2481 }
2482 Ok(())
2483}
2484
2485/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real
2486/// mi `(mi_r, mi_c)` (lane-av1-intrabc).
2487///
2488/// libaom treats an intrabc block as INTER for everything except the mode-info
2489/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA`
2490/// (`blockd.h:373`), so
2491///
2492/// * `parse_decode_block` reads the transform size through the INTER var-tx
2493/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose
2494/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and
2495/// whose leaves publish their own resolved size back;
2496/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT
2497/// frame's own pre-loop-filter reconstruction, at the coded block vector
2498/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`);
2499/// * `decode_token_recon_block`'s inter branch then reads one residual per
2500/// transform unit, through the INTER coefficient sets
2501/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane
2502/// inheriting the colocated luma unit's coded `tx_type`.
2503///
2504/// Text order is libaom's: transform tree, prediction, luma residual, chroma
2505/// residual, bookkeeping. A skipped block codes no residual at all -- the
2506/// prediction is the reconstruction.
2507#[allow(clippy::too_many_arguments)]
2508pub(super) fn decode_intrabc_rect(
2509 dec: &mut SymbolDecoder,
2510 cdfs: &mut Cdfs,
2511 neighbours: &mut Neighbours,
2512 (mi_r, mi_c): (usize, usize),
2513 (bw, bh): (usize, usize),
2514 skip: bool,
2515 (dv_row, dv_col): (i32, i32),
2516 y: &mut PlaneBuf<'static>,
2517 u: &mut PlaneBuf<'static>,
2518 v: &mut PlaneBuf<'static>,
2519 base_q_idx: u8,
2520 fctx: &crate::decode::FrameCtx,
2521) -> Result<()> {
2522 hit!(INTRABC_RECT_HITS);
2523 // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
2524 let idx = usize::from(bh > bw);
2525 if skip {
2526 INTRABC_RECT_SKIPPED_HITS.with(|c| {
2527 let mut seen = c.get();
2528 seen[idx] += 1;
2529 c.set(seen);
2530 });
2531 } else {
2532 INTRABC_RECT_CODED_HITS.with(|c| {
2533 let mut seen = c.get();
2534 seen[idx] += 1;
2535 c.set(seen);
2536 });
2537 }
2538 let (px, py) = (mi_c * MI, mi_r * MI);
2539 // lane-whtshape: a LOSSLESS block's chroma plane block is
2540 // `bw >> ss_x` by `bh >> ss_y` at its own origin -- `av1_get_max_uv_txsize`
2541 // is `ss_size_lookup[bsize]` (no halving of its own), so at 4:4:4 that is
2542 // the block's OWN footprint, not the 4:2:0 halving the lossy arm hard-codes.
2543 // Measured on this lane's 4:4:4 lossless witness: with the halving, a
2544 // 16x8 intrabc block's chroma plane block came out 8x4 and the lossless
2545 // walk below coded 2 units per plane where libaom codes 8.
2546 //
2547 // lane-ibc444c: UNSCOPED now. lane-whtshape split this on `lossless` and
2548 // named the LOSSY 4:4:4 footprint as another lane's open cell; this is
2549 // that cell. Measured on `444_intrabc_rect4_witness.obu`: with the
2550 // halving, an 8x16 luma block's 8x16 chroma plane block was read as ONE
2551 // 4x8 rect unit where libaom codes ONE TX_8X16, and the U `txb_skip` of
2552 // the block at mi (92, 104) read all_zero=0 here against the oracle's
2553 // all_zero=1 -- the bit position forks there. Identical arithmetic at
2554 // 4:2:0, where `ss_x = ss_y = 1`, so the pinned 4:2:0 twin of the
2555 // witness is the identity arm of this lane's gate.
2556 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
2557 // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the
2558 // halved shape's own `max_txsize_rect_lookup` entry IS that size for every
2559 // shape this helper is called at, so the uv plane block is ONE unit --
2560 // the same call `decode_token_recon_block`'s own chroma loop makes.
2561 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
2562 // lane-av1-intrabc r2: the square stride the proven INTER path uses
2563 // (`side`). The residual grids, the prediction windows AND
2564 // `TxParams::stride` are all laid out at it -- the block's own width
2565 // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h`
2566 // exceeds the stride).
2567 let side = bw.max(bh);
2568 let cside = cw.max(ch);
2569 // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right
2570 // or bottom frame edge reads no transform-tree symbol for the units
2571 // outside it.
2572 let mi_cols = 2 * y.true_width.div_ceil(8);
2573 let mi_rows = 2 * y.true_height.div_ceil(8);
2574 let leaves = read_block_tx_size_rect(
2575 dec,
2576 cdfs,
2577 neighbours,
2578 (mi_r, mi_c),
2579 (bw, bh),
2580 (mi_cols, mi_rows),
2581 skip,
2582 fctx,
2583 )?;
2584 if leaves.is_some() {
2585 hit!(INTRABC_RECT_VARTX_HITS);
2586 }
2587 if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
2588 hit!(IBC_RECT_CHROMA_FOOTPRINT_444_HITS);
2589 }
2590 // lane-ibc444c: per-block geometry, for the chroma-tail attribution.
2591 if crate::envflags::env_flag!("EC_IBCBLOCK") {
2592 eprintln!(
2593 "EC_IBCBLOCK mi=({mi_r},{mi_c}) bw={bw} bh={bh} cpx={cpx} cpy={cpy} \
2594 cw={cw} ch={ch} cside={cside} skip={skip}"
2595 );
2596 }
2597 // The whole-block prediction: `predict_inter_block` runs once, before any
2598 // coefficient is read. The source is this frame's own reconstruction,
2599 // which is already written.
2600 // `mc::predict_with_filter` writes a DENSE window; the residual machinery
2601 // reads it at the square stride, so re-lay it -- the same step the inter
2602 // path takes for its own square prediction buffer.
2603 let mut pred_y_dense = vec![0u16; bw * bh];
2604 mc::predict_with_filter(
2605 &y.data,
2606 y.width,
2607 y.true_width,
2608 y.true_height,
2609 mv_to_q4(px, dv_col, 0),
2610 mv_to_q4(py, dv_row, 0),
2611 bw,
2612 bh,
2613 mc::InterpFilterKind::Bilinear,
2614 &mut pred_y_dense,
2615 fctx,
2616 );
2617 let mut pred_y = vec![0u16; side * side];
2618 for row in 0..bh {
2619 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
2620 }
2621 let mut pred_u_dense = vec![0u16; cw * ch];
2622 mc::predict_with_filter(
2623 &u.data,
2624 u.width,
2625 u.true_width,
2626 u.true_height,
2627 mv_to_q4(cpx, dv_col, ss_x(fctx)),
2628 mv_to_q4(cpy, dv_row, ss_y(fctx)),
2629 cw,
2630 ch,
2631 mc::InterpFilterKind::Bilinear,
2632 &mut pred_u_dense,
2633 fctx,
2634 );
2635 let mut pred_u = vec![0u16; cside * cside];
2636 for row in 0..ch {
2637 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
2638 }
2639 let mut pred_v_dense = vec![0u16; cw * ch];
2640 mc::predict_with_filter(
2641 &v.data,
2642 v.width,
2643 v.true_width,
2644 v.true_height,
2645 mv_to_q4(cpx, dv_col, ss_x(fctx)),
2646 mv_to_q4(cpy, dv_row, ss_y(fctx)),
2647 cw,
2648 ch,
2649 mc::InterpFilterKind::Bilinear,
2650 &mut pred_v_dense,
2651 fctx,
2652 );
2653 let mut pred_v = vec![0u16; cside * cside];
2654 for row in 0..ch {
2655 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
2656 }
2657 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
2658 let luma_tx_type: TxType;
2659 let (luma_grid, u_grid, v_grid);
2660 // lane-whtshape: the LOSSLESS chroma walk's composed plane-major grids,
2661 // kept so their per-4x4 slices can be re-stamped over the whole-block
2662 // record in the tail. `None` on every other arm.
2663 let mut ll_chroma: Option<(Vec<i32>, Vec<i32>)> = None;
2664 if skip {
2665 // No residual syntax at all: the prediction IS the block.
2666 // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes
2667 // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip
2668 // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm.
2669 push_mc_rect(
2670 y,
2671 u,
2672 v,
2673 0,
2674 px,
2675 py,
2676 side,
2677 bw,
2678 bh,
2679 Pred::Inline(&pred_y, side),
2680 &ZERO_RESIDUAL[..side * side],
2681 fctx,
2682 );
2683 push_mc_rect(
2684 y,
2685 u,
2686 v,
2687 1,
2688 cpx,
2689 cpy,
2690 cside,
2691 cw,
2692 ch,
2693 Pred::Inline(&pred_u, cside),
2694 &ZERO_RESIDUAL[..cside * cside],
2695 fctx,
2696 );
2697 push_mc_rect(
2698 y,
2699 u,
2700 v,
2701 2,
2702 cpx,
2703 cpy,
2704 cside,
2705 cw,
2706 ch,
2707 Pred::Inline(&pred_v, cside),
2708 &ZERO_RESIDUAL[..cside * cside],
2709 fctx,
2710 );
2711 if let Some(ls) = leaves.as_ref() {
2712 // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s
2713 // skip arm performs -- libaom `av1_reset_entropy_context`
2714 // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a
2715 // SKIPPED block zeroes its whole entropy-band footprint. This
2716 // helper serves `decode_block_rect4`'s 1:4 strips on this tree,
2717 // so a skipped lossless strip whose `leaves` resolved (every
2718 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
2719 // returns the 4x4 grid before it looks at `skip`) left the
2720 // PREVIOUS occupant's luma bands standing and the NEXT block's
2721 // partition parse diverged from libaom's: the 320x242 lossless
2722 // sb128 gate read a phantom unskipped 8x32 intrabc strip at
2723 // mi(56,66) right after the skipped 8x16 one at mi(48,66).
2724 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
2725 for &(row, col, tw, th) in ls {
2726 neighbours.record_mi_luma_rect(
2727 (mi_r + row, mi_c + col),
2728 tw,
2729 th,
2730 &ZERO_RESIDUAL[..tw * th],
2731 );
2732 }
2733 }
2734 luma_tx_type = TxType::DctDct;
2735 luma_grid = Grid::Zero(side * side);
2736 u_grid = Grid::Zero(cside * cside);
2737 v_grid = Grid::Zero(cside * cside);
2738 } else {
2739 match leaves.as_ref() {
2740 None => {
2741 // One whole-block rectangular transform unit.
2742 // lane-av1422mi24: at ss (1,0) the chroma above span is
2743 // `bw >> 1` chroma cells spread over `bw` luma mi columns --
2744 // the per-mi gather counts every chroma column's whole-unit
2745 // dc sign twice (t422 frame 1, the mi(26,60) intra-in-inter
2746 // strip's U dc_sign read ctx 1 where the oracle's cell sum
2747 // is 0 -> ctx 0). Luma keeps the per-mi gather; the two
2748 // chroma planes take
2749 // [`Neighbours::around_mi_422_chroma`]'s every-second
2750 // above-cell sampling, like every other 4:2:2 chroma gather.
2751 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
2752 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
2753 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
2754 around[1] = c[1];
2755 around[2] = c[2];
2756 }
2757 let (grid, tx_type) = read_inter_plane_rect(
2758 dec,
2759 cdfs,
2760 rect_inter_luma_set(bw, bh, fctx)?,
2761 (bw, bh),
2762 side,
2763 0,
2764 around[0],
2765 0,
2766 y,
2767 u,
2768 v,
2769 px,
2770 py,
2771 Pred::Inline(&pred_y, side),
2772 None,
2773 None,
2774 fctx,
2775 )?;
2776 luma_tx_type = tx_type;
2777 luma_grid = embed_grid_stride(&grid, bw, bh, side);
2778 let (ug, _) = read_inter_plane_rect(
2779 dec,
2780 cdfs,
2781 rect_inter_chroma_set(cw, ch)?,
2782 (cw, ch),
2783 cside,
2784 1,
2785 around[1],
2786 0,
2787 y,
2788 u,
2789 v,
2790 cpx,
2791 cpy,
2792 Pred::Inline(&pred_u, cside),
2793 Some(luma_tx_type),
2794 None,
2795 fctx,
2796 )?;
2797 u_grid = embed_grid_stride(&ug, cw, ch, cside);
2798 let (vg, _) = read_inter_plane_rect(
2799 dec,
2800 cdfs,
2801 rect_inter_chroma_set(cw, ch)?,
2802 (cw, ch),
2803 cside,
2804 2,
2805 around[2],
2806 0,
2807 y,
2808 u,
2809 v,
2810 cpx,
2811 cpy,
2812 Pred::Inline(&pred_v, cside),
2813 Some(luma_tx_type),
2814 None,
2815 fctx,
2816 )?;
2817 v_grid = embed_grid_stride(&vg, cw, ch, cside);
2818 }
2819 Some(leaves) => {
2820 // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies
2821 // the split override to LUMA only, per leaf -- the step the
2822 // proven inter var-tx path applies right after its own residual
2823 // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the
2824 // leaf's own transform edges are never filtered.
2825 for &(row, col, tw, th) in leaves.iter() {
2826 neighbours.fill_lf_grid_leaf_luma(
2827 (mi_r + row, mi_c + col),
2828 tw / MI,
2829 th / MI,
2830 tw as u8,
2831 th as u8,
2832 );
2833 }
2834 // One residual per transform unit, in the order the tree coded
2835 // them; each unit reads its own neighbour-magnitude context off
2836 // the units already decoded before it, and every unit adds onto
2837 // its own window of the block's single prediction.
2838 let mut first_tx_type = TxType::DctDct;
2839 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
2840 let tu_mi = (mi_r + row, mi_c + col);
2841 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
2842 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
2843 let (tu_grid, tu_tx_type) = if tw == th {
2844 let scan = default_scan(tw.min(32));
2845 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
2846 read_inter_plane(
2847 dec,
2848 cdfs,
2849 inter_txbset_for(tw, reduced),
2850 scan,
2851 0,
2852 neighbours.around_mi(tu_mi, tw)[0],
2853 0,
2854 y,
2855 u,
2856 v,
2857 tu_px,
2858 tu_py,
2859 tw,
2860 base_q_idx,
2861 tu_pred,
2862 None,
2863 Some(tu_skip_ctx),
2864 fctx,
2865 )?
2866 } else {
2867 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
2868 read_inter_plane_rect(
2869 dec,
2870 cdfs,
2871 rect_inter_luma_set(tw, th, fctx)?,
2872 (tw, th),
2873 side,
2874 0,
2875 neighbours.around_mi_rect(tu_mi, tw, th)[0],
2876 0,
2877 y,
2878 u,
2879 v,
2880 tu_px,
2881 tu_py,
2882 tu_pred,
2883 None,
2884 Some(tu_skip_ctx),
2885 fctx,
2886 )?
2887 };
2888 if idx == 0 {
2889 first_tx_type = tu_tx_type;
2890 }
2891 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
2892 }
2893 // `av1_get_tx_type`'s chroma lookup lands on the colocated
2894 // LUMA unit, which for a split block is the top-left one.
2895 luma_tx_type = first_tx_type;
2896 // lane-av1422mi24: same 4:2:2 chroma gather rule as the
2897 // `None` arm above -- the per-mi rect gather double-counts
2898 // each chroma column's whole-unit dc sign at ss (1,0).
2899 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
2900 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
2901 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
2902 around[1] = c[1];
2903 around[2] = c[2];
2904 }
2905 if lossless(fctx) {
2906 // lane-whtshape: at lossless libaom codes TX_4X4 on EVERY
2907 // plane of a block -- `read_tx_size` returns `TX_4X4` for a
2908 // lossless block before it looks at a tree, `read_tx_mode`
2909 // already forced `ONLY_4X4` for the frame, and
2910 // `get_vartx_max_txsize` returns `TX_4X4` for every plane
2911 // -- so this block's chroma plane block is a
2912 // `(cw/4) * (ch/4)` raster of 4x4 units, PLANE-MAJOR
2913 // (`decode_token_recon_block`: every U unit, then every V
2914 // unit), not the single rect unit the two
2915 // `read_inter_plane_rect` calls below read. That single
2916 // 8x4 unit is what reached the lossless WHT with the wrong
2917 // shape (the `debug_assert_eq!((w, h), (4, 4))` this lane
2918 // replaced). Same helper, same walk, as the inter 8x8 and
2919 // 128 paths.
2920 hit!(INTRABC_RECT_LOSSLESS_CHROMA4_HITS);
2921 let mut uo = vec![0i32; cside * cside];
2922 let mut vo = vec![0i32; cside * cside];
2923 read_inter_chroma_lossless(
2924 y,
2925 u,
2926 v,
2927 dec,
2928 cdfs,
2929 neighbours,
2930 Pred::Inline(&pred_u, cside),
2931 Pred::Inline(&pred_v, cside),
2932 (mi_r, mi_c),
2933 (cpx, cpy),
2934 (0, 0),
2935 (cw, ch),
2936 (cw, ch),
2937 cside,
2938 0,
2939 base_q_idx,
2940 &mut uo,
2941 &mut vo,
2942 fctx,
2943 )?;
2944 // The per-unit walk stamped every unit's own coefficient
2945 // context, but the whole-block `record_split_luma_rect_mi`
2946 // in the tail rewrites every chroma cell with ONE composed
2947 // state, which drops the per-unit DC signs and levels (class
2948 // `override-slot-on-one-arm` -- the same one
2949 // `decode_rect_split`'s `ll_chroma_units` replay exists
2950 // for). The grids are kept here and replayed AFTER that
2951 // record, from the same 4x4 slices, so the same states.
2952 u_grid = embed_grid_stride(&Grid::Own(uo.clone()), cw, ch, cside);
2953 v_grid = embed_grid_stride(&Grid::Own(vo.clone()), cw, ch, cside);
2954 ll_chroma = Some((uo, vo));
2955 luma_grid = Grid::Zero(side * side);
2956 } else {
2957 let (ug, _) = read_inter_plane_rect(
2958 dec,
2959 cdfs,
2960 rect_inter_chroma_set(cw, ch)?,
2961 (cw, ch),
2962 cside,
2963 1,
2964 around[1],
2965 0,
2966 y,
2967 u,
2968 v,
2969 cpx,
2970 cpy,
2971 Pred::Inline(&pred_u, cside),
2972 Some(luma_tx_type),
2973 None,
2974 fctx,
2975 )?;
2976 u_grid = embed_grid_stride(&ug, cw, ch, cside);
2977 let (vg, _) = read_inter_plane_rect(
2978 dec,
2979 cdfs,
2980 rect_inter_chroma_set(cw, ch)?,
2981 (cw, ch),
2982 cside,
2983 2,
2984 around[2],
2985 0,
2986 y,
2987 u,
2988 v,
2989 cpx,
2990 cpy,
2991 Pred::Inline(&pred_v, cside),
2992 Some(luma_tx_type),
2993 None,
2994 fctx,
2995 )?;
2996 v_grid = embed_grid_stride(&vg, cw, ch, cside);
2997 luma_grid = Grid::Zero(side * side);
2998 }
2999 }
3000 }
3001 }
3002 let _ = luma_tx_type;
3003 // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the
3004 // next block reads a neighbour mode, its own block size in both `TXFM`
3005 // bands (already done by `read_block_tx_size_rect`), a zeroed palette
3006 // state (a stale entry would feed the next block's colour cache), and its
3007 // DV into the intrabc mi grid the next block's DV predictor reads.
3008 if leaves.is_some() {
3009 neighbours.record_split_luma_rect_mi(
3010 (mi_r, mi_c),
3011 bw,
3012 bh,
3013 DC_PRED,
3014 DC_PRED,
3015 [&u_grid, &v_grid],
3016 );
3017 } else {
3018 neighbours.record_rect_mi(
3019 (mi_r, mi_c),
3020 bw,
3021 bh,
3022 DC_PRED,
3023 DC_PRED,
3024 &[&luma_grid, &u_grid, &v_grid],
3025 );
3026 }
3027 // lane-whtshape: replay the LOSSLESS walk's per-4x4 chroma states over
3028 // the whole-block record above, so the NEXT block reads the per-unit DC
3029 // signs and levels libaom's plane-major walk left behind instead of one
3030 // composed state for the whole plane block.
3031 if let Some((uo, vo)) = ll_chroma {
3032 for (plane_idx, comp) in [(1usize, &uo), (2, &vo)] {
3033 for ur in 0..ch / 4 {
3034 for uc in 0..cw / 4 {
3035 let mut unit = Vec::with_capacity(16);
3036 for r in 0..4 {
3037 unit.extend_from_slice(&comp[(ur * 4 + r) * cside + uc * 4..][..4]);
3038 }
3039 neighbours.record_mi_chroma(
3040 // lane-av1lm444loss-corr: the MI STEP between chroma
3041 // units is that same footprint expressed in luma mi
3042 // cells, `(4 << ss) / MI` -- which is exactly what
3043 // `decode_inter_block`'s reference `mu_chroma_units`
3044 // construction writes (decode.rs:43688,
3045 // `at.0 + cr * ((cu << ss_y(fctx)) / MI)` with
3046 // `cu = 4` on a lossless frame). The `4 >> ss_y` form
3047 // this replaces is 4:2:0-only arithmetic that happens
3048 // to agree there: at ss (1,1) it is `4 >> 1` = 2 mi
3049 // and the footprint form is `(4 << 1) / 4` = 2 mi, the
3050 // SAME value, so 4:2:0 is unchanged by construction.
3051 // At ss (0,0) it is `4 >> 0` = 4 mi -- four luma mi
3052 // (16 luma px) per 4x4 chroma unit, where a TX_4X4
3053 // chroma unit covers `4 << 0` = 4 luma px = ONE mi.
3054 // The step therefore lands every replayed unit at 4x
3055 // its own mi row/column on a 4:4:4 lossless frame, and
3056 // the whole block's per-unit states are stamped over
3057 // cells that belong to other blocks (or to nothing).
3058 (
3059 mi_r + ur * ((4 << ss_y(fctx)) / MI),
3060 mi_c + uc * ((4 << ss_x(fctx)) / MI),
3061 ),
3062 4 << ss_x(fctx),
3063 4 << ss_y(fctx),
3064 plane_idx,
3065 &Grid::Own(unit),
3066 );
3067 }
3068 }
3069 }
3070 }
3071 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
3072 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
3073 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
3074 // lane-av1oddheightfork3: `read_block_tx_size_rect` ran above, so the
3075 // bands are the tree's own per-leaf publication (libaom's var-tx branch
3076 // never calls `set_txfm_ctxs`) -- publishing the block's own size over
3077 // them here is the defect this call site carried.
3078 neighbours.fill_lf_grid_rect_after_vartx(
3079 (mi_r, mi_c),
3080 bw / MI,
3081 bh / MI,
3082 bw.min(64) as u8,
3083 bh.min(64) as u8,
3084 0,
3085 fctx,
3086 );
3087 record_intrabc_mi_rect(
3088 mi_r,
3089 mi_c,
3090 bw / MI,
3091 bh / MI,
3092 Some((dv_row, dv_col)),
3093 neighbours,
3094 fctx,
3095 );
3096 Ok(())
3097}
3098
3099/// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root
3100/// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape
3101/// `decode_block_128rect` refused by name before this port. libaom decodes
3102/// such a block through the INTER machinery (an intrabc block
3103/// `is_inter_block`): `predict_inter_block` copies the whole block from this
3104/// frame's own reconstruction at the integer block vector once, then
3105/// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks --
3106/// per chunk every plane, luma units at the block's own resolved transform
3107/// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at
3108/// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per
3109/// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits
3110/// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`,
3111/// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in
3112/// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here.
3113#[allow(clippy::too_many_arguments)]
3114pub(super) fn decode_intrabc_128rect(
3115 dec: &mut SymbolDecoder,
3116 cdfs: &mut Cdfs,
3117 neighbours: &mut Neighbours,
3118 (mi_r, mi_c): (usize, usize),
3119 (bw, bh): (usize, usize),
3120 skip: bool,
3121 (dv_row, dv_col): (i32, i32),
3122 y: &mut PlaneBuf<'static>,
3123 u: &mut PlaneBuf<'static>,
3124 v: &mut PlaneBuf<'static>,
3125 base_q_idx: u8,
3126 fctx: &crate::decode::FrameCtx,
3127) -> Result<()> {
3128 hit!(INTRABC_128RECT_HITS);
3129 if crate::envflags::env_flag!("EC_AV1_TRACE") {
3130 let (rng, _) = dec.debug_state();
3131 eprintln!(
3132 "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}"
3133 );
3134 }
3135 let (px, py) = (mi_c * MI, mi_r * MI);
3136 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis
3137 // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's
3138 // `mv_to_q4(cpy, dv_row, ss_y(fctx))` calls two lines below already
3139 // scaled the DV on the y axis by ITS OWN subsampling, so the hardcoded
3140 // `/2` origin and extent made the prediction window half as tall as
3141 // the motion vector asked for), 4:2:2 is HALF-WIDTH and FULL-HEIGHT,
3142 // 4:4:4 is luma-sized. At ss (1,1) every value below is the old
3143 // `bw / 2, bh / 2` line-for-line.
3144 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
3145 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
3146 // The square strides the proven INTER path lays its residual grids,
3147 // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2
3148 // note): 128/64 here.
3149 let side = bw.max(bh);
3150 let cside = cw.max(ch);
3151 // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code
3152 // nothing (`decode_reconstruct_tx`'s max_blocks_* early return).
3153 let mi_cols = 2 * y.true_width.div_ceil(8);
3154 let mi_rows = 2 * y.true_height.div_ceil(8);
3155 // An intrabc block is is_inter_block: the tx tree is the INTER one, and
3156 // [`read_block_tx_size_rect`]'s 128-root branch already carries the
3157 // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree
3158 // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid)
3159 // arms (lane-sb128c r7).
3160 let leaves = read_block_tx_size_rect(
3161 dec,
3162 cdfs,
3163 neighbours,
3164 (mi_r, mi_c),
3165 (bw, bh),
3166 (mi_cols, mi_rows),
3167 skip,
3168 fctx,
3169 )?;
3170 // Whole-block prediction, once, before any coefficient is read
3171 // (`predict_inter_block`); the source is this frame's own
3172 // reconstruction, including the writes this superblock has queued.
3173 let mut pred_y_dense = vec![0u16; bw * bh];
3174 mc::predict_with_filter(
3175 &y.data,
3176 y.width,
3177 y.true_width,
3178 y.true_height,
3179 mv_to_q4(px, dv_col, 0),
3180 mv_to_q4(py, dv_row, 0),
3181 bw,
3182 bh,
3183 mc::InterpFilterKind::Bilinear,
3184 &mut pred_y_dense,
3185 fctx,
3186 );
3187 let mut pred_y = vec![0u16; side * side];
3188 for row in 0..bh {
3189 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
3190 }
3191 let mut pred_u_dense = vec![0u16; cw * ch];
3192 mc::predict_with_filter(
3193 &u.data,
3194 u.width,
3195 u.true_width,
3196 u.true_height,
3197 mv_to_q4(cpx, dv_col, ss_x(fctx)),
3198 mv_to_q4(cpy, dv_row, ss_y(fctx)),
3199 cw,
3200 ch,
3201 mc::InterpFilterKind::Bilinear,
3202 &mut pred_u_dense,
3203 fctx,
3204 );
3205 let mut pred_u = vec![0u16; cside * cside];
3206 for row in 0..ch {
3207 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
3208 }
3209 let mut pred_v_dense = vec![0u16; cw * ch];
3210 mc::predict_with_filter(
3211 &v.data,
3212 v.width,
3213 v.true_width,
3214 v.true_height,
3215 mv_to_q4(cpx, dv_col, ss_x(fctx)),
3216 mv_to_q4(cpy, dv_row, ss_y(fctx)),
3217 cw,
3218 ch,
3219 mc::InterpFilterKind::Bilinear,
3220 &mut pred_v_dense,
3221 fctx,
3222 );
3223 let mut pred_v = vec![0u16; cside * cside];
3224 for row in 0..ch {
3225 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
3226 }
3227 let (luma_grid, u_grid, v_grid);
3228 // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour
3229 // contexts per transform unit -- the replay after this fn's end-of-block
3230 // record restores them (the record itself re-stamps both planes with ONE
3231 // composed state, class `override-slot-on-one-arm`).
3232 let mut mu_chroma = false;
3233 if skip {
3234 // No residual syntax at all: the prediction IS the block. Strides are
3235 // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes
3236 // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun).
3237 push_mc_rect(
3238 y,
3239 u,
3240 v,
3241 0,
3242 px,
3243 py,
3244 side,
3245 bw,
3246 bh,
3247 Pred::Inline(&pred_y, side),
3248 &ZERO_RESIDUAL[..side * side],
3249 fctx,
3250 );
3251 push_mc_rect(
3252 y,
3253 u,
3254 v,
3255 1,
3256 cpx,
3257 cpy,
3258 cside,
3259 cw,
3260 ch,
3261 Pred::Inline(&pred_u, cside),
3262 &ZERO_RESIDUAL[..cside * cside],
3263 fctx,
3264 );
3265 push_mc_rect(
3266 y,
3267 u,
3268 v,
3269 2,
3270 cpx,
3271 cpy,
3272 cside,
3273 cw,
3274 ch,
3275 Pred::Inline(&pred_v, cside),
3276 &ZERO_RESIDUAL[..cside * cside],
3277 fctx,
3278 );
3279 if let Some(ls) = leaves.as_ref() {
3280 // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4
3281 // grid before it looks at `skip`; the skipped block still zeroes
3282 // its entropy-band footprint over every unit (libaom
3283 // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) --
3284 // the same arm [`decode_intrabc_rect`]'s loss64 merge added.
3285 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
3286 for &(row, col, tw, th) in ls {
3287 neighbours.record_mi_luma_rect(
3288 (mi_r + row, mi_c + col),
3289 tw,
3290 th,
3291 &ZERO_RESIDUAL[..tw * th],
3292 );
3293 }
3294 }
3295 luma_grid = Grid::Zero(side * side);
3296 u_grid = Grid::Zero(cside * cside);
3297 v_grid = Grid::Zero(cside * cside);
3298 } else {
3299 let leaves = leaves
3300 .expect("read_block_tx_size_rect returns None only for skip below 128 at this shape");
3301 // libaom `get_transform_size`'s split override applies to LUMA only,
3302 // per leaf -- each unit's own transform edges get filtered
3303 // ([`decode_intrabc_rect`]'s P2, the proven inter path's step).
3304 for &(row, col, tw, th) in leaves.iter() {
3305 neighbours.fill_lf_grid_leaf_luma(
3306 (mi_r + row, mi_c + col),
3307 tw / MI,
3308 th / MI,
3309 tw as u8,
3310 th as u8,
3311 );
3312 }
3313 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
3314 let mut u_units: Vec<i32> = Vec::new();
3315 let mut v_units: Vec<i32> = Vec::new();
3316 let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new();
3317 // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose
3318 // top-left sample is outside the frame codes nothing.
3319 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
3320 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
3321 // lane-av1h5: chunk-major token order at 128 (see [`mu_chunk_order`]).
3322 let (order, _mu_reordered) = mu_chunk_order(&leaves, side);
3323 for (pos, &idx) in order.iter().enumerate() {
3324 let (row, col, tw, th) = leaves[idx];
3325 debug_assert_eq!(
3326 tw, th,
3327 "a square TX_64X64 tree root only yields square leaves"
3328 );
3329 let tu_mi = (mi_r + row, mi_c + col);
3330 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
3331 if tu_px >= y.true_width || tu_py >= y.true_height {
3332 continue;
3333 }
3334 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
3335 let scan = default_scan(tw.min(32));
3336 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
3337 let (tu_grid, tu_tx_type) = read_inter_plane(
3338 dec,
3339 cdfs,
3340 inter_txbset_for(tw, reduced),
3341 scan,
3342 0,
3343 neighbours.around_mi(tu_mi, tw)[0],
3344 0,
3345 y,
3346 u,
3347 v,
3348 tu_px,
3349 tu_py,
3350 tw,
3351 base_q_idx,
3352 tu_pred,
3353 None,
3354 Some(tu_skip_ctx),
3355 fctx,
3356 )?;
3357 leaf_tx_types.push((row, col, tw, th, tu_tx_type));
3358 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
3359 // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64
3360 // mu chunk before the next one starts: once this chunk's leaves
3361 // are done, its chroma is read immediately (the inter 128 path's
3362 // interleave).
3363 let chunk = (row / 16, col / 16);
3364 let done = pos + 1 == order.len()
3365 || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 1]].1 / 16) != chunk;
3366 if done {
3367 let (cr, cc) = chunk;
3368 // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one
3369 // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster
3370 // within the chunk, plane-major inside the chunk.
3371 let cu_tx = 32usize;
3372 // lane-av1-ibc128chunk: a 64x64 mu chunk's chroma plane
3373 // block is PER-AXIS `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at
3374 // 4:2:0, TWO STACKED TX_32X32 at 4:2:2 (the chunk's chroma
3375 // plane block is 32x64 there), four at 4:4:4. The old
3376 // `chunk_chroma = cside * 64 / side` walked a
3377 // `chroma_side`-SQUARE chunk, i.e. the 4:2:0 count on both
3378 // axes: at 4:2:2 it read HALF the chroma units of a chunk
3379 // (one 32x32 at the chunk's top-left instead of two), left
3380 // the chunk's lower 32 chroma rows with no residual at all,
3381 // and stamped every unit's entropy context over a 16x16-mi
3382 // luma span instead of 16x8. The same defect and the same
3383 // per-axis repair as `decode_inter_block`'s
3384 // `chunk_chroma_w/chunk_chroma_h` (lane-av1-422bigblock,
3385 // witnessed on `422_sb128_3f.obu`).
3386 let chunk_chroma_w = (64usize) >> ss_x(fctx);
3387 let chunk_chroma_h = (64usize) >> ss_y(fctx);
3388 // The unit's own footprint on the LUMA mi grid, per axis:
3389 // `(32 << ss) px` = `(32 << ss) / MI` mi -- 16x16 at 4:2:0,
3390 // 16x8 at 4:2:2, 8x8 at 4:4:4. `around_mi_rect` reads and
3391 // `record_mi_chroma` stamp exactly the unit's own cells.
3392 let unit_luma_w = cu_tx << ss_x(fctx);
3393 let unit_luma_h = cu_tx << ss_y(fctx);
3394 INTRABC_128RECT_CHUNK_SHAPE.with(|c| {
3395 c.set((chunk_chroma_w << 8) | chunk_chroma_h);
3396 });
3397 let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16));
3398 let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16));
3399 let units_x = chunk_w_mi / (unit_luma_w / MI);
3400 let units_y = chunk_h_mi / (unit_luma_h / MI);
3401 if lossless(fctx) {
3402 // TX_4X4 chroma units over this chunk (lane-lossless2's
3403 // walk, shared with the inter 128 path).
3404 read_inter_chroma_lossless(
3405 y,
3406 u,
3407 v,
3408 dec,
3409 cdfs,
3410 neighbours,
3411 Pred::Inline(&pred_u, cside),
3412 Pred::Inline(&pred_v, cside),
3413 (mi_r, mi_c),
3414 (cpx, cpy),
3415 (cc * chunk_chroma_w, cr * chunk_chroma_h),
3416 (chunk_chroma_w, chunk_chroma_h),
3417 (cw, ch),
3418 cside,
3419 0,
3420 base_q_idx,
3421 &mut u_units,
3422 &mut v_units,
3423 fctx,
3424 )?;
3425 // lane-av1-ibcrect: read_inter_chroma_lossless stamped
3426 // every TX_4X4 unit's own context (`record_mi_chroma`
3427 // inside the walk) -- the end-of-block record below must
3428 // not overwrite them with the composed grid (the inter
3429 // 128 path sets the same flag on this arm).
3430 mu_chroma = true;
3431 continue;
3432 }
3433 let cu_scan = default_scan(cu_tx);
3434 for plane_idx in 1..3 {
3435 let src = if plane_idx == 1 {
3436 Pred::Inline(&pred_u, cside)
3437 } else {
3438 Pred::Inline(&pred_v, cside)
3439 };
3440 for ur in 0..units_y {
3441 for uc in 0..units_x {
3442 let unit_mi = (
3443 mi_r + cr * 16 + ur * (unit_luma_h / MI),
3444 mi_c + cc * 16 + uc * (unit_luma_w / MI),
3445 );
3446 // Per unit, AFTER the earlier units' stamps: this
3447 // unit's coefficient context must see them.
3448 //
3449 // lane-av1muchunk422sym: same 4:2:2 pair rule as
3450 // `decode_inter_block`'s mu-chunk walk -- at ss
3451 // (1, 0) one CHROMA column spans two luma mi
3452 // columns, so the plain rect gather doubles the
3453 // above dc vote and flips `dc_sign_ctx` whenever
3454 // above and left cancel.
3455 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
3456 neighbours.around_mi_422_chroma(unit_mi, unit_luma_w, unit_luma_h)
3457 } else {
3458 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h)
3459 };
3460 if crate::envflags::env_flag!("EC_ECDUMP") {
3461 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
3462 #[allow(clippy::needless_range_loop)]
3463 for p in 1..3 {
3464 let ab: Vec<String> = (0..unit_luma_w / MI)
3465 .map(|k| {
3466 format!(
3467 "{:?}/{}",
3468 neighbours.above[unit_mi.1 + k][p].dc,
3469 neighbours.above[unit_mi.1 + k][p].level
3470 )
3471 })
3472 .collect();
3473 let lf: Vec<String> = (0..unit_luma_h / MI)
3474 .map(|k| {
3475 format!(
3476 "{:?}/{}",
3477 neighbours.left[unit_mi.0 + k][p].dc,
3478 neighbours.left[unit_mi.0 + k][p].level
3479 )
3480 })
3481 .collect();
3482 eprintln!(
3483 "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]",
3484 cu_around[p].0,
3485 cu_around[p].1,
3486 cu_around[p].2,
3487 ab.join(","),
3488 lf.join(",")
3489 );
3490 }
3491 }
3492 let (cu_x, cu_y) = (
3493 cpx + cc * chunk_chroma_w + uc * cu_tx,
3494 cpy + cr * chunk_chroma_h + ur * cu_tx,
3495 );
3496 // `av1_get_tx_type` (blockd.h:1291): an inter
3497 // block's chroma unit never codes a tx_type; it
3498 // inherits the coded type of the luma leaf
3499 // covering its own quadrant (all of this chunk's
3500 // leaves are read by now).
3501 let unit_rel_mi = (unit_mi.0 - mi_r, unit_mi.1 - mi_c);
3502 let covering = covering_leaf_tx_type(&leaf_tx_types, unit_rel_mi);
3503 // The prediction window is the block's own square
3504 // `cside` buffer with the unit's true per-axis
3505 // position inside it.
3506 let cu_pred = src.offset(
3507 (cr * chunk_chroma_h + ur * cu_tx) * cside
3508 + cc * chunk_chroma_w
3509 + uc * cu_tx,
3510 );
3511 let cu_grid = read_inter_plane(
3512 dec,
3513 cdfs,
3514 TxbSet::Chroma32,
3515 cu_scan,
3516 plane_idx,
3517 cu_around[plane_idx],
3518 0,
3519 y,
3520 u,
3521 v,
3522 cu_x,
3523 cu_y,
3524 cu_tx,
3525 base_q_idx,
3526 cu_pred,
3527 Some(covering.unwrap_or(TxType::DctDct)),
3528 Some(3),
3529 fctx,
3530 )?
3531 .0;
3532 // Immediately, so the NEXT unit reads this one's
3533 // coefficient context.
3534 neighbours.record_mi_chroma(
3535 unit_mi,
3536 unit_luma_w,
3537 unit_luma_h,
3538 plane_idx,
3539 &cu_grid,
3540 );
3541 if crate::envflags::env_flag!("EC_ECDUMP") {
3542 let st = crate::decode::neighbour_state(&cu_grid);
3543 eprintln!(
3544 "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})",
3545 st.dc, st.level
3546 );
3547 }
3548 hit!(CHROMA_SPLIT_TX_HITS);
3549 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(c.get() + 1));
3550 // lane-av1-ibcrect: per-unit chroma context -- the
3551 // end-of-block record's composed-grid re-stamp
3552 // must not stand (replayed below).
3553 mu_chroma = true;
3554 let dst = mu_units(
3555 if plane_idx == 1 {
3556 &mut u_units
3557 } else {
3558 &mut v_units
3559 },
3560 cside * cside,
3561 );
3562 for rr in 0..cu_tx {
3563 let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * cside
3564 + cc * chunk_chroma_w
3565 + uc * cu_tx;
3566 dst[start..start + cu_tx]
3567 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
3568 }
3569 }
3570 }
3571 }
3572 }
3573 }
3574 // The block-level luma bands were recorded per leaf above; the
3575 // composed chroma grids carry every unit in place.
3576 luma_grid = Grid::Zero(side * side);
3577 u_grid = if u_units.is_empty() {
3578 Grid::Zero(cside * cside)
3579 } else {
3580 Grid::Own(std::mem::take(&mut u_units))
3581 };
3582 v_grid = if v_units.is_empty() {
3583 Grid::Zero(cside * cside)
3584 } else {
3585 Grid::Own(std::mem::take(&mut v_units))
3586 };
3587 }
3588 // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a
3589 // neighbour reads a mode, zeroed palette state, the skip grid, the
3590 // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them),
3591 // and the DV into the intrabc mi grid.
3592 if skip {
3593 neighbours.record_rect_mi(
3594 (mi_r, mi_c),
3595 bw,
3596 bh,
3597 DC_PRED,
3598 DC_PRED,
3599 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
3600 );
3601 } else {
3602 neighbours.record_split_luma_rect_mi(
3603 (mi_r, mi_c),
3604 bw,
3605 bh,
3606 DC_PRED,
3607 DC_PRED,
3608 [&u_grid[..], &v_grid[..]],
3609 );
3610 }
3611 // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER
3612 // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside
3613 // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps
3614 // both planes with ONE `neighbour_state(composed_grid)` over the whole
3615 // span -- level = the SUM of every unit's levels and dc = the top-left
3616 // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128
3617 // inter block: the next block read a stale `dc_sign_ctx` one row low).
3618 // Measured on this shape: the 128x64 block at mi(64,32) of the
3619 // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared
3620 // into chunk-0's cells and the block below read `txb_skip` off the sum.
3621 // Replay every coded unit's own state after the record, in mu-chunk order
3622 // so a later unit still wins over an earlier one on the shared seam cells
3623 // (the composed construction `mu_chroma_units` uses, transcribed here).
3624 if mu_chroma {
3625 let cu = if lossless(fctx) { 4usize } else { 32usize };
3626 // The unit's own footprint on the LUMA mi grid (the chroma context
3627 // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s
3628 // convention), PER AXIS: `cu << ss` px, i.e. 8 px per TX_4x4 unit and
3629 // 64 px per TX_32X32 one at 4:2:0 -- 4 px / 32 px at 4:2:2.
3630 let unit_luma_w = cu << ss_x(fctx);
3631 let unit_luma_h = cu << ss_y(fctx);
3632 // A 64x64 mu chunk's chroma plane block is PER-AXIS
3633 // `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at 4:2:0 (ONE TX_32X32 per
3634 // chunk), 32x64 at 4:2:2 (TWO STACKED), 64x64 at 4:4:4 (FOUR);
3635 // `av1_get_max_uv_txsize` caps the unit at 32 on each axis.
3636 let chunk_chroma_w = (64usize) >> ss_x(fctx);
3637 let chunk_chroma_h = (64usize) >> ss_y(fctx);
3638 if lossless(fctx) {
3639 // lane-av1-ibc128chunk, PRE-EXISTING and NOT this lane's: on a
3640 // LOSSLESS frame `cu` is 4 and the composed plane grid is a raster
3641 // of TX_4x4 units, not a `cu`-per-chunk tiling -- so `rows`/`cols`
3642 // below (which count mu CHUNKS at the 4:2:0 chunk extent) do not
3643 // enumerate it, and this arm re-stamps only the 4x4 at each
3644 // chunk's top-left with a 2x2-mi span. The twin
3645 // (`decode_inter_block`'s `mu_chroma_units`, lane-av1-llinter)
3646 // instead raster-walks the WHOLE plane block at `cu` steps, and
3647 // that is the correct shape here too. It is left as-is on purpose:
3648 // it is a 4:2:0 defect, not a subsampling square-cut, and fixing
3649 // it would change 4:2:0 LOSSLESS output -- which this lane's
3650 // byte-identity requirement forbids doing on an unverified
3651 // reconstruction. Measured unreachability: this arm is entered
3652 // 0 times by the whole `lossless` and `intrabc` gate battery
3653 // (temporary env-gated counter in the arm). Unblock: one
3654 // lossless sb128 4:2:0 stream coding a NON-SKIP 128-root
3655 // intrabc strip (`--lossless=1 --sb-size=128
3656 // --min-partition-size=64 --enable-rect-partitions=1
3657 // --enable-intrabc=1` over near-match screen content).
3658 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
3659 for cr in 0..rows {
3660 for cc in 0..cols {
3661 let unit_mi = (
3662 mi_r + cr * (unit_luma_h / MI),
3663 mi_c + cc * (unit_luma_w / MI),
3664 );
3665 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
3666 let mut unit = Vec::with_capacity(cu * cu);
3667 for rr in 0..cu {
3668 let start = (cr * chunk_chroma_h + rr) * cside + cc * chunk_chroma_w;
3669 unit.extend_from_slice(&grid[start..start + cu]);
3670 }
3671 neighbours.record_mi_chroma(
3672 unit_mi,
3673 unit_luma_w,
3674 unit_luma_h,
3675 plane_idx,
3676 &unit,
3677 );
3678 }
3679 }
3680 }
3681 } else {
3682 // The chunk count on each axis, then EVERY unit inside each
3683 // chunk at its own mi origin, its own `(cu << ss)`-px entropy-cell
3684 // span, and its own quadrant of the composed plane grid -- the
3685 // twin's loop (decode_inter_block's `mu_chroma_units`,
3686 // lane-av1-444 c8). lane-av1-ibc128chunk: the loop used to count
3687 // mu CHUNKS in `rows`/`cols` and then step the mi origin and read
3688 // the grid PER UNIT, which only agrees when a chunk holds exactly
3689 // one unit. At 4:2:0 (`chunk_chroma == cu`) it is
3690 // line-identical to the old walk; at 4:2:2 and 4:4:4 a chunk holds
3691 // 2 or 4, so the old body reached only the first of the stacked
3692 // units and the rest of the chunk kept the composed-grid smearing
3693 // this replay exists to undo. A unit the frame edge clipped codes
3694 // nothing and carries no composed samples beyond the clip, so it
3695 // replays as the zero state exactly like libaom's uncoded unit.
3696 let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);
3697 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
3698 for cr in 0..rows {
3699 for cc in 0..cols {
3700 for kr in 0..ur {
3701 for kc in 0..uc {
3702 let unit_mi = (
3703 mi_r + (cr * 64 + kr * unit_luma_h) / MI,
3704 mi_c + (cc * 64 + kc * unit_luma_w) / MI,
3705 );
3706 let (cy, cx) =
3707 (cr * chunk_chroma_h + kr * cu, cc * chunk_chroma_w + kc * cu);
3708 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
3709 let mut unit = Vec::with_capacity(cu * cu);
3710 for rr in 0..cu {
3711 let start = (cy + rr) * cside + cx;
3712 unit.extend_from_slice(&grid[start..start + cu]);
3713 }
3714 neighbours.record_mi_chroma(
3715 unit_mi,
3716 unit_luma_w,
3717 unit_luma_h,
3718 plane_idx,
3719 &unit,
3720 );
3721 }
3722 }
3723 }
3724 }
3725 }
3726 }
3727 }
3728 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
3729 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
3730 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
3731 // lane-av1oddheightfork3: see `decode_intrabc_rect`'s call -- the tree
3732 // published the bands, so no whole-footprint publish here.
3733 neighbours.fill_lf_grid_rect_after_vartx(
3734 (mi_r, mi_c),
3735 bw / MI,
3736 bh / MI,
3737 bw.min(64) as u8,
3738 bh.min(64) as u8,
3739 0,
3740 fctx,
3741 );
3742 record_intrabc_mi_rect(
3743 mi_r,
3744 mi_c,
3745 bw / MI,
3746 bh / MI,
3747 Some((dv_row, dv_col)),
3748 neighbours,
3749 fctx,
3750 );
3751 Ok(())
3752}
3753
3754/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
3755/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
3756/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
3757/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
3758/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
3759/// has no rectangular-transform coefficient reader, and a chroma plane here
3760/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
3761/// with no depth-based square-tiling escape the way luma's own resolved
3762/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
3763/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
3764#[allow(clippy::too_many_arguments)]
3765pub(super) fn decode_block_rect(
3766 dec: &mut SymbolDecoder,
3767 cdfs: &mut Cdfs,
3768 neighbours: &mut Neighbours,
3769 at: (usize, usize),
3770 bw: usize,
3771 bh: usize,
3772 y: &mut PlaneBuf<'static>,
3773 u: &mut PlaneBuf<'static>,
3774 v: &mut PlaneBuf<'static>,
3775 enable_filter_intra: bool,
3776 allow_screen_content_tools: bool,
3777 base_q_idx: u8,
3778 tx_select: bool,
3779 reduced_tx_set: bool,
3780 fctx: &crate::decode::FrameCtx,
3781) -> Result<()> {
3782 let (r, c) = at;
3783 let (px, py) = (c * SUB, r * SUB);
3784 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
3785 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
3786 let palette_uv_cache = neighbours.palette_uv_cache(at);
3787 let (
3788 skip,
3789 mode,
3790 angle_delta_y,
3791 uv_mode,
3792 angle_delta_uv,
3793 alpha,
3794 filter_intra,
3795 palette_y,
3796 palette_uv,
3797 intrabc,
3798 ) = read_intra_mode_rect(
3799 dec,
3800 cdfs,
3801 nb_above_mode,
3802 nb_left_mode,
3803 true,
3804 true,
3805 bw,
3806 bh,
3807 enable_filter_intra,
3808 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
3809 allow_screen_content_tools,
3810 Some((palette_ctx, &palette_cache)),
3811 &palette_uv_cache,
3812 r * (SUB / MI),
3813 c * (SUB / MI),
3814 fctx,
3815 )?;
3816
3817 if let Some((dv_row, dv_col)) = intrabc {
3818 return decode_intrabc_rect(
3819 dec,
3820 cdfs,
3821 neighbours,
3822 (r * (SUB / MI), c * (SUB / MI)),
3823 (bw, bh),
3824 skip,
3825 (dv_row, dv_col),
3826 y,
3827 u,
3828 v,
3829 base_q_idx,
3830 fctx,
3831 );
3832 }
3833 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
3834 if smooth_neighbor {
3835 hit!(SMOOTH_LUMA_HITS);
3836 }
3837 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
3838 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
3839 // `uv_mode`, not the luma one.
3840 let smooth_neighbor_uv =
3841 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
3842 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
3843 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
3844 // rectangle just as happily), so a `use_filter_intra` strip at this level
3845 // predicts instead of refusing. The below-16x16 leaf arm
3846 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
3847 if filter_intra.is_some() {
3848 hit!(FILTER_INTRA_RECT_HITS);
3849 }
3850 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3851 DC_PRED
3852 } else {
3853 uv_mode
3854 };
3855 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3856 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
3857 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
3858 // one did not, so with `--enable-tx-size-search=0` -- which several gate
3859 // recipes use -- the decoder consumed a symbol the encoder never wrote and
3860 // desynced the tile from that point on. That is why both strips of the
3861 // pinned HORZ quadrant were wrong from their very first pixel, and why our
3862 // range after the read equalled the oracle's range for the whole block.
3863 // lane-av1mixloss: the lossless-segment early return
3864 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment
3865 // rect block codes no depth symbol here either (class sweep of the sub8
3866 // leaf's fix).
3867 let depth = if tx_select && !lossless(fctx) {
3868 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
3869 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
3870 // intra-only frame publishes them from every block too
3871 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
3872 // 1920x792 128-superblock stream,
3873 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
3874 // `tx_size_cat2` row 1 where libaom reads row 2.
3875 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
3876 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
3877 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
3878 eprintln!(
3879 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
3880 dec.debug_state().0
3881 );
3882 }
3883 d
3884 } else {
3885 0
3886 };
3887 // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame
3888 // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
3889 publish_txfm_bands_if_in_inter(
3890 neighbours,
3891 (mi_r, mi_c),
3892 depth_to_tx_wh(bw, bh, depth, fctx),
3893 (bw, bh),
3894 fctx,
3895 );
3896 if depth != 0 || lossless(fctx) {
3897 hit!(TX_DEPTH_HITS);
3898 // lane-rectsplit r1: a split transform is predicted and reconstructed
3899 // per transform unit, each unit taking its edges from the previous
3900 // unit's reconstruction inside this same strip (spec 5.11.36) --
3901 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
3902 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
3903 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
3904 eprintln!(
3905 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
3906 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
3907 angle_y={angle_delta_y}"
3908 );
3909 }
3910 let modes = RectStripModes {
3911 skip,
3912 mode,
3913 angle_delta_y,
3914 uv_predict_mode,
3915 angle_delta_uv,
3916 alpha,
3917 filter_intra,
3918 smooth_neighbor,
3919 smooth_neighbor_uv,
3920 palette_y: palette_y
3921 .as_ref()
3922 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
3923 palette_uv: palette_uv.as_ref().map(|p| {
3924 (
3925 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
3926 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
3927 )
3928 }),
3929 };
3930 if palette_y.is_some() || palette_uv.is_some() {
3931 hit!(PALETTE_SPLIT_TX_HITS);
3932 }
3933 decode_rect_split(
3934 dec,
3935 cdfs,
3936 neighbours,
3937 (mi_r, mi_c),
3938 bw,
3939 bh,
3940 tx_w,
3941 tx_h,
3942 &modes,
3943 y,
3944 u,
3945 v,
3946 base_q_idx,
3947 reduced_tx_set,
3948 fctx,
3949 )?;
3950 // This early return skips this fn's own tail, so the palette
3951 // neighbour state has to be stamped HERE too: without it a split-tx
3952 // strip left the above/left palette arrays holding a DEAD block's
3953 // colours, and the next block's colour cache
3954 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
3955 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
3956 // and only those pixels were wrong (lane-palette2 r10).
3957 let (py_size, py_colors) = palette_y
3958 .as_ref()
3959 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
3960 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
3961 let (puv_size, puv_colors) = palette_uv
3962 .as_ref()
3963 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
3964 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
3965 hit!(RECT_PARTITION_HITS);
3966 return Ok(());
3967 }
3968 let (tx_w, tx_h) = (bw, bh);
3969 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
3970 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
3971 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
3972 if crate::envflags::env_flag!("EC_AV1_TRACE") {
3973 let (rng, _) = dec.debug_state();
3974 eprintln!(
3975 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
3976 skip={} tx={depth} rng={rng}",
3977 skip as i32
3978 );
3979 }
3980 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
3981 // block's prediction is the reconstructed colour-index map, set fresh
3982 // right before each `reconstruct_rect` call below (lane-palette2 r4).
3983 if let Some(ref pyv) = palette_y {
3984 let buf: Vec<u16> = pyv
3985 .map
3986 .iter()
3987 .map(|&idx| pyv.colors[idx as usize])
3988 .collect();
3989 set_palette_pred(buf, fctx);
3990 }
3991 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
3992 (
3993 puv.map
3994 .iter()
3995 .map(|&idx| puv.u_colors[idx as usize])
3996 .collect(),
3997 puv.map
3998 .iter()
3999 .map(|&idx| puv.v_colors[idx as usize])
4000 .collect(),
4001 )
4002 });
4003 if skip {
4004 push_intra_rect(
4005 y,
4006 u,
4007 v,
4008 0,
4009 px,
4010 py,
4011 bw,
4012 bh,
4013 mode,
4014 angle_delta_y,
4015 reach,
4016 &ZERO_RESIDUAL[..bw * bh],
4017 None,
4018 filter_intra,
4019 smooth_neighbor,
4020 fctx,
4021 );
4022 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
4023 if let Some((ub, _)) = &palette_uv_bufs {
4024 set_palette_pred(ub.clone(), fctx);
4025 }
4026 push_intra_rect(
4027 y,
4028 u,
4029 v,
4030 1,
4031 cpx,
4032 cpy,
4033 chroma_w,
4034 chroma_h,
4035 uv_predict_mode,
4036 angle_delta_uv,
4037 reach,
4038 &ZERO_RESIDUAL[..chroma_w * chroma_h],
4039 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
4040 None,
4041 smooth_neighbor_uv,
4042 fctx,
4043 );
4044 if let Some((_, vb)) = &palette_uv_bufs {
4045 set_palette_pred(vb.clone(), fctx);
4046 }
4047 push_intra_rect(
4048 y,
4049 u,
4050 v,
4051 2,
4052 cpx,
4053 cpy,
4054 chroma_w,
4055 chroma_h,
4056 uv_predict_mode,
4057 angle_delta_uv,
4058 reach,
4059 &ZERO_RESIDUAL[..chroma_w * chroma_h],
4060 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
4061 None,
4062 smooth_neighbor_uv,
4063 fctx,
4064 );
4065 neighbours.record_rect(
4066 at,
4067 bw,
4068 bh,
4069 mode,
4070 uv_predict_mode,
4071 &[
4072 &ZERO_RESIDUAL[..bw * bh],
4073 &ZERO_RESIDUAL[..chroma_w * chroma_h],
4074 &ZERO_RESIDUAL[..chroma_w * chroma_h],
4075 ],
4076 );
4077 } else {
4078 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
4079 // reduces both size pairs to their square-up CDF sets
4080 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
4081 // doc comments); the scan order and 2D context tables are the real
4082 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
4083 let luma_scan: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 };
4084 // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a
4085 // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16
4086 // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis).
4087 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
4088 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
4089 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
4090 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8),
4091 (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16),
4092 // lane-av1-422: a 4:2:2 strip halves only the width. A 32x16
4093 // luma strip's chroma is a 16x16 SQUARE (`TxbSet::Chroma16`, the
4094 // set any 16x16 chroma plane reads); a 16x32 strip's chroma is
4095 // 8x32, whose entropy set is the 16x16 one and whose DCT-only
4096 // default follows the >=32 rule below -- the same pairing the
4097 // (8,32) row of [`decode_rect_split`]'s chroma table proves. At
4098 // 4:2:0 and 4:4:4 a strip's chroma is itself rect, so neither row
4099 // is reachable there.
4100 (16, 16) => (TxbSet::Chroma16, default_scan(16)),
4101 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
4102 _ => {
4103 return Err(unsupported(
4104 "a rectangular chroma transform whose size has no coefficient table",
4105 ));
4106 }
4107 };
4108 let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 {
4109 TxType::DctDct
4110 } else {
4111 default_intra_tx_type(uv_predict_mode as u8)
4112 };
4113 // lane-rectwire r3: real coefficients desync a pixel-exact gate
4114 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
4115 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
4116 // pixel (not a subtle context-table off-by-one), while the sibling
4117 // non-rect quadrants of the same frame match. Range-ladder bisection
4118 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
4119 // but the intra key-frame path has no traced symbol between the
4120 // partition read and the first coefficient block (mode/skip/tx_depth
4121 // reads are all untraced in libaom's decodeframe.c intra path, unlike
4122 // the inter EC_TRACE_MODE this round added), so a same-length range
4123 // comparison wasn't reachable within budget -- see
4124 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
4125 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
4126 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
4127 // libaom and match). lane-rectwire r4: range-ladder against the
4128 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
4129 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
4130 // both confirmed in sync -- rng=58692 on both sides right after
4131 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
4132 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
4133 // immediately after: ours moves rng 58692 -> 43570, which cannot be
4134 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
4135 // its own tx_size read) unless oracle's tx symbol is a near-certainty
4136 // CDF that barely narrows the range -- i.e. this decoder's
4137 // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for
4138 // a 32x16/16x32 strip is the first diverging symbol, not the
4139 // coefficient-context math r3 already cleared. Not confirmed byte-
4140 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
4141 // `read_tx_size`'s own rng, not attempted this round -- budget), so
4142 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
4143 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
4144 // it unconditionally where both square paths gate on `tx_select`. With
4145 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
4146 // decoder consumed one that was never there.
4147 {
4148 // lane-av1422warp r20: this 32x16/16x32 strip reader is the SIBLING of
4149 // `decode_leaf_rect`, and it was the one left ungated: at ss (1,0) the
4150 // strip's chroma is a square (side/2, side) block whose above cells
4151 // spread over `side` LUMA mi columns, so the per-mi rect gather
4152 // double-counts every chroma column's whole-unit dc sign. Measured on
4153 // the pinned 4:2:2 rotzoom stream (a1.obu frame 0): the chroma-U 4x4
4154 // transform of the 32x16 strip at mi(68,16) reads its DC sign from
4155 // `dc_sign_ctx` 1 where libaom reads row 0 -- the first read of
4156 // 45260 whose pre-state, bit position and symbol all match and only
4157 // the CDF row differs, and the first divergence in the EC_SYMR
4158 // sequence (all 45259 reads before it pair exactly). Luma keeps the
4159 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
4160 let mut around = neighbours.around_rect(at, bw, bh);
4161 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
4162 let c2 =
4163 neighbours.around_mi_422_chroma((at.0 * (SUB / MI), at.1 * (SUB / MI)), bw, bh);
4164 around[1] = c2[1];
4165 around[2] = c2[2];
4166 }
4167 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
4168 let (luma_levels, luma_tx_type) = read_coeffs_rect(
4169 dec,
4170 &mut luma_coding,
4171 luma_scan,
4172 bw,
4173 bh,
4174 0,
4175 dc_sign_ctx(around[0].2),
4176 TxType::DctDct,
4177 0,
4178 )?;
4179 if crate::envflags::env_flag!("EC_AV1_TRACE") {
4180 let (rng, _) = dec.debug_state();
4181 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
4182 }
4183 let luma_residual = dequant_and_inverse_typed_wh(
4184 &luma_levels,
4185 bw,
4186 bh,
4187 crate::decode::bit_depth(fctx),
4188 block_q_idx(fctx),
4189 plane_q_delta(0, fctx).0,
4190 plane_q_delta(0, fctx).1,
4191 luma_tx_type,
4192 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
4193 );
4194 push_intra_rect(
4195 y,
4196 u,
4197 v,
4198 0,
4199 px,
4200 py,
4201 bw,
4202 bh,
4203 mode,
4204 angle_delta_y,
4205 reach,
4206 &luma_residual,
4207 None,
4208 filter_intra,
4209 smooth_neighbor,
4210 fctx,
4211 );
4212 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
4213 if let Some((ub, _)) = &palette_uv_bufs {
4214 set_palette_pred(ub.clone(), fctx);
4215 }
4216 let u_default_tx = chroma_default_tx;
4217 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
4218 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
4219 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
4220 dec,
4221 &mut u_coding,
4222 chroma_scan,
4223 chroma_w,
4224 chroma_h,
4225 u_skip_ctx,
4226 dc_sign_ctx(around[1].2),
4227 u_default_tx,
4228 fctx,
4229 1,
4230 )?;
4231 if crate::envflags::env_flag!("EC_AV1_TRACE") {
4232 let (rng, _) = dec.debug_state();
4233 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
4234 }
4235 let u_residual = dequant_and_inverse_typed_wh(
4236 &u_levels,
4237 chroma_w,
4238 chroma_h,
4239 crate::decode::bit_depth(fctx),
4240 block_q_idx(fctx),
4241 plane_q_delta(1, fctx).0,
4242 plane_q_delta(1, fctx).1,
4243 u_tx_type,
4244 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
4245 );
4246 push_intra_rect(
4247 y,
4248 u,
4249 v,
4250 1,
4251 cpx,
4252 cpy,
4253 chroma_w,
4254 chroma_h,
4255 uv_predict_mode,
4256 angle_delta_uv,
4257 reach,
4258 &u_residual,
4259 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
4260 None,
4261 smooth_neighbor_uv,
4262 fctx,
4263 );
4264 if let Some((_, vb)) = &palette_uv_bufs {
4265 set_palette_pred(vb.clone(), fctx);
4266 }
4267 let v_default_tx = chroma_default_tx;
4268 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
4269 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
4270 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
4271 dec,
4272 &mut v_coding,
4273 chroma_scan,
4274 chroma_w,
4275 chroma_h,
4276 v_skip_ctx,
4277 dc_sign_ctx(around[2].2),
4278 v_default_tx,
4279 fctx,
4280 2,
4281 )?;
4282 if crate::envflags::env_flag!("EC_AV1_TRACE") {
4283 let (rng, _) = dec.debug_state();
4284 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
4285 }
4286 let v_residual = dequant_and_inverse_typed_wh(
4287 &v_levels,
4288 chroma_w,
4289 chroma_h,
4290 crate::decode::bit_depth(fctx),
4291 block_q_idx(fctx),
4292 plane_q_delta(2, fctx).0,
4293 plane_q_delta(2, fctx).1,
4294 v_tx_type,
4295 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
4296 );
4297 push_intra_rect(
4298 y,
4299 u,
4300 v,
4301 2,
4302 cpx,
4303 cpy,
4304 chroma_w,
4305 chroma_h,
4306 uv_predict_mode,
4307 angle_delta_uv,
4308 reach,
4309 &v_residual,
4310 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
4311 None,
4312 smooth_neighbor_uv,
4313 fctx,
4314 );
4315 neighbours.record_rect(
4316 at,
4317 bw,
4318 bh,
4319 mode,
4320 uv_predict_mode,
4321 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
4322 );
4323 hit!(RECT_COEFF_HITS);
4324 }
4325 }
4326 let (py_size, py_colors) = palette_y
4327 .as_ref()
4328 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
4329 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
4330 let (puv_size, puv_colors) = palette_uv
4331 .as_ref()
4332 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
4333 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
4334 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
4335 neighbours.fill_lf_grid_rect(
4336 (mi_r, mi_c),
4337 bw / MI,
4338 bh / MI,
4339 tx_w as u8,
4340 tx_h as u8,
4341 0,
4342 fctx,
4343 );
4344 hit!(RECT_PARTITION_HITS);
4345 if crate::envflags::env_flag!("EC_AV1_TRACE") {
4346 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
4347 }
4348 Ok(())
4349}
4350
4351/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
4352/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
4353/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
4354/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
4355/// the second strip of a HORZ/VERT split sits offset by half the 16x16
4356/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
4357/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
4358/// previous strip is directly above (same column, `mi_h` rows up) or
4359/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
4360/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
4361/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
4362/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
4363/// this strip's real position, never the coarse `record_rect` (which the
4364/// caller uses once, after both strips, exactly like the `VERT_B` arm next
4365/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
4366/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
4367/// chroma half (`TxbSet::ChromaRect8x4`) at 4:2:0 -- an 8x8 *square* chroma
4368/// plane (`TxbSet::Chroma8` + the default scan) at 4:2:2 (lane-av1-422e:
4369/// half-width, unhalved height), the two size classes one level
4370/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
4371#[allow(clippy::too_many_arguments)]
4372pub(super) fn decode_leaf_rect(
4373 dec: &mut SymbolDecoder,
4374 cdfs: &mut Cdfs,
4375 neighbours: &mut Neighbours,
4376 outer_at: (usize, usize),
4377 leaf_mi: (usize, usize),
4378 bw: usize,
4379 bh: usize,
4380 prev_leaf: Option<((usize, usize), usize)>,
4381 y: &mut PlaneBuf<'static>,
4382 u: &mut PlaneBuf<'static>,
4383 v: &mut PlaneBuf<'static>,
4384 enable_filter_intra: bool,
4385 allow_screen_content_tools: bool,
4386 base_q_idx: u8,
4387 tx_select: bool,
4388 reduced_tx_set: bool,
4389 fctx: &crate::decode::FrameCtx,
4390) -> Result<usize> {
4391 let _ = base_q_idx;
4392 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
4393 eprintln!(
4394 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
4395 dec.debug_state().0
4396 );
4397 }
4398 let (r, c) = outer_at;
4399 let mut above_mode = neighbours.above_mode[c];
4400 let mut left_mode = neighbours.left_mode[r];
4401 let (mi_w, mi_h) = (bw / MI, bh / MI);
4402 if let Some(((pr, pc), pmode)) = prev_leaf {
4403 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
4404 above_mode = pmode;
4405 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
4406 left_mode = pmode;
4407 }
4408 }
4409 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
4410 // cannot hold the modes a split (or a pair of strips) leaves behind, so
4411 // when the map holds the block at exactly this strip's above/left mi it
4412 // is the neighbour libaom's `above_mi`/`left_mi` reads.
4413 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
4414 // availability-correct -- four 16x8 strips share one coarse 16x16
4415 // `left_mode` cell too, so the fallback must not stand in for an absent
4416 // tile-edge neighbour.
4417 let (above_mode, left_mode) =
4418 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
4419 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
4420 if smooth_neighbor {
4421 hit!(SMOOTH_LUMA_HITS);
4422 }
4423 // The palette-Y mode CDF row is picked by the neighbours' palette use
4424 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
4425 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
4426 // a palette narrows the wrong interval and desyncs the tile even when the
4427 // decoded bit is the same. The cell is the 16px-SUB cell containing the
4428 // leaf (the palette neighbour arrays have no finer granularity).
4429 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
4430 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
4431 // exclusion and the neighbour palette lookup itself are mi-granular
4432 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
4433 let pal_at = leaf_mi;
4434 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
4435 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
4436 let (
4437 skip,
4438 mode,
4439 angle_delta_y,
4440 uv_mode,
4441 angle_delta_uv,
4442 alpha,
4443 filter_intra,
4444 palette_y,
4445 palette_uv,
4446 intrabc,
4447 ) = read_intra_mode_rect(
4448 dec,
4449 cdfs,
4450 above_mode,
4451 left_mode,
4452 true,
4453 true,
4454 bw,
4455 bh,
4456 enable_filter_intra,
4457 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
4458 allow_screen_content_tools,
4459 Some((palette_ctx, &palette_cache)),
4460 &palette_uv_cache,
4461 leaf_mi.0,
4462 leaf_mi.1,
4463 fctx,
4464 )?;
4465
4466 if let Some((dv_row, dv_col)) = intrabc {
4467 decode_intrabc_rect(
4468 dec,
4469 cdfs,
4470 neighbours,
4471 leaf_mi,
4472 (bw, bh),
4473 skip,
4474 (dv_row, dv_col),
4475 y,
4476 u,
4477 v,
4478 base_q_idx,
4479 fctx,
4480 )?;
4481 return Ok(DC_PRED);
4482 }
4483 // lane-kf900 r4: palette prediction on this shape, the same colour-index
4484 // map -> base colours buffer [`decode_block_rect`] hands each
4485 // `reconstruct_rect` through [`set_palette_pred`].
4486 if palette_y.is_some() || palette_uv.is_some() {
4487 hit!(RECT4_PALETTE_HITS);
4488 }
4489 let palette_y_buf: Option<Vec<u16>> = palette_y
4490 .as_ref()
4491 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
4492 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
4493 (
4494 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
4495 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
4496 )
4497 });
4498 let (pal_y_size, pal_y_colors) = palette_y
4499 .as_ref()
4500 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
4501 let (pal_uv_size, pal_uv_colors) = palette_uv
4502 .as_ref()
4503 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
4504 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
4505 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
4506 }
4507 if filter_intra.is_some() {
4508 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
4509 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
4510 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
4511 // below already makes; this refusal was square-only prose.
4512 hit!(FILTER_INTRA_RECT_HITS);
4513 hit!(FILTER_INTRA_RECT_SUB16_HITS);
4514 }
4515 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
4516 DC_PRED
4517 } else {
4518 uv_mode
4519 };
4520 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
4521 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
4522 // a constant `false`.
4523 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
4524 let depth = if tx_select && !lossless(fctx) {
4525 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
4526 // every other rect reader now does -- a no-op on a key frame.
4527 // lane-av1mixloss: libaom `read_tx_size`'s first line
4528 // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return
4529 // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment
4530 // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4).
4531 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
4532 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
4533 // read was the leaf's own txb_skip.
4534 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
4535 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
4536 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
4537 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
4538 // count (3), different CDF row: a wrong-table read of a real symbol,
4539 // the class that cost lane-rectsplit r1 its 64x32 depth.
4540 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
4541 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
4542 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
4543 // function also decodes) sit at depth 2, so they read
4544 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
4545 // while `tx_size_cat2` belongs to the 32-level shapes
4546 // ([`decode_block_rect`]). Both tables carry three symbols, so the
4547 // wrong one decodes a plausible depth from the wrong probabilities:
4548 // the range diverges silently at the first such leaf and every later
4549 // symbol in the tile is read from the wrong place (class
4550 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
4551 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
4552 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
4553 eprintln!(
4554 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
4555 leaf_mi.0,
4556 leaf_mi.1,
4557 dec.debug_state().0
4558 );
4559 }
4560 d
4561 } else {
4562 0
4563 };
4564 // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads
4565 // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
4566 publish_txfm_bands_if_in_inter(
4567 neighbours,
4568 leaf_mi,
4569 depth_to_tx_wh(bw, bh, depth, fctx),
4570 (bw, bh),
4571 fctx,
4572 );
4573 if depth != 0 || lossless(fctx) {
4574 // The same per-transform-unit walk the bigger strips take
4575 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
4576 // depth 2), addressed at this leaf's own mi position.
4577 hit!(TX_DEPTH_HITS);
4578 hit!(SUB16_SPLIT_HITS);
4579 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
4580 let modes = RectStripModes {
4581 skip,
4582 mode,
4583 angle_delta_y,
4584 uv_predict_mode,
4585 angle_delta_uv,
4586 alpha,
4587 filter_intra,
4588 smooth_neighbor,
4589 // lane-rectsplitx r3: the split arm hard-coded `false` here while
4590 // the unsplit arm below passes the real neighbour answer -- chroma
4591 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
4592 smooth_neighbor_uv,
4593 palette_y: palette_y_buf.clone(),
4594 palette_uv: palette_uv_bufs.clone(),
4595 };
4596 if palette_y.is_some() || palette_uv.is_some() {
4597 hit!(PALETTE_SPLIT_TX_HITS);
4598 }
4599 decode_rect_split(
4600 dec,
4601 cdfs,
4602 neighbours,
4603 leaf_mi,
4604 bw,
4605 bh,
4606 tx_w,
4607 tx_h,
4608 &modes,
4609 y,
4610 u,
4611 v,
4612 base_q_idx,
4613 reduced_tx_set,
4614 fctx,
4615 )?;
4616 record_strip_palette(
4617 neighbours,
4618 pal_at,
4619 bw,
4620 bh,
4621 pal_y_size,
4622 pal_y_colors,
4623 pal_uv_size,
4624 pal_uv_colors,
4625 );
4626 return Ok(mode);
4627 }
4628 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
4629 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
4630 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
4631 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
4632 let (luma_levels, u_levels, v_levels);
4633 if skip {
4634 luma_levels = Grid::Zero(bw * bh);
4635 u_levels = Grid::Zero(chroma_w * chroma_h);
4636 v_levels = Grid::Zero(chroma_w * chroma_h);
4637 if let Some(b) = &palette_y_buf {
4638 set_palette_pred(b.clone(), fctx);
4639 }
4640 push_intra_rect(
4641 y,
4642 u,
4643 v,
4644 0,
4645 px,
4646 py,
4647 bw,
4648 bh,
4649 mode,
4650 angle_delta_y,
4651 reach,
4652 &luma_levels,
4653 None,
4654 filter_intra,
4655 smooth_neighbor,
4656 fctx,
4657 );
4658 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
4659 if let Some((ub, _)) = &palette_uv_bufs {
4660 set_palette_pred(ub.clone(), fctx);
4661 }
4662 push_intra_rect(
4663 y,
4664 u,
4665 v,
4666 1,
4667 cpx,
4668 cpy,
4669 chroma_w,
4670 chroma_h,
4671 uv_predict_mode,
4672 angle_delta_uv,
4673 reach,
4674 &u_levels,
4675 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
4676 None,
4677 smooth_neighbor_uv,
4678 fctx,
4679 );
4680 if let Some((_, vb)) = &palette_uv_bufs {
4681 set_palette_pred(vb.clone(), fctx);
4682 }
4683 push_intra_rect(
4684 y,
4685 u,
4686 v,
4687 2,
4688 cpx,
4689 cpy,
4690 chroma_w,
4691 chroma_h,
4692 uv_predict_mode,
4693 angle_delta_uv,
4694 reach,
4695 &v_levels,
4696 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
4697 None,
4698 smooth_neighbor_uv,
4699 fctx,
4700 );
4701 } else {
4702 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
4703 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
4704 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
4705 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
4706 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
4707 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
4708 // lane-av1-422e: a 4:2:2 strip halves only the width, so the chroma
4709 // half of a 16x8/8x16 luma leaf is an 8x8 SQUARE (`TxbSet::Chroma8` +
4710 // the default scan -- the pairing any 8x8 chroma plane reads). 4:2:0
4711 // halves both axes (8x4/4x8 rect, `TxbSet::ChromaRect8x4`); 4:4:4
4712 // leaves the full 16x8/8x16 rect (`TxbSet::ChromaRect16x8`).
4713 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
4714 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 {
4715 if bw == 16 {
4716 (&SCAN_16X8, &SCAN_16X8)
4717 } else {
4718 (&SCAN_8X16, &SCAN_8X16)
4719 }
4720 } else if chroma_422 {
4721 if bw == 16 {
4722 (&SCAN_16X8, default_scan(8))
4723 } else {
4724 (&SCAN_8X16, default_scan(8))
4725 }
4726 } else if bw == 16 {
4727 (&SCAN_16X8, &SCAN_8X4)
4728 } else {
4729 (&SCAN_8X16, &SCAN_4X8)
4730 };
4731 let chroma_rect_set = if ss_x(fctx) == 0 {
4732 TxbSet::ChromaRect16x8
4733 } else if chroma_422 {
4734 TxbSet::Chroma8
4735 } else {
4736 TxbSet::ChromaRect8x4
4737 };
4738 // lane-av1422warp: at ss (1,0) this leaf's chroma is a SQUARE
4739 // (side/2, side) block, so `side` chroma 4-px cells above it spread
4740 // over `side` LUMA mi columns -- one chroma column per PAIR of luma
4741 // mi cells, and both carry the covering unit's whole-unit dc sign.
4742 // The per-mi rect gather therefore double-counts every chroma
4743 // column's sign. `around_mi_422_chroma`'s every-second above-cell
4744 // sampling is libaom's `txb_w_unit` sum, and every other 4:2:2 chroma
4745 // gather in this file already routes through it (see the gate at this
4746 // arm's siblings); this one did not, so a 4:2:2 rect leaf voted over
4747 // luma unit counts. Measured on the pinned 4:2:2 rotzoom stream
4748 // (a1.obu frame 0): the 16x8 leaf at mi(48,28) resolved its V plane's
4749 // dc sign from vote 0 (`dc_sign_cdf[0]`) where the oracle resolves a
4750 // negative vote (`dc_sign_cdf[1]`), which is the first bit-position
4751 // divergence in the frame (the bit offset is a clean constant through
4752 // coefficient unit 1418 and turns 6 bits at 1419). Luma keeps the
4753 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
4754 let mut around = neighbours.around_mi_rect(leaf_mi, bw, bh);
4755 if chroma_422 {
4756 let c = neighbours.around_mi_422_chroma(leaf_mi, bw, bh);
4757 around[1] = c[1];
4758 around[2] = c[2];
4759 }
4760 let luma_set = if reduced_tx_set {
4761 TxbSet::LumaRect16x8
4762 } else {
4763 TxbSet::LumaRect16x8Set1
4764 };
4765 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
4766 let (l_levels, luma_tx_type) = read_coeffs_rect(
4767 dec,
4768 &mut luma_coding,
4769 luma_scan,
4770 bw,
4771 bh,
4772 0,
4773 dc_sign_ctx(around[0].2),
4774 TxType::DctDct,
4775 0,
4776 )?;
4777 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
4778 let nz: Vec<(usize, i32)> = l_levels
4779 .iter()
4780 .copied()
4781 .enumerate()
4782 .filter(|(_, v)| *v != 0)
4783 .collect();
4784 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
4785 }
4786 luma_levels = l_levels;
4787 let luma_residual = dequant_and_inverse_typed_wh(
4788 &luma_levels,
4789 bw,
4790 bh,
4791 crate::decode::bit_depth(fctx),
4792 block_q_idx(fctx),
4793 plane_q_delta(0, fctx).0,
4794 plane_q_delta(0, fctx).1,
4795 luma_tx_type,
4796 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
4797 );
4798 if let Some(b) = &palette_y_buf {
4799 set_palette_pred(b.clone(), fctx);
4800 }
4801 push_intra_rect(
4802 y,
4803 u,
4804 v,
4805 0,
4806 px,
4807 py,
4808 bw,
4809 bh,
4810 mode,
4811 angle_delta_y,
4812 reach,
4813 &luma_residual,
4814 None,
4815 filter_intra,
4816 smooth_neighbor,
4817 fctx,
4818 );
4819 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
4820 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
4821 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
4822 let mut u_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
4823 let (u_l, u_tx_type) = read_chroma_coeffs_rect(
4824 dec,
4825 &mut u_coding,
4826 chroma_scan,
4827 chroma_w,
4828 chroma_h,
4829 u_skip_ctx,
4830 dc_sign_ctx(around[1].2),
4831 u_default_tx,
4832 fctx,
4833 1,
4834 )?;
4835 u_levels = u_l;
4836 let u_residual = dequant_and_inverse_typed_wh(
4837 &u_levels,
4838 chroma_w,
4839 chroma_h,
4840 crate::decode::bit_depth(fctx),
4841 block_q_idx(fctx),
4842 plane_q_delta(1, fctx).0,
4843 plane_q_delta(1, fctx).1,
4844 u_tx_type,
4845 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
4846 );
4847 if let Some((ub, _)) = &palette_uv_bufs {
4848 set_palette_pred(ub.clone(), fctx);
4849 }
4850 push_intra_rect(
4851 y,
4852 u,
4853 v,
4854 1,
4855 cpx,
4856 cpy,
4857 chroma_w,
4858 chroma_h,
4859 uv_predict_mode,
4860 angle_delta_uv,
4861 reach,
4862 &u_residual,
4863 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
4864 None,
4865 smooth_neighbor_uv,
4866 fctx,
4867 );
4868 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
4869 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
4870 let mut v_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
4871 let (v_l, v_tx_type) = read_chroma_coeffs_rect(
4872 dec,
4873 &mut v_coding,
4874 chroma_scan,
4875 chroma_w,
4876 chroma_h,
4877 v_skip_ctx,
4878 dc_sign_ctx(around[2].2),
4879 v_default_tx,
4880 fctx,
4881 2,
4882 )?;
4883 v_levels = v_l;
4884 let v_residual = dequant_and_inverse_typed_wh(
4885 &v_levels,
4886 chroma_w,
4887 chroma_h,
4888 crate::decode::bit_depth(fctx),
4889 block_q_idx(fctx),
4890 plane_q_delta(2, fctx).0,
4891 plane_q_delta(2, fctx).1,
4892 v_tx_type,
4893 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
4894 );
4895 if let Some((_, vb)) = &palette_uv_bufs {
4896 set_palette_pred(vb.clone(), fctx);
4897 }
4898 push_intra_rect(
4899 y,
4900 u,
4901 v,
4902 2,
4903 cpx,
4904 cpy,
4905 chroma_w,
4906 chroma_h,
4907 uv_predict_mode,
4908 angle_delta_uv,
4909 reach,
4910 &v_residual,
4911 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
4912 None,
4913 smooth_neighbor_uv,
4914 fctx,
4915 );
4916 hit!(RECT_LEAF_COEFF_HITS);
4917 }
4918 neighbours.record_mi_rect(
4919 leaf_mi,
4920 bw,
4921 bh,
4922 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
4923 );
4924 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
4925 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
4926 // The leaf's own palette state (`0` clears, as this site always did
4927 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
4928 // AXIS only until the pair's closing leaf: the coarse cell holds one
4929 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
4930 // real left neighbour leaf 1 reads (lane-kf900 r4).
4931 record_strip_palette(
4932 neighbours,
4933 pal_at,
4934 bw,
4935 bh,
4936 pal_y_size,
4937 pal_y_colors,
4938 pal_uv_size,
4939 pal_uv_colors,
4940 );
4941 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
4942 // rows -- record the whole span, not one cell.
4943 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
4944 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
4945 Ok(mode)
4946}