forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB214cdf2Tahinli3 months ago821 commits

mvstack.rs2570 lines, 98.9 KiBHistoryRawDownload
1//! Reference MV list construction (AV1 spec 7.10.2, `find_mv_stack`),
2//! reduced to the single-reference, non-compound, `use_ref_frame_mvs = 0`
3//! case a key/inter frame without temporal MV projection needs.
4//!
5//! Implemented from the spec: the row-above scan (7.10.2.2), the col-left
6//! scan (7.10.2.3), a single top-right probe (the first of 7.10.2.4's extra
7//! positions), weight-based dedupe (7.10.2.5's `add_ref_mv_candidate`), the
8//! weight-descending sort (7.10.2.6), and the `NewMvContext`/`RefMvContext`/
9//! `ZeroMvContext`/`DrlCtx` derivations of 7.10.2.8, ported from libaom's
10//! `av1_find_mv_stack` (`av1/common/mvref_common.c`, the `mode_context`
11//! switch around its `nearest_match`/`ref_match_count` and the
12//! `newmv_count > 0` tests) and `av1_drl_ctx` (`mvref_common.h`), plus MV
13//! clamping (7.10.2.14, libaom's `clamp_mv_ref`).
14//!
15//! This module's immediate row/col/top-right scan alone is *not* enough to
16//! get `RefMvContext` (`ref_mv_ctx`) right, *nor* `NewMvContext` at
17//! `nearest_match == 0` (see below). Ported straight from libaom's
18//! `av1_find_mv_stack` (`av1/common/mvref_common.c`, `setup_ref_mv_list`,
19//! ~line 480 on): after the immediate row (-1), col (-1) and top-right
20//! probes settle `nearest_match` (and `mode_context`'s `new_mv` bits, which
21//! for `nearest_match >= 1` depend on `nearest_match` alone), libaom runs one
22//! more probe *before* computing `ref_match_count` — `scan_blk_mbmi` at the
23//! diagonal top-left corner `(-1, -1)` — whose match folds into
24//! `row_match_count` (and hence can flip `ref_match_count`'s row term true)
25//! without ever touching the already-captured `nearest_match`. So
26//! `ref_match_count >= nearest_match` always, sometimes strictly greater, and
27//! `ref_mv_ctx` (the `REFMV_OFFSET` half of libaom's `mode_context` switch,
28//! mvref_common.c ~line 619-643) genuinely depends on both counts, not
29//! `nearest_match` alone — that collapse was the bug this module shipped
30//! with for several rounds (see the crate report). The `case 0` arm of that
31//! same switch *also* sets `new_mv_ctx`'s own bit from `ref_match_count`
32//! (`mode_context[ref_frame] |= 1` when `ref_match_count >= 1`) — a second
33//! corner-probe dependency this module missed for several more rounds after
34//! the first fix, until real-content inter streams (I8 CLASS B) caught it:
35//! synthetic fixtures never produced a block with `nearest_match == 0` and a
36//! genuine corner match. [`find_mv_stack`] now runs that corner probe and
37//! computes both `ref_mv_ctx` and `new_mv_ctx` from the true
38//! `(nearest_match, ref_match_count)` pair.
39//!
40//! The corner probe's own candidate is added to the stack too (matching
41//! libaom: a genuinely new MV there becomes a real, if low-weight, entry),
42//! at libaom's real `2 * mi_size_wide[BLOCK_8X8]` (`CORNER_WEIGHT`, 4) —
43//! same as the top-right probe, which shares `scan_blk_mbmi`'s fixed weight
44//! in libaom too. The row/col scans (`scan_row`/`scan_col`) carry libaom's
45//! real per-block-run `len * weight` formula (`scan_row_mbmi`/
46//! `scan_col_mbmi`, mvref_common.c), not a flat per-cell weight: this
47//! module shipped a flat `IMMEDIATE_WEIGHT = 2` for several rounds, exact
48//! only for `tile.rs`'s own encoder (always a fixed `bw4 == bh4 == 8` query
49//! against same-size-8 neighbours, where the real formula's `bw4 <= n4`
50//! weight boost applies identically on every candidate and so never
51//! reorders anything) — decode.rs's real variable partition sizes need the
52//! real formula, since a same-or-wider neighbour against a *smaller* query
53//! block gets a real, non-flat weight boost there libaom's DRL-index
54//! selection depends on.
55//!
56//! The corner probe's own match does *not* count toward the real
57//! `newmv_count` that feeds `new_mv_ctx` (libaom passes it a `dummy_newmv_count`
58//! there) — only row/col/top-right do.
59//!
60//! Also ported (from `av1_drl_ctx`, `mvref_common.h`): the `REF_CAT_LEVEL`
61//! (640) bonus applies only to the entries the row/col/top-right scan found
62//! (`nearest_refmv_count`), added to their stored weight *before* the corner
63//! probe can add a new, unboosted entry — so `drl_ctx` can now be non-zero
64//! when the corner probe contributes a genuinely new candidate.
65//!
66//! The `GLOBALMV_OFFSET` bit of libaom's `mode_context` is set only inside
67//! `cm->features.allow_ref_frame_mvs` (temporal MV projection), which this
68//! module never has (`use_ref_frame_mvs = 0`), so `zero_mv_ctx` is always 0
69//! here — exact for the case this module covers, not a stand-in.
70//!
71//! Deliberately reduced away (see the crate report, not reproduced bit-exact
72//! here): compound/multi-reference candidates, the temporal MV projection
73//! scan, and the single-reference "extension" pass that re-walks the same
74//! row/col
75//! neighbours through `process_single_ref_mv_candidate` (a no-op here: with
76//! only one reference frame ever in play, whatever it would add was already
77//! added by the row/col scan), and the "extra search" that pads a short
78//! stack to two entries (spec 7.10.2.12) — this module's stack can be
79//! shorter than two candidates where libaom's never is.
80
81/// How many query blocks [`find_mv_stack_with_sign_bias`] has folded at
82/// least one temporal MV candidate into (spec 7.9/7.10.2.8's
83/// `add_tpl_ref_mv`) — the real-aomenc temporal-MV gate's own firing
84/// counter (`crate::decode::tmv_hits`), proving the projection path in
85/// [`crate::motion_field`] is actually reached, not just compiled.
86static TMV_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
87
88/// The number of query blocks that received at least one temporal MV
89/// candidate so far, across every [`find_mv_stack_with_sign_bias`] call in
90/// this process.
91pub(crate) fn tmv_hits() -> usize {
92 TMV_HITS.load(std::sync::atomic::Ordering::Relaxed)
93}
94
95/// Everything [`find_mv_stack_with_sign_bias`] needs to fold temporal MV
96/// candidates into a block's stack (spec 7.10.2.8, only reached when the
97/// frame header's own `use_ref_frame_mvs` is set): the current frame's own
98/// projected motion field, the distance (in `get_relative_dist` units) from
99/// the current frame to *this query's* single reference frame's own
100/// `OrderHint` (`cur_offset_0`, spec 7.9.3 — computed by the caller, since
101/// this module has no reason to carry `order_hint_bits`/`OrderHints[]`
102/// itself), and `allow_high_precision_mv` (`lower_mv_precision`, spec
103/// 7.10.2.8).
104pub struct TplArgs<'a> {
105 /// The current frame's projected temporal motion field
106 /// ([`crate::motion_field::setup_motion_field`]'s output).
107 pub field: &'a crate::motion_field::TplField,
108 /// `get_relative_dist(OrderHint, OrderHints[ref_frame - LAST_FRAME])`,
109 /// pre-computed by the caller.
110 pub cur_offset_0: i32,
111 /// The frame header's own `allow_high_precision_mv`.
112 pub allow_high_precision_mv: bool,
113}
114
115/// One 4x4 `mi` unit's motion state, as the encode loop will have filled it
116/// in by the time it asks for a block's MV stack.
117#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub struct MiInfo {
119 /// Whether this unit was coded inter (as opposed to intra).
120 pub is_inter: bool,
121 /// The single reference frame this unit's MV points into. Ignored (and
122 /// the unit contributes no candidate) when `is_inter` is `false`.
123 pub ref_frame: i8,
124 /// The unit's *second* reference frame when it was coded compound
125 /// (spec `RefFrames[1]`), `None` for a single-reference/intra unit --
126 /// lane-av1comp: today's callers (single-ref decode/encode) never set
127 /// this, so it exists only so [`MiGrid`] can carry compound state once
128 /// `read_ref_frames` (spec 5.11.25) lands; nothing reads it yet, and
129 /// [`find_mv_stack`]'s scan still matches candidates on `ref_frame`
130 /// alone (its own compound dual-ref scan is unported -- see the ledger).
131 pub ref_frame1: Option<i8>,
132 /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units.
133 pub mv: (i32, i32),
134 /// The unit's second motion vector, matching `ref_frame1` (spec
135 /// `Mvs[1]`) — `Some` only for a compound-coded unit, `None` otherwise.
136 /// lane-av1comp step 4: exists so the compound mvstack scan below can
137 /// read a compound neighbour's second MV; no caller sets it yet (same
138 /// unwired state `ref_frame1` landed in for r3).
139 pub mv1: Option<(i32, i32)>,
140 /// Whether this unit's own mode was `NEWMV` (spec's
141 /// `have_newmv_in_inter_mode`, compound modes excluded since this module
142 /// has no compound candidates). Feeds `NewMvContext` (7.10.2.8): a
143 /// neighbour's own coded-with-NEWMV state, not this block's.
144 pub is_new_mv: bool,
145 /// The side, in 4x4 units, of the square block this unit belongs to (8
146 /// for a whole 32x32 block, 4 for a 16x16 leaf -- every block this crate
147 /// ever codes is square, so one dimension is enough). Feeds the extended
148 /// row/col scan's `processed_rows`/`processed_cols` (spec 7.10.2.2/.3,
149 /// libaom `scan_row_mbmi`/`scan_col_mbmi`'s `inc` term): a query block no
150 /// wider than its immediate neighbour has that neighbour's whole span
151 /// already covered by the immediate (-1) scan, so the extended scan
152 /// below only has to run past that. Set for *every* coded unit, intra or
153 /// inter -- libaom's `scan_row_mbmi` advances `processed_rows` from any
154 /// candidate's `bsize` regardless of whether it also casts a vote (that
155 /// requires a ref-frame match, checked separately in `add_ref_mv_candidate`).
156 pub size: usize,
157}
158
159/// The whole frame's `mi` grid, one [`MiInfo`] per 4x4 unit, in raster order.
160/// A unit an encode pass hasn't visited yet (or that sits outside the tile)
161/// reads as `None` and contributes nothing to any block's MV stack.
162#[derive(Clone, Debug)]
163pub struct MiGrid {
164 cols: usize,
165 rows: usize,
166 cells: Vec<Option<MiInfo>>,
167}
168
169impl MiGrid {
170 /// A grid of `cols` by `rows` 4x4 units, all initially unset.
171 pub fn new(cols: usize, rows: usize) -> Self {
172 Self {
173 cols,
174 rows,
175 cells: vec![None; cols * rows],
176 }
177 }
178
179 /// Records the unit at `(row, col)`. Out-of-range coordinates are a
180 /// no-op — the caller only ever addresses units inside the grid it built.
181 pub fn set(&mut self, row: usize, col: usize, info: MiInfo) {
182 if row < self.rows && col < self.cols {
183 self.cells[row * self.cols + col] = Some(info);
184 }
185 }
186
187 /// The unit at `(row, col)`, or `None` when it is outside the grid (the
188 /// tile) or hasn't been coded.
189 pub fn get(&self, row: usize, col: usize) -> Option<&MiInfo> {
190 if row < self.rows && col < self.cols {
191 self.cells[row * self.cols + col].as_ref()
192 } else {
193 None
194 }
195 }
196}
197
198/// One entry of the reference MV stack: a candidate motion vector and the
199/// total weight the neighbours that agreed on it contributed.
200#[derive(Clone, Copy, Debug, PartialEq, Eq)]
201pub struct StackEntry {
202 /// The candidate `(row, col)` motion vector.
203 pub mv: (i32, i32),
204 /// The summed weight of every neighbour cell that voted for this MV.
205 pub weight: u32,
206}
207
208/// The result of [`find_mv_stack`]: the sorted candidate list, the two
209/// predictors a `NEARESTMV`/`NEARMV` block reads from it, the predictor a
210/// `NEWMV` residual is coded against, and the symbol contexts the block's
211/// mode and DRL-index syntax elements are coded with.
212#[derive(Clone, Debug, PartialEq, Eq)]
213pub struct MvStack {
214 /// The candidates, highest weight first (ties keep scan order: above,
215 /// then left, then top-right).
216 pub entries: Vec<StackEntry>,
217 /// `RefStackMv[0]`, or `(0, 0)` when the stack is empty.
218 pub nearest_mv: (i32, i32),
219 /// `RefStackMv[1]`, or `(0, 0)` when the stack has fewer than two
220 /// entries.
221 pub near_mv: (i32, i32),
222 /// The predictor a `NEWMV` block's MV difference is coded against:
223 /// `nearest_mv` when the stack is non-empty, `(0, 0)` otherwise.
224 pub pred_mv: (i32, i32),
225 /// Context for the `new_mv` symbol.
226 pub new_mv_ctx: usize,
227 /// Context for the `ref_mv` symbol.
228 pub ref_mv_ctx: usize,
229 /// Context for the `zero_mv` symbol.
230 pub zero_mv_ctx: usize,
231 /// Context for each `drl_mode` symbol between consecutive stack
232 /// entries, `entries.len().saturating_sub(1)` long.
233 pub drl_ctx: Vec<usize>,
234}
235
236/// Spec 7.10.2.8's threshold a candidate's weight is compared against to
237/// pick its DRL context.
238const REF_CAT_LEVEL: u32 = 640;
239
240/// The most candidates a stack keeps (spec `MAX_REF_MV_STACK_SIZE`).
241const MAX_STACK_SIZE: usize = 8;
242
243/// The single-reference extension's own, *smaller* cap (spec's
244/// `MAX_MV_REF_CANDIDATES`, `av1/common/enums.h`): that pass only ever tops
245/// the stack up to two entries — enough to guarantee `NEARESTMV`/`NEARMV`
246/// predictors — never all the way to [`MAX_STACK_SIZE`]. libaom gates its
247/// two extension loops on `*refmv_count < MAX_MV_REF_CANDIDATES`, not the
248/// 8-entry stack cap; this module's prior hand-written pass used
249/// `MAX_STACK_SIZE` here, which is the wrong bound.
250const MAX_MV_REF_CANDIDATES: usize = 2;
251
252/// The floor libaom's `scan_row_mbmi`/`scan_col_mbmi` weight starts at
253/// before a same-or-wider candidate block can raise it (`uint16_t weight =
254/// 2;`, mvref_common.c).
255const ROW_COL_WEIGHT_FLOOR: u32 = 2;
256
257/// Fixed weight libaom's `scan_blk_mbmi` uses for both single-cell probes
258/// (`2 * mi_size_wide[BLOCK_8X8]` = `2 * 2`): the diagonal corner and the
259/// top-right, neither of which ever runs the row/col scans' real per-block
260/// weight below.
261const CORNER_WEIGHT: u32 = 4;
262
263/// Spec `MVREF_ROW_COLS`: the extended row/col scan runs at offsets `-3` and
264/// `-5` (`idx = 2..=3`), one past the immediate scan's own `-1`.
265const MVREF_ROW_COLS: usize = 3;
266
267/// Adds one candidate MV with `weight` to `candidates`, merging it into an
268/// existing entry with the same MV rather than duplicating it (spec
269/// `add_ref_mv_candidate`, 7.10.2.5).
270fn add_candidate(candidates: &mut Vec<StackEntry>, mv: (i32, i32), weight: u32) {
271 if let Some(entry) = candidates.iter_mut().find(|e| e.mv == mv) {
272 entry.weight += weight;
273 } else {
274 candidates.push(StackEntry { mv, weight });
275 }
276}
277
278/// `cm->ref_frame_sign_bias[ref_frame]`, looked up from the frame header's
279/// own `ref_frame_sign_bias` (spec 5.9.2's `get_relative_dist(ref_order_hint,
280/// OrderHint) > 0` per active reference, already computed by
281/// `ec_av1_syntax::frame::read_uncompressed_header` and indexed exactly like
282/// `ref_frame_idx`: `table[ref_frame - LAST_FRAME]`). `find_mv_stack`'s
283/// no-sign-bias callers (this crate's own encoder, which only ever writes
284/// `LAST_FRAME`) pass an all-`false` table, matching this stub's old
285/// always-`false` behaviour exactly.
286fn sign_bias(table: &SignBiasTable, ref_frame: i8) -> bool {
287 table[(ref_frame - LAST_FRAME) as usize]
288}
289
290/// One `bool` per `MV_REFERENCE_FRAME` past `INTRA_FRAME`/`NONE`
291/// (`LAST_FRAME`..=`ALTREF_FRAME`), indexed `[ref_frame - LAST_FRAME]` --
292/// spec `ec_av1_syntax::frame::FrameHeader::ref_frame_sign_bias`'s own
293/// shape, threaded straight through.
294pub type SignBiasTable = [bool; 7];
295
296/// The all-`false` table every no-sign-bias caller (this crate's own
297/// encoder, and every test below) passes: correct as long as no candidate
298/// or query ever names a backward reference, exactly this module's old
299/// hardcoded `sign_bias` stub.
300pub const NO_SIGN_BIAS: SignBiasTable = [false; 7];
301
302/// libaom's `process_single_ref_mv_candidate` (mvref_common.c): folds one
303/// already-coded neighbour into the stack as a low-weight (`2`, unboosted)
304/// filler entry, used only by the single-reference extension pass below.
305/// Unlike every scan above, this runs over *any* inter neighbour regardless
306/// of which reference frame it coded — that is the whole point of the
307/// pass (topping the stack up when the real scans found too few same-ref
308/// candidates) — and dedupes by MV value against the *whole* stack so far,
309/// silently dropping the candidate (no weight bump, unlike
310/// [`add_candidate`]) when a match is already there.
311///
312/// libaom's real signature loops `rf_idx` over the candidate's up to two
313/// coded reference-frame slots (a compound-coded neighbour donates two
314/// candidates, one per slot); this crate's [`MiInfo`] carries a single
315/// `ref_frame`, since no coded neighbour here is ever compound — ported as
316/// that loop's `rf_idx == 0` iteration alone.
317fn process_single_ref_mv_candidate(
318 candidate: &MiInfo,
319 ref_frame: i8,
320 sign_bias_table: &SignBiasTable,
321 candidates: &mut Vec<StackEntry>,
322) {
323 if !candidate.is_inter {
324 return;
325 }
326 let mut this_mv = candidate.mv;
327 if sign_bias(sign_bias_table, candidate.ref_frame) != sign_bias(sign_bias_table, ref_frame) {
328 this_mv = (-this_mv.0, -this_mv.1);
329 }
330 if !candidates.iter().any(|e| e.mv == this_mv) {
331 candidates.push(StackEntry {
332 mv: this_mv,
333 weight: 2,
334 });
335 }
336}
337
338/// The row scan (spec 7.10.2.2, libaom `scan_row_mbmi`): walks candidate
339/// *blocks* — not individual 4x4 cells — along the row `row_offset` mi units
340/// above the block's own row, in run-length steps sized by each candidate's
341/// own block width. Handles both the immediate probe (`row_offset == -1`)
342/// and the extended ones (`-3`, `-5`) libaom threads through the same
343/// function: `max_row_offset` is the immediate scan's own reach (spec
344/// 7.10.2.4's `find_valid_row_offset`, clamped to the tile's top edge), used
345/// only to size the weight boost below, not to gate whether this call runs
346/// at all (the caller does that via `processed_rows`/the tile edge).
347///
348/// Each matching candidate's vote is weighted `len * weight`: `len` is how
349/// many mi columns the run covers (the candidate's own width, floored to
350/// the query block's `bw4` and — at the wide/extended-scan geometries
351/// libaom's own `use_step_16`/`abs(row_offset) > 1` branches cover — raised
352/// to a block-size floor); `weight` starts at 2 and, only when the candidate
353/// is at least as wide as the query block (`bw4 <= n4`), rises to how much
354/// of `max_row_offset`'s remaining reach the candidate's own height can
355/// still cover. That `bw4 <= n4` condition is why this module's old flat
356/// `IMMEDIATE_WEIGHT = 2` was exact for every real caller before decode.rs
357/// existed: `tile.rs`'s own encoder only ever asks with `bw4 == 8` against
358/// neighbours it also always wrote at `size == 8`, and every synthetic test
359/// neighbour here uses `size: 1` (which the `n4 < weight`-floor condition
360/// keeps at the `2` floor regardless of `bw4`) — this real formula only
361/// diverges from that flat weight when a *bigger* candidate meets a
362/// *smaller* query block, which only decode.rs's variable partition sizes
363/// ever produce.
364///
365/// Threads `processed_rows` (`*mut` in libaom, `&mut` here) across every row
366/// call — immediate, then the two extended offsets — the way libaom's
367/// single stack `int` does: only the `bw4 <= n4` branch above updates it,
368/// same as libaom only updating `*processed_rows` there.
369#[allow(clippy::too_many_arguments)]
370fn scan_row(
371 grid: &MiGrid,
372 mi_row: usize,
373 mi_col: usize,
374 bw4: usize,
375 row_offset: isize,
376 max_row_offset: isize,
377 ref_frame: i8,
378 candidates: &mut Vec<StackEntry>,
379 newmv_count: &mut u32,
380 processed_rows: &mut usize,
381) -> bool {
382 let Some(row) = mi_row.checked_add_signed(row_offset) else {
383 return false;
384 };
385 let col_shift: usize = if row_offset.unsigned_abs() > 1 { 1 } else { 0 };
386 let use_step_16 = bw4 >= 16;
387 let end_mi = bw4.min(16);
388 let mut found = false;
389 let mut i = 0usize;
390 while i < end_mi {
391 let Some(info) = grid.get(row, mi_col + col_shift + i) else {
392 i += 1;
393 continue;
394 };
395 let n4 = info.size;
396 let mut len = bw4.min(n4);
397 if use_step_16 {
398 len = len.max(4);
399 } else if row_offset.unsigned_abs() > 1 {
400 len = len.max(2);
401 }
402 let mut weight = ROW_COL_WEIGHT_FLOOR;
403 if bw4 <= n4 {
404 let inc = ((-max_row_offset + row_offset + 1) as usize).min(n4);
405 weight = weight.max(inc as u32);
406 *processed_rows = (inc as isize - row_offset - 1).max(0) as usize;
407 }
408 if info.is_inter && info.ref_frame == ref_frame {
409 found = true;
410 add_candidate(candidates, info.mv, len as u32 * weight);
411 *newmv_count += u32::from(info.is_new_mv);
412 }
413 i += len.max(1);
414 }
415 found
416}
417
418/// The col scan (spec 7.10.2.3, libaom `scan_col_mbmi`): `scan_row`,
419/// transposed.
420#[allow(clippy::too_many_arguments)]
421fn scan_col(
422 grid: &MiGrid,
423 mi_row: usize,
424 mi_col: usize,
425 bh4: usize,
426 col_offset: isize,
427 max_col_offset: isize,
428 ref_frame: i8,
429 candidates: &mut Vec<StackEntry>,
430 newmv_count: &mut u32,
431 processed_cols: &mut usize,
432) -> bool {
433 let Some(col) = mi_col.checked_add_signed(col_offset) else {
434 return false;
435 };
436 let row_shift: usize = if col_offset.unsigned_abs() > 1 { 1 } else { 0 };
437 let use_step_16 = bh4 >= 16;
438 let end_mi = bh4.min(16);
439 let mut found = false;
440 let mut i = 0usize;
441 while i < end_mi {
442 let Some(info) = grid.get(mi_row + row_shift + i, col) else {
443 i += 1;
444 continue;
445 };
446 let n4 = info.size;
447 let mut len = bh4.min(n4);
448 if use_step_16 {
449 len = len.max(4);
450 } else if col_offset.unsigned_abs() > 1 {
451 len = len.max(2);
452 }
453 let mut weight = ROW_COL_WEIGHT_FLOOR;
454 if bh4 <= n4 {
455 let inc = ((-max_col_offset + col_offset + 1) as usize).min(n4);
456 weight = weight.max(inc as u32);
457 *processed_cols = (inc as isize - col_offset - 1).max(0) as usize;
458 }
459 if info.is_inter && info.ref_frame == ref_frame {
460 found = true;
461 add_candidate(candidates, info.mv, len as u32 * weight);
462 *newmv_count += u32::from(info.is_new_mv);
463 }
464 i += len.max(1);
465 }
466 found
467}
468
469/// The single top-right probe this reduction keeps of spec 7.10.2.4's extra
470/// scan positions, at the unit diagonally above-right of the block. Its
471/// vote is folded into the row scan's candidates (it sits on the same row
472/// as the block's neighbours above), which is what makes the row and column
473/// scans asymmetric under transposing a grid — spec has no matching
474/// bottom-left probe.
475fn scan_top_right(
476 grid: &MiGrid,
477 mi_row: usize,
478 mi_col: usize,
479 bw4: usize,
480 ref_frame: i8,
481 candidates: &mut Vec<StackEntry>,
482 newmv_count: &mut u32,
483) -> bool {
484 let Some(row) = mi_row.checked_sub(1) else {
485 return false;
486 };
487 let col = mi_col + bw4;
488 if let Some(info) = grid.get(row, col)
489 && info.is_inter
490 && info.ref_frame == ref_frame
491 {
492 add_candidate(candidates, info.mv, CORNER_WEIGHT);
493 *newmv_count += u32::from(info.is_new_mv);
494 return true;
495 }
496 false
497}
498
499/// The diagonal top-left corner probe (libaom `scan_blk_mbmi` at
500/// `row_offset = col_offset = -1`, mvref_common.c's "second outer area",
501/// called *after* `nearest_match` is already captured): the single unit
502/// diagonally above-left of the block. Its match folds into the row bucket
503/// too (see module doc) but must never move `nearest_match` itself or the
504/// real `newmv_count` — callers pass a throwaway counter for the latter.
505fn scan_corner(
506 grid: &MiGrid,
507 mi_row: usize,
508 mi_col: usize,
509 ref_frame: i8,
510 candidates: &mut Vec<StackEntry>,
511 newmv_count: &mut u32,
512) -> bool {
513 let (Some(row), Some(col)) = (mi_row.checked_sub(1), mi_col.checked_sub(1)) else {
514 return false;
515 };
516 if let Some(info) = grid.get(row, col)
517 && info.is_inter
518 && info.ref_frame == ref_frame
519 {
520 add_candidate(candidates, info.mv, CORNER_WEIGHT);
521 *newmv_count += u32::from(info.is_new_mv);
522 return true;
523 }
524 false
525}
526
527/// `MV_BORDER` (spec 7.10.2.14): 16 pixels of slack in 1/8-pel units, added
528/// on top of the block's own span before a candidate is clamped to the
529/// frame.
530const MV_BORDER: i32 = 16 << 3;
531
532/// Clamps one candidate MV to the range spec 7.10.2.14 (libaom's
533/// `clamp_mv_ref`) allows for a `bw4`-by-`bh4` block at `(mi_row, mi_col)` in
534/// a `mi_cols`-by-`mi_rows` frame: the distance from the block's own edge to
535/// the matching frame edge, plus the block's own span and [`MV_BORDER`] of
536/// slack, in every direction.
537fn clamp_mv_ref(
538 mv: (i32, i32),
539 mi_row: usize,
540 mi_col: usize,
541 bw4: usize,
542 bh4: usize,
543 mi_cols: usize,
544 mi_rows: usize,
545) -> (i32, i32) {
546 // Pixels-to-1/8-pel: 4 mi units/pixel-row * 8 subpel steps/pixel.
547 let to_subpel = |mi_units: usize| (mi_units as i32) * 4 * 8;
548 let (bw8, bh8) = (to_subpel(bw4), to_subpel(bh4));
549 let to_left = -to_subpel(mi_col);
550 let to_right = to_subpel(mi_cols.saturating_sub(bw4).saturating_sub(mi_col));
551 let to_top = -to_subpel(mi_row);
552 let to_bottom = to_subpel(mi_rows.saturating_sub(bh4).saturating_sub(mi_row));
553
554 let (row, col) = mv;
555 (
556 row.clamp(to_top - bh8 - MV_BORDER, to_bottom + bh8 + MV_BORDER),
557 col.clamp(to_left - bw8 - MV_BORDER, to_right + bw8 + MV_BORDER),
558 )
559}
560
561/// Builds the reference MV stack for the `bw4`-by-`bh4` (in 4x4 units)
562/// block at `(mi_row, mi_col)`, predicting against `ref_frame`, in a frame
563/// that is `mi_cols`-by-`mi_rows` 4x4 units (used only to clamp the
564/// predictors to the frame, spec 7.10.2.14).
565pub fn find_mv_stack(
566 grid: &MiGrid,
567 mi_row: usize,
568 mi_col: usize,
569 bw4: usize,
570 bh4: usize,
571 ref_frame: i8,
572 mi_cols: usize,
573 mi_rows: usize,
574) -> MvStack {
575 find_mv_stack_with_sign_bias(
576 grid,
577 mi_row,
578 mi_col,
579 bw4,
580 bh4,
581 ref_frame,
582 mi_cols,
583 mi_rows,
584 &NO_SIGN_BIAS,
585 None,
586 )
587}
588
589/// [`find_mv_stack`], with the frame header's real `ref_frame_sign_bias`
590/// (lane-av1refs: `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` are forward
591/// in display order, so the single-reference extension pass's borrowed-MV
592/// flip is no longer always inert once one of them is live next to a
593/// backward-biased neighbour).
594#[allow(clippy::too_many_arguments)]
595pub fn find_mv_stack_with_sign_bias(
596 grid: &MiGrid,
597 mi_row: usize,
598 mi_col: usize,
599 bw4: usize,
600 bh4: usize,
601 ref_frame: i8,
602 mi_cols: usize,
603 mi_rows: usize,
604 sign_bias_table: &SignBiasTable,
605 tpl: Option<TplArgs>,
606) -> MvStack {
607 let mut candidates = Vec::new();
608 let mut newmv_count = 0u32;
609
610 // libaom's `max_row_offset`/`max_col_offset` (`setup_ref_mv_list`): how
611 // far the row/col scans may reach, clamped to the tile's near edge
612 // (single-tile-per-frame here, so that's just the frame edge at 0) --
613 // `row_adj`/`col_adj` only ever fire for a sub-8x8 query block, which no
614 // real caller of this module ever is, but are ported anyway since
615 // nothing here relies on that.
616 let row_adj = bh4 < 2 && mi_row % 2 == 1;
617 let col_adj = bw4 < 2 && mi_col % 2 == 1;
618 let max_row_offset: isize = if mi_row > 0 {
619 let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj);
620 reach.max(-(mi_row as isize))
621 } else {
622 0
623 };
624 let max_col_offset: isize = if mi_col > 0 {
625 let reach = if bw4 < 2 { -4 } else { -6 } + isize::from(col_adj);
626 reach.max(-(mi_col as isize))
627 } else {
628 0
629 };
630
631 let mut processed_rows = 0usize;
632 let mut processed_cols = 0usize;
633 let found_above = mi_row > 0
634 && scan_row(
635 grid,
636 mi_row,
637 mi_col,
638 bw4,
639 -1,
640 max_row_offset,
641 ref_frame,
642 &mut candidates,
643 &mut newmv_count,
644 &mut processed_rows,
645 );
646 let found_left = mi_col > 0
647 && scan_col(
648 grid,
649 mi_row,
650 mi_col,
651 bh4,
652 -1,
653 max_col_offset,
654 ref_frame,
655 &mut candidates,
656 &mut newmv_count,
657 &mut processed_cols,
658 );
659 let found_top_right = scan_top_right(
660 grid,
661 mi_row,
662 mi_col,
663 bw4,
664 ref_frame,
665 &mut candidates,
666 &mut newmv_count,
667 );
668
669 // libaom's `row_match_count`/`col_match_count` (mvref_common.c) fold the
670 // top-right probe into the row side, so "found above" for context
671 // purposes means the row scan *or* the top-right one matched.
672 let row_matched = found_above || found_top_right;
673 let nearest_match = usize::from(row_matched) + usize::from(found_left);
674
675 // av1_find_mv_stack boosts only the entries the immediate scan found —
676 // exactly `candidates` at this point, before the corner probe (below)
677 // can add anything else (mvref_common.c ~line 544-545).
678 for entry in &mut candidates {
679 entry.weight += REF_CAT_LEVEL;
680 }
681
682 // Temporal MV candidates (spec 7.10.2.8's `add_tpl_ref_mv`, only reached
683 // when the frame header set `use_ref_frame_mvs`): probed over a grid of
684 // 8x8-unit offsets spanning the block (libaom's own `blk_row_end`/
685 // `blk_col_end`/`step_h`/`step_w`, every real block this crate ever
686 // codes being square and no wider than 32x32 — `BLOCK_64X64`'s own
687 // 16x16-mi-unit step branch is dead here, ported anyway since nothing
688 // relies on that), plus three "extension" samples past the block's own
689 // span (`tpl_sample_pos`) once the block is at least 8x8 and smaller
690 // than 64x64 (`allow_extension` — true for every block size this crate
691 // codes). Folded in *after* the row/col/top-right scan's own
692 // `REF_CAT_LEVEL` boost above and *before* the corner probe, matching
693 // libaom's call order in `setup_ref_mv_list` exactly (a temporal
694 // candidate never gets the boost, and the corner probe can still add a
695 // genuinely new, lower-weight entry after it).
696 let mut zero_mv_ctx = 0usize;
697 if let Some(TplArgs {
698 field,
699 cur_offset_0,
700 allow_high_precision_mv,
701 }) = tpl
702 {
703 let mut any_hit = false;
704 let voffset = bh4.max(2);
705 let hoffset = bw4.max(2);
706 let blk_row_end = bh4.min(16);
707 let blk_col_end = bw4.min(16);
708 let step_h = if bh4 >= 16 { 4 } else { 2 };
709 let step_w = if bw4 >= 16 { 4 } else { 2 };
710 let mut first_sample_missing = true;
711 let mut first_sample_far = false;
712 let mut blk_row = 0usize;
713 while blk_row < blk_row_end {
714 let mut blk_col = 0usize;
715 while blk_col < blk_col_end {
716 if let Some(cand) = crate::motion_field::add_tpl_ref_mv(
717 field,
718 mi_row,
719 mi_col,
720 blk_row as isize,
721 blk_col as isize,
722 cur_offset_0,
723 allow_high_precision_mv,
724 ) {
725 any_hit = true;
726 if blk_row == 0 && blk_col == 0 {
727 first_sample_missing = false;
728 first_sample_far = cand.mv.0.abs() >= 16 || cand.mv.1.abs() >= 16;
729 }
730 add_candidate(&mut candidates, cand.mv, 2);
731 }
732 blk_col += step_w;
733 }
734 blk_row += step_h;
735 }
736 // Three "extension" samples past the block's own span (libaom
737 // `tpl_sample_pos`), reachable for every 8x8..32x32 block this crate
738 // codes (`allow_extension`), gated on staying inside the block's own
739 // 64x64 superblock (`check_sb_border`).
740 let allow_extension = (2..16).contains(&bh4) && (2..16).contains(&bw4);
741 if allow_extension {
742 let sb_mask = 16isize;
743 for (row_off, col_off) in [
744 (voffset as isize, -2isize),
745 (voffset as isize, hoffset as isize),
746 (voffset as isize - 2, hoffset as isize),
747 ] {
748 let row = (mi_row as isize & (sb_mask - 1)) + row_off;
749 let col = (mi_col as isize & (sb_mask - 1)) + col_off;
750 if row < 0 || row >= sb_mask || col < 0 || col >= sb_mask {
751 continue;
752 }
753 if let Some(cand) = crate::motion_field::add_tpl_ref_mv(
754 field,
755 mi_row,
756 mi_col,
757 row_off,
758 col_off,
759 cur_offset_0,
760 allow_high_precision_mv,
761 ) {
762 any_hit = true;
763 add_candidate(&mut candidates, cand.mv, 2);
764 }
765 }
766 }
767 if any_hit {
768 TMV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
769 }
770 zero_mv_ctx = usize::from(first_sample_missing || first_sample_far);
771 }
772
773 // The diagonal top-left corner probe (module doc): folds into the row
774 // side for `ref_match_count` without moving the already-captured
775 // `nearest_match`, and its own newmv-ness is a dummy count libaom
776 // discards (`&dummy_newmv_count` at the real call site).
777 let mut dummy_newmv_count = 0u32;
778 let corner_matched = scan_corner(
779 grid,
780 mi_row,
781 mi_col,
782 ref_frame,
783 &mut candidates,
784 &mut dummy_newmv_count,
785 );
786 // The extended row/col scan (spec 7.10.2.4's `idx = 2..MVREF_ROW_COLS`,
787 // libaom's second `scan_row_mbmi`/`scan_col_mbmi` loop): reachable only
788 // once the immediate scan's own reach (`processed_rows`/`processed_cols`,
789 // threaded across calls the way libaom's own `int`s are) leaves a gap
790 // `max_row_offset`/`max_col_offset` (the tile edge) doesn't already
791 // clip. At this module's fixed 8-mi `tile.rs` geometry with every coded
792 // cell (intra or inter) feeding coverage, that reach always hits
793 // `MVREF_ROW_COLS`'s farthest offset first -- a true no-op there (see
794 // `extended_scan_is_a_no_op_at_8mi_geometry` below); decode.rs's smaller
795 // query blocks can leave real gaps this now actually scans. Folds into
796 // the row/col match booleans, never `nearest_match`; shares the corner
797 // probe's `dummy_newmv_count` (libaom's `setup_ref_mv_list` does too).
798 let mut row_matched_ext = false;
799 let mut col_matched_ext = false;
800 for idx in 2..=MVREF_ROW_COLS {
801 let row_offset = -((idx as isize) * 2) + 1 + isize::from(row_adj);
802 let col_offset = -((idx as isize) * 2) + 1 + isize::from(col_adj);
803 if row_offset.unsigned_abs() <= max_row_offset.unsigned_abs()
804 && row_offset.unsigned_abs() > processed_rows
805 && scan_row(
806 grid,
807 mi_row,
808 mi_col,
809 bw4,
810 row_offset,
811 max_row_offset,
812 ref_frame,
813 &mut candidates,
814 &mut dummy_newmv_count,
815 &mut processed_rows,
816 )
817 {
818 row_matched_ext = true;
819 }
820 if col_offset.unsigned_abs() <= max_col_offset.unsigned_abs()
821 && col_offset.unsigned_abs() > processed_cols
822 && scan_col(
823 grid,
824 mi_row,
825 mi_col,
826 bh4,
827 col_offset,
828 max_col_offset,
829 ref_frame,
830 &mut candidates,
831 &mut dummy_newmv_count,
832 &mut processed_cols,
833 )
834 {
835 col_matched_ext = true;
836 }
837 }
838 let ref_match_count = usize::from(row_matched || corner_matched || row_matched_ext)
839 + usize::from(found_left || col_matched_ext);
840
841 // Highest weight first; a stable sort keeps scan order (above, left,
842 // top-right, corner) among ties, matching spec 7.10.2.6. The corner
843 // probe's un-boosted entry (if new) always sorts after the boosted
844 // ones above, matching libaom's separate two-phase ranking.
845 candidates.sort_by_key(|e| std::cmp::Reverse(e.weight));
846 candidates.truncate(MAX_STACK_SIZE);
847
848 // libaom's "single reference frame extension" (`setup_ref_mv_list`,
849 // mvref_common.c, the `else` branch under "Handle single reference
850 // frame extension", calling `process_single_ref_mv_candidate`): when
851 // fewer than [`MAX_MV_REF_CANDIDATES`] (2, *not* `MAX_STACK_SIZE`) survive
852 // the scans above, top the stack up to that guarantee by re-walking the
853 // row directly above and the column directly left, gated on
854 // `refmv_count < MAX_MV_REF_CANDIDATES` per step (so it can stop after
855 // just one addition) -- over *any* inter neighbour regardless of which
856 // reference frame it coded, not just `ref_frame`. This module's doc
857 // used to call this pass a no-op ("whatever it would add was already
858 // added by the row/col scan"), true only while a stream ever has one
859 // live reference frame: once a second reference (`GOLDEN_FRAME`) is
860 // live next to `LAST_FRAME` blocks, this pass pulls in the other
861 // reference's MV as a low-weight (`2`, unboosted -- below
862 // `REF_CAT_LEVEL`) filler entry purely to make `entries.len()` (and
863 // hence how many `drl_mode` bits a `NEWMV` block reads) match the real
864 // bitstream -- round 10 (lane-av1golden8) traced a `GOLDEN_FRAME`
865 // `NEWMV` block desyncing its own `read_mv` by exactly this gap (real
866 // stack `len=2`, this module's `len=1`, one missing `drl_mode` bit).
867 // Round 11 replaced that round's hand-proved reduction (a bespoke
868 // re-scan gated on `MAX_STACK_SIZE`, weighing every hit `2` unconditionally)
869 // with this exact port: real gate is `MAX_MV_REF_CANDIDATES` (2), real
870 // reach is the block's own `bw4`/`bh4` (see `mi_size` below, not a flat
871 // 16), and dedup/weight/sign-bias now live in
872 // [`process_single_ref_mv_candidate`] itself, ported from libaom's
873 // function of the same name rather than re-derived by hand.
874 // libaom's `mi_size` for this pass (`setup_ref_mv_list`): the block's
875 // own span (`xd->width`/`xd->height`, i.e. `bw4`/`bh4` here), capped at
876 // a 64x64 superblock's 16 mi units, further clipped to the frame edge —
877 // never just "16, clipped to the frame edge" the way the prior
878 // hand-written pass had it, which over-walked past a small query
879 // block's own row/col run into cells that real neighbour scan (a wider
880 // block covering more than `bw4`/`bh4`) had already folded in above.
881 let mi_width = (16usize).min(bw4).min(mi_cols.saturating_sub(mi_col));
882 let mi_height = (16usize).min(bh4).min(mi_rows.saturating_sub(mi_row));
883 let mi_size = mi_width.min(mi_height);
884 if max_row_offset.unsigned_abs() >= 1 {
885 let mut idx = 0usize;
886 while idx < mi_size && candidates.len() < MAX_MV_REF_CANDIDATES {
887 let cand = grid.get(mi_row - 1, mi_col + idx);
888 let step = cand.map_or(1, |c| c.size).max(1);
889 if let Some(c) = cand {
890 process_single_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut candidates);
891 }
892 idx += step;
893 }
894 }
895 if max_col_offset.unsigned_abs() >= 1 {
896 let mut idx = 0usize;
897 while idx < mi_size && candidates.len() < MAX_MV_REF_CANDIDATES {
898 let cand = grid.get(mi_row + idx, mi_col - 1);
899 let step = cand.map_or(1, |c| c.size).max(1);
900 if let Some(c) = cand {
901 process_single_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut candidates);
902 }
903 idx += step;
904 }
905 }
906
907 let clamp = |mv| clamp_mv_ref(mv, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows);
908 let nearest_mv = candidates.first().map_or((0, 0), |e| clamp(e.mv));
909 let near_mv = candidates.get(1).map_or((0, 0), |e| clamp(e.mv));
910 let pred_mv = if candidates.is_empty() {
911 (0, 0)
912 } else {
913 nearest_mv
914 };
915
916 // Exact port of the `mode_context[ref_frame]` switch (mvref_common.c
917 // ~line 619-643). `new_mv_ctx` depends on `nearest_match` and the real
918 // `newmv_count` alone — libaom's switch never reads `ref_match_count`
919 // for those bits, so this half was already exact before this round.
920 let new_mv_ctx = match nearest_match {
921 // libaom's `case 0` also sets this bit from `ref_match_count`
922 // (`mode_context[ref_frame] |= 1` when `ref_match_count >= 1`,
923 // mvref_common.c ~line 621) — the corner-probe-derived count, not
924 // `nearest_match` alone, despite this module's doc comment above
925 // having claimed the opposite for several rounds.
926 0 => usize::from(ref_match_count >= 1),
927 1 => {
928 if newmv_count > 0 {
929 2
930 } else {
931 3
932 }
933 }
934 _ => {
935 if newmv_count >= 1 {
936 4
937 } else {
938 5
939 }
940 }
941 };
942 // `ref_mv_ctx` (the `REFMV_OFFSET` half of the same switch) genuinely
943 // depends on both counts — this is the part that was wrongly collapsed
944 // to `nearest_match` alone (see module doc / crate report).
945 let ref_mv_ctx = match nearest_match {
946 0 => match ref_match_count {
947 0 => 0,
948 1 => 1,
949 _ => 2,
950 },
951 1 => {
952 if ref_match_count >= 2 {
953 4
954 } else {
955 3
956 }
957 }
958 _ => 5,
959 };
960 // `zero_mv_ctx` was already computed above, from the temporal-MV pass
961 // when `tpl` is `Some` (GLOBALMV_OFFSET, spec 7.10.2.8) — `0` otherwise,
962 // exactly this reduction's old always-0 behaviour when
963 // `use_ref_frame_mvs` is unset.
964
965 // av1_drl_ctx (mvref_common.h): weight was boosted in place above for
966 // the nearest entries only, so this now compares the real stored weight
967 // against the threshold directly, the way libaom does.
968 let drl_ctx = candidates
969 .windows(2)
970 .map(|w| {
971 let (a, b) = (w[0].weight, w[1].weight);
972 if a >= REF_CAT_LEVEL && b >= REF_CAT_LEVEL {
973 0
974 } else if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL {
975 1
976 } else {
977 2
978 }
979 })
980 .collect();
981
982 MvStack {
983 entries: candidates,
984 nearest_mv,
985 near_mv,
986 pred_mv,
987 new_mv_ctx,
988 ref_mv_ctx,
989 zero_mv_ctx,
990 drl_ctx,
991 }
992}
993
994/// One neighbour's vote for a compound-reference (spec `RefFrame[0]` *and*
995/// `RefFrame[1]` both active) candidate: two full motion vectors and the
996/// combined weight — spec 7.10.2's compound half of `add_ref_mv_candidate`
997/// (libaom `mvref_common.c`, the `is_compound` branch of `scan_row_mbmi`/
998/// `scan_col_mbmi`/`scan_blk_mbmi`).
999#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1000pub struct CompoundStackEntry {
1001 /// The candidate's vote for `RefFrame[0]`'s motion vector.
1002 pub mv0: (i32, i32),
1003 /// The candidate's vote for `RefFrame[1]`'s motion vector.
1004 pub mv1: (i32, i32),
1005 /// The summed weight of every neighbour cell that voted for this pair.
1006 pub weight: u32,
1007}
1008
1009/// [`find_mv_stack_compound`]'s result — [`MvStack`]'s shape, doubled for
1010/// the reference pair.
1011#[derive(Clone, Debug, PartialEq, Eq)]
1012pub struct CompoundMvStack {
1013 /// The candidates, highest weight first.
1014 pub entries: Vec<CompoundStackEntry>,
1015 /// `RefStackMv[0]` for both refs, or `((0,0),(0,0))` when the stack is
1016 /// empty.
1017 pub nearest_mv: ((i32, i32), (i32, i32)),
1018 /// `RefStackMv[1]` for both refs, or `((0,0),(0,0))` when the stack has
1019 /// fewer than two entries.
1020 pub near_mv: ((i32, i32), (i32, i32)),
1021 /// The predictor pair a `NEW_NEWMV`-family block's MV differences are
1022 /// coded against.
1023 pub pred_mv: ((i32, i32), (i32, i32)),
1024 /// Context for the compound `new_mv` symbol.
1025 pub new_mv_ctx: usize,
1026 /// Context for the compound `ref_mv` symbol.
1027 pub ref_mv_ctx: usize,
1028 /// Context for the compound `zero_mv` symbol.
1029 pub zero_mv_ctx: usize,
1030 /// Context for each `drl_mode` symbol between consecutive stack entries.
1031 pub drl_ctx: Vec<usize>,
1032}
1033
1034/// [`add_candidate`], doubled: dedupes on the whole `(mv0, mv1)` pair.
1035fn add_compound_candidate(
1036 candidates: &mut Vec<CompoundStackEntry>,
1037 mv0: (i32, i32),
1038 mv1: (i32, i32),
1039 weight: u32,
1040) {
1041 if let Some(entry) = candidates.iter_mut().find(|e| e.mv0 == mv0 && e.mv1 == mv1) {
1042 entry.weight += weight;
1043 } else {
1044 candidates.push(CompoundStackEntry { mv0, mv1, weight });
1045 }
1046}
1047
1048/// The compound row scan (spec 7.10.2.2's compound branch, libaom
1049/// `scan_row_mbmi`'s `is_compound` path): [`scan_row`]'s weight/run-length
1050/// math unchanged, but a candidate only votes when *both* its `ref_frame`
1051/// and `ref_frame1` equal the query's pair exactly, in that order — a
1052/// compound pair is always encoded forward-then-backward
1053/// (`RefFrame[0]`/`RefFrame[1]`), so unlike [`process_single_ref_mv_candidate`]'s
1054/// extension pass, no sign-bias flip ever applies to an exact-pair scan
1055/// match (libaom's own `scan_row_mbmi` compound branch doesn't flip either).
1056#[allow(clippy::too_many_arguments)]
1057fn scan_row_compound(
1058 grid: &MiGrid,
1059 mi_row: usize,
1060 mi_col: usize,
1061 bw4: usize,
1062 row_offset: isize,
1063 max_row_offset: isize,
1064 ref_frame: (i8, i8),
1065 candidates: &mut Vec<CompoundStackEntry>,
1066 newmv_count: &mut u32,
1067 processed_rows: &mut usize,
1068) -> bool {
1069 let Some(row) = mi_row.checked_add_signed(row_offset) else {
1070 return false;
1071 };
1072 let col_shift: usize = if row_offset.unsigned_abs() > 1 { 1 } else { 0 };
1073 let use_step_16 = bw4 >= 16;
1074 let end_mi = bw4.min(16);
1075 let mut found = false;
1076 let mut i = 0usize;
1077 while i < end_mi {
1078 let Some(info) = grid.get(row, mi_col + col_shift + i) else {
1079 i += 1;
1080 continue;
1081 };
1082 let n4 = info.size;
1083 let mut len = bw4.min(n4);
1084 if use_step_16 {
1085 len = len.max(4);
1086 } else if row_offset.unsigned_abs() > 1 {
1087 len = len.max(2);
1088 }
1089 let mut weight = ROW_COL_WEIGHT_FLOOR;
1090 if bw4 <= n4 {
1091 let inc = ((-max_row_offset + row_offset + 1) as usize).min(n4);
1092 weight = weight.max(inc as u32);
1093 *processed_rows = (inc as isize - row_offset - 1).max(0) as usize;
1094 }
1095 if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 == Some(ref_frame.1) {
1096 found = true;
1097 add_compound_candidate(
1098 candidates,
1099 info.mv,
1100 info.mv1.unwrap_or((0, 0)),
1101 len as u32 * weight,
1102 );
1103 *newmv_count += u32::from(info.is_new_mv);
1104 }
1105 i += len.max(1);
1106 }
1107 found
1108}
1109
1110/// The compound col scan (spec 7.10.2.3's compound branch): [`scan_row_compound`],
1111/// transposed — mirrors [`scan_col`]/[`scan_row`]'s own relationship.
1112#[allow(clippy::too_many_arguments)]
1113fn scan_col_compound(
1114 grid: &MiGrid,
1115 mi_row: usize,
1116 mi_col: usize,
1117 bh4: usize,
1118 col_offset: isize,
1119 max_col_offset: isize,
1120 ref_frame: (i8, i8),
1121 candidates: &mut Vec<CompoundStackEntry>,
1122 newmv_count: &mut u32,
1123 processed_cols: &mut usize,
1124) -> bool {
1125 let Some(col) = mi_col.checked_add_signed(col_offset) else {
1126 return false;
1127 };
1128 let row_shift: usize = if col_offset.unsigned_abs() > 1 { 1 } else { 0 };
1129 let use_step_16 = bh4 >= 16;
1130 let end_mi = bh4.min(16);
1131 let mut found = false;
1132 let mut i = 0usize;
1133 while i < end_mi {
1134 let Some(info) = grid.get(mi_row + row_shift + i, col) else {
1135 i += 1;
1136 continue;
1137 };
1138 let n4 = info.size;
1139 let mut len = bh4.min(n4);
1140 if use_step_16 {
1141 len = len.max(4);
1142 } else if col_offset.unsigned_abs() > 1 {
1143 len = len.max(2);
1144 }
1145 let mut weight = ROW_COL_WEIGHT_FLOOR;
1146 if bh4 <= n4 {
1147 let inc = ((-max_col_offset + col_offset + 1) as usize).min(n4);
1148 weight = weight.max(inc as u32);
1149 *processed_cols = (inc as isize - col_offset - 1).max(0) as usize;
1150 }
1151 if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 == Some(ref_frame.1) {
1152 found = true;
1153 add_compound_candidate(
1154 candidates,
1155 info.mv,
1156 info.mv1.unwrap_or((0, 0)),
1157 len as u32 * weight,
1158 );
1159 *newmv_count += u32::from(info.is_new_mv);
1160 }
1161 i += len.max(1);
1162 }
1163 found
1164}
1165
1166/// The compound top-right probe ([`scan_top_right`]'s pair-matched twin).
1167fn scan_top_right_compound(
1168 grid: &MiGrid,
1169 mi_row: usize,
1170 mi_col: usize,
1171 bw4: usize,
1172 ref_frame: (i8, i8),
1173 candidates: &mut Vec<CompoundStackEntry>,
1174 newmv_count: &mut u32,
1175) -> bool {
1176 let Some(row) = mi_row.checked_sub(1) else {
1177 return false;
1178 };
1179 let col = mi_col + bw4;
1180 if let Some(info) = grid.get(row, col)
1181 && info.is_inter
1182 && info.ref_frame == ref_frame.0
1183 && info.ref_frame1 == Some(ref_frame.1)
1184 {
1185 add_compound_candidate(
1186 candidates,
1187 info.mv,
1188 info.mv1.unwrap_or((0, 0)),
1189 CORNER_WEIGHT,
1190 );
1191 *newmv_count += u32::from(info.is_new_mv);
1192 return true;
1193 }
1194 false
1195}
1196
1197/// The compound diagonal corner probe ([`scan_corner`]'s pair-matched twin).
1198fn scan_corner_compound(
1199 grid: &MiGrid,
1200 mi_row: usize,
1201 mi_col: usize,
1202 ref_frame: (i8, i8),
1203 candidates: &mut Vec<CompoundStackEntry>,
1204 newmv_count: &mut u32,
1205) -> bool {
1206 let (Some(row), Some(col)) = (mi_row.checked_sub(1), mi_col.checked_sub(1)) else {
1207 return false;
1208 };
1209 if let Some(info) = grid.get(row, col)
1210 && info.is_inter
1211 && info.ref_frame == ref_frame.0
1212 && info.ref_frame1 == Some(ref_frame.1)
1213 {
1214 add_compound_candidate(
1215 candidates,
1216 info.mv,
1217 info.mv1.unwrap_or((0, 0)),
1218 CORNER_WEIGHT,
1219 );
1220 *newmv_count += u32::from(info.is_new_mv);
1221 return true;
1222 }
1223 false
1224}
1225
1226/// Per-side unresolved-MV accumulator [`process_compound_ref_mv_candidate`]
1227/// fills across every candidate the compound extension pass walks: up to two
1228/// motion vectors that matched `ref_frame.0`/`.1` exactly (`ref_id`), and up
1229/// to two more borrowed from a differently-referenced but still-inter
1230/// neighbour under the sign-bias flip [`process_single_ref_mv_candidate`]
1231/// also applies (`ref_diff`). Ported from libaom's `setup_ref_mv_list`
1232/// (`mvref_common.c`, `process_compound_ref_mv_candidate` ~line 380-430 plus
1233/// the combine step at ~696-762): the extension walk fills this once across
1234/// the whole row-then-col scan, and [`combine_compound_candidates`] below
1235/// zips the two independently-filled sides back into full pair candidates.
1236#[derive(Default)]
1237struct CompoundRefLists {
1238 ref_id: [Vec<(i32, i32)>; 2],
1239 ref_diff: [Vec<(i32, i32)>; 2],
1240}
1241
1242/// libaom's `process_compound_ref_mv_candidate`: folds one already-coded
1243/// neighbour's up to two reference slots into `lists`, split by which side
1244/// of `ref_frame` (the query block's own compound pair) each slot's own
1245/// reference frame matches — an exact match goes to that side's `ref_id`
1246/// list, anything else (still inter, wrong reference) goes to `ref_diff`
1247/// under the usual sign-bias flip.
1248fn process_compound_ref_mv_candidate(
1249 candidate: &MiInfo,
1250 ref_frame: (i8, i8),
1251 sign_bias_table: &SignBiasTable,
1252 lists: &mut CompoundRefLists,
1253) {
1254 if !candidate.is_inter {
1255 return;
1256 }
1257 let slots = [
1258 Some((candidate.ref_frame, candidate.mv)),
1259 candidate
1260 .ref_frame1
1261 .map(|rf1| (rf1, candidate.mv1.unwrap_or((0, 0)))),
1262 ];
1263 for (candidate_ref, candidate_mv) in slots.into_iter().flatten() {
1264 for (i, side_ref) in [ref_frame.0, ref_frame.1].into_iter().enumerate() {
1265 if candidate_ref == side_ref {
1266 if lists.ref_id[i].len() < 2 {
1267 lists.ref_id[i].push(candidate_mv);
1268 }
1269 } else if lists.ref_diff[i].len() < 2 {
1270 let mut mv = candidate_mv;
1271 if sign_bias(sign_bias_table, candidate_ref) != sign_bias(sign_bias_table, side_ref)
1272 {
1273 mv = (-mv.0, -mv.1);
1274 }
1275 lists.ref_diff[i].push(mv);
1276 }
1277 }
1278 }
1279}
1280
1281/// libaom's combine step (`setup_ref_mv_list`, `mvref_common.c` ~696-720):
1282/// zips each side's `ref_id` (exact matches) then `ref_diff` (borrowed,
1283/// sign-flipped) entries, position-wise and independently per side, into up
1284/// to two full `(mv0, mv1)` pair candidates — missing slots default to
1285/// `(0, 0)`, matching libaom's zero-initialized `combined_mvs`.
1286fn combine_compound_candidates(lists: &CompoundRefLists) -> [((i32, i32), (i32, i32)); 2] {
1287 let side_slots = |side: usize| -> [(i32, i32); 2] {
1288 let merged: Vec<(i32, i32)> = lists.ref_id[side]
1289 .iter()
1290 .chain(lists.ref_diff[side].iter())
1291 .take(2)
1292 .copied()
1293 .collect();
1294 std::array::from_fn(|i| merged.get(i).copied().unwrap_or((0, 0)))
1295 };
1296 let side0 = side_slots(0);
1297 let side1 = side_slots(1);
1298 [(side0[0], side1[0]), (side0[1], side1[1])]
1299}
1300
1301/// [`find_mv_stack_with_sign_bias`]'s compound-reference twin (spec
1302/// 7.10.2's `is_compound` path throughout): builds the reference MV stack
1303/// for a block predicted against *two* simultaneously-active reference
1304/// frames (`ref_frame.0`, `ref_frame.1`), keeping every existing
1305/// single-reference caller of [`find_mv_stack`]/[`find_mv_stack_with_sign_bias`]
1306/// untouched — this is a new, parallel entry point, not an extension of the
1307/// single-ref one. Same reduction scope as the single-ref module doc
1308/// (single tile, square blocks, `IDENTITY` global motion only); the
1309/// mode-context switch below reuses the identical `(nearest_match,
1310/// ref_match_count)` derivation the single-ref path uses, since libaom's own
1311/// switch statement (`mvref_common.c` ~619-643) is ref-count-agnostic — it
1312/// only ever reads those two counts, regardless of which `MODE_CTX_REF_FRAMES`
1313/// slot `mode_context` it's indexing.
1314///
1315/// The compound extension combine step (`setup_ref_mv_list`, ~line 700-754)
1316/// and the temporal `add_tpl_ref_mv` fold-in (~line 341-433) are both exact
1317/// ports of libaom's real behaviour as of r5 — see the inline comments at
1318/// each site.
1319#[allow(clippy::too_many_arguments)]
1320pub fn find_mv_stack_compound(
1321 grid: &MiGrid,
1322 mi_row: usize,
1323 mi_col: usize,
1324 bw4: usize,
1325 bh4: usize,
1326 ref_frame: (i8, i8),
1327 mi_cols: usize,
1328 mi_rows: usize,
1329 sign_bias_table: &SignBiasTable,
1330 tpl: Option<CompoundTplArgs>,
1331) -> CompoundMvStack {
1332 let mut candidates: Vec<CompoundStackEntry> = Vec::new();
1333 let mut newmv_count = 0u32;
1334
1335 let row_adj = bh4 < 2 && mi_row % 2 == 1;
1336 let col_adj = bw4 < 2 && mi_col % 2 == 1;
1337 let max_row_offset: isize = if mi_row > 0 {
1338 let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj);
1339 reach.max(-(mi_row as isize))
1340 } else {
1341 0
1342 };
1343 let max_col_offset: isize = if mi_col > 0 {
1344 let reach = if bw4 < 2 { -4 } else { -6 } + isize::from(col_adj);
1345 reach.max(-(mi_col as isize))
1346 } else {
1347 0
1348 };
1349
1350 let mut processed_rows = 0usize;
1351 let mut processed_cols = 0usize;
1352 let found_above = mi_row > 0
1353 && scan_row_compound(
1354 grid,
1355 mi_row,
1356 mi_col,
1357 bw4,
1358 -1,
1359 max_row_offset,
1360 ref_frame,
1361 &mut candidates,
1362 &mut newmv_count,
1363 &mut processed_rows,
1364 );
1365 let found_left = mi_col > 0
1366 && scan_col_compound(
1367 grid,
1368 mi_row,
1369 mi_col,
1370 bh4,
1371 -1,
1372 max_col_offset,
1373 ref_frame,
1374 &mut candidates,
1375 &mut newmv_count,
1376 &mut processed_cols,
1377 );
1378 let found_top_right = scan_top_right_compound(
1379 grid,
1380 mi_row,
1381 mi_col,
1382 bw4,
1383 ref_frame,
1384 &mut candidates,
1385 &mut newmv_count,
1386 );
1387
1388 let row_matched = found_above || found_top_right;
1389 let nearest_match = usize::from(row_matched) + usize::from(found_left);
1390
1391 for entry in &mut candidates {
1392 entry.weight += REF_CAT_LEVEL;
1393 }
1394
1395 // Temporal compound candidates (spec 7.10.2.8's compound
1396 // `add_tpl_ref_mv`): the same projected field, read once per side of the
1397 // pair through the existing single-ref [`crate::motion_field::add_tpl_ref_mv`]
1398 // — each side's own `cur_offset` scales the *same* stored candidate to
1399 // that side's reference frame. libaom's real `add_tpl_ref_mv` looks up
1400 // the stored `mfmv0`/`ref_frame_offset` pair exactly once per `(blk_row,
1401 // blk_col)` and, if present, always projects it to *both* sides (the
1402 // lookup itself never fails for one side and succeeds for the other);
1403 // a missing side there is `INVALID_MV`/global-motion zero-fill, never a
1404 // dropped candidate. Ported exactly: each side is read independently and
1405 // a missing side zero-fills rather than vetoing the pair.
1406 let mut zero_mv_ctx = 0usize;
1407 if let Some(CompoundTplArgs {
1408 field,
1409 cur_offset_0,
1410 cur_offset_1,
1411 allow_high_precision_mv,
1412 }) = tpl
1413 {
1414 let mut any_hit = false;
1415 let blk_row_end = bh4.min(16);
1416 let blk_col_end = bw4.min(16);
1417 let step_h = if bh4 >= 16 { 4 } else { 2 };
1418 let step_w = if bw4 >= 16 { 4 } else { 2 };
1419 let mut first_sample_missing = true;
1420 let mut first_sample_far = false;
1421 let mut blk_row = 0usize;
1422 while blk_row < blk_row_end {
1423 let mut blk_col = 0usize;
1424 while blk_col < blk_col_end {
1425 let cand0 = crate::motion_field::add_tpl_ref_mv(
1426 field,
1427 mi_row,
1428 mi_col,
1429 blk_row as isize,
1430 blk_col as isize,
1431 cur_offset_0,
1432 allow_high_precision_mv,
1433 );
1434 let cand1 = crate::motion_field::add_tpl_ref_mv(
1435 field,
1436 mi_row,
1437 mi_col,
1438 blk_row as isize,
1439 blk_col as isize,
1440 cur_offset_1,
1441 allow_high_precision_mv,
1442 );
1443 if cand0.is_some() || cand1.is_some() {
1444 any_hit = true;
1445 let mv0 = cand0.map_or((0, 0), |c| c.mv);
1446 let mv1 = cand1.map_or((0, 0), |c| c.mv);
1447 if blk_row == 0 && blk_col == 0 {
1448 first_sample_missing = false;
1449 first_sample_far = mv0.0.abs() >= 16
1450 || mv0.1.abs() >= 16
1451 || mv1.0.abs() >= 16
1452 || mv1.1.abs() >= 16;
1453 }
1454 add_compound_candidate(&mut candidates, mv0, mv1, 2);
1455 }
1456 blk_col += step_w;
1457 }
1458 blk_row += step_h;
1459 }
1460 if any_hit {
1461 TMV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1462 }
1463 zero_mv_ctx = usize::from(first_sample_missing || first_sample_far);
1464 }
1465
1466 let mut dummy_newmv_count = 0u32;
1467 let corner_matched = scan_corner_compound(
1468 grid,
1469 mi_row,
1470 mi_col,
1471 ref_frame,
1472 &mut candidates,
1473 &mut dummy_newmv_count,
1474 );
1475 let mut row_matched_ext = false;
1476 let mut col_matched_ext = false;
1477 for idx in 2..=MVREF_ROW_COLS {
1478 let row_offset = -((idx as isize) * 2) + 1 + isize::from(row_adj);
1479 let col_offset = -((idx as isize) * 2) + 1 + isize::from(col_adj);
1480 if row_offset.unsigned_abs() <= max_row_offset.unsigned_abs()
1481 && row_offset.unsigned_abs() > processed_rows
1482 && scan_row_compound(
1483 grid,
1484 mi_row,
1485 mi_col,
1486 bw4,
1487 row_offset,
1488 max_row_offset,
1489 ref_frame,
1490 &mut candidates,
1491 &mut dummy_newmv_count,
1492 &mut processed_rows,
1493 )
1494 {
1495 row_matched_ext = true;
1496 }
1497 if col_offset.unsigned_abs() <= max_col_offset.unsigned_abs()
1498 && col_offset.unsigned_abs() > processed_cols
1499 && scan_col_compound(
1500 grid,
1501 mi_row,
1502 mi_col,
1503 bh4,
1504 col_offset,
1505 max_col_offset,
1506 ref_frame,
1507 &mut candidates,
1508 &mut dummy_newmv_count,
1509 &mut processed_cols,
1510 )
1511 {
1512 col_matched_ext = true;
1513 }
1514 }
1515 let ref_match_count = usize::from(row_matched || corner_matched || row_matched_ext)
1516 + usize::from(found_left || col_matched_ext);
1517
1518 candidates.sort_by_key(|e| std::cmp::Reverse(e.weight));
1519 candidates.truncate(MAX_STACK_SIZE);
1520
1521 // The compound extension pass (libaom's `setup_ref_mv_list`, "Handle
1522 // compound reference frame extension"): gather across the row directly
1523 // above and the column directly left (same `mi_size` reach as the
1524 // single-ref pass), then combine once.
1525 let mi_width = (16usize).min(bw4).min(mi_cols.saturating_sub(mi_col));
1526 let mi_height = (16usize).min(bh4).min(mi_rows.saturating_sub(mi_row));
1527 let mi_size = mi_width.min(mi_height);
1528 if candidates.len() < MAX_MV_REF_CANDIDATES {
1529 let mut lists = CompoundRefLists::default();
1530 if max_row_offset.unsigned_abs() >= 1 {
1531 let mut idx = 0usize;
1532 while idx < mi_size {
1533 let cand = grid.get(mi_row - 1, mi_col + idx);
1534 let step = cand.map_or(1, |c| c.size).max(1);
1535 if let Some(c) = cand {
1536 process_compound_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut lists);
1537 }
1538 idx += step;
1539 }
1540 }
1541 if max_col_offset.unsigned_abs() >= 1 {
1542 let mut idx = 0usize;
1543 while idx < mi_size {
1544 let cand = grid.get(mi_row + idx, mi_col - 1);
1545 let step = cand.map_or(1, |c| c.size).max(1);
1546 if let Some(c) = cand {
1547 process_compound_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut lists);
1548 }
1549 idx += step;
1550 }
1551 }
1552 // libaom's real dedup (`setup_ref_mv_list` ~735-754): when the stack
1553 // already has exactly one entry, compare only `comp_list[0]` against
1554 // it and, on a match, take `comp_list[1]` instead (skip, no weight
1555 // bump) — otherwise append `comp_list[0]` as a brand-new entry. When
1556 // the stack is empty, both `comp_list[0]` and `comp_list[1]` are
1557 // appended unconditionally, with no dedup check at all.
1558 let comp_list = combine_compound_candidates(&lists);
1559 if candidates.len() == 1 {
1560 let (mv0, mv1) = if comp_list[0] == (candidates[0].mv0, candidates[0].mv1) {
1561 comp_list[1]
1562 } else {
1563 comp_list[0]
1564 };
1565 candidates.push(CompoundStackEntry {
1566 mv0,
1567 mv1,
1568 weight: 2,
1569 });
1570 } else if candidates.is_empty() {
1571 for (mv0, mv1) in comp_list {
1572 candidates.push(CompoundStackEntry {
1573 mv0,
1574 mv1,
1575 weight: 2,
1576 });
1577 }
1578 }
1579 }
1580
1581 let clamp = |mv| clamp_mv_ref(mv, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows);
1582 let nearest_mv = candidates
1583 .first()
1584 .map_or(((0, 0), (0, 0)), |e| (clamp(e.mv0), clamp(e.mv1)));
1585 let near_mv = candidates
1586 .get(1)
1587 .map_or(((0, 0), (0, 0)), |e| (clamp(e.mv0), clamp(e.mv1)));
1588 let pred_mv = if candidates.is_empty() {
1589 ((0, 0), (0, 0))
1590 } else {
1591 nearest_mv
1592 };
1593
1594 let new_mv_ctx = match nearest_match {
1595 0 => usize::from(ref_match_count >= 1),
1596 1 => {
1597 if newmv_count > 0 {
1598 2
1599 } else {
1600 3
1601 }
1602 }
1603 _ => {
1604 if newmv_count >= 1 {
1605 4
1606 } else {
1607 5
1608 }
1609 }
1610 };
1611 let ref_mv_ctx = match nearest_match {
1612 0 => match ref_match_count {
1613 0 => 0,
1614 1 => 1,
1615 _ => 2,
1616 },
1617 1 => {
1618 if ref_match_count >= 2 {
1619 4
1620 } else {
1621 3
1622 }
1623 }
1624 _ => 5,
1625 };
1626
1627 let drl_ctx = candidates
1628 .windows(2)
1629 .map(|w| {
1630 let (a, b) = (w[0].weight, w[1].weight);
1631 if a >= REF_CAT_LEVEL && b >= REF_CAT_LEVEL {
1632 0
1633 } else if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL {
1634 1
1635 } else {
1636 2
1637 }
1638 })
1639 .collect();
1640
1641 CompoundMvStack {
1642 entries: candidates,
1643 nearest_mv,
1644 near_mv,
1645 pred_mv,
1646 new_mv_ctx,
1647 ref_mv_ctx,
1648 zero_mv_ctx,
1649 drl_ctx,
1650 }
1651}
1652
1653/// [`find_mv_stack_compound`]'s temporal-MV inputs — [`TplArgs`], doubled:
1654/// one `cur_offset` per side of the pair (`get_relative_dist(OrderHint,
1655/// OrderHints[ref_frame.N - LAST_FRAME])`, spec 7.9.3), since a compound
1656/// query projects the same stored field twice, once per reference.
1657pub struct CompoundTplArgs<'a> {
1658 /// The current frame's projected temporal motion field.
1659 pub field: &'a crate::motion_field::TplField,
1660 /// `get_relative_dist` for `ref_frame.0`.
1661 pub cur_offset_0: i32,
1662 /// `get_relative_dist` for `ref_frame.1`.
1663 pub cur_offset_1: i32,
1664 /// The frame header's own `allow_high_precision_mv`.
1665 pub allow_high_precision_mv: bool,
1666}
1667
1668/// The single-reference context shared by the `single_ref_p1`/`p3`/`p4`
1669/// binary decisions this crate's LAST-only reference chain codes (spec
1670/// 5.11.25; libaom's `av1_get_pred_context_single_ref_p1/p3/p4`,
1671/// `pred_common.c`). Each of those three functions compares a forward-ref
1672/// neighbour count against a same-direction count that is always zero in a
1673/// LAST-only world (no LAST2/LAST3/GOLDEN/backward candidate ever exists
1674/// here), which collapses all three of libaom's formulas to the same
1675/// two-valued test: "is there an inter neighbour at all". `has_inter`
1676/// gathers that over the block's whole span, the way spec 5.11.39 reads any
1677/// neighbour-derived context.
1678pub(crate) fn single_ref_ctx(has_inter_neighbour: bool) -> usize {
1679 if has_inter_neighbour { 2 } else { 1 }
1680}
1681
1682/// `MV_REFERENCE_FRAME` values a single (non-compound) reference can name
1683/// (spec 6.10.24's `ref_frame` alphabet; libaom `av1/common/enums.h`).
1684pub(crate) const LAST_FRAME: i8 = 1;
1685pub(crate) const LAST2_FRAME: i8 = 2;
1686pub(crate) const LAST3_FRAME: i8 = 3;
1687pub(crate) const GOLDEN_FRAME: i8 = 4;
1688pub(crate) const BWDREF_FRAME: i8 = 5;
1689pub(crate) const ALTREF2_FRAME: i8 = 6;
1690pub(crate) const ALTREF_FRAME: i8 = 7;
1691
1692/// libaom `pred_common.c`'s shared shape behind every `single_ref_p*`/
1693/// `comp_ref*` context function once compound prediction (a second ref per
1694/// neighbour) is out of scope: count how many of the immediate above/left
1695/// neighbours (spec 5.11.25's own single-neighbour read, not a whole-span
1696/// scan -- `av1_collect_neighbors_ref_counts`, `MACROBLOCKD::above_mbmi`/
1697/// `left_mbmi`) coded a reference in `a_set` vs. `b_set`, and compare: fewer
1698/// `a`s than `b`s is context 0, equal is 1 (also every unavailable-neighbour
1699/// case, both counts zero), more `a`s is 2.
1700fn ref_ctx(above: Option<i8>, left: Option<i8>, a_set: &[i8], b_set: &[i8]) -> usize {
1701 let a = [above, left]
1702 .into_iter()
1703 .flatten()
1704 .filter(|r| a_set.contains(r))
1705 .count();
1706 let b = [above, left]
1707 .into_iter()
1708 .flatten()
1709 .filter(|r| b_set.contains(r))
1710 .count();
1711 match a.cmp(&b) {
1712 std::cmp::Ordering::Less => 0,
1713 std::cmp::Ordering::Equal => 1,
1714 std::cmp::Ordering::Greater => 2,
1715 }
1716}
1717
1718const FORWARD_REFS: [i8; 4] = [LAST_FRAME, LAST2_FRAME, LAST3_FRAME, GOLDEN_FRAME];
1719const BACKWARD_REFS: [i8; 3] = [BWDREF_FRAME, ALTREF2_FRAME, ALTREF_FRAME];
1720
1721/// `av1_get_pred_context_single_ref_p1`: forward vs. backward reference.
1722pub(crate) fn single_ref_p1_ctx(above: Option<i8>, left: Option<i8>) -> usize {
1723 ref_ctx(above, left, &FORWARD_REFS, &BACKWARD_REFS)
1724}
1725
1726/// `av1_get_pred_context_single_ref_p2`
1727/// (`get_pred_context_brfarf2_or_arf`): `BWDREF`/`ALTREF2` vs. `ALTREF`.
1728pub(crate) fn single_ref_p2_ctx(above: Option<i8>, left: Option<i8>) -> usize {
1729 ref_ctx(above, left, &[BWDREF_FRAME, ALTREF2_FRAME], &[ALTREF_FRAME])
1730}
1731
1732/// `av1_get_pred_context_single_ref_p3`
1733/// (`get_pred_context_ll2_or_l3gld`): `LAST`/`LAST2` vs. `LAST3`/`GOLDEN`.
1734pub(crate) fn single_ref_p3_ctx(above: Option<i8>, left: Option<i8>) -> usize {
1735 ref_ctx(
1736 above,
1737 left,
1738 &[LAST_FRAME, LAST2_FRAME],
1739 &[LAST3_FRAME, GOLDEN_FRAME],
1740 )
1741}
1742
1743/// `av1_get_pred_context_single_ref_p4`
1744/// (`get_pred_context_last_or_last2`): `LAST` vs. `LAST2`.
1745pub(crate) fn single_ref_p4_ctx(above: Option<i8>, left: Option<i8>) -> usize {
1746 ref_ctx(above, left, &[LAST_FRAME], &[LAST2_FRAME])
1747}
1748
1749/// `av1_get_pred_context_single_ref_p5`
1750/// (`get_pred_context_last3_or_gld`): `LAST3` vs. `GOLDEN`.
1751pub(crate) fn single_ref_p5_ctx(above: Option<i8>, left: Option<i8>) -> usize {
1752 ref_ctx(above, left, &[LAST3_FRAME], &[GOLDEN_FRAME])
1753}
1754
1755/// `av1_get_pred_context_single_ref_p6`
1756/// (`get_pred_context_brf_or_arf2`): `BWDREF` vs. `ALTREF2`.
1757pub(crate) fn single_ref_p6_ctx(above: Option<i8>, left: Option<i8>) -> usize {
1758 ref_ctx(above, left, &[BWDREF_FRAME], &[ALTREF2_FRAME])
1759}
1760
1761/// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` vs. `LAST3`/`GOLDEN`,
1762/// conditioned on a unidirectional pair known to be one of the three
1763/// `LAST`-anchored ones (lane-av1comp).
1764pub(crate) fn uni_comp_ref_p1_ctx(above: Option<i8>, left: Option<i8>) -> usize {
1765 ref_ctx(above, left, &[LAST2_FRAME], &[LAST3_FRAME, GOLDEN_FRAME])
1766}
1767
1768/// One neighbouring block's reference-frame shape, as
1769/// [`reference_mode_ctx`]/[`comp_reference_type_ctx`] need it: `None` for an
1770/// out-of-frame neighbour, `Some(ref0, None)` for an intra or single-ref
1771/// inter block, `Some(ref0, Some(ref1))` for a compound one. `uni` is
1772/// `ref1`'s meaning only when compound: whether the pair libaom's
1773/// `has_uni_comp_refs` would call unidirectional (both refs on the same
1774/// side of the current frame).
1775#[derive(Clone, Copy)]
1776pub(crate) struct NeighbourRef {
1777 pub is_inter: bool,
1778 pub ref0: i8,
1779 pub ref1: Option<i8>,
1780 pub uni: bool,
1781}
1782
1783fn is_backward(r: i8) -> bool {
1784 (BWDREF_FRAME..=ALTREF_FRAME).contains(&r)
1785}
1786
1787/// `av1_get_reference_mode_context` (spec 5.11.25's `comp_mode` context,
1788/// libaom `pred_common.c`): 5 contexts from how many of the above/left
1789/// neighbours are themselves compound-predicted, and (when neither/one is)
1790/// whether their single reference is a backward one.
1791pub(crate) fn reference_mode_ctx(above: Option<NeighbourRef>, left: Option<NeighbourRef>) -> usize {
1792 match (above, left) {
1793 (Some(a), Some(l)) => match (a.ref1.is_some(), l.ref1.is_some()) {
1794 (false, false) => usize::from(is_backward(a.ref0) ^ is_backward(l.ref0)),
1795 (false, true) => 2 + usize::from(is_backward(a.ref0) || !a.is_inter),
1796 (true, false) => 2 + usize::from(is_backward(l.ref0) || !l.is_inter),
1797 (true, true) => 4,
1798 },
1799 (Some(e), None) | (None, Some(e)) => {
1800 if e.ref1.is_some() {
1801 3
1802 } else {
1803 usize::from(is_backward(e.ref0))
1804 }
1805 }
1806 (None, None) => 1,
1807 }
1808}
1809
1810/// `av1_get_comp_reference_type_context` (spec 5.11.25's
1811/// `comp_reference_type` context, libaom `pred_common.c`): 5 contexts from
1812/// whether the above/left neighbours are intra, single-ref, unidirectional
1813/// compound, or bidirectional compound.
1814pub(crate) fn comp_reference_type_ctx(
1815 above: Option<NeighbourRef>,
1816 left: Option<NeighbourRef>,
1817) -> usize {
1818 match (above, left) {
1819 (Some(a), Some(l)) => match (a.is_inter, l.is_inter) {
1820 (false, false) => 2,
1821 (false, true) | (true, false) => {
1822 let inter = if a.is_inter { a } else { l };
1823 if inter.ref1.is_none() {
1824 2
1825 } else {
1826 1 + 2 * usize::from(inter.uni)
1827 }
1828 }
1829 (true, true) => {
1830 let (a_sg, l_sg) = (a.ref1.is_none(), l.ref1.is_none());
1831 if a_sg && l_sg {
1832 1 + 2 * usize::from(!(is_backward(a.ref0) ^ is_backward(l.ref0)))
1833 } else if a_sg || l_sg {
1834 let uni = if a_sg { l.uni } else { a.uni };
1835 if !uni {
1836 1
1837 } else {
1838 3 + usize::from(!(is_backward(a.ref0) ^ is_backward(l.ref0)))
1839 }
1840 } else if !a.uni && !l.uni {
1841 0
1842 } else if !a.uni || !l.uni {
1843 2
1844 } else {
1845 3 + usize::from(!((a.ref0 == BWDREF_FRAME) ^ (l.ref0 == BWDREF_FRAME)))
1846 }
1847 }
1848 },
1849 (Some(e), None) | (None, Some(e)) => {
1850 if !e.is_inter {
1851 2
1852 } else if e.ref1.is_none() {
1853 2
1854 } else {
1855 4 * usize::from(e.uni)
1856 }
1857 }
1858 (None, None) => 2,
1859 }
1860}
1861
1862#[cfg(test)]
1863mod tests {
1864 use super::*;
1865
1866 fn inter(mv: (i32, i32)) -> MiInfo {
1867 MiInfo {
1868 is_inter: true,
1869 ref_frame: 1,
1870 ref_frame1: None,
1871 mv1: None,
1872 mv,
1873 is_new_mv: false,
1874 // 1: smaller than every `bw4`/`bh4` these small-grid tests use,
1875 // so it never trips the extended-scan coverage boost -- these
1876 // tests only exercise the immediate/corner/top-right scans.
1877 size: 1,
1878 }
1879 }
1880
1881 #[test]
1882 fn all_same_mv_neighbourhood_dedupes_to_one_entry() {
1883 let mut grid = MiGrid::new(8, 8);
1884 // Block at (2, 2), 2x2 mi units. Above row 1, cols 2..4; left col 1,
1885 // rows 2..4; top-right at (1, 4). All the same MV.
1886 let mv = (4, 4);
1887 grid.set(1, 2, inter(mv));
1888 grid.set(1, 3, inter(mv));
1889 grid.set(2, 1, inter(mv));
1890 grid.set(3, 1, inter(mv));
1891 grid.set(1, 4, inter(mv));
1892
1893 let stack = find_mv_stack(&grid, 2, 2, 2, 2, 1, 8, 8);
1894
1895 assert_eq!(stack.entries.len(), 1);
1896 assert_eq!(stack.entries[0].mv, mv);
1897 // 2 above cells + 2 left cells (weight 2 each, `size: 1` neighbours
1898 // below the `bw4 <= n4` weight-boost floor) + 1 top-right (libaom's
1899 // real `scan_blk_mbmi` weight, `CORNER_WEIGHT` = 4, not a flat 2),
1900 // plus the REF_CAT_LEVEL boost av1_find_mv_stack applies to every
1901 // entry the immediate row/col/top-right scan found (module doc).
1902 assert_eq!(stack.entries[0].weight, 12 + REF_CAT_LEVEL);
1903 assert_eq!(stack.nearest_mv, mv);
1904 // Exact ctx (see module doc): both sides matched (nearest_match=2)
1905 // and no neighbour was coded NEWMV, which is libaom's
1906 // `mode_context[ref_frame] |= 5` branch.
1907 assert_eq!(stack.new_mv_ctx, 5);
1908 assert_eq!(stack.ref_mv_ctx, 5);
1909 assert_eq!(stack.zero_mv_ctx, 0);
1910 }
1911
1912 #[test]
1913 fn two_distinct_neighbour_mvs_yield_two_entries_in_weight_order() {
1914 let mut grid = MiGrid::new(8, 8);
1915 // Block at (3, 3), bw4=2, bh4=3: above spans 2 cells (weight 4),
1916 // left spans 3 cells (weight 6) — distinct MVs, distinct weights.
1917 let above_mv = (4, 4);
1918 let left_mv = (8, 8);
1919 grid.set(2, 3, inter(above_mv));
1920 grid.set(2, 4, inter(above_mv));
1921 grid.set(3, 2, inter(left_mv));
1922 grid.set(4, 2, inter(left_mv));
1923 grid.set(5, 2, inter(left_mv));
1924
1925 let stack = find_mv_stack(&grid, 3, 3, 2, 3, 1, 8, 8);
1926
1927 // Both are entries the immediate scan found, so both get the
1928 // REF_CAT_LEVEL boost (module doc) — their relative order is
1929 // unaffected.
1930 assert_eq!(stack.entries.len(), 2);
1931 assert_eq!(
1932 stack.entries[0],
1933 StackEntry {
1934 mv: left_mv,
1935 weight: 6 + REF_CAT_LEVEL
1936 }
1937 );
1938 assert_eq!(
1939 stack.entries[1],
1940 StackEntry {
1941 mv: above_mv,
1942 weight: 4 + REF_CAT_LEVEL
1943 }
1944 );
1945 assert_eq!(stack.nearest_mv, left_mv);
1946 assert_eq!(stack.near_mv, above_mv);
1947 }
1948
1949 #[test]
1950 fn transposing_above_and_left_produces_a_different_stack() {
1951 // Grid A: above = (4,4) x2 cells, left = (8,8) x2 cells, top-right
1952 // matches the above MV (so it folds into the above bucket, making
1953 // it heavier than left).
1954 let mut a = MiGrid::new(8, 8);
1955 a.set(1, 2, inter((4, 4)));
1956 a.set(1, 3, inter((4, 4)));
1957 a.set(2, 1, inter((8, 8)));
1958 a.set(3, 1, inter((8, 8)));
1959 a.set(1, 4, inter((4, 4)));
1960 let stack_a = find_mv_stack(&a, 2, 2, 2, 2, 1, 8, 8);
1961
1962 // Grid B: the naive transpose — swap which MV sits above vs left —
1963 // with the top-right probe again matching whatever now sits above.
1964 let mut b = MiGrid::new(8, 8);
1965 b.set(1, 2, inter((8, 8)));
1966 b.set(1, 3, inter((8, 8)));
1967 b.set(2, 1, inter((4, 4)));
1968 b.set(3, 1, inter((4, 4)));
1969 b.set(1, 4, inter((8, 8)));
1970 let stack_b = find_mv_stack(&b, 2, 2, 2, 2, 1, 8, 8);
1971
1972 assert_ne!(stack_a, stack_b);
1973 assert_eq!(stack_a.entries[0].mv, (4, 4));
1974 assert_eq!(stack_b.entries[0].mv, (8, 8));
1975 }
1976
1977 #[test]
1978 fn mi_units_outside_the_tile_contribute_nothing() {
1979 let grid = MiGrid::new(4, 4);
1980 // Block at the tile's top-left corner: no row above, no col left,
1981 // and the top-right probe is also off the top edge.
1982 let stack = find_mv_stack(&grid, 0, 0, 2, 2, 1, 4, 4);
1983
1984 assert!(stack.entries.is_empty());
1985 assert_eq!(stack.nearest_mv, (0, 0));
1986 assert_eq!(stack.near_mv, (0, 0));
1987 assert_eq!(stack.pred_mv, (0, 0));
1988 assert!(stack.drl_ctx.is_empty());
1989 assert_eq!(stack.new_mv_ctx, 0);
1990 assert_eq!(stack.ref_mv_ctx, 0);
1991
1992 // Out-of-range reads are also inert directly against the grid.
1993 assert!(grid.get(0, 10).is_none());
1994 assert!(grid.get(10, 0).is_none());
1995 }
1996
1997 #[test]
1998 fn a_candidate_far_outside_the_frame_is_clamped_to_it() {
1999 // A 4x4-mi frame (16x16 px), block 1x1 mi at (1, 1): room for one
2000 // neighbour above and one to the left, tight edges on every side.
2001 let mut grid = MiGrid::new(4, 4);
2002 grid.set(0, 1, inter((100_000, 100_000)));
2003
2004 let stack = find_mv_stack(&grid, 1, 1, 1, 1, 1, 4, 4);
2005
2006 // Unclamped this candidate is (100000, 100000); spec 7.10.2.14 caps
2007 // it at the frame edge (2 mi below/right) plus the block's own 4x4
2008 // span plus MV_BORDER (128), all in 1/8-pel: (2*4)*8 + 1*4*8 + 128 =
2009 // 64 + 32 + 128 = 224.
2010 assert_eq!(stack.nearest_mv, (224, 224));
2011 assert_ne!(stack.entries[0].mv, stack.nearest_mv);
2012 }
2013
2014 #[test]
2015 fn a_neighbour_coded_newmv_raises_the_new_mv_context() {
2016 let mut grid = MiGrid::new(8, 8);
2017 grid.set(
2018 1,
2019 2,
2020 MiInfo {
2021 is_inter: true,
2022 ref_frame: 1,
2023 ref_frame1: None,
2024 mv1: None,
2025 mv: (4, 4),
2026 is_new_mv: true,
2027 size: 1,
2028 },
2029 );
2030 // Only the row matches (nearest_match == 1): newmv_count > 0 picks
2031 // libaom's `mode_context[ref_frame] |= 2` branch.
2032 let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8);
2033 assert_eq!(stack.new_mv_ctx, 2);
2034 assert_eq!(stack.ref_mv_ctx, 3);
2035 }
2036
2037 #[test]
2038 fn a_diagonal_corner_match_raises_ref_mv_ctx_past_nearest_match() {
2039 // Block at (2, 2), 1x1 mi unit: only the col to the left matches
2040 // (nearest_match == 1, so a pre-fix `ref_mv_ctx` collapse would say
2041 // 3 regardless of anything else — this is the exact round-10 defect
2042 // shape). The row above has no match of its own, but the diagonal
2043 // top-left corner (1, 1) does; libaom folds that into the row side
2044 // of `ref_match_count` (raising it to 2) without ever touching the
2045 // already-captured `nearest_match`.
2046 let mut grid = MiGrid::new(8, 8);
2047 grid.set(2, 1, inter((4, 4)));
2048 grid.set(1, 1, inter((8, 8)));
2049
2050 let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8);
2051
2052 assert_eq!(stack.new_mv_ctx, 3); // depends on nearest_match alone: unchanged
2053 assert_eq!(stack.ref_mv_ctx, 4); // nearest_match=1, ref_match_count=2
2054 // The corner's distinct MV becomes its own low-weight stack entry,
2055 // ranked behind the boosted nearest one — DRL context sees a real
2056 // (non-nearest) second candidate for the first time.
2057 assert_eq!(stack.entries.len(), 2);
2058 assert_eq!(stack.entries[0].mv, (4, 4));
2059 assert_eq!(stack.entries[1].mv, (8, 8));
2060 assert_eq!(stack.drl_ctx, vec![1]);
2061 }
2062
2063 #[test]
2064 fn a_corner_only_match_raises_new_mv_ctx_even_when_nearest_match_is_zero() {
2065 // Block at (2, 2), 1x1 mi unit: row above (1, 2), col left (2, 1)
2066 // and top-right (1, 3) all empty — nearest_match == 0 — but the
2067 // diagonal top-left corner (1, 1) matches. libaom's `case 0` arm
2068 // (mvref_common.c ~line 621) sets `new_mv_ctx`'s own bit from
2069 // `ref_match_count` here, not just `ref_mv_ctx`'s: this is I8 CLASS
2070 // B's real-content bitstream desync (real clips hit blocks whose
2071 // *only* neighbour match is diagonal; the repo's synthetic tests
2072 // never had one until this case).
2073 let mut grid = MiGrid::new(8, 8);
2074 grid.set(1, 1, inter((4, 4)));
2075
2076 let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8);
2077
2078 assert_eq!(stack.entries.len(), 1);
2079 assert_eq!(stack.new_mv_ctx, 1); // ref_match_count == 1, not the old hard-0
2080 assert_eq!(stack.ref_mv_ctx, 1); // nearest_match=0, ref_match_count=1
2081 }
2082
2083 /// The class this round ports: a query block *smaller* than its
2084 /// same-row neighbour (decode.rs's real variable partition sizes, never
2085 /// `tile.rs`'s fixed `bw4 == 8`) gets libaom's real, non-flat weight —
2086 /// hand-computed against `scan_row_mbmi` (mvref_common.c): `bw4 = 2`
2087 /// against an `n4 = 8` neighbour 6 mi rows from the frame's top edge
2088 /// gives `len = min(bw4, n4) = 2`, `inc = min(-max_row_offset +
2089 /// row_offset + 1, n4) = min(6 - 1 + 1, 8) = 6`, `weight = max(2, inc) =
2090 /// 6`, total `len * weight = 12` -- not the flat `IMMEDIATE_WEIGHT = 2`
2091 /// this module used to report for every match regardless of block size.
2092 #[test]
2093 fn a_wider_neighbour_than_the_query_block_gets_libaoms_real_weight() {
2094 let mut grid = MiGrid::new(32, 32);
2095 let (mi_row, mi_col) = (8, 8);
2096 let mv = (4, 4);
2097 grid.set(
2098 mi_row - 1,
2099 mi_col,
2100 MiInfo {
2101 is_inter: true,
2102 ref_frame: 1,
2103 ref_frame1: None,
2104 mv1: None,
2105 mv,
2106 is_new_mv: false,
2107 size: 8,
2108 },
2109 );
2110
2111 let stack = find_mv_stack(&grid, mi_row, mi_col, 2, 2, 1, 32, 32);
2112
2113 assert_eq!(stack.entries.len(), 1);
2114 assert_eq!(stack.entries[0].mv, mv);
2115 assert_eq!(stack.entries[0].weight, 12 + REF_CAT_LEVEL);
2116 }
2117
2118 #[test]
2119 fn single_ref_ctx_matches_libaoms_collapsed_forward_only_case() {
2120 assert_eq!(single_ref_ctx(false), 1);
2121 assert_eq!(single_ref_ctx(true), 2);
2122 }
2123
2124 /// An 8-mi-sized (`size: 8`) coded-but-intra neighbour: contributes no
2125 /// vote (`is_inter: false`) but must still count for extended-scan
2126 /// coverage, the way libaom's `scan_row_mbmi`/`scan_col_mbmi` advance
2127 /// `processed_rows`/`processed_cols` from any candidate's `bsize` alone.
2128 fn intra8() -> MiInfo {
2129 MiInfo {
2130 is_inter: false,
2131 ref_frame: -1,
2132 ref_frame1: None,
2133 mv1: None,
2134 mv: (0, 0),
2135 is_new_mv: false,
2136 size: 8,
2137 }
2138 }
2139
2140 /// An 8-mi-sized inter neighbour with an arbitrary, distinctive `mv` --
2141 /// used below as a "would this get picked up" tracer at extended-scan
2142 /// offsets that a correct implementation must never reach at 8-mi
2143 /// geometry.
2144 fn inter8(mv: (i32, i32)) -> MiInfo {
2145 MiInfo {
2146 is_inter: true,
2147 ref_frame: 1,
2148 ref_frame1: None,
2149 mv1: None,
2150 mv,
2151 is_new_mv: false,
2152 size: 8,
2153 }
2154 }
2155
2156 /// The class of bug this round fixed: at 8-mi geometry, an intra
2157 /// neighbour directly above the query block must suppress the extended
2158 /// row scan exactly as an inter one would (spec 7.10.2.2's
2159 /// `processed_rows` tracks *coded* neighbours, not merely *matching*
2160 /// ones). Two tracer candidates sit at the row's extended-scan offsets
2161 /// (-3 and -5, spec 7.10.2.4) with MVs no other scan could produce; if
2162 /// the coverage bug regresses, they show up in `stack.entries`.
2163 #[test]
2164 fn extended_row_scan_is_a_no_op_at_8mi_geometry_even_behind_an_intra_neighbour() {
2165 let mut grid = MiGrid::new(32, 32);
2166 let (mi_row, mi_col) = (10, 10);
2167 for col in mi_col..mi_col + 8 {
2168 grid.set(mi_row - 1, col, intra8());
2169 }
2170 for col in mi_col + 1..mi_col + 1 + 8 {
2171 grid.set(mi_row - 3, col, inter8((999, 999)));
2172 grid.set(mi_row - 5, col, inter8((888, 888)));
2173 }
2174
2175 let stack = find_mv_stack(&grid, mi_row, mi_col, 8, 8, 1, 32, 32);
2176
2177 assert!(
2178 stack.entries.is_empty(),
2179 "extended row scan fired at 8-mi geometry: {:?}",
2180 stack.entries
2181 );
2182 }
2183
2184 /// `extended_row_scan_is_a_no_op_at_8mi_geometry_even_behind_an_intra_neighbour`,
2185 /// transposed to the col-left scan.
2186 #[test]
2187 fn extended_col_scan_is_a_no_op_at_8mi_geometry_even_behind_an_intra_neighbour() {
2188 let mut grid = MiGrid::new(32, 32);
2189 let (mi_row, mi_col) = (10, 10);
2190 for row in mi_row..mi_row + 8 {
2191 grid.set(row, mi_col - 1, intra8());
2192 }
2193 for row in mi_row + 1..mi_row + 1 + 8 {
2194 grid.set(row, mi_col - 3, inter8((999, 999)));
2195 grid.set(row, mi_col - 5, inter8((888, 888)));
2196 }
2197
2198 let stack = find_mv_stack(&grid, mi_row, mi_col, 8, 8, 1, 32, 32);
2199
2200 assert!(
2201 stack.entries.is_empty(),
2202 "extended col scan fired at 8-mi geometry: {:?}",
2203 stack.entries
2204 );
2205 }
2206
2207 /// Same shape, but the immediate neighbour is itself inter (a same-size
2208 /// vote) rather than intra -- the geometry-only coverage path must not
2209 /// have broken the ordinary matching one.
2210 #[test]
2211 fn extended_row_scan_is_a_no_op_at_8mi_geometry_behind_an_inter_neighbour() {
2212 let mut grid = MiGrid::new(32, 32);
2213 let (mi_row, mi_col) = (10, 10);
2214 for col in mi_col..mi_col + 8 {
2215 grid.set(mi_row - 1, col, inter8((4, 4)));
2216 }
2217 for col in mi_col + 1..mi_col + 1 + 8 {
2218 grid.set(mi_row - 3, col, inter8((999, 999)));
2219 grid.set(mi_row - 5, col, inter8((888, 888)));
2220 }
2221
2222 let stack = find_mv_stack(&grid, mi_row, mi_col, 8, 8, 1, 32, 32);
2223
2224 assert_eq!(stack.entries.len(), 1);
2225 assert_eq!(stack.entries[0].mv, (4, 4));
2226 }
2227
2228 fn single(ref0: i8) -> NeighbourRef {
2229 NeighbourRef {
2230 is_inter: true,
2231 ref0,
2232 ref1: None,
2233 uni: false,
2234 }
2235 }
2236 fn comp(ref0: i8, ref1: i8, uni: bool) -> NeighbourRef {
2237 NeighbourRef {
2238 is_inter: true,
2239 ref0,
2240 ref1: Some(ref1),
2241 uni,
2242 }
2243 }
2244 fn intra() -> NeighbourRef {
2245 NeighbourRef {
2246 is_inter: false,
2247 ref0: 0,
2248 ref1: None,
2249 uni: false,
2250 }
2251 }
2252
2253 /// `av1_get_reference_mode_context`, no edges available: libaom's `ctx
2254 /// = 1` fallback.
2255 #[test]
2256 fn reference_mode_ctx_no_edges_is_one() {
2257 assert_eq!(reference_mode_ctx(None, None), 1);
2258 }
2259
2260 /// Both edges single-ref, same forward/backward-ness: `ctx = 0`; one of
2261 /// each: `ctx = 1` (the XOR in libaom's `ctx = IS_BACKWARD(above) ^
2262 /// IS_BACKWARD(left)`).
2263 #[test]
2264 fn reference_mode_ctx_single_single() {
2265 assert_eq!(
2266 reference_mode_ctx(Some(single(LAST_FRAME)), Some(single(LAST2_FRAME))),
2267 0
2268 );
2269 assert_eq!(
2270 reference_mode_ctx(Some(single(LAST_FRAME)), Some(single(BWDREF_FRAME))),
2271 1
2272 );
2273 }
2274
2275 /// One edge compound, the other single forward: libaom's `2 +
2276 /// IS_BACKWARD(above)` collapses to `2` here (forward, inter).
2277 #[test]
2278 fn reference_mode_ctx_single_and_compound() {
2279 assert_eq!(
2280 reference_mode_ctx(
2281 Some(single(LAST_FRAME)),
2282 Some(comp(LAST_FRAME, LAST2_FRAME, true))
2283 ),
2284 2
2285 );
2286 assert_eq!(
2287 reference_mode_ctx(
2288 Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2289 Some(single(LAST_FRAME))
2290 ),
2291 2
2292 );
2293 }
2294
2295 /// Both edges compound: libaom's fixed `ctx = 4`.
2296 #[test]
2297 fn reference_mode_ctx_compound_compound_is_four() {
2298 assert_eq!(
2299 reference_mode_ctx(
2300 Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2301 Some(comp(BWDREF_FRAME, ALTREF_FRAME, true))
2302 ),
2303 4
2304 );
2305 }
2306
2307 /// `av1_get_comp_reference_type_context`, no edges: libaom's `ctx = 2`
2308 /// fallback.
2309 #[test]
2310 fn comp_reference_type_ctx_no_edges_is_two() {
2311 assert_eq!(comp_reference_type_ctx(None, None), 2);
2312 }
2313
2314 /// Both edges intra: libaom's `ctx = 2`.
2315 #[test]
2316 fn comp_reference_type_ctx_intra_intra_is_two() {
2317 assert_eq!(comp_reference_type_ctx(Some(intra()), Some(intra())), 2);
2318 }
2319
2320 /// Both edges single/single: forward-vs-backward split doubles the same
2321 /// way `single_ref_p1`'s own XOR does (libaom's `1 + 2 * !(a ^ l)`).
2322 #[test]
2323 fn comp_reference_type_ctx_single_single() {
2324 assert_eq!(
2325 comp_reference_type_ctx(Some(single(LAST_FRAME)), Some(single(LAST2_FRAME))),
2326 3
2327 );
2328 assert_eq!(
2329 comp_reference_type_ctx(Some(single(LAST_FRAME)), Some(single(BWDREF_FRAME))),
2330 1
2331 );
2332 }
2333
2334 /// Both edges bidirectional compound: libaom's `ctx = 0`.
2335 #[test]
2336 fn comp_reference_type_ctx_bidir_bidir_is_zero() {
2337 assert_eq!(
2338 comp_reference_type_ctx(
2339 Some(comp(LAST_FRAME, BWDREF_FRAME, false)),
2340 Some(comp(LAST2_FRAME, ALTREF_FRAME, false))
2341 ),
2342 0
2343 );
2344 }
2345
2346 /// Both edges unidirectional compound: libaom's `3 + !(a==BWDREF ^
2347 /// l==BWDREF)`.
2348 #[test]
2349 fn comp_reference_type_ctx_unidir_unidir() {
2350 assert_eq!(
2351 comp_reference_type_ctx(
2352 Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2353 Some(comp(LAST_FRAME, LAST3_FRAME, true))
2354 ),
2355 4
2356 );
2357 assert_eq!(
2358 comp_reference_type_ctx(
2359 Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2360 Some(comp(BWDREF_FRAME, ALTREF_FRAME, true))
2361 ),
2362 3
2363 );
2364 }
2365
2366 /// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` beats `LAST3`/
2367 /// `GOLDEN` in the vote, context 2 (libaom's `<` branch reversed --
2368 /// fewer `a`s than `b`s is context 0, matching [`ref_ctx`]'s shared
2369 /// convention).
2370 #[test]
2371 fn uni_comp_ref_p1_ctx_matches_ref_ctx_shape() {
2372 assert_eq!(uni_comp_ref_p1_ctx(Some(LAST2_FRAME), None), 2);
2373 assert_eq!(uni_comp_ref_p1_ctx(Some(LAST3_FRAME), None), 0);
2374 assert_eq!(uni_comp_ref_p1_ctx(None, None), 1);
2375 }
2376
2377 // --- lane-av1comp step 4: compound mvstack (find_mv_stack_compound) ---
2378
2379 const COMP_PAIR: (i8, i8) = (LAST_FRAME, ALTREF_FRAME);
2380
2381 fn comp_inter(mv0: (i32, i32), mv1: (i32, i32)) -> MiInfo {
2382 MiInfo {
2383 is_inter: true,
2384 ref_frame: COMP_PAIR.0,
2385 ref_frame1: Some(COMP_PAIR.1),
2386 mv: mv0,
2387 mv1: Some(mv1),
2388 is_new_mv: false,
2389 size: 1,
2390 }
2391 }
2392
2393 #[test]
2394 fn compound_scan_only_matches_the_exact_pair() {
2395 let mut grid = MiGrid::new(8, 8);
2396 // Same-side single-ref neighbour (LAST only) must not vote.
2397 grid.set(1, 2, inter((4, 4)));
2398 // Wrong second ref (GOLDEN, not ALTREF) must not vote either.
2399 grid.set(
2400 1,
2401 3,
2402 MiInfo {
2403 is_inter: true,
2404 ref_frame: LAST_FRAME,
2405 ref_frame1: Some(GOLDEN_FRAME),
2406 mv: (9, 9),
2407 mv1: Some((9, 9)),
2408 is_new_mv: false,
2409 size: 1,
2410 },
2411 );
2412 // Exact pair match.
2413 let (mv0, mv1) = ((2, 2), (-6, 3));
2414 grid.set(2, 1, comp_inter(mv0, mv1));
2415
2416 let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None);
2417
2418 // The exact-pair immediate scan lands one boosted entry; the
2419 // compound extension pass (short stack, len < MAX_MV_REF_CANDIDATES)
2420 // separately tops it up with a low-weight combo built from the two
2421 // near-miss neighbours it's allowed to gather over regardless of
2422 // reference frame -- a real second entry, not spurious.
2423 assert_eq!(stack.entries.len(), 2);
2424 assert_eq!(stack.entries[0].mv0, mv0);
2425 assert_eq!(stack.entries[0].mv1, mv1);
2426 assert_eq!(stack.entries[0].weight, 2 + REF_CAT_LEVEL);
2427 assert_eq!(stack.nearest_mv, (mv0, mv1));
2428 }
2429
2430 #[test]
2431 fn compound_dedupes_same_pair_and_sums_weight() {
2432 let mut grid = MiGrid::new(8, 8);
2433 let (mv0, mv1) = ((4, 4), (-4, -4));
2434 // Block at (2, 2), 2x2 mi units: above spans cols 2..4, left rows 2..4.
2435 grid.set(1, 2, comp_inter(mv0, mv1));
2436 grid.set(1, 3, comp_inter(mv0, mv1));
2437 grid.set(2, 1, comp_inter(mv0, mv1));
2438 grid.set(3, 1, comp_inter(mv0, mv1));
2439
2440 let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None);
2441
2442 // Exact libaom `is_dup` port: with exactly one entry already in the
2443 // stack (the four identical-pair neighbours deduped by the
2444 // immediate-scan pass), the extension combine step compares only
2445 // `comp_list[0]` against that entry -- a match here, since both are
2446 // built from the same identical-pair neighbours -- so it takes
2447 // `comp_list[1]` (the *second* ref_id slot, still the same (mv0,
2448 // mv1) pair) as a brand-new stack entry rather than folding weight
2449 // into the existing one. Two entries, same pair, not merged.
2450 assert_eq!(stack.entries.len(), 2);
2451 assert_eq!(stack.entries[0].mv0, mv0);
2452 assert_eq!(stack.entries[0].mv1, mv1);
2453 // 2 above + 2 left cells, weight 2 each (size:1 floor), plus the
2454 // REF_CAT_LEVEL boost every immediate-scan entry gets.
2455 assert_eq!(stack.entries[0].weight, 8 + REF_CAT_LEVEL);
2456 assert_eq!(stack.entries[1].mv0, mv0);
2457 assert_eq!(stack.entries[1].mv1, mv1);
2458 assert_eq!(stack.entries[1].weight, 2);
2459 }
2460
2461 #[test]
2462 fn compound_two_distinct_pairs_sort_by_weight() {
2463 let mut grid = MiGrid::new(8, 8);
2464 let above = ((4, 4), (1, 1));
2465 let left = ((8, 8), (2, 2));
2466 grid.set(2, 3, comp_inter(above.0, above.1));
2467 grid.set(2, 4, comp_inter(above.0, above.1));
2468 grid.set(3, 2, comp_inter(left.0, left.1));
2469 grid.set(4, 2, comp_inter(left.0, left.1));
2470 grid.set(5, 2, comp_inter(left.0, left.1));
2471
2472 let stack = find_mv_stack_compound(&grid, 3, 3, 2, 3, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None);
2473
2474 assert_eq!(stack.entries.len(), 2);
2475 assert_eq!(stack.entries[0].mv0, left.0);
2476 assert_eq!(stack.entries[0].mv1, left.1);
2477 assert_eq!(stack.entries[1].mv0, above.0);
2478 assert_eq!(stack.entries[1].mv1, above.1);
2479 assert_eq!(stack.nearest_mv, left);
2480 assert_eq!(stack.near_mv, above);
2481 }
2482
2483 #[test]
2484 fn combine_compound_candidates_zips_ref_id_then_ref_diff_per_side() {
2485 let mut lists = CompoundRefLists::default();
2486 lists.ref_id[0].push((1, 1));
2487 lists.ref_diff[0].push((2, 2));
2488 lists.ref_id[1].push((3, 3));
2489 // side 1 has only one entry -> comp_idx 1 falls back to ref_diff.
2490 lists.ref_diff[1].push((4, 4));
2491
2492 let combined = combine_compound_candidates(&lists);
2493 assert_eq!(combined[0], ((1, 1), (3, 3)));
2494 assert_eq!(combined[1], ((2, 2), (4, 4)));
2495 }
2496
2497 #[test]
2498 fn process_compound_ref_mv_candidate_splits_exact_vs_borrowed() {
2499 let mut lists = CompoundRefLists::default();
2500 // Exact match on side 0 (LAST_FRAME), wrong ref on side 1 -> borrowed
2501 // into ref_diff[1] with no sign flip (NO_SIGN_BIAS).
2502 let candidate = MiInfo {
2503 is_inter: true,
2504 ref_frame: LAST_FRAME,
2505 ref_frame1: None,
2506 mv: (5, 5),
2507 mv1: None,
2508 is_new_mv: false,
2509 size: 1,
2510 };
2511 process_compound_ref_mv_candidate(&candidate, COMP_PAIR, &NO_SIGN_BIAS, &mut lists);
2512 assert_eq!(lists.ref_id[0], vec![(5, 5)]);
2513 assert_eq!(lists.ref_diff[1], vec![(5, 5)]);
2514 assert!(lists.ref_id[1].is_empty());
2515 assert!(lists.ref_diff[0].is_empty());
2516 }
2517
2518 #[test]
2519 fn compound_extension_pass_tops_up_a_short_stack() {
2520 // No exact-pair neighbour at all, but a LAST-only neighbour above and
2521 // an ALTREF-only neighbour left: the extension pass should combine
2522 // them into one topped-up candidate rather than leaving the stack
2523 // empty.
2524 let mut grid = MiGrid::new(8, 8);
2525 grid.set(
2526 1,
2527 2,
2528 MiInfo {
2529 is_inter: true,
2530 ref_frame: LAST_FRAME,
2531 ref_frame1: None,
2532 mv: (7, 7),
2533 mv1: None,
2534 is_new_mv: false,
2535 size: 8,
2536 },
2537 );
2538 grid.set(
2539 2,
2540 1,
2541 MiInfo {
2542 is_inter: true,
2543 ref_frame: ALTREF_FRAME,
2544 ref_frame1: None,
2545 mv: (-3, -3),
2546 mv1: None,
2547 is_new_mv: false,
2548 size: 8,
2549 },
2550 );
2551
2552 let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None);
2553
2554 // The combine step (libaom's real "Handle compound reference frame
2555 // extension") zips each side's ref_id-then-ref_diff lists
2556 // independently, producing *two* distinct combos here (the exact
2557 // match and the borrowed one land on opposite sides for each combo
2558 // index) — both get added, `MAX_MV_REF_CANDIDATES` (2) is exactly
2559 // this stack's cap.
2560 assert_eq!(stack.entries.len(), 2);
2561 assert_eq!(stack.entries[0].weight, 2);
2562 // combo 0: side 0's own exact ref_id match, side 1's borrowed one.
2563 assert_eq!(stack.entries[0].mv0, (7, 7));
2564 assert_eq!(stack.entries[0].mv1, (-3, -3));
2565 // combo 1: the mirror -- side 0's borrowed entry, side 1's own exact
2566 // ref_id match.
2567 assert_eq!(stack.entries[1].mv0, (-3, -3));
2568 assert_eq!(stack.entries[1].mv1, (7, 7));
2569 }
2570}