forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBf44b458Tahinli3 months ago649 commits

mvstack.rs983 lines, 38.2 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//! but — like the reduced row/col/top-right scans — at this module's own
43//! `IMMEDIATE_WEIGHT` scale rather than libaom's real `len * max(2, inc)`
44//! (row/col) or `2 * mi_size_wide[BLOCK_8X8]` (corner/top-right) weights.
45//! That scale mismatch is harmless for every caller this module has: the
46//! only real caller (`tile.rs`) always asks for a fixed `bw4 == bh4 == 8`
47//! block, at which size libaom's row and col weights are *always tied*
48//! (both scan a full-width same-size neighbour) and its corner/top-right
49//! weight is *always* far below either — exactly the ordering
50//! `IMMEDIATE_WEIGHT` already reproduces, so sort order and the
51//! `REF_CAT_LEVEL`-vs-not DRL split (which only tests a threshold, not a
52//! magnitude) come out identical either way. A caller with mixed block
53//! sizes would need the real weight formula; none exists today.
54//!
55//! The corner probe's own match does *not* count toward the real
56//! `newmv_count` that feeds `new_mv_ctx` (libaom passes it a `dummy_newmv_count`
57//! there) — only row/col/top-right do.
58//!
59//! Also ported (from `av1_drl_ctx`, `mvref_common.h`): the `REF_CAT_LEVEL`
60//! (640) bonus applies only to the entries the row/col/top-right scan found
61//! (`nearest_refmv_count`), added to their stored weight *before* the corner
62//! probe can add a new, unboosted entry — so `drl_ctx` can now be non-zero
63//! when the corner probe contributes a genuinely new candidate.
64//!
65//! The `GLOBALMV_OFFSET` bit of libaom's `mode_context` is set only inside
66//! `cm->features.allow_ref_frame_mvs` (temporal MV projection), which this
67//! module never has (`use_ref_frame_mvs = 0`), so `zero_mv_ctx` is always 0
68//! here — exact for the case this module covers, not a stand-in.
69//!
70//! Deliberately reduced away (see the crate report, not reproduced bit-exact
71//! here): compound/multi-reference candidates, the temporal MV projection
72//! scan, the real (non-corner) `idx = 2..MVREF_ROW_COLS` extended row/col
73//! scan positions (libaom's own `processed_rows`/`processed_cols` bookkeeping
74//! means those never fire for this module's fixed 8-mi block geometry — the
75//! immediate-offset scan's coverage window already reaches as far as the
76//! extended offsets can, so nothing there is left unscanned), the
77//! single-reference "extension" pass that re-walks the same row/col
78//! neighbours through `process_single_ref_mv_candidate` (a no-op here: with
79//! only one reference frame ever in play, whatever it would add was already
80//! added by the row/col scan), and the "extra search" that pads a short
81//! stack to two entries (spec 7.10.2.12) — this module's stack can be
82//! shorter than two candidates where libaom's never is.
83
84/// One 4x4 `mi` unit's motion state, as the encode loop will have filled it
85/// in by the time it asks for a block's MV stack.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct MiInfo {
88 /// Whether this unit was coded inter (as opposed to intra).
89 pub is_inter: bool,
90 /// The single reference frame this unit's MV points into. Ignored (and
91 /// the unit contributes no candidate) when `is_inter` is `false`.
92 pub ref_frame: i8,
93 /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units.
94 pub mv: (i32, i32),
95 /// Whether this unit's own mode was `NEWMV` (spec's
96 /// `have_newmv_in_inter_mode`, compound modes excluded since this module
97 /// has no compound candidates). Feeds `NewMvContext` (7.10.2.8): a
98 /// neighbour's own coded-with-NEWMV state, not this block's.
99 pub is_new_mv: bool,
100 /// The side, in 4x4 units, of the square block this unit belongs to (8
101 /// for a whole 32x32 block, 4 for a 16x16 leaf -- every block this crate
102 /// ever codes is square, so one dimension is enough). Feeds the extended
103 /// row/col scan's `processed_rows`/`processed_cols` (spec 7.10.2.2/.3,
104 /// libaom `scan_row_mbmi`/`scan_col_mbmi`'s `inc` term): a query block no
105 /// wider than its immediate neighbour has that neighbour's whole span
106 /// already covered by the immediate (-1) scan, so the extended scan
107 /// below only has to run past that. Set for *every* coded unit, intra or
108 /// inter -- libaom's `scan_row_mbmi` advances `processed_rows` from any
109 /// candidate's `bsize` regardless of whether it also casts a vote (that
110 /// requires a ref-frame match, checked separately in `add_ref_mv_candidate`).
111 pub size: usize,
112}
113
114/// The whole frame's `mi` grid, one [`MiInfo`] per 4x4 unit, in raster order.
115/// A unit an encode pass hasn't visited yet (or that sits outside the tile)
116/// reads as `None` and contributes nothing to any block's MV stack.
117#[derive(Clone, Debug)]
118pub struct MiGrid {
119 cols: usize,
120 rows: usize,
121 cells: Vec<Option<MiInfo>>,
122}
123
124impl MiGrid {
125 /// A grid of `cols` by `rows` 4x4 units, all initially unset.
126 pub fn new(cols: usize, rows: usize) -> Self {
127 Self {
128 cols,
129 rows,
130 cells: vec![None; cols * rows],
131 }
132 }
133
134 /// Records the unit at `(row, col)`. Out-of-range coordinates are a
135 /// no-op — the caller only ever addresses units inside the grid it built.
136 pub fn set(&mut self, row: usize, col: usize, info: MiInfo) {
137 if row < self.rows && col < self.cols {
138 self.cells[row * self.cols + col] = Some(info);
139 }
140 }
141
142 /// The unit at `(row, col)`, or `None` when it is outside the grid (the
143 /// tile) or hasn't been coded.
144 pub fn get(&self, row: usize, col: usize) -> Option<&MiInfo> {
145 if row < self.rows && col < self.cols {
146 self.cells[row * self.cols + col].as_ref()
147 } else {
148 None
149 }
150 }
151}
152
153/// One entry of the reference MV stack: a candidate motion vector and the
154/// total weight the neighbours that agreed on it contributed.
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156pub struct StackEntry {
157 /// The candidate `(row, col)` motion vector.
158 pub mv: (i32, i32),
159 /// The summed weight of every neighbour cell that voted for this MV.
160 pub weight: u32,
161}
162
163/// The result of [`find_mv_stack`]: the sorted candidate list, the two
164/// predictors a `NEARESTMV`/`NEARMV` block reads from it, the predictor a
165/// `NEWMV` residual is coded against, and the symbol contexts the block's
166/// mode and DRL-index syntax elements are coded with.
167#[derive(Clone, Debug, PartialEq, Eq)]
168pub struct MvStack {
169 /// The candidates, highest weight first (ties keep scan order: above,
170 /// then left, then top-right).
171 pub entries: Vec<StackEntry>,
172 /// `RefStackMv[0]`, or `(0, 0)` when the stack is empty.
173 pub nearest_mv: (i32, i32),
174 /// `RefStackMv[1]`, or `(0, 0)` when the stack has fewer than two
175 /// entries.
176 pub near_mv: (i32, i32),
177 /// The predictor a `NEWMV` block's MV difference is coded against:
178 /// `nearest_mv` when the stack is non-empty, `(0, 0)` otherwise.
179 pub pred_mv: (i32, i32),
180 /// Context for the `new_mv` symbol.
181 pub new_mv_ctx: usize,
182 /// Context for the `ref_mv` symbol.
183 pub ref_mv_ctx: usize,
184 /// Context for the `zero_mv` symbol.
185 pub zero_mv_ctx: usize,
186 /// Context for each `drl_mode` symbol between consecutive stack
187 /// entries, `entries.len().saturating_sub(1)` long.
188 pub drl_ctx: Vec<usize>,
189}
190
191/// Spec 7.10.2.8's threshold a candidate's weight is compared against to
192/// pick its DRL context.
193const REF_CAT_LEVEL: u32 = 640;
194
195/// The most candidates a stack keeps (spec `MAX_REF_MV_STACK_SIZE`).
196const MAX_STACK_SIZE: usize = 8;
197
198/// Weight one immediate (row `-1` / col `-1`) neighbour 4x4 unit's vote
199/// counts for (spec: `len * 2` with `len = 1` per unit for the reduction
200/// this module makes — see the module doc).
201const IMMEDIATE_WEIGHT: u32 = 2;
202
203/// Spec `MVREF_ROW_COLS`: the extended row/col scan runs at offsets `-3` and
204/// `-5` (`idx = 2..=3`), one past `IMMEDIATE_WEIGHT`'s own `-1`.
205const MVREF_ROW_COLS: usize = 3;
206
207/// Adds one candidate MV with `weight` to `candidates`, merging it into an
208/// existing entry with the same MV rather than duplicating it (spec
209/// `add_ref_mv_candidate`, 7.10.2.5).
210fn add_candidate(candidates: &mut Vec<StackEntry>, mv: (i32, i32), weight: u32) {
211 if let Some(entry) = candidates.iter_mut().find(|e| e.mv == mv) {
212 entry.weight += weight;
213 } else {
214 candidates.push(StackEntry { mv, weight });
215 }
216}
217
218/// The row-above scan (spec 7.10.2.2): every 4x4 unit directly above the
219/// block's span. Returns whether any unit voted, and `processed_rows`
220/// (libaom `scan_row_mbmi`'s output): how many rows past the immediate one
221/// this span already covers by *geometry* alone (0 unless a same-or-wider
222/// neighbour occupies it, in which case that neighbour's own `size` is the
223/// coverage, spec 7.10.2.2's `inc` term reduced to this crate's square,
224/// fixed-weight candidates) -- tracked for *every* coded cell, intra or
225/// inter, since libaom's `processed_rows` update sits outside the
226/// ref-frame-matching `add_ref_mv_candidate` call.
227fn scan_row(
228 grid: &MiGrid,
229 mi_row: usize,
230 mi_col: usize,
231 bw4: usize,
232 ref_frame: i8,
233 candidates: &mut Vec<StackEntry>,
234 newmv_count: &mut u32,
235) -> (bool, usize) {
236 let Some(row) = mi_row.checked_sub(1) else {
237 return (false, 0);
238 };
239 let mut found = false;
240 let mut processed_rows = 0;
241 for col in mi_col..mi_col + bw4 {
242 let Some(info) = grid.get(row, col) else {
243 continue;
244 };
245 if bw4 <= info.size {
246 processed_rows = processed_rows.max(info.size);
247 }
248 if info.is_inter && info.ref_frame == ref_frame {
249 found = true;
250 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
251 *newmv_count += u32::from(info.is_new_mv);
252 }
253 }
254 (found, processed_rows)
255}
256
257/// The col-left scan (spec 7.10.2.3): every 4x4 unit directly left of the
258/// block's span. Returns whether any unit voted, and `processed_cols`
259/// (`scan_row`'s doc, transposed).
260fn scan_col(
261 grid: &MiGrid,
262 mi_row: usize,
263 mi_col: usize,
264 bh4: usize,
265 ref_frame: i8,
266 candidates: &mut Vec<StackEntry>,
267 newmv_count: &mut u32,
268) -> (bool, usize) {
269 let Some(col) = mi_col.checked_sub(1) else {
270 return (false, 0);
271 };
272 let mut found = false;
273 let mut processed_cols = 0;
274 for row in mi_row..mi_row + bh4 {
275 let Some(info) = grid.get(row, col) else {
276 continue;
277 };
278 if bh4 <= info.size {
279 processed_cols = processed_cols.max(info.size);
280 }
281 if info.is_inter && info.ref_frame == ref_frame {
282 found = true;
283 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
284 *newmv_count += u32::from(info.is_new_mv);
285 }
286 }
287 (found, processed_cols)
288}
289
290/// The extended row scan (spec 7.10.2.4's `idx = 2..MVREF_ROW_COLS` row
291/// positions, libaom `mvref_common.c`'s second loop): probes rows `-3` and
292/// `-5`, shifted one column right (`col_offset = 1`, libaom's `col_adj`
293/// collapses to that for every block size this crate ever queries), each
294/// only run when the immediate scan's own `processed_rows` hasn't already
295/// covered it and the tile's top edge doesn't clip it first. Its match folds
296/// into the row side (`ref_match_count`, never `nearest_match`), same as the
297/// corner probe.
298fn scan_row_extended(
299 grid: &MiGrid,
300 mi_row: usize,
301 mi_col: usize,
302 bw4: usize,
303 ref_frame: i8,
304 candidates: &mut Vec<StackEntry>,
305 processed_rows: usize,
306) -> bool {
307 let max_row_offset = mi_row.min(MVREF_ROW_COLS * 2);
308 let mut found = false;
309 for idx in 2..=MVREF_ROW_COLS {
310 let offset = idx * 2 - 1;
311 if offset > max_row_offset || offset <= processed_rows {
312 continue;
313 }
314 let Some(row) = mi_row.checked_sub(offset) else {
315 continue;
316 };
317 for col in mi_col + 1..mi_col + 1 + bw4 {
318 if let Some(info) = grid.get(row, col)
319 && info.is_inter
320 && info.ref_frame == ref_frame
321 {
322 found = true;
323 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
324 }
325 }
326 }
327 found
328}
329
330/// The extended col scan: `scan_row_extended`, transposed (probes cols `-3`
331/// and `-5`, shifted one row down).
332fn scan_col_extended(
333 grid: &MiGrid,
334 mi_row: usize,
335 mi_col: usize,
336 bh4: usize,
337 ref_frame: i8,
338 candidates: &mut Vec<StackEntry>,
339 processed_cols: usize,
340) -> bool {
341 let max_col_offset = mi_col.min(MVREF_ROW_COLS * 2);
342 let mut found = false;
343 for idx in 2..=MVREF_ROW_COLS {
344 let offset = idx * 2 - 1;
345 if offset > max_col_offset || offset <= processed_cols {
346 continue;
347 }
348 let Some(col) = mi_col.checked_sub(offset) else {
349 continue;
350 };
351 for row in mi_row + 1..mi_row + 1 + bh4 {
352 if let Some(info) = grid.get(row, col)
353 && info.is_inter
354 && info.ref_frame == ref_frame
355 {
356 found = true;
357 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
358 }
359 }
360 }
361 found
362}
363
364/// The single top-right probe this reduction keeps of spec 7.10.2.4's extra
365/// scan positions, at the unit diagonally above-right of the block. Its
366/// vote is folded into the row scan's candidates (it sits on the same row
367/// as the block's neighbours above), which is what makes the row and column
368/// scans asymmetric under transposing a grid — spec has no matching
369/// bottom-left probe.
370fn scan_top_right(
371 grid: &MiGrid,
372 mi_row: usize,
373 mi_col: usize,
374 bw4: usize,
375 ref_frame: i8,
376 candidates: &mut Vec<StackEntry>,
377 newmv_count: &mut u32,
378) -> bool {
379 let Some(row) = mi_row.checked_sub(1) else {
380 return false;
381 };
382 let col = mi_col + bw4;
383 if let Some(info) = grid.get(row, col)
384 && info.is_inter
385 && info.ref_frame == ref_frame
386 {
387 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
388 *newmv_count += u32::from(info.is_new_mv);
389 return true;
390 }
391 false
392}
393
394/// The diagonal top-left corner probe (libaom `scan_blk_mbmi` at
395/// `row_offset = col_offset = -1`, mvref_common.c's "second outer area",
396/// called *after* `nearest_match` is already captured): the single unit
397/// diagonally above-left of the block. Its match folds into the row bucket
398/// too (see module doc) but must never move `nearest_match` itself or the
399/// real `newmv_count` — callers pass a throwaway counter for the latter.
400fn scan_corner(
401 grid: &MiGrid,
402 mi_row: usize,
403 mi_col: usize,
404 ref_frame: i8,
405 candidates: &mut Vec<StackEntry>,
406 newmv_count: &mut u32,
407) -> bool {
408 let (Some(row), Some(col)) = (mi_row.checked_sub(1), mi_col.checked_sub(1)) else {
409 return false;
410 };
411 if let Some(info) = grid.get(row, col)
412 && info.is_inter
413 && info.ref_frame == ref_frame
414 {
415 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
416 *newmv_count += u32::from(info.is_new_mv);
417 return true;
418 }
419 false
420}
421
422/// `MV_BORDER` (spec 7.10.2.14): 16 pixels of slack in 1/8-pel units, added
423/// on top of the block's own span before a candidate is clamped to the
424/// frame.
425const MV_BORDER: i32 = 16 << 3;
426
427/// Clamps one candidate MV to the range spec 7.10.2.14 (libaom's
428/// `clamp_mv_ref`) allows for a `bw4`-by-`bh4` block at `(mi_row, mi_col)` in
429/// a `mi_cols`-by-`mi_rows` frame: the distance from the block's own edge to
430/// the matching frame edge, plus the block's own span and [`MV_BORDER`] of
431/// slack, in every direction.
432fn clamp_mv_ref(
433 mv: (i32, i32),
434 mi_row: usize,
435 mi_col: usize,
436 bw4: usize,
437 bh4: usize,
438 mi_cols: usize,
439 mi_rows: usize,
440) -> (i32, i32) {
441 // Pixels-to-1/8-pel: 4 mi units/pixel-row * 8 subpel steps/pixel.
442 let to_subpel = |mi_units: usize| (mi_units as i32) * 4 * 8;
443 let (bw8, bh8) = (to_subpel(bw4), to_subpel(bh4));
444 let to_left = -to_subpel(mi_col);
445 let to_right = to_subpel(mi_cols.saturating_sub(bw4).saturating_sub(mi_col));
446 let to_top = -to_subpel(mi_row);
447 let to_bottom = to_subpel(mi_rows.saturating_sub(bh4).saturating_sub(mi_row));
448
449 let (row, col) = mv;
450 (
451 row.clamp(to_top - bh8 - MV_BORDER, to_bottom + bh8 + MV_BORDER),
452 col.clamp(to_left - bw8 - MV_BORDER, to_right + bw8 + MV_BORDER),
453 )
454}
455
456/// Builds the reference MV stack for the `bw4`-by-`bh4` (in 4x4 units)
457/// block at `(mi_row, mi_col)`, predicting against `ref_frame`, in a frame
458/// that is `mi_cols`-by-`mi_rows` 4x4 units (used only to clamp the
459/// predictors to the frame, spec 7.10.2.14).
460pub fn find_mv_stack(
461 grid: &MiGrid,
462 mi_row: usize,
463 mi_col: usize,
464 bw4: usize,
465 bh4: usize,
466 ref_frame: i8,
467 mi_cols: usize,
468 mi_rows: usize,
469) -> MvStack {
470 let mut candidates = Vec::new();
471 let mut newmv_count = 0u32;
472 let (found_above, processed_rows) = scan_row(
473 grid,
474 mi_row,
475 mi_col,
476 bw4,
477 ref_frame,
478 &mut candidates,
479 &mut newmv_count,
480 );
481 let (found_left, processed_cols) = scan_col(
482 grid,
483 mi_row,
484 mi_col,
485 bh4,
486 ref_frame,
487 &mut candidates,
488 &mut newmv_count,
489 );
490 let found_top_right = scan_top_right(
491 grid,
492 mi_row,
493 mi_col,
494 bw4,
495 ref_frame,
496 &mut candidates,
497 &mut newmv_count,
498 );
499
500 // libaom's `row_match_count`/`col_match_count` (mvref_common.c) fold the
501 // top-right probe into the row side, so "found above" for context
502 // purposes means the row scan *or* the top-right one matched.
503 let row_matched = found_above || found_top_right;
504 let nearest_match = usize::from(row_matched) + usize::from(found_left);
505
506 // av1_find_mv_stack boosts only the entries the immediate scan found —
507 // exactly `candidates` at this point, before the corner probe (below)
508 // can add anything else (mvref_common.c ~line 544-545).
509 for entry in &mut candidates {
510 entry.weight += REF_CAT_LEVEL;
511 }
512
513 // The diagonal top-left corner probe (module doc): folds into the row
514 // side for `ref_match_count` without moving the already-captured
515 // `nearest_match`, and its own newmv-ness is a dummy count libaom
516 // discards (`&dummy_newmv_count` at the real call site).
517 let mut dummy_newmv_count = 0u32;
518 let corner_matched = scan_corner(
519 grid,
520 mi_row,
521 mi_col,
522 ref_frame,
523 &mut candidates,
524 &mut dummy_newmv_count,
525 );
526 // The extended row/col scan (spec 7.10.2.4's `idx = 2..MVREF_ROW_COLS`):
527 // only reachable once the immediate scan's own reach (`processed_rows`/
528 // `processed_cols`) leaves a gap the tile's edge doesn't already clip.
529 // At this module's fixed 8-mi block geometry with every coded cell
530 // (intra or inter) now feeding coverage, that reach always hits
531 // `MVREF_ROW_COLS`'s farthest offset first -- a true no-op there (see
532 // module doc and `extended_scan_is_a_no_op_at_8mi_geometry` below). Folds
533 // into the row/col match booleans, never `nearest_match`.
534 let row_matched_ext = scan_row_extended(
535 grid,
536 mi_row,
537 mi_col,
538 bw4,
539 ref_frame,
540 &mut candidates,
541 processed_rows,
542 );
543 let col_matched_ext = scan_col_extended(
544 grid,
545 mi_row,
546 mi_col,
547 bh4,
548 ref_frame,
549 &mut candidates,
550 processed_cols,
551 );
552 let ref_match_count = usize::from(row_matched || corner_matched || row_matched_ext)
553 + usize::from(found_left || col_matched_ext);
554
555 // Highest weight first; a stable sort keeps scan order (above, left,
556 // top-right, corner) among ties, matching spec 7.10.2.6. The corner
557 // probe's un-boosted entry (if new) always sorts after the boosted
558 // ones above, matching libaom's separate two-phase ranking.
559 candidates.sort_by_key(|e| std::cmp::Reverse(e.weight));
560 candidates.truncate(MAX_STACK_SIZE);
561
562 let clamp = |mv| clamp_mv_ref(mv, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows);
563 let nearest_mv = candidates.first().map_or((0, 0), |e| clamp(e.mv));
564 let near_mv = candidates.get(1).map_or((0, 0), |e| clamp(e.mv));
565 let pred_mv = if candidates.is_empty() {
566 (0, 0)
567 } else {
568 nearest_mv
569 };
570
571 // Exact port of the `mode_context[ref_frame]` switch (mvref_common.c
572 // ~line 619-643). `new_mv_ctx` depends on `nearest_match` and the real
573 // `newmv_count` alone — libaom's switch never reads `ref_match_count`
574 // for those bits, so this half was already exact before this round.
575 let new_mv_ctx = match nearest_match {
576 // libaom's `case 0` also sets this bit from `ref_match_count`
577 // (`mode_context[ref_frame] |= 1` when `ref_match_count >= 1`,
578 // mvref_common.c ~line 621) — the corner-probe-derived count, not
579 // `nearest_match` alone, despite this module's doc comment above
580 // having claimed the opposite for several rounds.
581 0 => usize::from(ref_match_count >= 1),
582 1 => {
583 if newmv_count > 0 {
584 2
585 } else {
586 3
587 }
588 }
589 _ => {
590 if newmv_count >= 1 {
591 4
592 } else {
593 5
594 }
595 }
596 };
597 // `ref_mv_ctx` (the `REFMV_OFFSET` half of the same switch) genuinely
598 // depends on both counts — this is the part that was wrongly collapsed
599 // to `nearest_match` alone (see module doc / crate report).
600 let ref_mv_ctx = match nearest_match {
601 0 => match ref_match_count {
602 0 => 0,
603 1 => 1,
604 _ => 2,
605 },
606 1 => {
607 if ref_match_count >= 2 {
608 4
609 } else {
610 3
611 }
612 }
613 _ => 5,
614 };
615 // GLOBALMV_OFFSET is only ever set by temporal MV projection
616 // (`cm->features.allow_ref_frame_mvs`), which this reduction never runs
617 // (see module doc) — exact, not a stand-in.
618 let zero_mv_ctx = 0;
619
620 // av1_drl_ctx (mvref_common.h): weight was boosted in place above for
621 // the nearest entries only, so this now compares the real stored weight
622 // against the threshold directly, the way libaom does.
623 let drl_ctx = candidates
624 .windows(2)
625 .map(|w| {
626 let (a, b) = (w[0].weight, w[1].weight);
627 if a >= REF_CAT_LEVEL && b >= REF_CAT_LEVEL {
628 0
629 } else if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL {
630 1
631 } else {
632 2
633 }
634 })
635 .collect();
636
637 MvStack {
638 entries: candidates,
639 nearest_mv,
640 near_mv,
641 pred_mv,
642 new_mv_ctx,
643 ref_mv_ctx,
644 zero_mv_ctx,
645 drl_ctx,
646 }
647}
648
649/// The single-reference context shared by the `single_ref_p1`/`p3`/`p4`
650/// binary decisions this crate's LAST-only reference chain codes (spec
651/// 5.11.25; libaom's `av1_get_pred_context_single_ref_p1/p3/p4`,
652/// `pred_common.c`). Each of those three functions compares a forward-ref
653/// neighbour count against a same-direction count that is always zero in a
654/// LAST-only world (no LAST2/LAST3/GOLDEN/backward candidate ever exists
655/// here), which collapses all three of libaom's formulas to the same
656/// two-valued test: "is there an inter neighbour at all". `has_inter`
657/// gathers that over the block's whole span, the way spec 5.11.39 reads any
658/// neighbour-derived context.
659pub(crate) fn single_ref_ctx(has_inter_neighbour: bool) -> usize {
660 if has_inter_neighbour { 2 } else { 1 }
661}
662
663#[cfg(test)]
664mod tests {
665 use super::*;
666
667 fn inter(mv: (i32, i32)) -> MiInfo {
668 MiInfo {
669 is_inter: true,
670 ref_frame: 1,
671 mv,
672 is_new_mv: false,
673 // 1: smaller than every `bw4`/`bh4` these small-grid tests use,
674 // so it never trips the extended-scan coverage boost -- these
675 // tests only exercise the immediate/corner/top-right scans.
676 size: 1,
677 }
678 }
679
680 #[test]
681 fn all_same_mv_neighbourhood_dedupes_to_one_entry() {
682 let mut grid = MiGrid::new(8, 8);
683 // Block at (2, 2), 2x2 mi units. Above row 1, cols 2..4; left col 1,
684 // rows 2..4; top-right at (1, 4). All the same MV.
685 let mv = (4, 4);
686 grid.set(1, 2, inter(mv));
687 grid.set(1, 3, inter(mv));
688 grid.set(2, 1, inter(mv));
689 grid.set(3, 1, inter(mv));
690 grid.set(1, 4, inter(mv));
691
692 let stack = find_mv_stack(&grid, 2, 2, 2, 2, 1, 8, 8);
693
694 assert_eq!(stack.entries.len(), 1);
695 assert_eq!(stack.entries[0].mv, mv);
696 // 2 above cells + 2 left cells + 1 top-right, each weight 2, plus the
697 // REF_CAT_LEVEL boost av1_find_mv_stack applies to every entry the
698 // immediate row/col/top-right scan found (module doc).
699 assert_eq!(stack.entries[0].weight, 10 + REF_CAT_LEVEL);
700 assert_eq!(stack.nearest_mv, mv);
701 // Exact ctx (see module doc): both sides matched (nearest_match=2)
702 // and no neighbour was coded NEWMV, which is libaom's
703 // `mode_context[ref_frame] |= 5` branch.
704 assert_eq!(stack.new_mv_ctx, 5);
705 assert_eq!(stack.ref_mv_ctx, 5);
706 assert_eq!(stack.zero_mv_ctx, 0);
707 }
708
709 #[test]
710 fn two_distinct_neighbour_mvs_yield_two_entries_in_weight_order() {
711 let mut grid = MiGrid::new(8, 8);
712 // Block at (3, 3), bw4=2, bh4=3: above spans 2 cells (weight 4),
713 // left spans 3 cells (weight 6) — distinct MVs, distinct weights.
714 let above_mv = (4, 4);
715 let left_mv = (8, 8);
716 grid.set(2, 3, inter(above_mv));
717 grid.set(2, 4, inter(above_mv));
718 grid.set(3, 2, inter(left_mv));
719 grid.set(4, 2, inter(left_mv));
720 grid.set(5, 2, inter(left_mv));
721
722 let stack = find_mv_stack(&grid, 3, 3, 2, 3, 1, 8, 8);
723
724 // Both are entries the immediate scan found, so both get the
725 // REF_CAT_LEVEL boost (module doc) — their relative order is
726 // unaffected.
727 assert_eq!(stack.entries.len(), 2);
728 assert_eq!(
729 stack.entries[0],
730 StackEntry {
731 mv: left_mv,
732 weight: 6 + REF_CAT_LEVEL
733 }
734 );
735 assert_eq!(
736 stack.entries[1],
737 StackEntry {
738 mv: above_mv,
739 weight: 4 + REF_CAT_LEVEL
740 }
741 );
742 assert_eq!(stack.nearest_mv, left_mv);
743 assert_eq!(stack.near_mv, above_mv);
744 }
745
746 #[test]
747 fn transposing_above_and_left_produces_a_different_stack() {
748 // Grid A: above = (4,4) x2 cells, left = (8,8) x2 cells, top-right
749 // matches the above MV (so it folds into the above bucket, making
750 // it heavier than left).
751 let mut a = MiGrid::new(8, 8);
752 a.set(1, 2, inter((4, 4)));
753 a.set(1, 3, inter((4, 4)));
754 a.set(2, 1, inter((8, 8)));
755 a.set(3, 1, inter((8, 8)));
756 a.set(1, 4, inter((4, 4)));
757 let stack_a = find_mv_stack(&a, 2, 2, 2, 2, 1, 8, 8);
758
759 // Grid B: the naive transpose — swap which MV sits above vs left —
760 // with the top-right probe again matching whatever now sits above.
761 let mut b = MiGrid::new(8, 8);
762 b.set(1, 2, inter((8, 8)));
763 b.set(1, 3, inter((8, 8)));
764 b.set(2, 1, inter((4, 4)));
765 b.set(3, 1, inter((4, 4)));
766 b.set(1, 4, inter((8, 8)));
767 let stack_b = find_mv_stack(&b, 2, 2, 2, 2, 1, 8, 8);
768
769 assert_ne!(stack_a, stack_b);
770 assert_eq!(stack_a.entries[0].mv, (4, 4));
771 assert_eq!(stack_b.entries[0].mv, (8, 8));
772 }
773
774 #[test]
775 fn mi_units_outside_the_tile_contribute_nothing() {
776 let grid = MiGrid::new(4, 4);
777 // Block at the tile's top-left corner: no row above, no col left,
778 // and the top-right probe is also off the top edge.
779 let stack = find_mv_stack(&grid, 0, 0, 2, 2, 1, 4, 4);
780
781 assert!(stack.entries.is_empty());
782 assert_eq!(stack.nearest_mv, (0, 0));
783 assert_eq!(stack.near_mv, (0, 0));
784 assert_eq!(stack.pred_mv, (0, 0));
785 assert!(stack.drl_ctx.is_empty());
786 assert_eq!(stack.new_mv_ctx, 0);
787 assert_eq!(stack.ref_mv_ctx, 0);
788
789 // Out-of-range reads are also inert directly against the grid.
790 assert!(grid.get(0, 10).is_none());
791 assert!(grid.get(10, 0).is_none());
792 }
793
794 #[test]
795 fn a_candidate_far_outside_the_frame_is_clamped_to_it() {
796 // A 4x4-mi frame (16x16 px), block 1x1 mi at (1, 1): room for one
797 // neighbour above and one to the left, tight edges on every side.
798 let mut grid = MiGrid::new(4, 4);
799 grid.set(0, 1, inter((100_000, 100_000)));
800
801 let stack = find_mv_stack(&grid, 1, 1, 1, 1, 1, 4, 4);
802
803 // Unclamped this candidate is (100000, 100000); spec 7.10.2.14 caps
804 // it at the frame edge (2 mi below/right) plus the block's own 4x4
805 // span plus MV_BORDER (128), all in 1/8-pel: (2*4)*8 + 1*4*8 + 128 =
806 // 64 + 32 + 128 = 224.
807 assert_eq!(stack.nearest_mv, (224, 224));
808 assert_ne!(stack.entries[0].mv, stack.nearest_mv);
809 }
810
811 #[test]
812 fn a_neighbour_coded_newmv_raises_the_new_mv_context() {
813 let mut grid = MiGrid::new(8, 8);
814 grid.set(
815 1,
816 2,
817 MiInfo {
818 is_inter: true,
819 ref_frame: 1,
820 mv: (4, 4),
821 is_new_mv: true,
822 size: 1,
823 },
824 );
825 // Only the row matches (nearest_match == 1): newmv_count > 0 picks
826 // libaom's `mode_context[ref_frame] |= 2` branch.
827 let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8);
828 assert_eq!(stack.new_mv_ctx, 2);
829 assert_eq!(stack.ref_mv_ctx, 3);
830 }
831
832 #[test]
833 fn a_diagonal_corner_match_raises_ref_mv_ctx_past_nearest_match() {
834 // Block at (2, 2), 1x1 mi unit: only the col to the left matches
835 // (nearest_match == 1, so a pre-fix `ref_mv_ctx` collapse would say
836 // 3 regardless of anything else — this is the exact round-10 defect
837 // shape). The row above has no match of its own, but the diagonal
838 // top-left corner (1, 1) does; libaom folds that into the row side
839 // of `ref_match_count` (raising it to 2) without ever touching the
840 // already-captured `nearest_match`.
841 let mut grid = MiGrid::new(8, 8);
842 grid.set(2, 1, inter((4, 4)));
843 grid.set(1, 1, inter((8, 8)));
844
845 let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8);
846
847 assert_eq!(stack.new_mv_ctx, 3); // depends on nearest_match alone: unchanged
848 assert_eq!(stack.ref_mv_ctx, 4); // nearest_match=1, ref_match_count=2
849 // The corner's distinct MV becomes its own low-weight stack entry,
850 // ranked behind the boosted nearest one — DRL context sees a real
851 // (non-nearest) second candidate for the first time.
852 assert_eq!(stack.entries.len(), 2);
853 assert_eq!(stack.entries[0].mv, (4, 4));
854 assert_eq!(stack.entries[1].mv, (8, 8));
855 assert_eq!(stack.drl_ctx, vec![1]);
856 }
857
858 #[test]
859 fn a_corner_only_match_raises_new_mv_ctx_even_when_nearest_match_is_zero() {
860 // Block at (2, 2), 1x1 mi unit: row above (1, 2), col left (2, 1)
861 // and top-right (1, 3) all empty — nearest_match == 0 — but the
862 // diagonal top-left corner (1, 1) matches. libaom's `case 0` arm
863 // (mvref_common.c ~line 621) sets `new_mv_ctx`'s own bit from
864 // `ref_match_count` here, not just `ref_mv_ctx`'s: this is I8 CLASS
865 // B's real-content bitstream desync (real clips hit blocks whose
866 // *only* neighbour match is diagonal; the repo's synthetic tests
867 // never had one until this case).
868 let mut grid = MiGrid::new(8, 8);
869 grid.set(1, 1, inter((4, 4)));
870
871 let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8);
872
873 assert_eq!(stack.entries.len(), 1);
874 assert_eq!(stack.new_mv_ctx, 1); // ref_match_count == 1, not the old hard-0
875 assert_eq!(stack.ref_mv_ctx, 1); // nearest_match=0, ref_match_count=1
876 }
877
878 #[test]
879 fn single_ref_ctx_matches_libaoms_collapsed_forward_only_case() {
880 assert_eq!(single_ref_ctx(false), 1);
881 assert_eq!(single_ref_ctx(true), 2);
882 }
883
884 /// An 8-mi-sized (`size: 8`) coded-but-intra neighbour: contributes no
885 /// vote (`is_inter: false`) but must still count for extended-scan
886 /// coverage, the way libaom's `scan_row_mbmi`/`scan_col_mbmi` advance
887 /// `processed_rows`/`processed_cols` from any candidate's `bsize` alone.
888 fn intra8() -> MiInfo {
889 MiInfo {
890 is_inter: false,
891 ref_frame: -1,
892 mv: (0, 0),
893 is_new_mv: false,
894 size: 8,
895 }
896 }
897
898 /// An 8-mi-sized inter neighbour with an arbitrary, distinctive `mv` --
899 /// used below as a "would this get picked up" tracer at extended-scan
900 /// offsets that a correct implementation must never reach at 8-mi
901 /// geometry.
902 fn inter8(mv: (i32, i32)) -> MiInfo {
903 MiInfo {
904 is_inter: true,
905 ref_frame: 1,
906 mv,
907 is_new_mv: false,
908 size: 8,
909 }
910 }
911
912 /// The class of bug this round fixed: at 8-mi geometry, an intra
913 /// neighbour directly above the query block must suppress the extended
914 /// row scan exactly as an inter one would (spec 7.10.2.2's
915 /// `processed_rows` tracks *coded* neighbours, not merely *matching*
916 /// ones). Two tracer candidates sit at the row's extended-scan offsets
917 /// (-3 and -5, spec 7.10.2.4) with MVs no other scan could produce; if
918 /// the coverage bug regresses, they show up in `stack.entries`.
919 #[test]
920 fn extended_row_scan_is_a_no_op_at_8mi_geometry_even_behind_an_intra_neighbour() {
921 let mut grid = MiGrid::new(32, 32);
922 let (mi_row, mi_col) = (10, 10);
923 for col in mi_col..mi_col + 8 {
924 grid.set(mi_row - 1, col, intra8());
925 }
926 for col in mi_col + 1..mi_col + 1 + 8 {
927 grid.set(mi_row - 3, col, inter8((999, 999)));
928 grid.set(mi_row - 5, col, inter8((888, 888)));
929 }
930
931 let stack = find_mv_stack(&grid, mi_row, mi_col, 8, 8, 1, 32, 32);
932
933 assert!(
934 stack.entries.is_empty(),
935 "extended row scan fired at 8-mi geometry: {:?}",
936 stack.entries
937 );
938 }
939
940 /// `extended_row_scan_is_a_no_op_at_8mi_geometry_even_behind_an_intra_neighbour`,
941 /// transposed to the col-left scan.
942 #[test]
943 fn extended_col_scan_is_a_no_op_at_8mi_geometry_even_behind_an_intra_neighbour() {
944 let mut grid = MiGrid::new(32, 32);
945 let (mi_row, mi_col) = (10, 10);
946 for row in mi_row..mi_row + 8 {
947 grid.set(row, mi_col - 1, intra8());
948 }
949 for row in mi_row + 1..mi_row + 1 + 8 {
950 grid.set(row, mi_col - 3, inter8((999, 999)));
951 grid.set(row, mi_col - 5, inter8((888, 888)));
952 }
953
954 let stack = find_mv_stack(&grid, mi_row, mi_col, 8, 8, 1, 32, 32);
955
956 assert!(
957 stack.entries.is_empty(),
958 "extended col scan fired at 8-mi geometry: {:?}",
959 stack.entries
960 );
961 }
962
963 /// Same shape, but the immediate neighbour is itself inter (a same-size
964 /// vote) rather than intra -- the geometry-only coverage path must not
965 /// have broken the ordinary matching one.
966 #[test]
967 fn extended_row_scan_is_a_no_op_at_8mi_geometry_behind_an_inter_neighbour() {
968 let mut grid = MiGrid::new(32, 32);
969 let (mi_row, mi_col) = (10, 10);
970 for col in mi_col..mi_col + 8 {
971 grid.set(mi_row - 1, col, inter8((4, 4)));
972 }
973 for col in mi_col + 1..mi_col + 1 + 8 {
974 grid.set(mi_row - 3, col, inter8((999, 999)));
975 grid.set(mi_row - 5, col, inter8((888, 888)));
976 }
977
978 let stack = find_mv_stack(&grid, mi_row, mi_col, 8, 8, 1, 32, 32);
979
980 assert_eq!(stack.entries.len(), 1);
981 assert_eq!(stack.entries[0].mv, (4, 4));
982 }
983}