forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB58b009bTahinli2 months ago2045 commits

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