forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

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