forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcfa93c0Tahinli3 months ago1659 commits

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