forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8fd360cTahinli2 months ago2655 commits

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