forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb123ba7Tahinli3 months ago1499 commits

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