forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2a2adbaTahinli2 months ago2117 commits

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