forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB50503afTahinli3 months ago1344 commits

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