forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1-mvstack': spec-7.10.2 MV stack, single-ref reduction

Browse files at this commit

402402f15a91ee311018e568b8cc7047328c6f94Ahmet Kaan GümüşParent: 166c28aec98d16
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -20,6 +20,7 @@ pub mod frame;
20 pub mod intra;20 pub mod intra;
21 pub mod mc;21 pub mod mc;
22 pub mod msac;22 pub mod msac;
23+pub mod mvstack;
23 pub mod obu;24 pub mod obu;
24 pub mod quant;25 pub mod quant;
25 pub mod sequence;26 pub mod sequence;
crates/ec-av1/src/mvstack.rsadded+399 -0
@@ -0,0 +1,399 @@
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 DRL context derivation from
9+//! `REF_CAT_LEVEL` (7.10.2.8, the one piece of that section whose constant
10+//! and shape is unambiguous from the spec text).
11+//!
12+//! Deliberately reduced away (see the crate report, not reproduced bit-exact
13+//! here): compound/multi-reference candidates, the temporal MV projection
14+//! scan, the `>1` row/col scans at offset 3 and their skip-by-block-size
15+//! stepping, and the exact `NewMvContext`/`RefMvContext`/`ZeroMvContext`
16+//! tables — spec 7.10.2.8 derives those through several more match classes
17+//! than this reduction tracks, and nothing in this crate consumes them yet
18+//! (no CDF wiring), so the formulas below are a documented, monotonic
19+//! stand-in rather than a proven port. Also reduced away: clamping
20+//! `NearestMv`/`NearMv`/`PredMv` to the frame's allowed MV range
21+//! (7.10.2.14) — the caller gets unclamped values.
22+
23+/// One 4x4 `mi` unit's motion state, as the encode loop will have filled it
24+/// in by the time it asks for a block's MV stack.
25+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26+pub struct MiInfo {
27+ /// Whether this unit was coded inter (as opposed to intra).
28+ pub is_inter: bool,
29+ /// The single reference frame this unit's MV points into. Ignored (and
30+ /// the unit contributes no candidate) when `is_inter` is `false`.
31+ pub ref_frame: i8,
32+ /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units.
33+ pub mv: (i32, i32),
34+}
35+
36+/// The whole frame's `mi` grid, one [`MiInfo`] per 4x4 unit, in raster order.
37+/// A unit an encode pass hasn't visited yet (or that sits outside the tile)
38+/// reads as `None` and contributes nothing to any block's MV stack.
39+#[derive(Clone, Debug)]
40+pub struct MiGrid {
41+ cols: usize,
42+ rows: usize,
43+ cells: Vec<Option<MiInfo>>,
44+}
45+
46+impl MiGrid {
47+ /// A grid of `cols` by `rows` 4x4 units, all initially unset.
48+ pub fn new(cols: usize, rows: usize) -> Self {
49+ Self {
50+ cols,
51+ rows,
52+ cells: vec![None; cols * rows],
53+ }
54+ }
55+
56+ /// Records the unit at `(row, col)`. Out-of-range coordinates are a
57+ /// no-op — the caller only ever addresses units inside the grid it built.
58+ pub fn set(&mut self, row: usize, col: usize, info: MiInfo) {
59+ if row < self.rows && col < self.cols {
60+ self.cells[row * self.cols + col] = Some(info);
61+ }
62+ }
63+
64+ /// The unit at `(row, col)`, or `None` when it is outside the grid (the
65+ /// tile) or hasn't been coded.
66+ pub fn get(&self, row: usize, col: usize) -> Option<&MiInfo> {
67+ if row < self.rows && col < self.cols {
68+ self.cells[row * self.cols + col].as_ref()
69+ } else {
70+ None
71+ }
72+ }
73+}
74+
75+/// One entry of the reference MV stack: a candidate motion vector and the
76+/// total weight the neighbours that agreed on it contributed.
77+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78+pub struct StackEntry {
79+ /// The candidate `(row, col)` motion vector.
80+ pub mv: (i32, i32),
81+ /// The summed weight of every neighbour cell that voted for this MV.
82+ pub weight: u32,
83+}
84+
85+/// The result of [`find_mv_stack`]: the sorted candidate list, the two
86+/// predictors a `NEARESTMV`/`NEARMV` block reads from it, the predictor a
87+/// `NEWMV` residual is coded against, and the symbol contexts the block's
88+/// mode and DRL-index syntax elements are coded with.
89+#[derive(Clone, Debug, PartialEq, Eq)]
90+pub struct MvStack {
91+ /// The candidates, highest weight first (ties keep scan order: above,
92+ /// then left, then top-right).
93+ pub entries: Vec<StackEntry>,
94+ /// `RefStackMv[0]`, or `(0, 0)` when the stack is empty.
95+ pub nearest_mv: (i32, i32),
96+ /// `RefStackMv[1]`, or `(0, 0)` when the stack has fewer than two
97+ /// entries.
98+ pub near_mv: (i32, i32),
99+ /// The predictor a `NEWMV` block's MV difference is coded against:
100+ /// `nearest_mv` when the stack is non-empty, `(0, 0)` otherwise.
101+ pub pred_mv: (i32, i32),
102+ /// Context for the `new_mv` symbol.
103+ pub new_mv_ctx: usize,
104+ /// Context for the `ref_mv` symbol.
105+ pub ref_mv_ctx: usize,
106+ /// Context for the `zero_mv` symbol.
107+ pub zero_mv_ctx: usize,
108+ /// Context for each `drl_mode` symbol between consecutive stack
109+ /// entries, `entries.len().saturating_sub(1)` long.
110+ pub drl_ctx: Vec<usize>,
111+}
112+
113+/// Spec 7.10.2.8's threshold a candidate's weight is compared against to
114+/// pick its DRL context.
115+const REF_CAT_LEVEL: u32 = 640;
116+
117+/// The most candidates a stack keeps (spec `MAX_REF_MV_STACK_SIZE`).
118+const MAX_STACK_SIZE: usize = 8;
119+
120+/// Weight one immediate (row `-1` / col `-1`) neighbour 4x4 unit's vote
121+/// counts for (spec: `len * 2` with `len = 1` per unit for the reduction
122+/// this module makes — see the module doc).
123+const IMMEDIATE_WEIGHT: u32 = 2;
124+
125+/// Adds one candidate MV with `weight` to `candidates`, merging it into an
126+/// existing entry with the same MV rather than duplicating it (spec
127+/// `add_ref_mv_candidate`, 7.10.2.5).
128+fn add_candidate(candidates: &mut Vec<StackEntry>, mv: (i32, i32), weight: u32) {
129+ if let Some(entry) = candidates.iter_mut().find(|e| e.mv == mv) {
130+ entry.weight += weight;
131+ } else {
132+ candidates.push(StackEntry { mv, weight });
133+ }
134+}
135+
136+/// The row-above scan (spec 7.10.2.2): every 4x4 unit directly above the
137+/// block's span. Returns whether any unit voted.
138+fn scan_row(
139+ grid: &MiGrid,
140+ mi_row: usize,
141+ mi_col: usize,
142+ bw4: usize,
143+ ref_frame: i8,
144+ candidates: &mut Vec<StackEntry>,
145+) -> bool {
146+ let Some(row) = mi_row.checked_sub(1) else {
147+ return false;
148+ };
149+ let mut found = false;
150+ for col in mi_col..mi_col + bw4 {
151+ if let Some(info) = grid.get(row, col)
152+ && info.is_inter
153+ && info.ref_frame == ref_frame
154+ {
155+ found = true;
156+ add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
157+ }
158+ }
159+ found
160+}
161+
162+/// The col-left scan (spec 7.10.2.3): every 4x4 unit directly left of the
163+/// block's span. Returns whether any unit voted.
164+fn scan_col(
165+ grid: &MiGrid,
166+ mi_row: usize,
167+ mi_col: usize,
168+ bh4: usize,
169+ ref_frame: i8,
170+ candidates: &mut Vec<StackEntry>,
171+) -> bool {
172+ let Some(col) = mi_col.checked_sub(1) else {
173+ return false;
174+ };
175+ let mut found = false;
176+ for row in mi_row..mi_row + bh4 {
177+ if let Some(info) = grid.get(row, col)
178+ && info.is_inter
179+ && info.ref_frame == ref_frame
180+ {
181+ found = true;
182+ add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
183+ }
184+ }
185+ found
186+}
187+
188+/// The single top-right probe this reduction keeps of spec 7.10.2.4's extra
189+/// scan positions, at the unit diagonally above-right of the block. Its
190+/// vote is folded into the row scan's candidates (it sits on the same row
191+/// as the block's neighbours above), which is what makes the row and column
192+/// scans asymmetric under transposing a grid — spec has no matching
193+/// bottom-left probe.
194+fn scan_top_right(
195+ grid: &MiGrid,
196+ mi_row: usize,
197+ mi_col: usize,
198+ bw4: usize,
199+ ref_frame: i8,
200+ candidates: &mut Vec<StackEntry>,
201+) -> bool {
202+ let Some(row) = mi_row.checked_sub(1) else {
203+ return false;
204+ };
205+ let col = mi_col + bw4;
206+ if let Some(info) = grid.get(row, col)
207+ && info.is_inter
208+ && info.ref_frame == ref_frame
209+ {
210+ add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
211+ return true;
212+ }
213+ false
214+}
215+
216+/// Builds the reference MV stack for the `bw4`-by-`bh4` (in 4x4 units)
217+/// block at `(mi_row, mi_col)`, predicting against `ref_frame`.
218+pub fn find_mv_stack(
219+ grid: &MiGrid,
220+ mi_row: usize,
221+ mi_col: usize,
222+ bw4: usize,
223+ bh4: usize,
224+ ref_frame: i8,
225+) -> MvStack {
226+ let mut candidates = Vec::new();
227+ let found_above = scan_row(grid, mi_row, mi_col, bw4, ref_frame, &mut candidates);
228+ let found_left = scan_col(grid, mi_row, mi_col, bh4, ref_frame, &mut candidates);
229+ let found_top_right = scan_top_right(grid, mi_row, mi_col, bw4, ref_frame, &mut candidates);
230+
231+ // Highest weight first; a stable sort keeps scan order (above, left,
232+ // top-right) among ties, matching spec 7.10.2.6.
233+ candidates.sort_by_key(|e| std::cmp::Reverse(e.weight));
234+ candidates.truncate(MAX_STACK_SIZE);
235+
236+ let nearest_mv = candidates.first().map_or((0, 0), |e| e.mv);
237+ let near_mv = candidates.get(1).map_or((0, 0), |e| e.mv);
238+ let pred_mv = if candidates.is_empty() {
239+ (0, 0)
240+ } else {
241+ nearest_mv
242+ };
243+
244+ let close_matches = usize::from(found_above) + usize::from(found_left);
245+ let total_matches = close_matches + usize::from(found_top_right);
246+
247+ // Reduced context tables (see module doc): monotonic in how much
248+ // neighbour agreement was found, not a bit-exact port of 7.10.2.8.
249+ let new_mv_ctx = match (found_above, found_left, candidates.len()) {
250+ (false, false, _) => 0,
251+ (true, false, _) | (false, true, _) => 1,
252+ (true, true, 1) => 2,
253+ (true, true, _) => 3,
254+ };
255+ let ref_mv_ctx = total_matches.min(5);
256+ let zero_mv_ctx = usize::from(nearest_mv != (0, 0));
257+
258+ let drl_ctx = candidates
259+ .windows(2)
260+ .map(|w| {
261+ let (a, b) = (w[0].weight, w[1].weight);
262+ if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL {
263+ 1
264+ } else if a < REF_CAT_LEVEL && b < REF_CAT_LEVEL {
265+ 2
266+ } else {
267+ 0
268+ }
269+ })
270+ .collect();
271+
272+ MvStack {
273+ entries: candidates,
274+ nearest_mv,
275+ near_mv,
276+ pred_mv,
277+ new_mv_ctx,
278+ ref_mv_ctx,
279+ zero_mv_ctx,
280+ drl_ctx,
281+ }
282+}
283+
284+#[cfg(test)]
285+mod tests {
286+ use super::*;
287+
288+ fn inter(mv: (i32, i32)) -> MiInfo {
289+ MiInfo {
290+ is_inter: true,
291+ ref_frame: 1,
292+ mv,
293+ }
294+ }
295+
296+ #[test]
297+ fn all_same_mv_neighbourhood_dedupes_to_one_entry() {
298+ let mut grid = MiGrid::new(8, 8);
299+ // Block at (2, 2), 2x2 mi units. Above row 1, cols 2..4; left col 1,
300+ // rows 2..4; top-right at (1, 4). All the same MV.
301+ let mv = (4, 4);
302+ grid.set(1, 2, inter(mv));
303+ grid.set(1, 3, inter(mv));
304+ grid.set(2, 1, inter(mv));
305+ grid.set(3, 1, inter(mv));
306+ grid.set(1, 4, inter(mv));
307+
308+ let stack = find_mv_stack(&grid, 2, 2, 2, 2, 1);
309+
310+ assert_eq!(stack.entries.len(), 1);
311+ assert_eq!(stack.entries[0].mv, mv);
312+ // 2 above cells + 2 left cells + 1 top-right, each weight 2.
313+ assert_eq!(stack.entries[0].weight, 10);
314+ assert_eq!(stack.nearest_mv, mv);
315+ // Documented reduced-context value (see module doc): both sides
316+ // found a match and they collapsed to a single stack entry.
317+ assert_eq!(stack.new_mv_ctx, 2);
318+ }
319+
320+ #[test]
321+ fn two_distinct_neighbour_mvs_yield_two_entries_in_weight_order() {
322+ let mut grid = MiGrid::new(8, 8);
323+ // Block at (3, 3), bw4=2, bh4=3: above spans 2 cells (weight 4),
324+ // left spans 3 cells (weight 6) — distinct MVs, distinct weights.
325+ let above_mv = (4, 4);
326+ let left_mv = (8, 8);
327+ grid.set(2, 3, inter(above_mv));
328+ grid.set(2, 4, inter(above_mv));
329+ grid.set(3, 2, inter(left_mv));
330+ grid.set(4, 2, inter(left_mv));
331+ grid.set(5, 2, inter(left_mv));
332+
333+ let stack = find_mv_stack(&grid, 3, 3, 2, 3, 1);
334+
335+ assert_eq!(stack.entries.len(), 2);
336+ assert_eq!(
337+ stack.entries[0],
338+ StackEntry {
339+ mv: left_mv,
340+ weight: 6
341+ }
342+ );
343+ assert_eq!(
344+ stack.entries[1],
345+ StackEntry {
346+ mv: above_mv,
347+ weight: 4
348+ }
349+ );
350+ assert_eq!(stack.nearest_mv, left_mv);
351+ assert_eq!(stack.near_mv, above_mv);
352+ }
353+
354+ #[test]
355+ fn transposing_above_and_left_produces_a_different_stack() {
356+ // Grid A: above = (4,4) x2 cells, left = (8,8) x2 cells, top-right
357+ // matches the above MV (so it folds into the above bucket, making
358+ // it heavier than left).
359+ let mut a = MiGrid::new(8, 8);
360+ a.set(1, 2, inter((4, 4)));
361+ a.set(1, 3, inter((4, 4)));
362+ a.set(2, 1, inter((8, 8)));
363+ a.set(3, 1, inter((8, 8)));
364+ a.set(1, 4, inter((4, 4)));
365+ let stack_a = find_mv_stack(&a, 2, 2, 2, 2, 1);
366+
367+ // Grid B: the naive transpose — swap which MV sits above vs left —
368+ // with the top-right probe again matching whatever now sits above.
369+ let mut b = MiGrid::new(8, 8);
370+ b.set(1, 2, inter((8, 8)));
371+ b.set(1, 3, inter((8, 8)));
372+ b.set(2, 1, inter((4, 4)));
373+ b.set(3, 1, inter((4, 4)));
374+ b.set(1, 4, inter((8, 8)));
375+ let stack_b = find_mv_stack(&b, 2, 2, 2, 2, 1);
376+
377+ assert_ne!(stack_a, stack_b);
378+ assert_eq!(stack_a.entries[0].mv, (4, 4));
379+ assert_eq!(stack_b.entries[0].mv, (8, 8));
380+ }
381+
382+ #[test]
383+ fn mi_units_outside_the_tile_contribute_nothing() {
384+ let grid = MiGrid::new(4, 4);
385+ // Block at the tile's top-left corner: no row above, no col left,
386+ // and the top-right probe is also off the top edge.
387+ let stack = find_mv_stack(&grid, 0, 0, 2, 2, 1);
388+
389+ assert!(stack.entries.is_empty());
390+ assert_eq!(stack.nearest_mv, (0, 0));
391+ assert_eq!(stack.near_mv, (0, 0));
392+ assert_eq!(stack.pred_mv, (0, 0));
393+ assert!(stack.drl_ctx.is_empty());
394+
395+ // Out-of-range reads are also inert directly against the grid.
396+ assert!(grid.get(0, 10).is_none());
397+ assert!(grid.get(10, 0).is_none());
398+ }
399+}