forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

inter_ctx.rs3047 lines, 122.5 KiBHistoryRawDownload
1//! Inter-block context and reference helpers: switchable interp and intra/inter contexts, the OBMC run, compound ref and mv readers. Moved out of `decode/mod.rs` (av1split D9); the items are unchanged apart from `pub(super)` visibility.
2
3use super::*;
4
5/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
6/// -- `above`/`left` are the neighbour's own resolved index for this
7/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
8/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
9/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
10/// block itself has a second reference) -- lane-av1idx: a stale "this
11/// decoder never codes a compound reference" assumption baked this to
12/// always-0, which desynced the CDF context bucket (not the decoded value
13/// outright, hence small pixel deltas rather than a hard desync) the moment
14/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
15/// filter frame.
16pub(super) fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
17 let base = dir * 8 + if is_compound { 4 } else { 0 };
18 let term = if left == above {
19 left
20 } else if left == 3 {
21 above
22 } else if above == 3 {
23 left
24 } else {
25 3
26 };
27 base + term as usize
28}
29
30/// Resolves the interpolation filter kernel(s) an inter block's motion
31/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
32/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
33/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
34/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
35/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
36/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
37/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
38/// which forces `EIGHTTAP` without reading anything.
39#[allow(clippy::too_many_arguments)]
40pub(super) fn resolve_interp_filter(
41 dec: &mut SymbolDecoder,
42 cdfs: &mut Cdfs,
43 interp_fixed: Option<mc::InterpFilterKind>,
44 enable_dual_filter: bool,
45 force_regular: bool,
46 above: [u8; 2],
47 left: [u8; 2],
48 is_compound: bool,
49) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
50 if let Some(kind) = interp_fixed {
51 return (kind, kind, [3, 3]);
52 }
53 if force_regular {
54 return (
55 mc::InterpFilterKind::Regular,
56 mc::InterpFilterKind::Regular,
57 [0, 0],
58 );
59 }
60 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
61 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
62 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
63 // "horizontal then vertical" despite `predict_with_filters`' own
64 // `h_kind`/`v_kind` argument order, which is why this function returns
65 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
66 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
67 if crate::envflags::env_flag!("EC_AV1_IFDBG") {
68 eprintln!(
69 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
70 &cdfs.switchable_interp[ctx0][..3]
71 );
72 }
73 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
74 let sym1 = if enable_dual_filter {
75 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
76 if crate::envflags::env_flag!("EC_AV1_IFDBG") {
77 eprintln!(
78 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
79 &cdfs.switchable_interp[ctx1][..3]
80 );
81 }
82 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
83 } else {
84 sym0
85 };
86 if enable_dual_filter && sym0 != sym1 {
87 hit!(DUAL_FILTER_DIFF_HITS);
88 }
89 if crate::envflags::env_flag!("EC_TRACE_MODE") {
90 eprintln!(
91 "EC_IF ctx0={ctx0} above={above:?} left={left:?} sym0={sym0} sym1={sym1} rng={}",
92 dec.debug_state().0
93 );
94 }
95 (
96 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
97 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
98 [sym0, sym1],
99 )
100}
101
102/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
103/// duplicating [`crate::tile`]'s private copy of the same rule.
104pub(crate) fn intra_inter_ctx(
105 has_above: bool,
106 has_left: bool,
107 above_inter: bool,
108 left_inter: bool,
109) -> usize {
110 match (has_above, has_left) {
111 (true, true) => {
112 let (above_intra, left_intra) = (!above_inter, !left_inter);
113 if above_intra && left_intra {
114 3
115 } else {
116 usize::from(above_intra || left_intra)
117 }
118 }
119 (true, false) => 2 * usize::from(!above_inter),
120 (false, true) => 2 * usize::from(!left_inter),
121 (false, false) => 0,
122 }
123}
124
125/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
126/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
127/// bits start counting from.
128fn mv_class_base(class: usize) -> i32 {
129 if class == 0 { 0 } else { 2i32 << (class + 2) }
130}
131
132/// One motion vector component's non-zero diff (spec 5.11.32
133/// `read_mv_component`), the inverse of [`crate::tile`]'s private
134/// `write_mv_component`.
135fn read_mv_component(
136 dec: &mut SymbolDecoder,
137 c: &mut MvComponentCdfs,
138 allow_high_precision_mv: bool,
139 force_integer_mv: bool,
140) -> i32 {
141 let sign = dec.symbol(&mut c.sign);
142 let class = dec.symbol(&mut c.class);
143 let local = if class == 0 {
144 let bit = dec.symbol(&mut c.class0_bit);
145 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
146 // forces integer motion vectors -- implicitly `3` (the top
147 // fractional value) rather than read, else every symbol after it
148 // in the tile desyncs by one read.
149 let fr = if force_integer_mv {
150 3
151 } else {
152 dec.symbol(&mut c.class0_fr[bit])
153 };
154 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
155 // high-precision motion vectors, else implicitly 1 (the low bit
156 // stays at half-pel precision) -- this crate's own writer always
157 // leaves the flag off, but a foreign stream can set it per frame.
158 let hp = if allow_high_precision_mv {
159 dec.symbol(&mut c.class0_hp)
160 } else {
161 1
162 };
163 (bit << 3) | (fr << 1) | hp
164 } else {
165 let mut d = 0;
166 for i in 0..class {
167 d |= dec.symbol(&mut c.bit[i]) << i;
168 }
169 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
170 // `mv_class0_fr` above.
171 let fr = if force_integer_mv {
172 3
173 } else {
174 dec.symbol(&mut c.fr)
175 };
176 let hp = if allow_high_precision_mv {
177 dec.symbol(&mut c.hp)
178 } else {
179 1
180 };
181 (d << 3) | (fr << 1) | hp
182 };
183 let mag = mv_class_base(class) + local as i32 + 1;
184 if sign == 1 { -mag } else { mag }
185}
186
187/// A motion vector coded as a residual against `pred` (spec 5.11.32
188/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
189pub(super) fn read_mv(
190 dec: &mut SymbolDecoder,
191 mv_comp: &mut [MvComponentCdfs; 2],
192 mv_joint: &mut [u16; 5],
193 pred: (i32, i32),
194 allow_high_precision_mv: bool,
195 force_integer_mv: bool,
196 fctx: &crate::decode::FrameCtx,
197) -> (i32, i32) {
198 let joint = dec.symbol(mv_joint);
199 let mut diff = (0, 0);
200 if joint == 2 || joint == 3 {
201 diff.0 = read_mv_component(
202 dec,
203 &mut mv_comp[0],
204 allow_high_precision_mv,
205 force_integer_mv,
206 );
207 }
208 if joint == 1 || joint == 3 {
209 diff.1 = read_mv_component(
210 dec,
211 &mut mv_comp[1],
212 allow_high_precision_mv,
213 force_integer_mv,
214 );
215 }
216 let mut mv = (pred.0 + diff.0, pred.1 + diff.1);
217 // Spec 6.10.25 (`is_mv_valid`): every component is strictly inside
218 // (MV_LOW, MV_UPP) = (-(1 << 14), 1 << 14). A conforming stream never leaves
219 // that range. Past it the vector would not fit the i16 storage of a mi unit,
220 // so flag the frame corrupt and clamp it into range for the rest of the decode.
221 const MV_LIMIT: i32 = 1 << 14;
222 let valid = |c: i32| c > -MV_LIMIT && c < MV_LIMIT;
223 if !valid(mv.0) || !valid(mv.1) {
224 fctx.flag_corrupt("motion vector outside the spec's range");
225 mv = (
226 mv.0.clamp(-MV_LIMIT + 1, MV_LIMIT - 1),
227 mv.1.clamp(-MV_LIMIT + 1, MV_LIMIT - 1),
228 );
229 }
230 crate::census::mv(mv.0, mv.1);
231 mv
232}
233
234/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
235/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
236///
237/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
238/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
239/// when that is zero, or -- when both are -- the fixed fallback DV one
240/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
241/// left when this is the tile's first superblock row. The predictor is then
242/// rounded to full pel, and the difference reads off the *dv* nmv context
243/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
244/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
245/// symbol is coded for a DV, so none of this can move the bitstream
246/// position -- only the reconstructed vector.
247pub(super) fn read_intrabc_dv(
248 dec: &mut SymbolDecoder,
249 cdfs: &mut Cdfs,
250 mi_r: usize,
251 mi_c: usize,
252 // The block's own mi footprint (`av1_find_mv_refs` takes the real bsize,
253 // so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4` leaf scans a 1x2/2x1 neighbourhood
254 // -- lane-av1txr).
255 (n4_w, n4_h): (usize, usize),
256 fctx: &crate::decode::FrameCtx,
257) -> (i32, i32) {
258 const INTRABC_DELAY_PIXELS: i32 = 256;
259 let stack_pred = fctx.intrabc_mi_grid.with(|g| {
260 let g = g.borrow();
261 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
262 let stack = crate::mvstack::find_mv_stack(
263 grid, mi_r, mi_c, n4_w, n4_h, 0, /* INTRA_FRAME */
264 *mi_cols, *mi_rows,
265 );
266 if stack.nearest_mv == (0, 0) {
267 stack.near_mv
268 } else {
269 stack.nearest_mv
270 }
271 })
272 });
273 let mut pred = stack_pred.unwrap_or((0, 0));
274 if pred == (0, 0) {
275 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
276 // single-tile-row case every intrabc gate stream is).
277 // lane-t900 r34: `av1_find_ref_dv` takes `mib_size` -- the SEQUENCE's
278 // superblock size in mi units -- so a 128x128 superblock stream's
279 // fallback DV is one 128-px superblock up (or 128+256 px left on the
280 // tile's first superblock row), never the 64 this hardcoded.
281 let sb_mi = sb_mi_cur(fctx) as i32;
282 let sb_px = sb_mi * MI as i32;
283 pred = if (mi_r as i32) < sb_mi {
284 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
285 } else {
286 (-sb_px * 8, 0)
287 };
288 }
289 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
290 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
291 let dv = read_mv(
292 dec,
293 &mut cdfs.dv_comp,
294 &mut cdfs.dv_joint,
295 pred,
296 false,
297 true,
298 fctx,
299 );
300 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
301 let (rng, _) = dec.debug_state();
302 eprintln!(
303 "EC_DV mi_row={mi_r} mi_col={mi_c} dv_col={} dv_row={} rng={rng}",
304 dv.1, dv.0
305 );
306 }
307 dv
308}
309
310/// A 1/8-pel motion vector component converted to the 1/16-pel offset
311/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
312/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
313pub(super) fn mv_to_q4(pos: usize, mv_component: i32, ss: usize) -> i32 {
314 // orig_pos += mv * (1 << (1 - ss)). Luma always passes 0.
315 (pos as i32) * 16 + mv_component * (1i32 << (1 - ss as i32))
316}
317
318impl PlaneBuf<'_> {
319 /// Adds `residual` onto an already-computed `prediction` (motion
320 /// compensation's output, rather than [`predict`]'s intra one), writing
321 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
322 /// counterpart of [`PlaneBuf::reconstruct`].
323 /// [`Self::reconstruct_mc_rect`], writing only a `w`x`h` sub-rectangle of the
324 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
325 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
326 /// VERT strip is predicted at its enclosing square `side` (matching
327 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
328 /// but only its own true `w`x`h` footprint is committed to the plane, so
329 /// two strips sharing a square's coordinate origin never clobber each
330 /// other's real pixels.
331 #[track_caller]
332 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
333 #[allow(clippy::too_many_arguments)]
334 pub(super) fn reconstruct_mc_rect(
335 &mut self,
336 x: usize,
337 y: usize,
338 plane: usize,
339 side: usize,
340 w: usize,
341 h: usize,
342 prediction: &[u16],
343 residual: &[i32],
344 fctx: &crate::decode::FrameCtx,
345 ) {
346 // lane-sb128c r7: a 128x64 half of a 128 root at the BOTTOM frame edge
347 // is the first block shape whose true footprint overhangs the padded
348 // coding surface (mi_rows = 198 -> a plane 800 rows tall, block rows
349 // 768..832). libaom reconstructs those rows into the frame buffer's
350 // border; nothing reads them back, so they are simply dropped here.
351 let (h, w) = (
352 h.min(self.height.saturating_sub(y)),
353 w.min(self.width.saturating_sub(x)),
354 );
355 // lane-perf4: one row of each operand at a time. `side` is the
356 // prediction/residual stride and `self.width` the plane's, so the
357 // three row bases are computed once per row instead of a
358 // multiply-add per sample (the samples themselves are unchanged).
359 let max = crate::decode::sample_max(fctx);
360
361 // lane-av1ibcfork: the MC/inter write's own origin and shape. The intra
362 // side's `EC_PRED` rung prints the PREDICTION, so a region whose
363 // prediction is byte-identical to the oracle's and whose committed
364 // samples are not can only be a DIFFERENT WRITE -- and this is the
365 // only write path with no rung of its own.
366 if crate::envflags::env_flag!("EC_MCWR") {
367 eprintln!(
368 "EC_MCWR x={x} y={y} side={side} w={w} h={h} empty_res={} at {}",
369 residual.is_empty(),
370 std::panic::Location::caller()
371 );
372 }
373 // lane-av1444altref r2: EC_CPRED, the picture-independent twin of the
374 // oracle's rung of the same name (aomdec's
375 // `dec_build_inter_predictor`). This is the ONE site every inter
376 // prediction reaches on its way into a plane -- after the compound
377 // blend and after the inter-intra blend, before the residual -- so it
378 // measures exactly the quantity the oracle's rung measures. Pairing
379 // is by (plane, x, y, w, h): the same chroma geometry recurs in many
380 // pictures, so a rung line alone is ambiguous, but a geometry whose
381 // samples differ by at most 1 is a unique match (any wrong pairing
382 // differs by tens).
383 // Env: EC_CPRED="x:y" (plane-absolute origin; -1 for either = any).
384 if let Ok(spec) = crate::envflags::var("EC_CPRED") {
385 let (fx, fy): (i64, i64) = spec
386 .split_once(':')
387 .and_then(|(a, b)| Some((a.trim().parse().ok()?, b.trim().parse().ok()?)))
388 .unwrap_or((-1, -1));
389 let hit = (fx < 0 || fx == x as i64) && (fy < 0 || fy == y as i64);
390 if hit {
391 // `PREFILT_PICTURE_IDX` is bumped once per frame just AFTER
392 // that frame's last block, so it still reads this frame's own
393 // decode-order index here -- the same numbering the oracle's
394 // `aom_ec_pict_idx` and the `.fN` prefilter dumps use.
395 let pict = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst);
396 eprintln!(
397 "OUR_CPRED pict={pict} plane={plane} x={x} y={y} w={w} h={h} side={side}"
398 );
399 for row in 0..h {
400 let src = &prediction[row * side..row * side + w];
401 let mut line = String::with_capacity(w * 4);
402 for v in src {
403 line.push(' ');
404 line.push_str(&v.to_string());
405 }
406 eprintln!("OUR_CPROW{row}:{line}");
407 }
408 }
409 }
410 // lane-recoparse: an all-zero residual (60% of the units) is a plain
411 // prediction copy -- the same arithmetic with `r == 0`, without
412 // reading `side * h` zeros out of [`ZERO_RESIDUAL`].
413 if residual.is_empty() {
414 for row in 0..h {
415 let src = row * side;
416 let dst = (y + row) * self.width + x;
417 let pred = &prediction[src..src + w];
418 let out = &mut self.data.to_mut()[dst..dst + w];
419 for (col, (o, &p)) in out.iter_mut().zip(pred).enumerate() {
420 let v = i32::from(p).clamp(0, max) as u16;
421 pix_write("mc_copy", x, y, w, x + col, y + row, *o, v);
422 *o = v;
423 }
424 }
425 return;
426 }
427 let residual = dense_residual(residual, side * h);
428 for row in 0..h {
429 let src = row * side;
430 let dst = (y + row) * self.width + x;
431 let pred = &prediction[src..src + w];
432 let res = &residual[src..src + w];
433 let out = &mut self.data.to_mut()[dst..dst + w];
434 for (col, ((o, &p), &r)) in out.iter_mut().zip(pred).zip(res).enumerate() {
435 let v = (i32::from(p) + r).clamp(0, max) as u16;
436 pix_write("mc_add", x, y, w, x + col, y + row, *o, v);
437 *o = v;
438 }
439 }
440 }
441}
442
443/// Reads one inter-coded plane's transform block and reconstructs it by
444/// adding its residual onto a motion-compensated `prediction` -- the inter
445/// counterpart of [`read_plane`] (every inter transform this decoder reads is
446/// `side`-square with no oversized-64 case, so there is no padded-grid
447/// branch to mirror).
448#[allow(clippy::too_many_arguments)]
449pub(super) fn read_inter_plane(
450 dec: &mut SymbolDecoder,
451 cdfs: &mut Cdfs,
452 set: TxbSet,
453 scan: &[u16],
454 plane_idx: usize,
455 around: (bool, bool, i32),
456 tx_mode: usize,
457 y: &mut PlaneBuf<'static>,
458 u: &mut PlaneBuf<'static>,
459 v: &mut PlaneBuf<'static>,
460 x: usize,
461 cy: usize,
462 side: usize,
463 _base_q_idx: u8,
464 prediction: Pred<'_>,
465 // lane-chromau: this block's own luma transform's *actual coded*
466 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
467 // chroma plane never codes its own `tx_type` symbol, but (unlike an
468 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
469 // the colocated luma transform's coded type, narrowed to the extended
470 // set the CHROMA size selects ([`reduce_inherited_chroma_tx_type`]).
471 // `None` for the luma call itself
472 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
473 // `DCT_DCT` default at 32-point+) already resolves it without help.
474 inherited_luma_tx_type: Option<TxType>,
475 // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than
476 // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size`
477 // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block
478 // transform every non-var-tx caller reads, whose plane-0 context is the
479 // lone-transform-unit 0.
480 luma_skip_ctx: Option<usize>,
481 fctx: &crate::decode::FrameCtx,
482) -> Result<(Grid, TxType)> {
483 // lane-av1mono: as [`read_plane`] -- a monochrome frame codes no chroma
484 // coefficients (`plane < av1_num_planes == 1`).
485 if plane_idx > 0 && mono(fctx) {
486 return Ok((Grid::Zero(side * side), TxType::DctDct));
487 }
488 // lane-av1readcensus: the units read from here on are this plane's.
489 set_census_plane(plane_idx);
490 let skip_ctx = if plane_idx == 0 {
491 luma_skip_ctx.unwrap_or(0)
492 } else {
493 // lane-sb128c r1: on a CHROMA plane this same parameter carries
494 // `get_txb_ctx`'s own offset instead -- `combine_entropy_contexts(..)`
495 // is +7 normally and +10 when the plane block is LARGER than the
496 // transform (a 128x128 block's 64x64 uv plane block with TX_32X32
497 // units, AV1's only such case), and the `txb_skip_chroma_32` table
498 // carries the offset-10 rows at +3 (lane-sb128b r3).
499 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
500 };
501 let mut coding = cdfs.txb(set, tx_mode);
502 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
503 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
504 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
505 // plane of a lossless block (the residual then goes through the WHT, so
506 // the type only picks the scan, which is the default one).
507 if lossless(fctx) {
508 coding.tx_type = None;
509 }
510 let default_tx_type = match inherited_luma_tx_type {
511 Some(t) => reduce_inherited_chroma_tx_type(t, side, side, fctx),
512 None => TxType::DctDct,
513 };
514 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
515 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
516 let default_tx_type = if lossless(fctx) {
517 TxType::DctDct
518 } else {
519 default_tx_type
520 };
521 let (grid, tx_type) = read_coeffs(
522 dec,
523 &mut coding,
524 scan,
525 skip_ctx,
526 dc_sign_ctx(around.2),
527 default_tx_type,
528 None,
529 )?;
530 note_chroma_class1(plane_idx, tx_type);
531 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
532 eprintln!(
533 "OUR_TXTYPE plane={plane_idx} x={x} y={cy} side={side} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}"
534 );
535 }
536 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
537 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
538 // caller hands the 32-point `scan` there, and the coded corner goes into
539 // the top-left of the true `side`-sized grid before dequantization
540 // (dqDenom is keyed by the true size, not the corner's), mirroring
541 // [`read_plane`]'s own `tx_side != side` branch. Every other transform
542 // this decoder codes has `tx_side == side`, so this is inert below 64.
543 let tx_side = side.min(32);
544 let grid = extend_corner(grid, tx_side, tx_side, side, side);
545 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
546 let tx = TxParams {
547 plane: plane_idx,
548 w: side,
549 h: side,
550 bit_depth: bit_depth(fctx),
551 q_idx: block_q_idx(fctx),
552 dc_delta,
553 ac_delta,
554 tx_type,
555 qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type),
556 stride: 0,
557 lossless: lossless(fctx),
558 };
559 push_mc_rect_tx(
560 y, u, v, plane_idx, x, cy, side, side, side, prediction, tx, &grid, fctx,
561 );
562 Ok((grid, tx_type))
563}
564
565/// The intra twin of [`read_inter_chroma_lossless`]: an INTRA block inside a
566/// lossless frame codes its chroma plane as 4x4 transform units, plane-major
567/// inside each 64x64 mu chunk (libaom `decode_token_recon_block`'s
568/// `for (plane..) for (blk_row..) for (blk_col..)` with `av1_get_tx_size`
569/// returning TX_4X4 under `xd->lossless[..]`). CfL never rides here:
570/// `is_cfl_allowed` (`blockd.h`) needs a BLOCK_4X4 chroma plane block, i.e. a
571/// luma block of 8x8 or less, which the sub-8x8 readers own.
572#[allow(clippy::too_many_arguments)]
573pub(super) fn read_intra_chroma_lossless(
574 y: &mut PlaneBuf<'static>,
575 u: &mut PlaneBuf<'static>,
576 v: &mut PlaneBuf<'static>,
577 dec: &mut SymbolDecoder,
578 cdfs: &mut Cdfs,
579 neighbours: &mut Neighbours,
580 at_mi: (usize, usize),
581 (px, py): (usize, usize),
582 (cpx, cpy): (usize, usize),
583 side: usize,
584 (blk_w, blk_h): (usize, usize),
585 (org_x, org_y): (usize, usize),
586 (reg_w, reg_h): (usize, usize),
587 stride: usize,
588 reach: Reach,
589 (frame_w, frame_h): (usize, usize),
590 mode: usize,
591 uv_predict_mode: usize,
592 angle_delta_uv: i32,
593 palette_uv_bufs: Option<(&[u16], &[u16])>,
594 smooth_neighbor_uv: bool,
595 base_q_idx: u8,
596 u_out: &mut Vec<i32>,
597 v_out: &mut Vec<i32>,
598 fctx: &crate::decode::FrameCtx,
599) -> Result<()> {
600 let scan4 = default_scan(4);
601 let offset = (blk_w > 4 || blk_h > 4).then_some(3);
602 for plane_idx in 1..3 {
603 for rr in 0..reg_h / 4 {
604 for cc in 0..reg_w / 4 {
605 let (ox, oy) = (org_x + cc * 4, org_y + rr * 4);
606 // libaom's `max_blocks_wide/high` clip: a unit whose origin is
607 // past the frame edge is not coded at all
608 // (`decode_token_recon_block`), same test `decode_block`'s
609 // luma loop already runs.
610 if cpx + ox >= u.true_width || cpy + oy >= u.true_height {
611 continue;
612 }
613 // Chroma pixels per mi cell: 2 at 4:2:0, 4 at 4:4:4. At
614 // 4:2:0 a TX_4X4 chroma unit spans two mi cells and anchors
615 // at the even one; at 4:4:4 it IS one mi cell.
616 let cu_mi = (
617 at_mi.0 + oy / (MI >> ss_y(fctx)),
618 at_mi.1 + ox / (MI >> ss_x(fctx)),
619 );
620 // libaom's chroma entropy-context arrays are SUBSAMPLED:
621 // `get_txb_ctx` reads exactly one entry per plane for a
622 // TX_4X4 chroma unit (`a[0]`/`l[0]`). Our bands are luma-mi
623 // indexed and carry that one entry replicated over the unit's
624 // two cells, so one cell is the same answer -- and the second
625 // cell is past the band on a unit whose block hangs off the
626 // frame edge, which libaom still codes.
627 let cu_around = neighbours.around_mi(cu_mi, MI);
628 // The unit's origin and extent in LUMA pixels: `<< ss` at
629 // 4:2:0 (8x8 luma for a 4x4 chroma unit), identity at 4:4:4.
630 let cu_reach = tu_reach_rect(
631 side,
632 side,
633 ox << ss_x(fctx),
634 oy << ss_y(fctx),
635 4 << ss_x(fctx),
636 4 << ss_y(fctx),
637 reach,
638 px,
639 py,
640 frame_w,
641 frame_h,
642 fctx,
643 );
644 if let Some((ub, vb)) = palette_uv_bufs {
645 let buf = if plane_idx == 1 { ub } else { vb };
646 set_palette_pred(palette_window(buf, stride, ox, oy, 4, 4), fctx);
647 }
648 let cu_grid = read_plane(
649 dec,
650 cdfs,
651 TxbSet::Chroma4,
652 scan4,
653 plane_idx,
654 cu_around[plane_idx],
655 mode,
656 uv_predict_mode,
657 angle_delta_uv,
658 cu_reach,
659 y,
660 u,
661 v,
662 cpx + ox,
663 cpy + oy,
664 4,
665 4,
666 base_q_idx,
667 None,
668 None,
669 offset,
670 smooth_neighbor_uv,
671 fctx,
672 )?;
673 // The unit's own footprint on the LUMA mi grid: 8 luma px
674 // (two cells) at 4:2:0, 4 (one cell) at 4:4:4.
675 neighbours.record_mi_chroma(
676 cu_mi,
677 4 << ss_x(fctx),
678 4 << ss_y(fctx),
679 plane_idx,
680 &cu_grid,
681 );
682 hit!(CHROMA_SPLIT_TX_HITS);
683 let dst = mu_units(
684 if plane_idx == 1 {
685 &mut *u_out
686 } else {
687 &mut *v_out
688 },
689 // lane-av1422lpf site 7: `stride * blk_h`, the intra twin
690 // of site 1. `read_intra_chroma_lossless`'s own
691 // `(blk_w, blk_h)` parameter is the block's whole CHROMA
692 // PLANE BLOCK, per-axis, and the walk below addresses up
693 // to row `org_y + reg_h - 1` at `stride` -- so the
694 // requirement is `stride * blk_h` and `stride * stride`
695 // underruns by exactly the ratio the plane block's height
696 // exceeds its width. Identical number at 4:2:0
697 // (`blk_h == stride`) and 4:4:4.
698 stride * blk_h,
699 );
700 for row in 0..4 {
701 let start = (oy + row) * stride + ox;
702 dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]);
703 }
704 }
705 }
706 }
707 Ok(())
708}
709
710/// lane-av1h5: the CHUNK-MAJOR token order for a block's var-tx leaf list.
711///
712/// libaom's `decode_token_recon_block` (`av1/decoder/decodeframe.c:972`)
713/// iterates 64x64 "mu" chunks with the PLANE loop INSIDE the chunk loop:
714/// `for (row..) for (col..) { for (plane..) for (blk_row..) for (blk_col..) }`,
715/// `blk_row`/`blk_col` restarting at the chunk origin, on a chunk grid of
716/// `mi_size_wide[BLOCK_64X64]` = 16 mi per axis.
717///
718/// The transform tree hands us a BLOCK-wide raster instead (32 leaves across
719/// at 128), whose chunk members are NOT contiguous: leaves 0..15 are chunk
720/// (0,0) row 0, but chunk (0,0) rows 1..15 are leaves 32..47, 64..79, ...
721/// Walking it as given closes each chunk every SIXTEEN leaves and codes its
722/// chroma sixteen times -- 64 chroma walks per 128 root where libaom codes 4,
723/// and 24576 chroma units per inter frame against the oracle's 1536.
724///
725/// Below 64 a block IS one chunk, so the two orders coincide and the sort is
726/// skipped (the returned order is the identity). `changed` is `true` only
727/// when the sort actually permutes the list, so a no-op ordering reads zero
728/// on [`MU_CHUNK_ORDER_HITS`] and cannot make a gate look armed.
729pub(super) fn mu_chunk_order(
730 leaves: &[(usize, usize, usize, usize)],
731 side: usize,
732) -> (Vec<usize>, bool) {
733 let identity: Vec<usize> = (0..leaves.len()).collect();
734 if side <= 64 {
735 return (identity, false);
736 }
737 let nchunk = (side / 64).max(1);
738 let mut order = identity.clone();
739 order.sort_by_key(|&i| ((leaves[i].0 / 16) * nchunk + (leaves[i].1 / 16), i));
740 let changed = order != identity;
741 if changed {
742 hit!(MU_CHUNK_ORDER_HITS);
743 }
744 (order, changed)
745}
746
747/// lane-lossless2: the chroma half of a lossless INTER block. libaom's
748/// `read_tx_size` (`av1/decoder/decodeframe.c`) returns TX_4X4 for EVERY
749/// plane of a lossless block, so the chroma plane block is a raster of 4x4
750/// transform units instead of one whole-block transform, and
751/// `decode_token_recon_block` walks them PLANE-MAJOR inside each 64x64 "mu"
752/// chunk (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
753/// the chunk, then every V unit. Reads one chunk-sized region
754/// (`org`/`reg`, chroma pixels relative to the block) and copies its units
755/// into the block-sized `u_out`/`v_out` grids.
756#[allow(clippy::too_many_arguments)]
757pub(super) fn read_inter_chroma_lossless(
758 y: &mut PlaneBuf<'static>,
759 u: &mut PlaneBuf<'static>,
760 v: &mut PlaneBuf<'static>,
761 dec: &mut SymbolDecoder,
762 cdfs: &mut Cdfs,
763 neighbours: &mut Neighbours,
764 su: Pred<'_>,
765 sv: Pred<'_>,
766 at_mi: (usize, usize),
767 (cpx, cpy): (usize, usize),
768 (org_x, org_y): (usize, usize),
769 (reg_w, reg_h): (usize, usize),
770 // the whole block's chroma plane block -- what `get_txb_ctx`'s offset is
771 // decided on.
772 (blk_w, blk_h): (usize, usize),
773 // the stride the predictors and the block-sized `u_out`/`v_out` are read
774 // at (the block's square chroma side, even for a 2:1 strip, which embeds
775 // its narrower plane block in the same square grid).
776 stride: usize,
777 mode_for_tx: usize,
778 base_q_idx: u8,
779 u_out: &mut Vec<i32>,
780 v_out: &mut Vec<i32>,
781 fctx: &crate::decode::FrameCtx,
782) -> Result<()> {
783 let scan4 = default_scan(4);
784 // `get_txb_ctx` (`av1/common/txb_common.h`): `ctx_offset` is 10 when the
785 // plane block is bigger than the transform and 7 when it is the
786 // transform -- our chroma tables carry the offset-10 rows at +3.
787 let offset = (blk_w > 4 || blk_h > 4).then_some(3);
788 // lane-av1h5: a plane block above 64 is the 128-root class, whose chroma
789 // libaom walks one 64x64 mu chunk at a time. Counted so a gate can pin
790 // the walk/unit totals exactly rather than as a floor on wrong output.
791 let counted_128 = blk_w > 64 || blk_h > 64;
792 if counted_128 {
793 hit!(MU_CHUNK_WALKS);
794 }
795 for plane_idx in 1..3 {
796 for rr in 0..reg_h / 4 {
797 for cc in 0..reg_w / 4 {
798 let (ox, oy) = (org_x + cc * 4, org_y + rr * 4);
799 // libaom's `max_blocks_wide/high` clip: a unit whose origin is
800 // past the frame edge is not coded at all
801 // (`decode_token_recon_block`), same test `decode_block`'s
802 // luma loop already runs.
803 if cpx + ox >= u.true_width || cpy + oy >= u.true_height {
804 continue;
805 }
806 // The chroma neighbour bands are indexed in LUMA mi: a 4-wide
807 // chroma unit spans `4 << ss` luma pixels, i.e. `4 >> ss` --
808 // 2 mi cells at 4:2:0, one at 4:4:4.
809 let cu_mi = (
810 at_mi.0 + oy / (4 >> ss_y(fctx)),
811 at_mi.1 + ox / (4 >> ss_x(fctx)),
812 );
813 // libaom's chroma entropy-context arrays are SUBSAMPLED:
814 // `get_txb_ctx` reads exactly one entry per plane for a
815 // TX_4X4 chroma unit (`a[0]`/`l[0]`). Our bands are luma-mi
816 // indexed and carry that one entry replicated over the unit's
817 // two cells, so one cell is the same answer -- and the second
818 // cell is past the band on a unit whose block hangs off the
819 // frame edge, which libaom still codes.
820 let cu_around = neighbours.around_mi(cu_mi, MI);
821 let src = if plane_idx == 1 { su } else { sv };
822 let cu_grid = read_inter_plane(
823 dec,
824 cdfs,
825 TxbSet::Chroma4,
826 scan4,
827 plane_idx,
828 cu_around[plane_idx],
829 mode_for_tx,
830 y,
831 u,
832 v,
833 cpx + ox,
834 cpy + oy,
835 4,
836 base_q_idx,
837 src.offset(oy * stride + ox),
838 // A lossless block codes DCT_DCT on every plane
839 // (`av1_get_tx_type`, `blockd.h`), so nothing is
840 // inherited from the luma unit.
841 None,
842 offset,
843 fctx,
844 )?
845 .0;
846 // Immediately, so the NEXT unit reads this one's context.
847 neighbours.record_mi_chroma(
848 cu_mi,
849 4 << ss_x(fctx),
850 4 << ss_y(fctx),
851 plane_idx,
852 &cu_grid,
853 );
854 hit!(CHROMA_SPLIT_TX_HITS);
855 if counted_128 {
856 hit!(MU_CHUNK_WALK_UNITS);
857 }
858 let dst = mu_units(
859 if plane_idx == 1 {
860 &mut *u_out
861 } else {
862 &mut *v_out
863 },
864 // lane-av1422lpf site 1: `stride * blk_h`, NOT
865 // `stride * stride`. The composed `u_out`/`v_out` grid is
866 // the block's whole CHROMA PLANE BLOCK read at `stride`,
867 // and libaom's plane block is PER-AXIS
868 // (`(bw >> ss_x) x (bh >> ss_y)`, decodeframe.c's
869 // `dec->uv_buffer` extent) -- square only when
870 // `ss_x == ss_y`. The walk above addresses row
871 // `org_y + reg_h - 1` at column `org_x + reg_w`, and every
872 // call site passes a region that is a sub-rect of `blk`
873 // with `org` inside `blk`, so the requirement is exactly
874 // `stride * blk_h` (the last row's end
875 // `(blk_h - 1) * stride + blk_w` fits because
876 // `blk_w <= stride` at all nine call sites).
877 //
878 // Where the plane block IS square -- 4:2:0 (`side/2` both
879 // axes) and 4:4:4 (`side` both axes) on a square block --
880 // `blk_h == stride` and this reduces to the old
881 // `stride * stride` verbatim, so it cannot move a byte
882 // there. It is not 4:2:2-only either: a 64x128 4:2:0 block
883 // has a 32x64 chroma plane block, and `ll420_a.obu`
884 // (`range end index 1028 out of range for slice of
885 // length 1024`) panicked on the old expression.
886 stride * blk_h,
887 );
888 for row in 0..4 {
889 let start = (oy + row) * stride + ox;
890 dst[start..start + 4].copy_from_slice(&cu_grid[row * 4..][..4]);
891 }
892 }
893 }
894 }
895 Ok(())
896}
897
898/// The 8x8 inter leaf's lossless chroma arm (lane-av1-llinter), shared by the
899/// single-ref and compound paths, for every plane block BIGGER than 4x4:
900/// libaom's `read_tx_size` (`av1/decoder/decodeframe.c:1197`,
901/// `if (xd->lossless[xd->mi[0]->segment_id]) return TX_4X4;`) returns TX_4X4
902/// for EVERY plane of a lossless block, not just luma, so the plane block is
903/// a raster of TX_4X4 units read by the same per-unit walk the bigger inter
904/// blocks run.
905///
906/// **The plane block is PER-AXIS**, `av1_ss_size_lookup[BLOCK_8X8][ss_x][ss_y]`
907/// (`av1/common/blockd.h:1186`): BLOCK_8X8 at 4:4:4 (2x2 units), BLOCK_4X8 at
908/// 4:2:2 (1x2 units), BLOCK_4X4 at 4:2:0 (one unit, `get_txb_ctx`'s
909/// `plane_bsize == txsize_to_bsize[tx_size]` branch, ctx_offset 7 -- the one
910/// shape that keeps the single-unit read and is NOT routed here). Gating this
911/// arm on the 4:4:4 shape instead left 4:2:2 coding its 4x8 plane block as ONE
912/// TX_4X8 unit at ctx_offset 7, where libaom reads TWO TX_4X4 units at
913/// ctx_offset 10 (`av1/common/txb_common.h:430-433`): the first unit's
914/// `txb_skip` symbol then came out of the wrong CDF row, which desynchronised
915/// the coder for the rest of the frame.
916///
917/// `(blk_w, blk_h)` is that per-axis plane block and `stride` the composed
918/// grid's row pitch (the leaf's `chroma_w`); the grids are `stride * blk_h`
919/// (`Grid::Zero` when every unit hung off the frame edge) and each unit's own
920/// coefficient context is left stamped in the neighbour bands -- the caller's
921/// tail must not let its whole-block `record_mi` overwrite them.
922#[allow(clippy::too_many_arguments)]
923pub(super) fn leaf8_inter_chroma_lossless(
924 y: &mut PlaneBuf<'static>,
925 u: &mut PlaneBuf<'static>,
926 v: &mut PlaneBuf<'static>,
927 dec: &mut SymbolDecoder,
928 cdfs: &mut Cdfs,
929 neighbours: &mut Neighbours,
930 su: Pred<'_>,
931 sv: Pred<'_>,
932 at_mi: (usize, usize),
933 (cpx, cpy): (usize, usize),
934 // The leaf's CHROMA PLANE BLOCK, per axis, and the composed grid's row
935 // pitch -- `(8, 8)`/`8` at 4:4:4, `(4, 8)`/`4` at 4:2:2.
936 (blk_w, blk_h): (usize, usize),
937 stride: usize,
938 base_q_idx: u8,
939 fctx: &crate::decode::FrameCtx,
940) -> Result<(Grid, Grid)> {
941 let (mut uo, mut vo) = (Vec::new(), Vec::new());
942 read_inter_chroma_lossless(
943 y,
944 u,
945 v,
946 dec,
947 cdfs,
948 neighbours,
949 su,
950 sv,
951 at_mi,
952 (cpx, cpy),
953 (0, 0),
954 (blk_w, blk_h),
955 (blk_w, blk_h),
956 stride,
957 0,
958 base_q_idx,
959 &mut uo,
960 &mut vo,
961 fctx,
962 )?;
963 let n = stride * blk_h;
964 Ok((
965 if uo.is_empty() {
966 Grid::Zero(n)
967 } else {
968 Grid::Own(uo)
969 },
970 if vo.is_empty() {
971 Grid::Zero(n)
972 } else {
973 Grid::Own(vo)
974 },
975 ))
976}
977
978/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
979/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
980/// `reference_select` set before this is ever called, so that read is never
981/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
982/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
983pub(super) fn read_single_ref(
984 dec: &mut SymbolDecoder,
985 cdfs: &mut Cdfs,
986 above_ref: i8,
987 above_ref1: Option<i8>,
988 left_ref: i8,
989 left_ref1: Option<i8>,
990) -> i8 {
991 let above = (above_ref > 0).then_some(above_ref);
992 let left = (left_ref > 0).then_some(left_ref);
993 let p1 =
994 dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
995 let ref_frame = if p1 == 1 {
996 let p2 = dec
997 .symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
998 if p2 == 1 {
999 ALTREF_FRAME
1000 } else {
1001 let p6 = dec.symbol(
1002 &mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5],
1003 );
1004 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
1005 }
1006 } else {
1007 let p3 = dec
1008 .symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
1009 if p3 == 1 {
1010 let p5 = dec.symbol(
1011 &mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4],
1012 );
1013 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
1014 } else {
1015 let p4 = dec.symbol(
1016 &mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3],
1017 );
1018 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
1019 }
1020 };
1021 if ref_frame != LAST_FRAME {
1022 hit!(NON_LAST_REF_HITS);
1023 let c = match ref_frame {
1024 LAST2_FRAME => &LAST2_HITS,
1025 LAST3_FRAME => &LAST3_HITS,
1026 GOLDEN_FRAME => &GOLDEN_HITS,
1027 BWDREF_FRAME => &BWDREF_HITS,
1028 ALTREF2_FRAME => &ALTREF2_HITS,
1029 ALTREF_FRAME => &ALTREF_HITS,
1030 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
1031 };
1032 hit_do! { c.with(|v| v.set(v.get() + 1)); }
1033 }
1034 ref_frame
1035}
1036
1037/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
1038/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
1039/// `reference_select` header bit lets a block choose per-block instead of
1040/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
1041/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
1042/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
1043/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
1044/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
1045/// lane-twostage: this frame's references as DIMENSIONS now and PIXELS on
1046/// demand. An inter tile's parse reads reference SIZES (`mc::scale_factor`)
1047/// only, so the pictures are resolved at the first [`ref_planes`] call
1048/// rather than at frame entry. On the threaded path that resolution is a
1049/// WAIT on the producing frame's pixels, which is what lets a consumer parse
1050/// while its references are still being filtered.
1051/// lane-defer8: the prediction that asks for them can run in a closure, see
1052/// [`ref_planes_deferred`].
1053pub(crate) struct RefPix<'p> {
1054 /// `(width, height)` per `ref_frame` index (`LAST_FRAME` = 1). `None` is
1055 /// a slot this frame may not use: empty. A reference of another size is
1056 /// predicted from through `mc::RefScale` (spec 7.11.3.3).
1057 pub(super) dims: [Option<(usize, usize)>; 8],
1058 pub(super) src: RefSrc<'p>,
1059 pub(super) bufs: std::sync::OnceLock<[Option<(PlaneBuf<'p>, PlaneBuf<'p>, PlaneBuf<'p>)>; 8]>,
1060 /// lane-defer8: a prediction's [`ref_planes`] failure, parked here for
1061 /// the frame decoder to take ([`take_err`](Self::take_err)).
1062 pub(super) err: std::sync::Mutex<Option<Error>>,
1063 /// The same references as shared pictures, when they can be handed to a
1064 /// recon worker (the threaded stream): the worker waits for them itself.
1065 pub(super) shared: Option<SharedRefs>,
1066}
1067
1068/// A frame's reference pictures as `Arc`s behind a wait, for the recon
1069/// workers that build predictions off the parse thread.
1070#[derive(Clone)]
1071pub(crate) struct SharedRefs {
1072 pub(crate) dims: [Option<(usize, usize)>; 8],
1073 pub(crate) wait: std::sync::Arc<
1074 dyn Fn() -> Result<[Option<std::sync::Arc<Picture>>; 8]> + Send + Sync,
1075 >,
1076}
1077
1078/// Where a [`RefPix`] gets its pictures: already in hand, or behind a wait
1079/// the caller owns (`stream.rs`'s reference promises).
1080pub(super) enum RefSrc<'p> {
1081 Ready([Option<&'p Picture>; 8]),
1082 Lazy(&'p (dyn Fn() -> Result<[Option<&'p Picture>; 8]> + Send + Sync + 'p)),
1083}
1084
1085/// spec 7.11.3.3's scale of a reference of `(width, height)` (cropped luma
1086/// sizes) against this frame's `(width, height)`.
1087pub(crate) fn scale_of(
1088 (ref_width, ref_height): (usize, usize),
1089 (frame_width, frame_height): (usize, usize),
1090) -> mc::RefScale {
1091 mc::RefScale::new(ref_width, ref_height, frame_width, frame_height)
1092}
1093
1094impl<'p> RefPix<'p> {
1095 /// References already decoded: the single-threaded path and the test
1096 /// entry points, where [`ref_planes`] never waits.
1097 pub(crate) fn ready(refs: [Option<&'p Picture>; 8]) -> Self {
1098 let dims = std::array::from_fn(|i| refs[i].map(|p| (p.width, p.height)));
1099 Self {
1100 dims,
1101 src: RefSrc::Ready(refs),
1102 bufs: std::sync::OnceLock::new(),
1103 err: std::sync::Mutex::new(None),
1104 shared: None,
1105 }
1106 }
1107
1108 /// References whose sizes are known (from their producers' headers) but
1109 /// whose pixels `wait` still has to produce.
1110 pub(crate) fn lazy(
1111 dims: [Option<(usize, usize)>; 8],
1112 wait: &'p (dyn Fn() -> Result<[Option<&'p Picture>; 8]> + Send + Sync + 'p),
1113 shared: Option<SharedRefs>,
1114 ) -> Self {
1115 Self {
1116 dims,
1117 src: RefSrc::Lazy(wait),
1118 bufs: std::sync::OnceLock::new(),
1119 err: std::sync::Mutex::new(None),
1120 shared,
1121 }
1122 }
1123
1124 /// Whether a recon worker can wait for these references itself.
1125 pub(super) fn is_shared(&self) -> bool {
1126 self.shared.is_some()
1127 }
1128
1129 /// The shareable form of these references, if there is one.
1130 pub(super) fn shared(&self) -> Option<SharedRefs> {
1131 self.shared.clone()
1132 }
1133
1134 /// This slot's picture size, without touching its pixels.
1135 pub(crate) fn dims(&self, ref_frame: i8) -> Option<(usize, usize)> {
1136 self.dims.get(ref_frame as usize).copied().flatten()
1137 }
1138
1139 /// Parks a prediction's failure (first one wins).
1140 pub(super) fn park_err(&self, e: Error) {
1141 let mut slot = self
1142 .err
1143 .lock()
1144 .expect("the parked-error slot is never poisoned");
1145 if slot.is_none() {
1146 *slot = Some(e);
1147 }
1148 }
1149
1150 /// The first failure any prediction parked, taken once the frame's tiles
1151 /// are decoded.
1152 pub(crate) fn take_err(&self) -> Result<()> {
1153 match self
1154 .err
1155 .lock()
1156 .expect("the parked-error slot is never poisoned")
1157 .take()
1158 {
1159 Some(e) => Err(e),
1160 None => Ok(()),
1161 }
1162 }
1163
1164 /// Every usable slot's three planes, resolving (and, on the threaded
1165 /// path, waiting for) the pictures on the first call.
1166 pub(super) fn planes(
1167 &self,
1168 ) -> Result<&[Option<(PlaneBuf<'p>, PlaneBuf<'p>, PlaneBuf<'p>)>; 8]> {
1169 if let Some(bufs) = self.bufs.get() {
1170 return Ok(bufs);
1171 }
1172 let pics = match &self.src {
1173 RefSrc::Ready(refs) => *refs,
1174 RefSrc::Lazy(wait) => wait()?,
1175 };
1176 let dims = self.dims;
1177 let bufs = std::array::from_fn(|i| {
1178 dims[i].and(pics[i]).map(|g| {
1179 (
1180 whole_plane(&g.y, g.width, g.height),
1181 {
1182 // No subsampling field on a stored reference: the
1183 // chroma format comes off its own sample count --
1184 // 4:4:4 `w * h`, 4:2:2 `round_ss(w, 1) * h`, 4:2:0
1185 // `round_ss(w, 1) * round_ss(h, 1)`. The helper's own
1186 // doc carries the measurement behind those three arms
1187 // and the pre-existing odd-dimension 4:2:0 gap.
1188 let (cw, ch) = ref_chroma_shape(g.u.len(), g.width, g.height);
1189 whole_plane(&g.u, cw, ch)
1190 },
1191 {
1192 let (cw, ch) = ref_chroma_shape(g.v.len(), g.width, g.height);
1193 whole_plane(&g.v, cw, ch)
1194 },
1195 )
1196 })
1197 });
1198 let _ = self.bufs.set(bufs);
1199 Ok(self.bufs.get().expect("the plane array was just set"))
1200 }
1201}
1202
1203/// This slot's picture SIZE, with [`ref_planes`]' own error when the slot
1204/// carries no usable picture -- `dims` is `None` exactly when `planes()`
1205/// would have nothing there, so the parse thread keeps refusing the same
1206/// streams at the same block WITHOUT waiting for a producer's pixels
1207/// (lane-defer8).
1208pub(super) fn ref_dims(ref_frame: i8, refpix: &RefPix<'_>) -> Result<(usize, usize)> {
1209 refpix.dims(ref_frame).ok_or_else(|| {
1210 if crate::envflags::env_flag!("EC_AV1_REFPROBE") {
1211 eprintln!(
1212 "EC_REFPROBE missing ref {ref_frame}\n{}",
1213 std::backtrace::Backtrace::force_capture()
1214 );
1215 }
1216 // lane-hdrlossless: libaom errors on the same stream
1217 // (`decodeframe.c:5027`: `if (cm->ref_frame_map[ref] == NULL)
1218 // aom_internal_error(... AOM_CODEC_CORRUPT_FRAME, "Inter frame
1219 // requests nonexistent reference")`) -- a spec-conformant guard.
1220 unsupported(
1221 "a reference frame selected with no picture at this frame's own \
1222 ref_frame_idx slot for it",
1223 )
1224 })
1225}
1226
1227/// [`ref_planes`] from inside a prediction closure, where there is no `?`
1228/// to take: the error is parked on the [`RefPix`] and taken by the frame
1229/// decoder ([`RefPix::take_err`]). The block's
1230/// prediction is left zeroed -- the frame is failing either way.
1231pub(super) fn ref_planes_deferred<'a, 'p>(
1232 ref_frame: i8,
1233 refpix: &'a RefPix<'p>,
1234) -> Option<(&'a PlaneBuf<'p>, &'a PlaneBuf<'p>, &'a PlaneBuf<'p>)> {
1235 match ref_planes(ref_frame, refpix) {
1236 Ok(planes) => Some(planes),
1237 Err(e) => {
1238 refpix.park_err(e);
1239 None
1240 }
1241 }
1242}
1243
1244/// A whole reference plane as a [`PlaneBuf`]: no tile window, no margin.
1245pub(super) fn whole_plane(data: &[u16], width: usize, height: usize) -> PlaneBuf<'_> {
1246 PlaneBuf {
1247 data: std::borrow::Cow::Borrowed(data),
1248 width,
1249 height,
1250 true_width: width,
1251 true_height: height,
1252 tile_x0: 0,
1253 tile_y0: 0,
1254 tile_x1: width,
1255 tile_y1: height,
1256 plane: 0,
1257 }
1258}
1259
1260/// A reference picture's own chroma plane shape, `(width, height)`, from its
1261/// luma size and its chroma sample count. A stored reference carries no
1262/// subsampling field, so the format is read back off the count -- and the
1263/// counts are the producer's own [`round_ss`] crops
1264/// (`decode.rs:25806`), so the test must use `round_ss` too and not a bare
1265/// halving: 4:4:4 stores `w * h`, 4:2:2 stores `round_ss(w, 1) * h` (half
1266/// width CEIL, full height), 4:2:0 stores `round_ss(w, 1) * round_ss(h, 1)`.
1267/// A floor test here silently misses every odd-width 4:2:2 reference and
1268/// drops it into the 4:2:0 arm -- the same defect one dimension over.
1269///
1270/// The two-way test this replaces ("luma-sized, else a quarter") folded 4:2:2
1271/// into the 4:2:0 shape entirely, so a 4:2:2 reference plane claimed
1272/// `h / 2` rows -- half the samples it actually holds. Every chroma MC
1273/// reading such a plane then had its source row clamped against
1274/// `true_height` (spec 7.11.3.4 / libaom's
1275/// `dec_calc_subpel_params_and_extend` clamps to the reference's valid
1276/// area), which folded every chroma row at or past the frame's midpoint
1277/// back onto the last valid row: on the pinned t422 fixture frame 1, the
1278/// 8x4 inter strip at luma (88, 208) MC-predicted chroma (88, 104) from
1279/// frame 0 with mv 0 and a pure copy, yet wrote (206, 204, 202, 200) x4
1280/// rows where the reference holds (202, 204, 204, 167) /
1281/// (185, 190, 190, 165) / ...
1282/// **Ambiguity, measured rather than argued away:** the inference reads a
1283/// format off a length, so it is only as good as the lengths being
1284/// distinct. Brute-forced against the producer's own `round_ss` crops over
1285/// every `w, h` in `1..=128`, the 4:4:4 and 4:2:2 counts are distinct from
1286/// each other and from the 4:2:0 count, and both route correctly for
1287/// **every `w >= 2 && h >= 2`**. No stream this decoder accepts reaches a
1288/// 1-pixel chroma plane; the pinned fixture's chroma is 128x144.
1289///
1290/// **4:2:0 at odd dimensions: CLOSED by lane-av1odd440.** The arm used to be
1291/// the old `(width / 2, height / 2)` floor, which was what the two-way test
1292/// this replaces produced -- harmless then, since no 4:2:0 stream changed
1293/// shape, and wrong for an odd-dimension 4:2:0 reference: the producer
1294/// stored `round_ss(w, 1) x round_ss(h, 1)`, so the floor arm
1295/// under-declared. Measured over the `1..=128` square, running each 4:2:0
1296/// count through this very function: 12160 of the 16384 pairs came back
1297/// smaller than the plane actually holds, 12033 of those with `w >= 2` and
1298/// 127 in the `w == 1` column, where the floor cannot even express
1299/// `(1, round_ss(h, 1))`. It was left alone pending "a lane that can bring
1300/// odd-dimension 4:2:0 fixtures with it" -- this is that lane: the pinned
1301/// `420_odd65x65_key.obu` is a real 65x65 4:2:0 key frame (declared at
1302/// `encode::encode_key_frame_at_size`, because aomenc rounds the coded size
1303/// down to even and cannot produce one) whose chroma planes are 33x33, and
1304/// the gate `an_odd_luma_420_key_frame_decodes_pixel_exact` decodes it
1305/// sample-exact against `aomdec`. The arm is now the producer's own crop,
1306/// so a 4:2:0 reference at ANY size routes back to the shape the producer
1307/// wrote. Even sizes are untouched: `(2k + 1) / 2 == k`, so every 4:2:0
1308/// reference this decoder met before this lane claims exactly the same
1309/// shape it did then.
1310pub(super) fn ref_chroma_shape(len: usize, width: usize, height: usize) -> (usize, usize) {
1311 let half_w = round_ss(width, 1);
1312 if len == width * height {
1313 (width, height)
1314 } else if len == half_w * height {
1315 (half_w, height)
1316 } else {
1317 (round_ss(width, 1), round_ss(height, 1))
1318 }
1319}
1320
1321/// Resolves a reference's own planes -- the `ref_frame -> picture` lookup
1322/// [`decode_inter_block`]'s single-ref path does, factored out so the
1323/// compound path can call it twice (lane-av1comp), and the point where
1324/// lane-twostage's pixel wait happens.
1325pub(super) fn ref_planes<'a, 'p>(
1326 ref_frame: i8,
1327 refpix: &'a RefPix<'p>,
1328) -> Result<(&'a PlaneBuf<'p>, &'a PlaneBuf<'p>, &'a PlaneBuf<'p>)> {
1329 match refpix
1330 .planes()?
1331 .get(ref_frame as usize)
1332 .and_then(Option::as_ref)
1333 {
1334 Some((y, u, v)) => Ok((y, u, v)),
1335 None => Err(unsupported(
1336 "a reference frame selected with no picture at this frame's own \
1337 ref_frame_idx slot for it",
1338 )),
1339 }
1340}
1341
1342/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
1343/// directly above this block's own column span, one bordering block at a
1344/// time (stepping by that neighbour's own `MiInfo::size`, which is always
1345/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
1346/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
1347/// unit at a time, and does not itself count as a step). `max_neighbors`
1348/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
1349/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
1350/// real blend pass. lane-intra16x4 r2: libaom's own "4-wide block, treat as
1351/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) IS
1352/// ported below -- the round-1 note that no block is narrower than 8px stopped
1353/// being true when the 1:4 partitions landed. A 16x4 / 4x16 strip has
1354/// `mi_size_high`/`mi_size_wide` 1, so libaom snaps the walk back to the pair's
1355/// even index, reads the ODD (chroma-carrying) half as the neighbour and steps
1356/// by 2. Measured: the 16x16 block right of a 16x16-level HORZ_4 partition
1357/// whose strip 0 is inter and strips 1..3 intra counted that inter strip as
1358/// overlappable here, while libaom's pair merge reads the INTRA strip 1 and
1359/// counts none -- so we read a `motion_mode` symbol libaom never wrote (class
1360/// `symbol-consumption-gap`), desyncing the tile at the next coefficient.
1361pub(super) fn overlappable_above(
1362 grid: &MiGrid,
1363 mi_row: usize,
1364 mi_col: usize,
1365 bw4: usize,
1366 mi_cols: usize,
1367 max_neighbors: usize,
1368) -> Vec<(usize, usize, MiInfo, usize)> {
1369 // lane-alloc: bounded by `max_neighbors`, so size it once.
1370 let mut out = Vec::with_capacity(max_neighbors);
1371 if mi_row == 0 {
1372 return out;
1373 }
1374 let end_col = (mi_col + bw4).min(mi_cols);
1375 let mut col = mi_col;
1376 while col < end_col && out.len() < max_neighbors {
1377 let cell = grid.get(mi_row - 1, col);
1378 let mut step = cell
1379 .map_or(1, |c| c.size as usize)
1380 .max(1)
1381 .min(SB_MI as usize);
1382 let mut nb = cell;
1383 // lane-obmcrec r1: the mi the neighbour's `MiInfo` is actually taken
1384 // from -- the pair merge below moves it, and libaom reads that same
1385 // `mbmi`'s `interp_filters` (`av1_setup_build_prediction_by_above_pred`).
1386 let mut src = col;
1387 if step == 1 {
1388 // The pair merge: the walk snaps back to the pair's even column
1389 // and the ODD half (the chroma-carrying one) is the neighbour for
1390 // both -- a 4-wide 1:4 strip is never an OBMC source on its own.
1391 // lane-av1422warp r33 (reviewer P2): the snap must be UNCONDITIONAL.
1392 // libaom `obmc.h:41-46` is
1393 // `above_mi = prev_row_mi + (above_mi_col & ~1) + 1` -- the snapped
1394 // COLUMN is used as-is and the +1 is what lands it back on the
1395 // block's own left edge. Clamping the snapped INDEX to `mi_col`
1396 // (an earlier r25 attempt) moved the index itself, so this
1397 // decoded the neighbour one column RIGHT of libaom's and, after
1398 // `col += step`, never visited `mi_col + 1`. Only the REPORTED
1399 // offset can be negative -- `above_mi - mi_col == -1` -- so the
1400 // clamp belongs there, not on the index.
1401 col &= !1;
1402 src = col + 1;
1403 nb = grid.get(mi_row - 1, src);
1404 step = 2;
1405 }
1406 if let Some(info) = nb
1407 && info.is_inter
1408 {
1409 if src != col {
1410 hit!(OBMC_PAIR_FILTER_HITS);
1411 }
1412 // lane-t900 r14: libaom passes `AOMMIN(xd->width, mi_step)`
1413 // as `op_mi_size` -- the block's OWN width, never the
1414 // frame-edge clamp `end_col` carries. Clamping here shrank the
1415 // neighbour PREDICTION at a frame edge, which picks the
1416 // 4-tap kernel below 8 px (class narrow-block-sharp-kernel);
1417 // the destination clip stays in `obmc_blend`.
1418 out.push((
1419 col.saturating_sub(mi_col),
1420 step.min(bw4),
1421 info,
1422 src - mi_col,
1423 ));
1424 }
1425 col += step;
1426 }
1427 out
1428}
1429
1430/// `foreach_overlappable_nb_left`'s left-column mirror of
1431/// [`overlappable_above`] -- see its doc for the shared corner-cut.
1432pub(super) fn overlappable_left(
1433 grid: &MiGrid,
1434 mi_row: usize,
1435 mi_col: usize,
1436 bh4: usize,
1437 mi_rows: usize,
1438 max_neighbors: usize,
1439) -> Vec<(usize, usize, MiInfo, usize)> {
1440 // lane-alloc: bounded by `max_neighbors`, so size it once.
1441 let mut out = Vec::with_capacity(max_neighbors);
1442 if mi_col == 0 {
1443 return out;
1444 }
1445 let end_row = (mi_row + bh4).min(mi_rows);
1446 let mut row = mi_row;
1447 while row < end_row && out.len() < max_neighbors {
1448 let cell = grid.get(row, mi_col - 1);
1449 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
1450 // width (8) would swallow the strip below it.
1451 let mut step = cell
1452 .map_or(1, |c| c.size_h as usize)
1453 .max(1)
1454 .min(SB_MI as usize);
1455 let mut nb = cell;
1456 // lane-obmcrec r1: see `overlappable_above`'s `src`.
1457 let mut src = row;
1458 if step == 1 {
1459 // The pair merge, left-column mirror: a 4-TALL neighbour (a 16x4
1460 // strip) is half of a chroma pair and the pair's SECOND row is the
1461 // neighbour for both.
1462 // lane-av1422warp r33 (reviewer P2): the row mirror of the
1463 // `overlappable_above` fix. libaom's left-column walk snaps
1464 // `(left_mi_row & ~1)` and adds 1; the snap is unconditional and
1465 // only the REPORTED `row - mi_row` can be -1. The r25 clamp moved
1466 // the snapped index itself, which read the neighbour one row
1467 // BELOW libaom's and then skipped `mi_row + 1` entirely.
1468 row &= !1;
1469 src = row + 1;
1470 nb = grid.get(src, mi_col - 1);
1471 step = 2;
1472 }
1473 if let Some(info) = nb
1474 && info.is_inter
1475 {
1476 if src != row {
1477 hit!(OBMC_PAIR_FILTER_HITS);
1478 }
1479 // lane-t900 r14: `AOMMIN(xd->height, mi_step)` -- see
1480 // `overlappable_above`.
1481 out.push((
1482 row.saturating_sub(mi_row),
1483 step.min(bh4),
1484 info,
1485 src - mi_row,
1486 ));
1487 }
1488 row += step;
1489 }
1490 out
1491}
1492
1493/// libaom `motion_mode_allowed`'s neighbour term: does ANY bordering inter
1494/// block sit on this block's above row or left column ("check_num_overlappable
1495/// _neighbors", `obmc.h`). The single source of truth for the DECODER's own
1496/// `motion_mode_eligible` and for the tile WRITER's (`tile::write_motion_mode`)
1497/// -- the two disagreeing by one block writes a `motion_mode` symbol the
1498/// decoder never reads (class `symbol-consumption-gap`).
1499pub(crate) fn has_overlappable_neighbour(
1500 grid: &MiGrid,
1501 mi_row: usize,
1502 mi_col: usize,
1503 bw4: usize,
1504 bh4: usize,
1505 mi_cols: usize,
1506 mi_rows: usize,
1507) -> bool {
1508 !overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, 1).is_empty()
1509 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, 1).is_empty()
1510}
1511
1512/// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples`
1513/// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2:
1514/// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128`
1515/// libaom's mask loop runs one level further and strips the top-right sample
1516/// off blocks whose neighbour IS decoded, so a warped 128-superblock frame
1517/// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates
1518/// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is
1519/// the block's own side in 4x4 (`mi`) units (square inter leaves only here).
1520pub(super) fn has_top_right(
1521 mi_row: usize,
1522 mi_col: usize,
1523 bs: usize,
1524 fctx: &crate::decode::FrameCtx,
1525) -> bool {
1526 crate::mvstack::has_top_right(mi_row, mi_col, bs, bs, fctx)
1527}
1528
1529/// `av1_findSamples` (`mvref_common.c`), full port: the up to
1530/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
1531/// samples (`record_samples`) that share this block's own single reference
1532/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
1533/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
1534/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
1535/// libaom are also mi units of that same square side here). Each sample's
1536/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
1537/// come from the *neighbour* cell's own coded size, not this block's.
1538#[allow(clippy::too_many_arguments)]
1539pub(crate) fn find_samples(
1540 grid: &MiGrid,
1541 mi_row: usize,
1542 mi_col: usize,
1543 bw4: usize,
1544 bh4: usize,
1545 mi_cols: usize,
1546 mi_rows: usize,
1547 ref_frame: i8,
1548 fctx: &crate::decode::FrameCtx,
1549) -> Vec<crate::warp::Sample> {
1550 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
1551 let up_available = mi_row > 0;
1552 let left_available = mi_col > 0;
1553 let mut samples = Vec::with_capacity(MAX);
1554 // lane-t900 r9: `EC_PROJ_MI=<mi_row>,<mi_col>` lists this block's warp
1555 // sample candidates in libaom's own order (above, left, top-left,
1556 // top-right) -- `num_proj_ref >= 1` is what picks the 3-symbol
1557 // motion_mode alphabet over the 2-symbol obmc one.
1558 // lane-alloc: the `format!` (and the map lookup's `String` clone) ran on
1559 // every warp block; the flag itself is a process constant.
1560 let proj_dbg = crate::envflags::env_flag!("EC_PROJ_MI")
1561 && crate::envflags::var("EC_PROJ_MI").is_ok_and(|v| v == format!("{mi_row},{mi_col}"));
1562 let single_ref_match = |info: &MiInfo| {
1563 let m = info.ref_frame == ref_frame && info.ref_frame1 == NO_REF1;
1564 if proj_dbg {
1565 eprintln!(
1566 "EC_PROJ cand ref={} ref1={:?} size={} size_h={} is_inter={} want={ref_frame} match={m}",
1567 info.ref_frame, info.ref_frame1, info.size, info.size_h, info.is_inter
1568 );
1569 }
1570 m
1571 };
1572 let mut do_tl = true;
1573 let mut do_tr = true;
1574 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
1575 let nb_bw = (info.size * 4) as i32;
1576 // lane-rect r2: the neighbour's own true height -- a rect strip
1577 // neighbour donates its sample at ITS center (aom pts y=-72 for a
1578 // 32x16 above strip; the square assumption put it at -136).
1579 let nb_bh = (info.size_h * 4) as i32;
1580 crate::warp::record_sample(
1581 nb_bw,
1582 nb_bh,
1583 mv32(info.mv),
1584 row_offset,
1585 sign_r,
1586 col_offset,
1587 sign_c,
1588 )
1589 };
1590
1591 'outer: {
1592 if up_available {
1593 let above = grid.get(mi_row - 1, mi_col);
1594 let superblock_width = above.map_or(1, |c| c.size as usize).max(1);
1595 if bw4 <= superblock_width {
1596 let col_offset = -((mi_col % superblock_width) as isize);
1597 if col_offset < 0 {
1598 do_tl = false;
1599 }
1600 if col_offset + superblock_width as isize > bw4 as isize {
1601 do_tr = false;
1602 }
1603 if let Some(info) = above
1604 && single_ref_match(&info)
1605 {
1606 samples.push(rec(&info, 0, -1, col_offset as i32, 1));
1607 if samples.len() >= MAX {
1608 break 'outer;
1609 }
1610 }
1611 } else {
1612 let mut i = 0usize;
1613 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
1614 while i < limit {
1615 let cell = grid.get(mi_row - 1, mi_col + i);
1616 let sw = cell.map_or(1, |c| c.size as usize).max(1);
1617 if let Some(info) = cell
1618 && single_ref_match(&info)
1619 {
1620 samples.push(rec(&info, 0, -1, i as i32, 1));
1621 if samples.len() >= MAX {
1622 break 'outer;
1623 }
1624 }
1625 i += sw;
1626 }
1627 }
1628 }
1629
1630 if left_available {
1631 let left = grid.get(mi_row, mi_col - 1);
1632 let superblock_height = left.map_or(1, |c| c.size_h as usize).max(1);
1633 if bh4 <= superblock_height {
1634 let row_offset = -((mi_row % superblock_height) as isize);
1635 if row_offset < 0 {
1636 do_tl = false;
1637 }
1638 if let Some(info) = left
1639 && single_ref_match(&info)
1640 {
1641 samples.push(rec(&info, row_offset as i32, 1, 0, -1));
1642 if samples.len() >= MAX {
1643 break 'outer;
1644 }
1645 }
1646 } else {
1647 let mut i = 0usize;
1648 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
1649 while i < limit {
1650 let cell = grid.get(mi_row + i, mi_col - 1);
1651 let sh = cell.map_or(1, |c| c.size_h as usize).max(1);
1652 if let Some(info) = cell
1653 && single_ref_match(&info)
1654 {
1655 samples.push(rec(&info, i as i32, 1, 0, -1));
1656 if samples.len() >= MAX {
1657 break 'outer;
1658 }
1659 }
1660 i += sh;
1661 }
1662 }
1663 }
1664
1665 if do_tl
1666 && left_available
1667 && up_available
1668 && let Some(info) = grid.get(mi_row - 1, mi_col - 1)
1669 && single_ref_match(&info)
1670 {
1671 samples.push(rec(&info, 0, -1, 0, -1));
1672 if samples.len() >= MAX {
1673 break 'outer;
1674 }
1675 }
1676
1677 // lane-t900 r9: libaom passes `AOMMAX(xd->width, xd->height)` here
1678 // (`mvref_common.c:1235`), NOT the block's width -- a rect block's
1679 // top-right reach is probed at its LONGER side. With `bw4` a 64x128
1680 // block found a top-right sample libaom never sees, so
1681 // `num_proj_ref >= 1` picked the 3-symbol `motion_mode_cdf` where
1682 // libaom reads the 2-symbol `obmc_cdf` (class
1683 // wrong-alphabet-same-value).
1684 let tr_reach = crate::mvstack::has_top_right(mi_row, mi_col, bw4, bh4, fctx);
1685 if do_tr && bw4 != bh4 && tr_reach != has_top_right(mi_row, mi_col, bw4, fctx) {
1686 hit!(TR_REACH_LONGER_SIDE_HITS);
1687 }
1688 if do_tr && tr_reach {
1689 let tr_col = mi_col + bw4;
1690 if mi_row > 0
1691 && tr_col < mi_cols
1692 && let Some(info) = grid.get(mi_row - 1, tr_col)
1693 && single_ref_match(&info)
1694 {
1695 samples.push(rec(&info, 0, -1, bw4 as i32, 1));
1696 }
1697 }
1698 }
1699 samples
1700}
1701
1702/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
1703/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
1704/// the 2-symbol `obmc_cdf` (spec 5.11.24).
1705#[allow(clippy::too_many_arguments)]
1706pub(crate) fn num_proj_ref(
1707 grid: &MiGrid,
1708 mi_row: usize,
1709 mi_col: usize,
1710 bw4: usize,
1711 bh4: usize,
1712 mi_cols: usize,
1713 mi_rows: usize,
1714 ref_frame: i8,
1715 fctx: &crate::decode::FrameCtx,
1716) -> u8 {
1717 find_samples(
1718 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx,
1719 )
1720 .len() as u8
1721}
1722
1723/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
1724/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
1725/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
1726/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
1727/// to 64 (no neighbour contribution) away from it. Only the lengths this
1728/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
1729/// are transcribed.
1730fn obmc_mask(len: usize) -> &'static [u8] {
1731 // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c`
1732 // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so
1733 // its overlap is 2 (and 1 at a half-block edge). Unreachable until this
1734 // round wired interior 16x16 splits down to real 8x8 leaves, where the
1735 // old `unreachable!()` below fired as a hard panic.
1736 const M1: [u8; 1] = [64];
1737 // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the
1738 // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2
1739 // chroma), which only became live once 8x8 inter leaves stopped being
1740 // refused.
1741 const M2: [u8; 2] = [45, 64];
1742 const M4: [u8; 4] = [39, 50, 59, 64];
1743 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
1744 const M16: [u8; 16] = [
1745 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
1746 ];
1747 const M32: [u8; 32] = [
1748 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60, 61,
1749 62, 64, 64, 64, 64, 64, 64, 64, 64,
1750 ];
1751 match len {
1752 1 => &M1,
1753 2 => &M2,
1754 4 => &M4,
1755 8 => &M8,
1756 16 => &M16,
1757 32 => &M32,
1758 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
1759 }
1760}
1761
1762/// A bordering block's own resolved interp filter kernel, `(h, v)` --
1763/// mirrors [`resolve_interp_filter`]'s own return order from its stored
1764/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
1765/// `[v_sym, h_sym]`). The `[3, 3]` sentinel is only ever stored for an intra
1766/// neighbour (excluded by [`overlappable_above`]/[`overlappable_left`]'s
1767/// `is_inter` gate) or when `interp_fixed` is `Some` for the whole frame
1768/// (handled here first) -- so a sentinel reaching the kernel lookup means the
1769/// stream desynced upstream, and this refuses instead of panicking.
1770pub(super) fn neighbour_filter(
1771 interp_fixed: Option<mc::InterpFilterKind>,
1772 sym: [u8; 2],
1773) -> Result<(mc::InterpFilterKind, mc::InterpFilterKind)> {
1774 if let Some(kind) = interp_fixed {
1775 return Ok((kind, kind));
1776 }
1777 // lane-golomb r9: this used to hand the sentinel straight to
1778 // `from_switchable_symbol`, which PANICS on any value above 2 -- a crash
1779 // on stream data (measured on a real 192x68 cq40 aomenc stream, where an
1780 // inter leaf below 8x8 desyncs upstream and leaves an unrecorded filter
1781 // behind). A decoder must refuse such a stream by name, never abort the
1782 // process; the desync that produces the sentinel belongs to lane-intersub8.
1783 if sym[0] > 2 || sym[1] > 2 {
1784 return Err(unsupported(
1785 "an OBMC neighbour whose switchable interp filter was never recorded",
1786 ));
1787 }
1788 hit!(OBMC_FILTER_BAND_READS);
1789 Ok((
1790 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
1791 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
1792 ))
1793}
1794
1795/// lane-obmcrec r1 MEASUREMENT rung (`EC_OBMCREC=1`): every OBMC neighbour whose
1796/// recorded switchable-filter symbols are the `[3, 3]` "never recorded" sentinel
1797/// -- names the neighbour's own position/shape/reference so the decode path that
1798/// failed to record its filter can be identified. Read-only, off by default.
1799#[allow(clippy::too_many_arguments)]
1800fn obmcrec_probe(
1801 dir: &str,
1802 mi_row: usize,
1803 mi_col: usize,
1804 write_w: usize,
1805 write_h: usize,
1806 off4: usize,
1807 span4: usize,
1808 nb: &MiInfo,
1809 syms: [u8; 2],
1810 cell: Option<MiInfo>,
1811 fixed: bool,
1812) {
1813 if (syms[0] <= 2 && syms[1] <= 2) || !crate::envflags::env_flag!("EC_OBMCREC") {
1814 return;
1815 }
1816 eprintln!(
1817 "OBMCREC {dir} cur_mi=({mi_row},{mi_col}) cur_wh=({write_w}x{write_h}) off4={off4} \
1818span4={span4} syms={syms:?} fixed={fixed} nb_size=({}x{}) nb_ref={} nb_ref1={:?} nb_mv=({},{}) \
1819nb_newmv={} cell_size={:?} cell_inter={:?} cell_ref={:?} sb_row_off={} sb_col_off={}",
1820 nb.size * 4,
1821 nb.size_h * 4,
1822 nb.ref_frame,
1823 nb.ref_frame1,
1824 nb.mv.0,
1825 nb.mv.1,
1826 nb.is_new_mv,
1827 cell.map(|c| (c.size * 4, c.size_h * 4)),
1828 cell.map(|c| c.is_inter),
1829 cell.map(|c| c.ref_frame),
1830 mi_row % 32,
1831 mi_col % 32,
1832 );
1833}
1834
1835/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
1836/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
1837/// under `av1_setup_build_prediction_by_{above,left}_pred`).
1838#[allow(clippy::too_many_arguments)]
1839fn obmc_neighbour_pred(
1840 refplane: &PlaneBuf<'_>,
1841 x: usize,
1842 y: usize,
1843 mv: (i32, i32),
1844 w: usize,
1845 h: usize,
1846 luma: bool,
1847 h_kind: mc::InterpFilterKind,
1848 v_kind: mc::InterpFilterKind,
1849 // lane-scaledref r1: spec 7.11.3.3's scale for THIS neighbour's own
1850 // reference (derived from luma sizes, applied unchanged to chroma whose
1851 // x_q4/y_q4 are already in its own plane's pixel units). An unscaled
1852 // reference takes the ordinary stride-1 path bit-exact.
1853 scale: mc::RefScale,
1854 // lane-alloc: the caller keeps one buffer per plane and reuses it across
1855 // every neighbour of both passes -- this was a fresh `vec![0u16; w * h]`
1856 // per neighbour per plane.
1857 out: &mut Vec<u16>,
1858 fctx: &crate::decode::FrameCtx,
1859) {
1860 out.clear();
1861 out.resize(w * h, 0);
1862 if scale.is_unscaled() {
1863 mc::predict_with_filters(
1864 &refplane.data,
1865 refplane.width,
1866 refplane.true_width,
1867 refplane.true_height,
1868 mv_to_q4(x, mv.1, if luma { 0 } else { ss_x(fctx) }),
1869 mv_to_q4(y, mv.0, if luma { 0 } else { ss_y(fctx) }),
1870 w,
1871 h,
1872 h_kind,
1873 v_kind,
1874 out,
1875 fctx,
1876 );
1877 } else {
1878 mc::predict_scaled(
1879 &refplane.data,
1880 refplane.width,
1881 refplane.true_width,
1882 refplane.true_height,
1883 mv_to_q4(x, mv.1, if luma { 0 } else { ss_x(fctx) }),
1884 mv_to_q4(y, mv.0, if luma { 0 } else { ss_y(fctx) }),
1885 scale,
1886 w,
1887 h,
1888 h_kind,
1889 v_kind,
1890 out,
1891 fctx,
1892 );
1893 }
1894}
1895
1896/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
1897/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
1898/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
1899pub(super) const II_WEIGHTS_1D: [u8; 128] = [
1900 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32, 31, 30, 29, 28, 27,
1901 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16, 16, 15, 15, 14, 14, 13, 13, 12, 12, 12,
1902 11, 11, 10, 10, 10, 9, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4, 4, 4,
1903 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1,
1904 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1905];
1906
1907/// lane-interintra r1: non-wedge interintra prediction for one plane
1908/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
1909/// `build_smooth_interintra_mask`). Builds the intra predictor for the
1910/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
1911/// own decoded edges at `(x, y)`, then blends it over the inter prediction
1912/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
1913/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
1914/// reduces to `128 / side` for the square plane sizes this decoder reaches.
1915/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
1916/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
1917// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1918#[allow(clippy::too_many_arguments)]
1919pub(super) fn interintra_blend(
1920 plane: &PlaneBuf<'_>,
1921 x: usize,
1922 y: usize,
1923 bw: usize,
1924 bh: usize,
1925 stride: usize,
1926 subw: usize,
1927 subh: usize,
1928 ii_mode: u8,
1929 wedge: Option<(&'static [u8], usize)>,
1930 pred: &mut [u16],
1931 fctx: &crate::decode::FrameCtx,
1932) {
1933 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
1934 let intra_mode = match ii_mode {
1935 0 => crate::intra::DC_PRED,
1936 1 => crate::intra::V_PRED,
1937 2 => crate::intra::H_PRED,
1938 _ => crate::intra::SMOOTH_PRED,
1939 };
1940 let (above, left, corner) = plane.edges_rect(
1941 x,
1942 y,
1943 bw,
1944 bh,
1945 crate::encode::Reach {
1946 above_right: false,
1947 below_left: false,
1948 },
1949 );
1950 let mut intra = vec![0u16; bw * bh];
1951 // Edge filtering never applies here: V/H at delta 0 are plain edge
1952 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
1953 // angle at all.
1954 predict(
1955 intra_mode,
1956 0,
1957 above.as_deref(),
1958 left.as_deref(),
1959 corner,
1960 bw,
1961 bh,
1962 false,
1963 false,
1964 &mut intra,
1965 fctx,
1966 );
1967 // `ii_size_scales[bsize]` is keyed on the block's LONGER side
1968 // (`MAX_SB_SIZE >> max(bw,bh)` order), not on the square this decoder
1969 // builds the predictor buffer at.
1970 let scale = 128 / bw.max(bh);
1971 for i in 0..bh {
1972 for j in 0..bw {
1973 let m = match wedge {
1974 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
1975 // over the wedge codebook, intra as src0, fixed sign 0).
1976 // `(subw, subh)` are the plane's own subsampling shifts;
1977 // the four branches mirror aom_dsp/blend-a64-mask.c's
1978 // `subw`/`subh` pair handling exactly: luma (0, 0) reads
1979 // the direct sample, (1, 1) the 2x2 box average
1980 // (reconinter.c sub8x8), and 4:2:2's (1, 0) the
1981 // `AOM_BLEND_AVG` column pair.
1982 Some((mask, ms)) => match (subw, subh) {
1983 (0, 0) => u32::from(mask[i * ms + j]),
1984 (1, 1) => {
1985 let t = 2 * i * ms + 2 * j;
1986 (u32::from(mask[t])
1987 + u32::from(mask[t + 1])
1988 + u32::from(mask[t + ms])
1989 + u32::from(mask[t + ms + 1])
1990 + 2)
1991 >> 2
1992 }
1993 (1, 0) => {
1994 let t = i * ms + 2 * j;
1995 (u32::from(mask[t]) + u32::from(mask[t + 1]) + 1) >> 1
1996 }
1997 (_sw, _sh) => {
1998 let t = 2 * i * ms + j;
1999 (u32::from(mask[t]) + u32::from(mask[t + ms]) + 1) >> 1
2000 }
2001 },
2002 None => u32::from(match ii_mode {
2003 0 => 32u8,
2004 1 => II_WEIGHTS_1D[i * scale],
2005 2 => II_WEIGHTS_1D[j * scale],
2006 _ => II_WEIGHTS_1D[i.min(j) * scale],
2007 }),
2008 };
2009 let idx = i * stride + j;
2010 pred[idx] = ((m * u32::from(intra[i * bw + j]) + (64 - m) * u32::from(pred[idx]) + 32)
2011 >> 6) as u16;
2012 }
2013 }
2014}
2015
2016/// `w` is the number of columns actually written (clipped to the block's own
2017/// buffer at a frame edge); `ts` is `tmp`'s own stride, the neighbour
2018/// prediction's full width.
2019#[allow(clippy::too_many_arguments)]
2020fn obmc_blend_v(
2021 dst: &mut [u16],
2022 stride: usize,
2023 ox: usize,
2024 oy: usize,
2025 w: usize,
2026 h: usize,
2027 ts: usize,
2028 tmp: &[u16],
2029) {
2030 let mask = obmc_mask(h);
2031 for row in 0..h {
2032 let m = u32::from(mask[row]);
2033 for col in 0..w {
2034 let d = &mut dst[(oy + row) * stride + ox + col];
2035 let t = u32::from(tmp[row * ts + col]);
2036 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
2037 }
2038 }
2039}
2040
2041/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
2042/// left-neighbour pass, `aom_blend_a64_hmask`).
2043fn obmc_blend_h(
2044 dst: &mut [u16],
2045 stride: usize,
2046 ox: usize,
2047 oy: usize,
2048 w: usize,
2049 h: usize,
2050 tmp: &[u16],
2051) {
2052 let mask = obmc_mask(w);
2053 for row in 0..h {
2054 for col in 0..w {
2055 let m = u32::from(mask[col]);
2056 let d = &mut dst[(oy + row) * stride + ox + col];
2057 let t = u32::from(tmp[row * w + col]);
2058 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
2059 }
2060 }
2061}
2062
2063/// libaom's own `BLOCK_SIZE` enum index for a `w4`x`h4` (mi-unit) block --
2064/// only for the `EC_OBMC` trace rung below, so it reads byte-identical to
2065/// the instrumented aomdec's `backup_mbmi.bsize`.
2066fn ec_obmc_bsize(w4: usize, h4: usize) -> i32 {
2067 match (w4, h4) {
2068 (1, 1) => 0,
2069 (1, 2) => 1,
2070 (2, 1) => 2,
2071 (2, 2) => 3,
2072 (2, 4) => 4,
2073 (4, 2) => 5,
2074 (4, 4) => 6,
2075 (4, 8) => 7,
2076 (8, 4) => 8,
2077 (8, 8) => 9,
2078 (8, 16) => 10,
2079 (16, 8) => 11,
2080 (16, 16) => 12,
2081 (1, 4) => 16,
2082 (4, 1) => 17,
2083 (2, 8) => 18,
2084 (8, 2) => 19,
2085 (4, 16) => 20,
2086 (16, 4) => 21,
2087 _ => -1,
2088 }
2089}
2090
2091/// The `EC_OBMC` rung: one line per blended neighbour, in the instrumented
2092/// aomdec's own byte format (`decodeframe.c`
2093/// `dec_build_prediction_by_{above,left}_pred`), so the two decoders' OBMC
2094/// neighbour lists diff line for line. `filt` is libaom's packed
2095/// `interp_filters.as_int` = `y_filter | (x_filter << 16)`.
2096#[allow(clippy::too_many_arguments)]
2097fn ec_obmc_trace(
2098 dir: &str,
2099 mi_row: usize,
2100 mi_col: usize,
2101 write_w: usize,
2102 write_h: usize,
2103 rel: usize,
2104 op: usize,
2105 nb: &MiInfo,
2106 h_kind: mc::InterpFilterKind,
2107 v_kind: mc::InterpFilterKind,
2108) {
2109 if !crate::envflags::env_flag!("EC_OBMC") {
2110 return;
2111 }
2112 let sym = |k: mc::InterpFilterKind| match k {
2113 mc::InterpFilterKind::Smooth => 1u32,
2114 mc::InterpFilterKind::Sharp => 2,
2115 _ => 0,
2116 };
2117 eprintln!(
2118 "EC_OBMC {dir} mi=({mi_row},{mi_col}) wh=({write_w}x{write_h}) rel={rel} op={op} \
2119nbmv=({},{}) nbref={} nbbsize={} filt={}",
2120 nb.mv.0,
2121 nb.mv.1,
2122 nb.ref_frame,
2123 ec_obmc_bsize(nb.size as usize, nb.size_h as usize),
2124 sym(v_kind) | (sym(h_kind) << 16),
2125 );
2126}
2127
2128/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
2129/// the overlap strip against each bordering above/left inter neighbour's own
2130/// mv/ref/filter and blends it into this block's just-built single-reference
2131/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
2132/// left, each reading only the *original* prediction this function was
2133/// handed (never the other pass's own output), matching libaom's own
2134/// independence between the two. `max_neighbor_obmc`'s own cap table
2135/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
2136/// decoder's own square blocks always index the same value both ways) bounds
2137/// how many bordering blocks actually get blended, separate from the
2138/// eligibility scan's own unbounded ("any at all") walk.
2139#[allow(clippy::too_many_arguments)]
2140pub(crate) fn obmc_plan(
2141 grid: &MiGrid,
2142 // The two switchable-filter bands (`Neighbours::above_filter`/
2143 // `left_filter`), read only when `interp_fixed` is `None`. The ENCODER
2144 // (`encode.rs`'s OBMC candidate) codes a fixed interpolation filter and
2145 // has no `Neighbours` of its own, so it passes both empty; the reads
2146 // below fall back to the `[3, 3]` never-recorded sentinel, which
2147 // `neighbour_filter` never reaches under a fixed filter.
2148 // corner-cut: ceiling is a switchable-filter ENCODER -- it must build and
2149 // pass the real bands here, exactly as the decoder does.
2150 above_filter: &[[u8; 2]],
2151 left_filter: &[[u8; 2]],
2152 mi_row: usize,
2153 mi_col: usize,
2154 bw4: usize,
2155 bh4: usize,
2156 mi_rows: usize,
2157 mi_cols: usize,
2158 side: usize,
2159 write_w: usize,
2160 write_h: usize,
2161 // lane-av1-llpred2: the FRAME's own subsampling pair -- the same pair the
2162 // chroma window half in [`obmc_run`] shifts by. A rect strip's ss cannot
2163 // be derived from a rect size over the square `chroma_side`: that ratio
2164 // gave a 16x8 strip at 4:2:0 ss=(1,0) (losing its above-chroma skip) and
2165 // divides by zero at 4:4:4 (`trailing_zeros(0)` = 64, a debug shift panic).
2166 ss_x: usize,
2167 ss_y: usize,
2168 chroma_stride: usize,
2169 px: usize,
2170 py: usize,
2171 cpx: usize,
2172 cpy: usize,
2173 refpix: &RefPix<'_>,
2174 interp_fixed: Option<mc::InterpFilterKind>,
2175 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
2176 // neighbour is re-predicted against ITS OWN reference, which may be
2177 // scaled differently from this block's (spec 7.11.3.3 / libaom
2178 // `av1_setup_build_prediction_by_above_pred` passing that ref's own
2179 // `scale_factors`).
2180 frame_size: (usize, usize),
2181) -> Result<ObmcPlan> {
2182 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
2183 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
2184 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
2185 // right only for square blocks.
2186 // libaom `max_neighbor_obmc[6] = { 0, 1, 2, 3, 4, 4 }` indexed by
2187 // `mi_size_wide_log2[bsize]` (above pass) / `mi_size_high_log2` (left):
2188 // 1 mi -> 0, 2 -> 1, 4 -> 2, 8 -> 3, 16+ -> 4. lane-inter4 r3: the old
2189 // `1..=4 => 2` row was right only for blocks at least 16 px on that axis
2190 // -- a 16x8 leaf's LEFT pass (bh4 = 2) walked up to two neighbours where
2191 // libaom walks one, blending an extra 8-px-tall neighbour into every
2192 // rect leaf with two of them on its left edge (class table-narrowed-to-
2193 // the-reachable-sizes; the square gates could never expose it).
2194 let max_nb = |n4: usize| match n4 {
2195 0..=1 => 0,
2196 2 => 1,
2197 3..=4 => 2,
2198 5..=8 => 3,
2199 _ => 4,
2200 };
2201 // lane-inter4 r4: r3 refused OBMC on a 16x8/8x16 leaf; re-measured
2202 // byte-exact against an instrumented aomdec, the refusal is gone and the
2203 // counter below is what the gate's `--enable-obmc=1` arm reads.
2204 if matches!((write_w, write_h), (16, 8) | (8, 16)) {
2205 hit!(OBMC_RECT_LEAF_HITS);
2206 }
2207 // lane-sb128c r1: libaom caps the overlap strip at a 64x64 block's own
2208 // half (`reconinter.c` 860/899), inert below 128.
2209 let overlap_above = write_h.min(64) / 2;
2210 let overlap_left = write_w.min(64) / 2;
2211 // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc`
2212 // (`reconinter.c` 829) switches on the PLANE block
2213 // (`get_plane_block_size`, ss-shifted): only 4x4/8x4/4x8 skip the ABOVE
2214 // pass's chroma (`return dir == 0`), the LEFT pass still blends them.
2215 // lane-av1-llpred: the old luma-shape list `(8,8)|(16,8)|(8,16)`
2216 // hardcoded the 4:2:0 plane sizes; at 4:4:4 the plane block is the luma
2217 // block itself (never 4-wide), so every one of those blocks was silently
2218 // missing its above-pass chroma OBMC blend.
2219 // lane-av1-llpred2: ss is the FRAME's own pair (`ss_x`/`ss_y(fctx)`, the
2220 // same values [`obmc_run`]'s chroma windows shift by), never a ratio of
2221 // the rect write size over the square `chroma_side` -- that ratio gave a
2222 // 4:2:0 16x8 strip ss=(1,0) and dropped its above-chroma skip, and at
2223 // 4:4:4 divided to zero (`trailing_zeros(0)` = 64, a debug shift panic).
2224 let skip_chroma_above = obmc_skip_chroma_above(write_w, write_h, ss_x, ss_y);
2225 let mut above = Vec::new();
2226 for (off4, span4, nb, src4) in
2227 overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
2228 {
2229 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns,
2230 // one step coarser than the mi(4px) units `overlappable_above` walks
2231 // in -- divide back down to that column. lane-gmaffine r2: the
2232 // neighbour's OWN mi-granular filter (libaom
2233 // `av1_setup_build_prediction_by_above_pred` reads
2234 // `above_mbmi->interp_filters`).
2235 let above_syms = above_filter.get(mi_col + src4).copied().unwrap_or([3; 2]);
2236 obmcrec_probe(
2237 "above",
2238 mi_row,
2239 mi_col,
2240 write_w,
2241 write_h,
2242 off4,
2243 span4,
2244 &nb,
2245 above_syms,
2246 grid.get(mi_row - 1, mi_col + src4),
2247 interp_fixed.is_some(),
2248 );
2249 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;
2250 ec_obmc_trace(
2251 "above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind,
2252 );
2253 let nb_dims = ref_dims(nb.ref_frame, refpix)?;
2254 if mi_col + off4 + span4 > mi_cols {
2255 hit!(OBMC_EDGE_SPAN_HITS);
2256 }
2257 above.push(ObmcNb {
2258 off4,
2259 span4,
2260 mv: mv32(nb.mv),
2261 ref_frame: nb.ref_frame,
2262 h_kind,
2263 v_kind,
2264 scale: scale_of(nb_dims, frame_size),
2265 });
2266 }
2267 let mut left = Vec::new();
2268 for (off4, span4, nb, src4) in
2269 overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4))
2270 {
2271 let left_syms = left_filter.get(mi_row + src4).copied().unwrap_or([3; 2]);
2272 obmcrec_probe(
2273 "left",
2274 mi_row,
2275 mi_col,
2276 write_w,
2277 write_h,
2278 off4,
2279 span4,
2280 &nb,
2281 left_syms,
2282 grid.get(mi_row + src4, mi_col - 1),
2283 interp_fixed.is_some(),
2284 );
2285 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;
2286 ec_obmc_trace(
2287 "left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind,
2288 );
2289 let nb_dims = ref_dims(nb.ref_frame, refpix)?;
2290 if mi_row + off4 + span4 > mi_rows {
2291 hit!(OBMC_EDGE_SPAN_HITS);
2292 }
2293 left.push(ObmcNb {
2294 off4,
2295 span4,
2296 mv: mv32(nb.mv),
2297 ref_frame: nb.ref_frame,
2298 h_kind,
2299 v_kind,
2300 scale: scale_of(nb_dims, frame_size),
2301 });
2302 }
2303 Ok(ObmcPlan {
2304 above,
2305 left,
2306 side,
2307 chroma_stride,
2308 write_w,
2309 write_h,
2310 px,
2311 py,
2312 cpx,
2313 cpy,
2314 overlap_above,
2315 overlap_left,
2316 skip_chroma_above,
2317 })
2318}
2319
2320/// `av1_skip_u4x4_pred_in_obmc`'s above-pass decision (libaom
2321/// `reconinter.c` 829): the PLANE block (`write_w >> ss_x`, `write_h >>
2322/// ss_y`) is 4x4, 8x4 or 4x8. `ss_x`/`ss_y` are the FRAME's own pair -- the
2323/// same values [`obmc_run`]'s chroma windows shift by -- never a ratio over
2324/// the square `chroma_side` (lane-av1-llpred2: that ratio dropped the
2325/// 4:2:0 16x8/8x16 skip and shifted by 64 at 4:4:4). Pure so the check
2326/// below pins the rect-strip decision without decoding a stream.
2327pub(crate) fn obmc_skip_chroma_above(
2328 write_w: usize,
2329 write_h: usize,
2330 ss_x: usize,
2331 ss_y: usize,
2332) -> bool {
2333 matches!((write_w >> ss_x, write_h >> ss_y), (4, 4) | (8, 4) | (4, 8))
2334}
2335
2336/// One OBMC neighbour as the PARSE thread resolved it (lane-defer8): every
2337/// value [`obmc_run`] needs that lives in the mode-info grid or the
2338/// neighbour bands, which the parse keeps overwriting as it walks on.
2339pub(super) struct ObmcNb {
2340 pub(super) off4: usize,
2341 pub(super) span4: usize,
2342 pub(super) mv: (i32, i32),
2343 pub(super) ref_frame: i8,
2344 pub(super) h_kind: mc::InterpFilterKind,
2345 pub(super) v_kind: mc::InterpFilterKind,
2346 /// spec 7.11.3.3's scale for THIS neighbour's own reference.
2347 pub(super) scale: mc::RefScale,
2348}
2349
2350/// [`obmc_plan`]'s result: the two neighbour passes plus this block's own
2351/// geometry, everything [`obmc_run`] reads apart from reference PIXELS.
2352pub(crate) struct ObmcPlan {
2353 pub(super) above: Vec<ObmcNb>,
2354 pub(super) left: Vec<ObmcNb>,
2355 pub(super) side: usize,
2356 /// The chroma PREDICTION buffer's own stride -- `chroma_stride`, the PLANE
2357 /// BLOCK's per-axis width, NOT the enclosing square `chroma_side`. At
2358 /// 4:2:2 that buffer is `(side/2, side)` (lane-av1-422blockhalf), and
2359 /// striding it with `chroma_side` put row `r` at `r*side`: a 32x16 luma
2360 /// strip's left-pass chroma blend wrote row 15 at index 15*32 = 480 of a
2361 /// 256-sample `16 x 16` buffer -- the out-of-bounds panic in
2362 /// `obmc_blend_h` the pinned 4:2:2 rotzoom stream opened. Every other
2363 /// consumer of `pred_u`/`pred_v` in this block already strides with
2364 /// `chroma_stride`; at 4:2:0 and 4:4:4 the two are equal.
2365 pub(super) chroma_stride: usize,
2366 pub(super) write_w: usize,
2367 pub(super) write_h: usize,
2368 pub(super) px: usize,
2369 pub(super) py: usize,
2370 pub(super) cpx: usize,
2371 pub(super) cpy: usize,
2372 pub(super) overlap_above: usize,
2373 pub(super) overlap_left: usize,
2374 pub(super) skip_chroma_above: bool,
2375}
2376
2377/// The reference-pixel half of OBMC: re-predicts every planned neighbour
2378/// over this block's own edge strips and blends it into the prediction
2379/// (libaom `av1_build_obmc_inter_prediction`). Reads nothing but reference
2380/// pixels and the plan, so it runs wherever the block's prediction is built
2381/// -- at the prediction's own push site (lane-defer8).
2382pub(crate) fn obmc_run(
2383 plan: &ObmcPlan,
2384 refpix: &RefPix<'_>,
2385 pred_y: &mut [u16],
2386 pred_u: &mut [u16],
2387 pred_v: &mut [u16],
2388 fctx: &crate::decode::FrameCtx,
2389) {
2390 let &ObmcPlan {
2391 side,
2392 chroma_stride,
2393 write_w,
2394 write_h,
2395 px,
2396 py,
2397 cpx,
2398 cpy,
2399 overlap_above,
2400 overlap_left,
2401 skip_chroma_above,
2402 ..
2403 } = plan;
2404 // lane-alloc: one neighbour-prediction buffer per plane for the whole
2405 // block, reused by every neighbour of the above and left passes.
2406 let (mut tmp_y, mut tmp_u, mut tmp_v) = (Vec::new(), Vec::new(), Vec::new());
2407
2408 // lane-t900 r13 rung: EC_MCB="<plane>:<px>:<py>[:<frame>]" (chroma plane
2409 // 1 only; <px>:<py> are chroma-plane pixels, the oracle's own dump
2410 // window) prints this block's chroma prediction rows before and after the
2411 // OBMC blend, matching the instrumented aomdec's EC_MCB dump.
2412 let ec_mcb: Option<(usize, usize, i64)> = crate::envflags::env_flag!("EC_MCB")
2413 .then(|| crate::envflags::var("EC_MCB").ok())
2414 .flatten()
2415 .and_then(|v| {
2416 let f: Vec<&str> = v.split(':').collect();
2417 if f.len() < 3 || f[0] != "1" {
2418 return None;
2419 }
2420 let (x, y) = (f[1].parse::<usize>().ok()?, f[2].parse::<usize>().ok()?);
2421 let fr = f.get(3).and_then(|s| s.parse::<i64>().ok()).unwrap_or(-1);
2422 let idx = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) as i64;
2423 // lane-av1ecmcb: the window is the CHROMA plane's own write region --
2424 // the oracle's EC_MCB spans are plane pixels, and at 4:4:4 (ss 0/0)
2425 // the chroma block is full-size, so nothing halves. The old
2426 // `write_w / 2` was a 4:2:0-era assumption that quartered the window
2427 // (and the dumps below) at ss 0/0.
2428 let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx));
2429 if x >= cpx && x < cpx + cw && y >= cpy && y < cpy + ch && (fr < 0 || fr == idx) {
2430 Some((x, y, idx))
2431 } else {
2432 None
2433 }
2434 });
2435 if let Some((_, _, idx)) = ec_mcb {
2436 let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx));
2437 eprintln!("OUR_MCB pre f={idx} cpx={cpx} cpy={cpy} cw={cw} ch={ch}");
2438 for r in 0..ch {
2439 let row: Vec<u16> = (0..cw).map(|c| pred_u[r * chroma_stride + c]).collect();
2440 eprintln!("OUR_MCB prerow{r}: {row:?}");
2441 }
2442 }
2443 for nb in &plan.above {
2444 let Some((ny, nu, nv)) = ref_planes_deferred(nb.ref_frame, refpix) else {
2445 return;
2446 };
2447 let (bw, bh, ox) = (nb.span4 * 4, overlap_above, nb.off4 * 4);
2448 // lane-t900 r14: the prediction is `op_mi_size` wide (kernel choice
2449 // included); only the WRITE is clipped to this block's own buffer.
2450 obmc_neighbour_pred(
2451 ny,
2452 px + ox,
2453 py,
2454 nb.mv,
2455 bw,
2456 bh,
2457 true,
2458 nb.h_kind,
2459 nb.v_kind,
2460 nb.scale,
2461 &mut tmp_y,
2462 fctx,
2463 );
2464 obmc_blend_v(pred_y, side, ox, 0, bw.min(write_w - ox), bh, bw, &tmp_y);
2465 if !skip_chroma_above {
2466 // lane-t900 r13 (measured, NOT a defect): libaom's min-4 clamp
2467 // sizes only the OBMC PREDICTION buffer; the blend length is the
2468 // plain overlap (`build_obmc_inter_pred_above`:
2469 // `overlap >> ss_y`) -- the PLANE's own subsampling shift, 0 at
2470 // 4:4:4 (lane-av1-llpred: the old `/2` hardcoded the 4:2:0 half
2471 // and half-blended every 4:4:4 OBMC block's chroma).
2472 let (cbw, cbh, cox) = (
2473 bw >> ss_x(fctx),
2474 overlap_above >> ss_y(fctx),
2475 ox >> ss_x(fctx),
2476 );
2477 let cw = cbw.min((write_w >> ss_x(fctx)) - cox);
2478 obmc_neighbour_pred(
2479 nu,
2480 cpx + cox,
2481 cpy,
2482 nb.mv,
2483 cbw,
2484 cbh,
2485 false,
2486 nb.h_kind,
2487 nb.v_kind,
2488 nb.scale,
2489 &mut tmp_u,
2490 fctx,
2491 );
2492 obmc_blend_v(pred_u, chroma_stride, cox, 0, cw, cbh, cbw, &tmp_u);
2493 obmc_neighbour_pred(
2494 nv,
2495 cpx + cox,
2496 cpy,
2497 nb.mv,
2498 cbw,
2499 cbh,
2500 false,
2501 nb.h_kind,
2502 nb.v_kind,
2503 nb.scale,
2504 &mut tmp_v,
2505 fctx,
2506 );
2507 obmc_blend_v(pred_v, chroma_stride, cox, 0, cw, cbh, cbw, &tmp_v);
2508 }
2509 }
2510
2511 for nb in &plan.left {
2512 let Some((ny, nu, nv)) = ref_planes_deferred(nb.ref_frame, refpix) else {
2513 return;
2514 };
2515 let (bw, bh, oy) = (overlap_left, nb.span4 * 4, nb.off4 * 4);
2516 obmc_neighbour_pred(
2517 ny,
2518 px,
2519 py + oy,
2520 nb.mv,
2521 bw,
2522 bh,
2523 true,
2524 nb.h_kind,
2525 nb.v_kind,
2526 nb.scale,
2527 &mut tmp_y,
2528 fctx,
2529 );
2530 obmc_blend_h(pred_y, side, 0, oy, bw, bh.min(write_h - oy), &tmp_y);
2531 let (cbw, cbh, coy) = (
2532 overlap_left >> ss_x(fctx),
2533 bh >> ss_y(fctx),
2534 oy >> ss_y(fctx),
2535 );
2536 obmc_neighbour_pred(
2537 nu,
2538 cpx,
2539 cpy + coy,
2540 nb.mv,
2541 cbw,
2542 cbh,
2543 false,
2544 nb.h_kind,
2545 nb.v_kind,
2546 nb.scale,
2547 &mut tmp_u,
2548 fctx,
2549 );
2550 if let Some((_, _, idx)) = ec_mcb {
2551 eprintln!(
2552 "OUR_MCB left f={idx} off4={} span4={} cbw={cbw} cbh={cbh} coy={coy} mv=({},{}) ref0={}",
2553 nb.off4, nb.span4, nb.mv.0, nb.mv.1, nb.ref_frame
2554 );
2555 for r in 0..cbh {
2556 let row: Vec<u16> = (0..cbw).map(|c| tmp_u[r * cbw + c]).collect();
2557 eprintln!("OUR_MCB lrow{r}: {row:?}");
2558 }
2559 }
2560 let ch = cbh.min((write_h >> ss_y(fctx)) - coy);
2561 obmc_blend_h(pred_u, chroma_stride, 0, coy, cbw, ch, &tmp_u);
2562 obmc_neighbour_pred(
2563 nv,
2564 cpx,
2565 cpy + coy,
2566 nb.mv,
2567 cbw,
2568 cbh,
2569 false,
2570 nb.h_kind,
2571 nb.v_kind,
2572 nb.scale,
2573 &mut tmp_v,
2574 fctx,
2575 );
2576 obmc_blend_h(pred_v, chroma_stride, 0, coy, cbw, ch, &tmp_v);
2577 }
2578 if let Some((_, _, idx)) = ec_mcb {
2579 let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx));
2580 for r in 0..ch {
2581 let row: Vec<u16> = (0..cw).map(|c| pred_u[r * chroma_stride + c]).collect();
2582 eprintln!("OUR_MCB post f={idx} row{r}: {row:?}");
2583 }
2584 }
2585}
2586
2587/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
2588/// the square block sizes this decoder ever decodes (32/16/8, all
2589/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
2590/// always `is_interinter_compound_used`, so the function is always `true`
2591/// for `side` -- kept as a named call (rather than inlined `true`) so a
2592/// future sub-8 block size does not silently misdecode a real stream.
2593pub(super) fn is_any_masked_compound_used_here(bw: usize, bh: usize) -> bool {
2594 // lane-inter16ab r4 (class sweep of the r3 CDF-row defect):
2595 // `is_comp_ref_allowed(bsize)` is `AOMMIN(block_size_wide, block_size_high)
2596 // >= 8` on the block's TRUE footprint -- a 16x4/4x16 strip is NOT allowed,
2597 // so libaom writes no `comp_group_idx` symbol there at all. Keyed off the
2598 // square `side` we read one the reference never wrote.
2599 bw.min(bh) >= 8
2600}
2601
2602/// The `BLOCK_SIZES_ALL` index of a `bw x bh` block (libaom `enum BLOCK_SIZE`,
2603/// `blockd.h`) -- the row every size-indexed inter CDF table
2604/// (`compound_type_cdf`, `wedge_idx_cdf`) is keyed by. Our `decode_inter_block`
2605/// carries the enclosing SQUARE `side` for context purposes (the accepted
2606/// strip corner-cut), so a 16x8 / 8x16 PARTITION_HORZ/VERT strip that reads
2607/// one of those symbols off `side` alone takes BLOCK_16X16's row and desyncs
2608/// (lane-inter16ab r3: a real 16x8 compound strip with `comp_group_idx == 1`,
2609/// decode-order frame 5, our range 64901 vs the oracle's 47271 at the very
2610/// next block's mode read).
2611pub(super) fn bsize_all_index(bw: usize, bh: usize) -> Option<usize> {
2612 Some(match (bw, bh) {
2613 (4, 4) => 0,
2614 (4, 8) => 1,
2615 (8, 4) => 2,
2616 (8, 8) => 3,
2617 (8, 16) => 4,
2618 (16, 8) => 5,
2619 (16, 16) => 6,
2620 (16, 32) => 7,
2621 (32, 16) => 8,
2622 (32, 32) => 9,
2623 (32, 64) => 10,
2624 (64, 32) => 11,
2625 (64, 64) => 12,
2626 (64, 128) => 13,
2627 (128, 64) => 14,
2628 (128, 128) => 15,
2629 (4, 16) => 16,
2630 (16, 4) => 17,
2631 (8, 32) => 18,
2632 (32, 8) => 19,
2633 (16, 64) => 20,
2634 (64, 16) => 21,
2635 _ => return None,
2636 })
2637}
2638
2639/// `av1_wedge_params_lookup[bsize].wedge_types > 0` (libaom `reconinter.c`):
2640/// the block sizes that carry a wedge codebook at all. A `compound_type`
2641/// symbol is written only for these; every other size infers
2642/// `COMPOUND_DIFFWTD`.
2643pub(super) fn wedge_used_bsize(bw: usize, bh: usize) -> bool {
2644 matches!(
2645 (bw, bh),
2646 (8, 8) | (8, 16) | (16, 8) | (16, 16) | (16, 32) | (32, 16) | (32, 32) | (8, 32) | (32, 8)
2647 )
2648}
2649
2650/// Whether a compound reference pair is unidirectional (both references on
2651/// the same temporal side of the current frame) -- `has_uni_comp_refs`
2652/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
2653/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
2654/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
2655/// is_backward(ref1)`). Used to build a real
2656/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
2657/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
2658pub(super) fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
2659 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
2660 backward(ref0) == backward(ref1)
2661}
2662
2663/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
2664/// above/left neighbour contributions [`Neighbours::record_inter`]/
2665/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
2666/// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units --
2667/// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four
2668/// leaves read the same neighbour cell (class context-read-from-one-cell).
2669pub(super) fn get_comp_group_idx_context(
2670 neighbours: &Neighbours,
2671 at_mi: (usize, usize),
2672 side: usize,
2673) -> usize {
2674 let _ = side;
2675 let (rmi, cmi) = at_mi;
2676 (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize)
2677 .min(5)
2678}
2679
2680/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
2681/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
2682/// block's own two references' distances from the current frame (spec
2683/// 7.11.3.15's `get_relative_dist`, same convention
2684/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
2685#[allow(clippy::too_many_arguments)]
2686pub(super) fn get_comp_index_context(
2687 neighbours: &Neighbours,
2688 at_mi: (usize, usize),
2689 side: usize,
2690 order_hint_bits: u32,
2691 cur_order_hint: u32,
2692 ref0_order_hint: u32,
2693 ref1_order_hint: u32,
2694) -> usize {
2695 let _ = side;
2696 let (rmi, cmi) = at_mi;
2697 let fwd =
2698 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
2699 .abs();
2700 let bck =
2701 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
2702 .abs();
2703 let offset = usize::from(fwd == bck);
2704 neighbours.above_compound_idx[cmi] as usize
2705 + neighbours.left_compound_idx[rmi] as usize
2706 + 3 * offset
2707}
2708
2709pub(super) fn read_comp_mode(
2710 dec: &mut SymbolDecoder,
2711 cdfs: &mut Cdfs,
2712 above: Option<NeighbourRef>,
2713 left: Option<NeighbourRef>,
2714) -> bool {
2715 let ctx = reference_mode_ctx(above, left);
2716 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
2717 if crate::envflags::env_flag!("EC_TRACE_MODE") {
2718 eprintln!(
2719 "EC_RCM ctx={ctx} val={} a={:?} l={:?} rng={}",
2720 usize::from(compound),
2721 above.map(|n| (n.is_inter, n.ref0, n.ref1)),
2722 left.map(|n| (n.is_inter, n.ref0, n.ref1)),
2723 dec.debug_state().0
2724 );
2725 }
2726 if compound {
2727 hit!(COMP_MODE_HITS);
2728 }
2729 compound
2730}
2731
2732/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
2733/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
2734/// arm), reached once [`read_comp_mode`] has already returned
2735/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
2736/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
2737/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
2738/// convention [`read_single_ref`] already uses, for every downstream binary
2739/// decision. libaom `pred_common.c`'s own compound context functions
2740/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
2741/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
2742/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
2743/// (same vote-the-neighbours-above-left shape, same forward/backward and
2744/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
2745/// against the C source rather than porting six near-duplicate functions.
2746/// Its caller today only needs the symbols consumed, correctly, to keep the
2747/// arithmetic decoder's own state in sync before refusing the block by name
2748/// -- the returned pair is not yet threaded into any motion-compensation
2749/// path.
2750pub(super) fn read_compound_ref_frames(
2751 dec: &mut SymbolDecoder,
2752 cdfs: &mut Cdfs,
2753 above: Option<NeighbourRef>,
2754 left: Option<NeighbourRef>,
2755 above_ref: i8,
2756 left_ref: i8,
2757) -> (i8, i8) {
2758 let a = (above_ref > 0).then_some(above_ref);
2759 let l = (left_ref > 0).then_some(left_ref);
2760 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
2761 // neighbour's references, not just its first -- `a1`/`l1` carry that
2762 // second reference through to every vote below (lane-av1blend r6: a
2763 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
2764 // row for a block sitting under a skip_mode-forced compound neighbour).
2765 let a1 = above.and_then(|n| n.ref1);
2766 let l1 = left.and_then(|n| n.ref1);
2767 let type_ctx = comp_reference_type_ctx(above, left);
2768 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
2769 if unidir {
2770 hit!(UNI_COMP_HITS);
2771 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
2772 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
2773 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
2774 if bit == 1 {
2775 (BWDREF_FRAME, ALTREF_FRAME)
2776 } else {
2777 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
2778 if p1 == 1 {
2779 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
2780 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
2781 if p2 == 1 {
2782 (LAST_FRAME, GOLDEN_FRAME)
2783 } else {
2784 (LAST_FRAME, LAST3_FRAME)
2785 }
2786 } else {
2787 (LAST_FRAME, LAST2_FRAME)
2788 }
2789 }
2790 } else {
2791 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
2792 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
2793 let ref0 = if bit0 == 0 {
2794 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
2795 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
2796 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
2797 } else {
2798 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
2799 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
2800 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
2801 };
2802 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
2803 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
2804 let ref1 = if bit1 == 0 {
2805 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
2806 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
2807 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
2808 } else {
2809 ALTREF_FRAME
2810 };
2811 (ref0, ref1)
2812 }
2813}
2814
2815/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
2816/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
2817/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
2818/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
2819/// libaom's `av1_mode_context_analyzer`'s compound branch --
2820/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
2821/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
2822/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
2823/// is not yet turned into an assigned MV pair or motion-compensated --
2824/// lane-av1comp.
2825pub(super) fn read_inter_compound_mode(
2826 dec: &mut SymbolDecoder,
2827 cdfs: &mut Cdfs,
2828 new_mv_ctx: usize,
2829 ref_mv_ctx: usize,
2830) -> u8 {
2831 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
2832 hit!(COMPOUND_MODE_HITS);
2833 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
2834}
2835
2836/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
2837/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
2838/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
2839/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
2840/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
2841/// non-`IDENTITY` global motion model before a tile is ever decoded.
2842///
2843/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
2844/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
2845/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
2846/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
2847/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
2848#[allow(clippy::too_many_arguments)]
2849pub(super) fn assign_compound_mv(
2850 dec: &mut SymbolDecoder,
2851 cdfs: &mut Cdfs,
2852 comp_stack: &crate::mvstack::CompoundMvStack,
2853 mode: u8,
2854 allow_high_precision_mv: bool,
2855 force_integer_mv: bool,
2856 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
2857 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
2858 global_mv: ((i32, i32), (i32, i32)),
2859 fctx: &crate::decode::FrameCtx,
2860) -> ((i32, i32), (i32, i32)) {
2861 const NEAREST_NEARESTMV: u8 = 0;
2862 const NEAR_NEARMV: u8 = 1;
2863 const NEAREST_NEWMV: u8 = 2;
2864 const NEW_NEARESTMV: u8 = 3;
2865 const NEAR_NEWMV: u8 = 4;
2866 const NEW_NEARMV: u8 = 5;
2867 const GLOBAL_GLOBALMV: u8 = 6;
2868 const NEW_NEWMV: u8 = 7;
2869
2870 let mut ref_mv_idx = 0usize;
2871 if mode == NEW_NEWMV {
2872 let mut idx = 0usize;
2873 while idx < 2 && comp_stack.entries.len() > idx + 1 {
2874 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
2875 break;
2876 }
2877 idx += 1;
2878 }
2879 ref_mv_idx = idx;
2880 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
2881 let mut idx = 1usize;
2882 while idx < 3 && comp_stack.entries.len() > idx + 1 {
2883 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
2884 break;
2885 }
2886 idx += 1;
2887 }
2888 ref_mv_idx = idx - 1;
2889 }
2890
2891 let near = comp_stack
2892 .entries
2893 .get(ref_mv_idx + 1)
2894 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
2895 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
2896 ref_mv_idx + 1
2897 } else {
2898 ref_mv_idx
2899 };
2900 let new_pred = comp_stack
2901 .entries
2902 .get(new_idx)
2903 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
2904
2905 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
2906 read_mv(
2907 dec,
2908 &mut cdfs.mv_comp,
2909 &mut cdfs.mv_joint,
2910 base,
2911 allow_high_precision_mv,
2912 force_integer_mv,
2913 fctx,
2914 )
2915 };
2916
2917 match mode {
2918 NEAREST_NEARESTMV => comp_stack.nearest_mv,
2919 NEAR_NEARMV => near,
2920 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
2921 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
2922 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
2923 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
2924 GLOBAL_GLOBALMV => global_mv,
2925 _ => (
2926 read_new(dec, cdfs, new_pred.0),
2927 read_new(dec, cdfs, new_pred.1),
2928 ),
2929 }
2930}
2931
2932/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
2933/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
2934/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
2935/// table is always computed at the *querying* block's position, never a
2936/// donating neighbour's).
2937pub(super) fn build_gm_mv_table(
2938 global_motion: &[ec_av1_syntax::WarpParams; 7],
2939 mi_row: usize,
2940 mi_col: usize,
2941 bw4: usize,
2942 bh4: usize,
2943 allow_high_precision_mv: bool,
2944 force_integer_mv: bool,
2945) -> crate::mvstack::GmMvTable {
2946 std::array::from_fn(|i| {
2947 let gm = &global_motion[i];
2948 crate::warp::gm_get_motion_vector(
2949 gm.model,
2950 &gm.params,
2951 mi_row,
2952 mi_col,
2953 bw4,
2954 bh4,
2955 allow_high_precision_mv,
2956 force_integer_mv,
2957 )
2958 })
2959}
2960
2961/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
2962/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
2963/// and motion-compensated reconstruction, or the inter frame's own intra
2964/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
2965/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
2966/// private `write_inter_frame_leaf` -- both share this one function here,
2967/// parameterised by `side`/the transform sets/scan tables/size group they
2968/// each use.
2969///
2970/// # Errors
2971/// Returns an error when a symbol names anything this decoder does not
2972/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
2973/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
2974/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
2975/// refuse.
2976#[allow(clippy::too_many_arguments)]
2977/// lane-inter4 r1: 16-px-cell coordinates -> MI (4-px) coordinates, the unit
2978/// [`decode_inter_block`]'s `at` now takes.
2979pub(super) const fn sub16_to_mi(t: (usize, usize)) -> (usize, usize) {
2980 (t.0 * (SUB / MI), t.1 * (SUB / MI))
2981}
2982
2983/// The luma transform leaf a chroma unit inherits its `tx_type` from
2984/// (libaom `av1_get_tx_type`, `blockd.h:1287-1297`): an INTER block's chroma
2985/// unit never codes a `tx_type` symbol of its own, so the type is read out
2986/// of `xd->tx_type_map` at the chroma unit's own position scaled back to luma
2987/// (`blk_row << ss_y`, `blk_col << ss_x`). `leaves` is the block's coded
2988/// transform tree in decode order, `(row, col, tw, th, tx_type)` with
2989/// `(row, col)` in MI relative to the block and `(tw, th)` in PIXELS;
2990/// `rel_mi` is the chroma unit's own luma-relative top-left MI cell. One
2991/// function serves the 128x128 mu-chunk tail and the 64x64 arms alike -- the
2992/// lookup is the same rule, so a second inline copy would be a second
2993/// convention.
2994///
2995/// A leaf that coded nothing resolves to `DctDct` here exactly as libaom's
2996/// `decodetxb.c:199-203` stamps `DCT_DCT` into that leaf's map cell on the
2997/// `all_zero` path: a chroma unit over a SKIPPED luma quadrant must NOT
2998/// inherit the block-level (top-left leaf) type.
2999pub(super) fn covering_leaf_tx_type(
3000 leaves: &[(usize, usize, usize, usize, TxType)],
3001 rel_mi: (usize, usize),
3002) -> Option<TxType> {
3003 leaves
3004 .iter()
3005 .copied()
3006 // leaf (row, col) are mi but (tw, th) are px (the rect leaf path
3007 // divides by MI too)
3008 .find(|&(lr, lc, lw, lh, _)| {
3009 lr <= rel_mi.0 && rel_mi.0 < lr + lh / MI && lc <= rel_mi.1 && rel_mi.1 < lc + lw / MI
3010 })
3011 .map(|(_, _, _, _, t)| t)
3012}
3013
3014thread_local! {
3015 /// lane-av1ichromatx: [`read_inter_rect_chroma`] units that fell through
3016 /// `covering_leaf_tx_type` to the BLOCK-level `luma_tx_type`, and of those
3017 /// the ones whose chroma plane is MULTI-unit (`nx*ny > 1`) -- the only
3018 /// shape where two units of one plane can disagree, i.e. where a
3019 /// block-level value could actually mistype a unit.
3020 ///
3021 /// Why this needs its own number: `CHROMA_RECT_LEAF_TX_HITS` counts the
3022 /// units that took the covering leaf, so it says nothing about the units
3023 /// that did NOT -- and the fallback is the only remaining place in
3024 /// `decode_inter_block` where a chroma unit is handed a block-level type
3025 /// on a split plane.
3026 pub(crate) static CHROMA_RECT_BLOCK_TX_FALLBACK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3027}
3028
3029thread_local! {
3030 /// Of [`CHROMA_RECT_BLOCK_TX_FALLBACK`], how many were on a multi-unit
3031 /// chroma plane -- the non-vacuity bar for the assertion at that site.
3032 pub(crate) static CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3033}
3034
3035/// [`CHROMA_RECT_BLOCK_TX_FALLBACK`]: rect chroma units handed the block-level
3036/// type because no luma leaf covered their own MI cell.
3037#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3038pub(crate) fn chroma_rect_block_tx_fallback() -> usize {
3039 CHROMA_RECT_BLOCK_TX_FALLBACK.with(std::cell::Cell::get)
3040}
3041
3042/// [`CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI`]: of those, the ones whose chroma
3043/// plane had more than one unit.
3044#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3045pub(crate) fn chroma_rect_block_tx_fallback_multi() -> usize {
3046 CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI.with(std::cell::Cell::get)
3047}