forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1-tile': inter tile writer + exact MV-stack contexts

Browse files at this commit

748d06c2f7489e5bae6a38914099054d5d9cb375Ahmet Kaan GümüşParent: 4320938302d3c4
crates/ec-av1/src/encode.rsmodified+2 -1
@@ -646,6 +646,7 @@ fn code_square(
646 v,646 v,
647 luma: luma_coeffs,647 luma: luma_coeffs,
648 mode,648 mode,
649+ ..BlockCoeffs::default()
649 },650 },
650 cost,651 cost,
651 )652 )
@@ -909,7 +910,7 @@ fn encode_key_frame_inner(
909 #[cfg(test)]910 #[cfg(test)]
910 mod tests {911 mod tests {
911 use super::*;912 use super::*;
912- use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};913+ use crate::intra::{D135_PRED, D45_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
913 use std::io::Write;914 use std::io::Write;
914 use std::process::{Command, Stdio};915 use std::process::{Command, Stdio};
915 916
crates/ec-av1/src/msac.rsmodified+1 -1
@@ -272,7 +272,7 @@ pub(crate) mod tests {
272 }272 }
273 273
274 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.274 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.
275- fn symbol(&mut self, cdf: &mut [u16]) -> usize {275+ pub(crate) fn symbol(&mut self, cdf: &mut [u16]) -> usize {
276 let s = self.symbol_fixed(cdf);276 let s = self.symbol_fixed(cdf);
277 update_cdf(cdf, s);277 update_cdf(cdf, s);
278 s278 s
crates/ec-av1/src/mvstack.rsmodified+225 -43
@@ -5,20 +5,36 @@
5 //! Implemented from the spec: the row-above scan (7.10.2.2), the col-left5 //! 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 extra6 //! 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`), the7 //! 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 from8+//! weight-descending sort (7.10.2.6), and the `NewMvContext`/`RefMvContext`/
9-//! `REF_CAT_LEVEL` (7.10.2.8, the one piece of that section whose constant9+//! `ZeroMvContext`/`DrlCtx` derivations of 7.10.2.8, ported from libaom's
10-//! and shape is unambiguous from the spec text).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 scan is already reduced to the immediate row/col/top-right
16+//! positions with no extended-offset scan (see below), which lets those
17+//! context formulas collapse exactly rather than approximately: libaom's
18+//! `ref_match_count` comes from the *same* row/col match counters as
19+//! `nearest_match` once the extended scan is gone, so `ref_match_count ==
20+//! nearest_match` always here, and every candidate this module finds is one
21+//! of libaom's "nearest" ones, so the `REF_CAT_LEVEL` (640) bonus
22+//! `av1_find_mv_stack` adds to nearest candidates before computing DRL
23+//! context applies to all of them uniformly — which is why [`find_mv_stack`]
24+//! always reports `drl_ctx == 0`: with the extended scan absent, no
25+//! candidate here can ever be a "non-nearest" (sub-640) one for a pair
26+//! comparison to distinguish. Likewise, the `GLOBALMV_OFFSET` bit of
27+//! libaom's `mode_context` is set only inside
28+//! `cm->features.allow_ref_frame_mvs` (temporal MV projection), which this
29+//! module never has (`use_ref_frame_mvs = 0`), so `zero_mv_ctx` is always 0
30+//! here — again exact for the case this module covers, not a stand-in.
11 //!31 //!
12 //! Deliberately reduced away (see the crate report, not reproduced bit-exact32 //! Deliberately reduced away (see the crate report, not reproduced bit-exact
13 //! here): compound/multi-reference candidates, the temporal MV projection33 //! here): compound/multi-reference candidates, the temporal MV projection
14-//! scan, the `>1` row/col scans at offset 3 and their skip-by-block-size34+//! scan, and the `>1` row/col scans at offset 3 and their skip-by-block-size
15-//! stepping, and the exact `NewMvContext`/`RefMvContext`/`ZeroMvContext`35+//! stepping (which is also why the "extra search" that pads a short stack to
16-//! tables — spec 7.10.2.8 derives those through several more match classes36+//! two entries, spec 7.10.2.12, is not implemented — this module's stack can
17-//! than this reduction tracks, and nothing in this crate consumes them yet37+//! be shorter than two candidates where libaom's never is).
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 38
23 /// One 4x4 `mi` unit's motion state, as the encode loop will have filled it39 /// 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.40 /// in by the time it asks for a block's MV stack.
@@ -31,6 +47,11 @@ pub struct MiInfo {
31 pub ref_frame: i8,47 pub ref_frame: i8,
32 /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units.48 /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units.
33 pub mv: (i32, i32),49 pub mv: (i32, i32),
50+ /// Whether this unit's own mode was `NEWMV` (spec's
51+ /// `have_newmv_in_inter_mode`, compound modes excluded since this module
52+ /// has no compound candidates). Feeds `NewMvContext` (7.10.2.8): a
53+ /// neighbour's own coded-with-NEWMV state, not this block's.
54+ pub is_new_mv: bool,
34 }55 }
35 56
36 /// The whole frame's `mi` grid, one [`MiInfo`] per 4x4 unit, in raster order.57 /// The whole frame's `mi` grid, one [`MiInfo`] per 4x4 unit, in raster order.
@@ -142,6 +163,7 @@ fn scan_row(
142 bw4: usize,163 bw4: usize,
143 ref_frame: i8,164 ref_frame: i8,
144 candidates: &mut Vec<StackEntry>,165 candidates: &mut Vec<StackEntry>,
166+ newmv_count: &mut u32,
145 ) -> bool {167 ) -> bool {
146 let Some(row) = mi_row.checked_sub(1) else {168 let Some(row) = mi_row.checked_sub(1) else {
147 return false;169 return false;
@@ -154,6 +176,7 @@ fn scan_row(
154 {176 {
155 found = true;177 found = true;
156 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);178 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
179+ *newmv_count += u32::from(info.is_new_mv);
157 }180 }
158 }181 }
159 found182 found
@@ -168,6 +191,7 @@ fn scan_col(
168 bh4: usize,191 bh4: usize,
169 ref_frame: i8,192 ref_frame: i8,
170 candidates: &mut Vec<StackEntry>,193 candidates: &mut Vec<StackEntry>,
194+ newmv_count: &mut u32,
171 ) -> bool {195 ) -> bool {
172 let Some(col) = mi_col.checked_sub(1) else {196 let Some(col) = mi_col.checked_sub(1) else {
173 return false;197 return false;
@@ -180,6 +204,7 @@ fn scan_col(
180 {204 {
181 found = true;205 found = true;
182 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);206 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
207+ *newmv_count += u32::from(info.is_new_mv);
183 }208 }
184 }209 }
185 found210 found
@@ -198,6 +223,7 @@ fn scan_top_right(
198 bw4: usize,223 bw4: usize,
199 ref_frame: i8,224 ref_frame: i8,
200 candidates: &mut Vec<StackEntry>,225 candidates: &mut Vec<StackEntry>,
226+ newmv_count: &mut u32,
201 ) -> bool {227 ) -> bool {
202 let Some(row) = mi_row.checked_sub(1) else {228 let Some(row) = mi_row.checked_sub(1) else {
203 return false;229 return false;
@@ -208,13 +234,50 @@ fn scan_top_right(
208 && info.ref_frame == ref_frame234 && info.ref_frame == ref_frame
209 {235 {
210 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);236 add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT);
237+ *newmv_count += u32::from(info.is_new_mv);
211 return true;238 return true;
212 }239 }
213 false240 false
214 }241 }
215 242
243+/// `MV_BORDER` (spec 7.10.2.14): 16 pixels of slack in 1/8-pel units, added
244+/// on top of the block's own span before a candidate is clamped to the
245+/// frame.
246+const MV_BORDER: i32 = 16 << 3;
247+
248+/// Clamps one candidate MV to the range spec 7.10.2.14 (libaom's
249+/// `clamp_mv_ref`) allows for a `bw4`-by-`bh4` block at `(mi_row, mi_col)` in
250+/// a `mi_cols`-by-`mi_rows` frame: the distance from the block's own edge to
251+/// the matching frame edge, plus the block's own span and [`MV_BORDER`] of
252+/// slack, in every direction.
253+fn clamp_mv_ref(
254+ mv: (i32, i32),
255+ mi_row: usize,
256+ mi_col: usize,
257+ bw4: usize,
258+ bh4: usize,
259+ mi_cols: usize,
260+ mi_rows: usize,
261+) -> (i32, i32) {
262+ // Pixels-to-1/8-pel: 4 mi units/pixel-row * 8 subpel steps/pixel.
263+ let to_subpel = |mi_units: usize| (mi_units as i32) * 4 * 8;
264+ let (bw8, bh8) = (to_subpel(bw4), to_subpel(bh4));
265+ let to_left = -to_subpel(mi_col);
266+ let to_right = to_subpel(mi_cols.saturating_sub(bw4).saturating_sub(mi_col));
267+ let to_top = -to_subpel(mi_row);
268+ let to_bottom = to_subpel(mi_rows.saturating_sub(bh4).saturating_sub(mi_row));
269+
270+ let (row, col) = mv;
271+ (
272+ row.clamp(to_top - bh8 - MV_BORDER, to_bottom + bh8 + MV_BORDER),
273+ col.clamp(to_left - bw8 - MV_BORDER, to_right + bw8 + MV_BORDER),
274+ )
275+}
276+
216 /// Builds the reference MV stack for the `bw4`-by-`bh4` (in 4x4 units)277 /// Builds the reference MV stack for the `bw4`-by-`bh4` (in 4x4 units)
217-/// block at `(mi_row, mi_col)`, predicting against `ref_frame`.278+/// block at `(mi_row, mi_col)`, predicting against `ref_frame`, in a frame
279+/// that is `mi_cols`-by-`mi_rows` 4x4 units (used only to clamp the
280+/// predictors to the frame, spec 7.10.2.14).
218 pub fn find_mv_stack(281 pub fn find_mv_stack(
219 grid: &MiGrid,282 grid: &MiGrid,
220 mi_row: usize,283 mi_row: usize,
@@ -222,49 +285,105 @@ pub fn find_mv_stack(
222 bw4: usize,285 bw4: usize,
223 bh4: usize,286 bh4: usize,
224 ref_frame: i8,287 ref_frame: i8,
288+ mi_cols: usize,
289+ mi_rows: usize,
225 ) -> MvStack {290 ) -> MvStack {
226 let mut candidates = Vec::new();291 let mut candidates = Vec::new();
227- let found_above = scan_row(grid, mi_row, mi_col, bw4, ref_frame, &mut candidates);292+ let mut newmv_count = 0u32;
228- let found_left = scan_col(grid, mi_row, mi_col, bh4, ref_frame, &mut candidates);293+ let found_above = scan_row(
229- let found_top_right = scan_top_right(grid, mi_row, mi_col, bw4, ref_frame, &mut candidates);294+ grid,
295+ mi_row,
296+ mi_col,
297+ bw4,
298+ ref_frame,
299+ &mut candidates,
300+ &mut newmv_count,
301+ );
302+ let found_left = scan_col(
303+ grid,
304+ mi_row,
305+ mi_col,
306+ bh4,
307+ ref_frame,
308+ &mut candidates,
309+ &mut newmv_count,
310+ );
311+ let found_top_right = scan_top_right(
312+ grid,
313+ mi_row,
314+ mi_col,
315+ bw4,
316+ ref_frame,
317+ &mut candidates,
318+ &mut newmv_count,
319+ );
230 320
231 // Highest weight first; a stable sort keeps scan order (above, left,321 // Highest weight first; a stable sort keeps scan order (above, left,
232 // top-right) among ties, matching spec 7.10.2.6.322 // top-right) among ties, matching spec 7.10.2.6.
233 candidates.sort_by_key(|e| std::cmp::Reverse(e.weight));323 candidates.sort_by_key(|e| std::cmp::Reverse(e.weight));
234 candidates.truncate(MAX_STACK_SIZE);324 candidates.truncate(MAX_STACK_SIZE);
235 325
236- let nearest_mv = candidates.first().map_or((0, 0), |e| e.mv);326+ let clamp = |mv| clamp_mv_ref(mv, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows);
237- let near_mv = candidates.get(1).map_or((0, 0), |e| e.mv);327+ let nearest_mv = candidates.first().map_or((0, 0), |e| clamp(e.mv));
328+ let near_mv = candidates.get(1).map_or((0, 0), |e| clamp(e.mv));
238 let pred_mv = if candidates.is_empty() {329 let pred_mv = if candidates.is_empty() {
239 (0, 0)330 (0, 0)
240 } else {331 } else {
241 nearest_mv332 nearest_mv
242 };333 };
243 334
244- let close_matches = usize::from(found_above) + usize::from(found_left);335+ // libaom's `row_match_count`/`col_match_count` (mvref_common.c) fold the
245- let total_matches = close_matches + usize::from(found_top_right);336+ // top-right probe into the row side, so "found above" for context
246-337+ // purposes means the row scan *or* the top-right one matched.
247- // Reduced context tables (see module doc): monotonic in how much338+ let row_matched = found_above || found_top_right;
248- // neighbour agreement was found, not a bit-exact port of 7.10.2.8.339+ let nearest_match = usize::from(row_matched) + usize::from(found_left);
249- let new_mv_ctx = match (found_above, found_left, candidates.len()) {340+
250- (false, false, _) => 0,341+ // Exact port of the `mode_context[ref_frame]` switch (mvref_common.c
251- (true, false, _) | (false, true, _) => 1,342+ // ~line 619-643): with no extended-offset scan, `ref_match_count` here is
252- (true, true, 1) => 2,343+ // always equal to `nearest_match` (both come from the same row/col match
253- (true, true, _) => 3,344+ // counters this module never advances further), so the `ref_match_count`
345+ // branches of libaom's switch collapse into the constants below — see
346+ // module doc.
347+ let new_mv_ctx = match nearest_match {
348+ 0 => 0,
349+ 1 => {
350+ if newmv_count > 0 {
351+ 2
352+ } else {
353+ 3
354+ }
355+ }
356+ _ => {
357+ if newmv_count >= 1 {
358+ 4
359+ } else {
360+ 5
361+ }
362+ }
254 };363 };
255- let ref_mv_ctx = total_matches.min(5);364+ let ref_mv_ctx = match nearest_match {
256- let zero_mv_ctx = usize::from(nearest_mv != (0, 0));365+ 0 => 0,
257-366+ 1 => 3,
367+ _ => 5,
368+ };
369+ // GLOBALMV_OFFSET is only ever set by temporal MV projection
370+ // (`cm->features.allow_ref_frame_mvs`), which this reduction never runs
371+ // (see module doc) — exact, not a stand-in.
372+ let zero_mv_ctx = 0;
373+
374+ // av1_drl_ctx (mvref_common.h): every candidate here is one of libaom's
375+ // "nearest" ones (see module doc), so each gets `REF_CAT_LEVEL` before
376+ // the comparison, which is why this always lands on 0.
258 let drl_ctx = candidates377 let drl_ctx = candidates
259 .windows(2)378 .windows(2)
260 .map(|w| {379 .map(|w| {
261- let (a, b) = (w[0].weight, w[1].weight);380+ let (a, b) = (w[0].weight + REF_CAT_LEVEL, w[1].weight + REF_CAT_LEVEL);
262- if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL {381+ if a >= REF_CAT_LEVEL && b >= REF_CAT_LEVEL {
382+ 0
383+ } else if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL {
263 1384 1
264- } else if a < REF_CAT_LEVEL && b < REF_CAT_LEVEL {
265- 2
266 } else {385 } else {
267- 0386+ 2
268 }387 }
269 })388 })
270 .collect();389 .collect();
@@ -281,6 +400,20 @@ pub fn find_mv_stack(
281 }400 }
282 }401 }
283 402
403+/// The single-reference context shared by the `single_ref_p1`/`p3`/`p4`
404+/// binary decisions this crate's LAST-only reference chain codes (spec
405+/// 5.11.25; libaom's `av1_get_pred_context_single_ref_p1/p3/p4`,
406+/// `pred_common.c`). Each of those three functions compares a forward-ref
407+/// neighbour count against a same-direction count that is always zero in a
408+/// LAST-only world (no LAST2/LAST3/GOLDEN/backward candidate ever exists
409+/// here), which collapses all three of libaom's formulas to the same
410+/// two-valued test: "is there an inter neighbour at all". `has_inter`
411+/// gathers that over the block's whole span, the way spec 5.11.39 reads any
412+/// neighbour-derived context.
413+pub(crate) fn single_ref_ctx(has_inter_neighbour: bool) -> usize {
414+ if has_inter_neighbour { 2 } else { 1 }
415+}
416+
284 #[cfg(test)]417 #[cfg(test)]
285 mod tests {418 mod tests {
286 use super::*;419 use super::*;
@@ -290,6 +423,7 @@ mod tests {
290 is_inter: true,423 is_inter: true,
291 ref_frame: 1,424 ref_frame: 1,
292 mv,425 mv,
426+ is_new_mv: false,
293 }427 }
294 }428 }
295 429
@@ -305,16 +439,19 @@ mod tests {
305 grid.set(3, 1, inter(mv));439 grid.set(3, 1, inter(mv));
306 grid.set(1, 4, inter(mv));440 grid.set(1, 4, inter(mv));
307 441
308- let stack = find_mv_stack(&grid, 2, 2, 2, 2, 1);442+ let stack = find_mv_stack(&grid, 2, 2, 2, 2, 1, 8, 8);
309 443
310 assert_eq!(stack.entries.len(), 1);444 assert_eq!(stack.entries.len(), 1);
311 assert_eq!(stack.entries[0].mv, mv);445 assert_eq!(stack.entries[0].mv, mv);
312 // 2 above cells + 2 left cells + 1 top-right, each weight 2.446 // 2 above cells + 2 left cells + 1 top-right, each weight 2.
313 assert_eq!(stack.entries[0].weight, 10);447 assert_eq!(stack.entries[0].weight, 10);
314 assert_eq!(stack.nearest_mv, mv);448 assert_eq!(stack.nearest_mv, mv);
315- // Documented reduced-context value (see module doc): both sides449+ // Exact ctx (see module doc): both sides matched (nearest_match=2)
316- // found a match and they collapsed to a single stack entry.450+ // and no neighbour was coded NEWMV, which is libaom's
317- assert_eq!(stack.new_mv_ctx, 2);451+ // `mode_context[ref_frame] |= 5` branch.
452+ assert_eq!(stack.new_mv_ctx, 5);
453+ assert_eq!(stack.ref_mv_ctx, 5);
454+ assert_eq!(stack.zero_mv_ctx, 0);
318 }455 }
319 456
320 #[test]457 #[test]
@@ -330,7 +467,7 @@ mod tests {
330 grid.set(4, 2, inter(left_mv));467 grid.set(4, 2, inter(left_mv));
331 grid.set(5, 2, inter(left_mv));468 grid.set(5, 2, inter(left_mv));
332 469
333- let stack = find_mv_stack(&grid, 3, 3, 2, 3, 1);470+ let stack = find_mv_stack(&grid, 3, 3, 2, 3, 1, 8, 8);
334 471
335 assert_eq!(stack.entries.len(), 2);472 assert_eq!(stack.entries.len(), 2);
336 assert_eq!(473 assert_eq!(
@@ -362,7 +499,7 @@ mod tests {
362 a.set(2, 1, inter((8, 8)));499 a.set(2, 1, inter((8, 8)));
363 a.set(3, 1, inter((8, 8)));500 a.set(3, 1, inter((8, 8)));
364 a.set(1, 4, inter((4, 4)));501 a.set(1, 4, inter((4, 4)));
365- let stack_a = find_mv_stack(&a, 2, 2, 2, 2, 1);502+ let stack_a = find_mv_stack(&a, 2, 2, 2, 2, 1, 8, 8);
366 503
367 // Grid B: the naive transpose — swap which MV sits above vs left —504 // Grid B: the naive transpose — swap which MV sits above vs left —
368 // with the top-right probe again matching whatever now sits above.505 // with the top-right probe again matching whatever now sits above.
@@ -372,7 +509,7 @@ mod tests {
372 b.set(2, 1, inter((4, 4)));509 b.set(2, 1, inter((4, 4)));
373 b.set(3, 1, inter((4, 4)));510 b.set(3, 1, inter((4, 4)));
374 b.set(1, 4, inter((8, 8)));511 b.set(1, 4, inter((8, 8)));
375- let stack_b = find_mv_stack(&b, 2, 2, 2, 2, 1);512+ let stack_b = find_mv_stack(&b, 2, 2, 2, 2, 1, 8, 8);
376 513
377 assert_ne!(stack_a, stack_b);514 assert_ne!(stack_a, stack_b);
378 assert_eq!(stack_a.entries[0].mv, (4, 4));515 assert_eq!(stack_a.entries[0].mv, (4, 4));
@@ -384,16 +521,61 @@ mod tests {
384 let grid = MiGrid::new(4, 4);521 let grid = MiGrid::new(4, 4);
385 // Block at the tile's top-left corner: no row above, no col left,522 // 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.523 // and the top-right probe is also off the top edge.
387- let stack = find_mv_stack(&grid, 0, 0, 2, 2, 1);524+ let stack = find_mv_stack(&grid, 0, 0, 2, 2, 1, 4, 4);
388 525
389 assert!(stack.entries.is_empty());526 assert!(stack.entries.is_empty());
390 assert_eq!(stack.nearest_mv, (0, 0));527 assert_eq!(stack.nearest_mv, (0, 0));
391 assert_eq!(stack.near_mv, (0, 0));528 assert_eq!(stack.near_mv, (0, 0));
392 assert_eq!(stack.pred_mv, (0, 0));529 assert_eq!(stack.pred_mv, (0, 0));
393 assert!(stack.drl_ctx.is_empty());530 assert!(stack.drl_ctx.is_empty());
531+ assert_eq!(stack.new_mv_ctx, 0);
532+ assert_eq!(stack.ref_mv_ctx, 0);
394 533
395 // Out-of-range reads are also inert directly against the grid.534 // Out-of-range reads are also inert directly against the grid.
396 assert!(grid.get(0, 10).is_none());535 assert!(grid.get(0, 10).is_none());
397 assert!(grid.get(10, 0).is_none());536 assert!(grid.get(10, 0).is_none());
398 }537 }
538+
539+ #[test]
540+ fn a_candidate_far_outside_the_frame_is_clamped_to_it() {
541+ // A 4x4-mi frame (16x16 px), block 1x1 mi at (1, 1): room for one
542+ // neighbour above and one to the left, tight edges on every side.
543+ let mut grid = MiGrid::new(4, 4);
544+ grid.set(0, 1, inter((100_000, 100_000)));
545+
546+ let stack = find_mv_stack(&grid, 1, 1, 1, 1, 1, 4, 4);
547+
548+ // Unclamped this candidate is (100000, 100000); spec 7.10.2.14 caps
549+ // it at the frame edge (2 mi below/right) plus the block's own 4x4
550+ // span plus MV_BORDER (128), all in 1/8-pel: (2*4)*8 + 1*4*8 + 128 =
551+ // 64 + 32 + 128 = 224.
552+ assert_eq!(stack.nearest_mv, (224, 224));
553+ assert_ne!(stack.entries[0].mv, stack.nearest_mv);
554+ }
555+
556+ #[test]
557+ fn a_neighbour_coded_newmv_raises_the_new_mv_context() {
558+ let mut grid = MiGrid::new(8, 8);
559+ grid.set(
560+ 1,
561+ 2,
562+ MiInfo {
563+ is_inter: true,
564+ ref_frame: 1,
565+ mv: (4, 4),
566+ is_new_mv: true,
567+ },
568+ );
569+ // Only the row matches (nearest_match == 1): newmv_count > 0 picks
570+ // libaom's `mode_context[ref_frame] |= 2` branch.
571+ let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8);
572+ assert_eq!(stack.new_mv_ctx, 2);
573+ assert_eq!(stack.ref_mv_ctx, 3);
574+ }
575+
576+ #[test]
577+ fn single_ref_ctx_matches_libaoms_collapsed_forward_only_case() {
578+ assert_eq!(single_ref_ctx(false), 1);
579+ assert_eq!(single_ref_ctx(true), 2);
580+ }
399 }581 }
crates/ec-av1/src/tile.rsmodified+710 -3
@@ -14,8 +14,9 @@ use std::sync::LazyLock;
14 use ec_core::{Error, Result};14 use ec_core::{Error, Result};
15 15
16 use crate::cdf;16 use crate::cdf;
17-use crate::cdf_state::{Cdfs, TxbSet, TxbTables};17+use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
18 use crate::msac::SymbolEncoder;18 use crate::msac::SymbolEncoder;
19+use crate::mvstack::{find_mv_stack, single_ref_ctx, MiGrid, MiInfo};
19 20
20 /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.21 /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
21 const PARTITION_NONE: usize = 0;22 const PARTITION_NONE: usize = 0;
@@ -352,6 +353,39 @@ pub struct BlockCoeffs {
352 /// [`Default`] and a plain coefficient list give). Chroma stays on353 /// [`Default`] and a plain coefficient list give). Chroma stays on
353 /// `DC_PRED`.354 /// `DC_PRED`.
354 pub mode: u8,355 pub mode: u8,
356+ /// Whether the block carries no residual at all (spec `skip`). An intra
357+ /// block may still be skipped; `false` (the [`Default`]) codes whatever
358+ /// `luma`/`u`/`v` carry.
359+ pub skip: bool,
360+ /// The block's inter mode and motion vector, or `None` for an intra
361+ /// block. Only [`sb_coeff_inter_frame_tile`] codes `is_inter`; the key
362+ /// frame writers never read this field.
363+ pub inter: Option<InterInfo>,
364+}
365+
366+/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take (spec
367+/// 5.11.24 `read_inter_mode`), reduced to the two branches its symbol chain
368+/// needs to prove out: the stack's own top candidate outright, or a coded
369+/// residual against it. `NEARMV`/`GLOBALMV` are never written.
370+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
371+pub enum InterMode {
372+ /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL.
373+ NearestMv,
374+ /// `NEWMV`: codes `mv` as a residual against `MvStack::pred_mv`, through
375+ /// a DRL index this writer always leaves at zero.
376+ NewMv,
377+}
378+
379+/// An inter-coded block's mode and motion vector, `mv` in the spec's 1/8-pel
380+/// `(row, col)` units. For [`InterMode::NearestMv`] this writer ignores `mv`
381+/// and codes the stack's own candidate instead — the decoder derives it, so
382+/// nothing here can disagree with it.
383+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
384+pub struct InterInfo {
385+ /// The mode this block is coded with.
386+ pub mode: InterMode,
387+ /// The motion vector a [`InterMode::NewMv`] block's residual targets.
388+ pub mv: (i32, i32),
355 }389 }
356 390
357 impl From<Vec<Coeff>> for BlockCoeffs {391 impl From<Vec<Coeff>> for BlockCoeffs {
@@ -468,6 +502,16 @@ struct Neighbours {
468 above_side: Vec<usize>,502 above_side: Vec<usize>,
469 /// The same, down the left edge.503 /// The same, down the left edge.
470 left_side: Vec<usize>,504 left_side: Vec<usize>,
505+ /// Whether the neighbour carried no residual, for [`sb_coeff_inter_frame_tile`]'s
506+ /// skip context. Unused (and left at its default) by the key frame writers.
507+ above_skip: Vec<bool>,
508+ /// The same, down the left edge.
509+ left_skip: Vec<bool>,
510+ /// Whether the neighbour was coded inter, for the `is_inter` context.
511+ /// Unused by the key frame writers.
512+ above_inter: Vec<bool>,
513+ /// The same, down the left edge.
514+ left_inter: Vec<bool>,
471 }515 }
472 516
473 /// What one plane's neighbours leave for a block, gathered across every cell517 /// What one plane's neighbours leave for a block, gathered across every cell
@@ -496,6 +540,10 @@ impl Neighbours {
496 left_mode: vec![DC_PRED; rows],540 left_mode: vec![DC_PRED; rows],
497 above_side: vec![SB; cols],541 above_side: vec![SB; cols],
498 left_side: vec![SB; rows],542 left_side: vec![SB; rows],
543+ above_skip: vec![false; cols],
544+ left_skip: vec![false; rows],
545+ above_inter: vec![false; cols],
546+ left_inter: vec![false; rows],
499 }547 }
500 }548 }
501 549
@@ -504,6 +552,8 @@ impl Neighbours {
504 self.left.iter_mut().for_each(|l| *l = Default::default());552 self.left.iter_mut().for_each(|l| *l = Default::default());
505 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);553 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
506 self.left_side.iter_mut().for_each(|s| *s = SB);554 self.left_side.iter_mut().for_each(|s| *s = SB);
555+ self.left_skip.iter_mut().for_each(|s| *s = false);
556+ self.left_inter.iter_mut().for_each(|i| *i = false);
507 }557 }
508 558
509 /// Writes one coded block into every 16x16 column and row it covers.559 /// Writes one coded block into every 16x16 column and row it covers.
@@ -520,6 +570,19 @@ impl Neighbours {
520 }570 }
521 }571 }
522 572
573+ /// Writes one inter-frame block's skip flag and inter/intra state into
574+ /// every 16x16 column and row it covers, the same span [`Self::record`]
575+ /// fills for the coefficient and mode state.
576+ fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool) {
577+ let (r, c) = at;
578+ for cell in 0..side / SUB {
579+ self.above_skip[c + cell] = skip;
580+ self.left_skip[r + cell] = skip;
581+ self.above_inter[c + cell] = is_inter;
582+ self.left_inter[r + cell] = is_inter;
583+ }
584+ }
585+
523 /// The context of a block's partition symbol (spec 9.3): whether the586 /// The context of a block's partition symbol (spec 9.3): whether the
524 /// blocks above it and to its left were split finer than it is.587 /// blocks above it and to its left were split finer than it is.
525 /// The gathered state of the blocks above and to the left of one block,588 /// The gathered state of the blocks above and to the left of one block,
@@ -1283,6 +1346,340 @@ fn dc_sign_ctx(vote: i32) -> usize {
1283 }1346 }
1284 }1347 }
1285 1348
1349+/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`,
1350+/// `pred_common.c`): both neighbours' intra/inter state when both are
1351+/// available, one neighbour's when only one is, and zero at a tile's own
1352+/// top-left corner.
1353+fn intra_inter_ctx(has_above: bool, has_left: bool, above_inter: bool, left_inter: bool) -> usize {
1354+ match (has_above, has_left) {
1355+ (true, true) => {
1356+ let (above_intra, left_intra) = (!above_inter, !left_inter);
1357+ if above_intra && left_intra {
1358+ 3
1359+ } else {
1360+ usize::from(above_intra || left_intra)
1361+ }
1362+ }
1363+ (true, false) => 2 * usize::from(!above_inter),
1364+ (false, true) => 2 * usize::from(!left_inter),
1365+ (false, false) => 0,
1366+ }
1367+}
1368+
1369+/// `CLASS0_SIZE << (class + 2)` (spec 3), the magnitude an `MV_CLASS_n`
1370+/// component's own bits start counting from; class zero starts at zero.
1371+fn mv_class_base(class: usize) -> i32 {
1372+ if class == 0 {
1373+ 0
1374+ } else {
1375+ 2i32 << (class + 2)
1376+ }
1377+}
1378+
1379+/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in — the inverse
1380+/// of `mv_class_base`'s doubling ranges, ported from libaom's
1381+/// `av1_get_mv_class` (`mv.h`).
1382+fn mv_class_of(z: i32) -> usize {
1383+ let mut class = 0;
1384+ while class < 10 && mv_class_base(class + 1) <= z {
1385+ class += 1;
1386+ }
1387+ class
1388+}
1389+
1390+/// Writes one motion vector component's non-zero diff (spec 5.11.32
1391+/// `read_mv_component`, run backwards): sign, class, then the class's own
1392+/// bits. `allow_high_precision_mv` is off in every frame this writer codes,
1393+/// so the eighth-pel bit is always inferred as one rather than coded — which
1394+/// means only diffs whose eighth-pel bit really is one are representable;
1395+/// anything else is refused rather than rounded, since rounding would silently
1396+/// code a different vector than the caller asked for.
1397+///
1398+/// # Errors
1399+/// Returns an error when `diff` needs the eighth-pel precision this writer's
1400+/// frames do not carry.
1401+fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
1402+ debug_assert_ne!(diff, 0);
1403+ let sign = diff < 0;
1404+ enc.symbol(usize::from(sign), &mut c.sign);
1405+ let mag = diff.unsigned_abs() as i32;
1406+ let z = mag - 1;
1407+ if z & 1 == 0 {
1408+ return Err(Error::unsupported(
1409+ "AV1 tile",
1410+ "a motion vector component needs eighth-pel precision, which \
1411+ allow_high_precision_mv off does not carry",
1412+ ));
1413+ }
1414+ let class = mv_class_of(z);
1415+ enc.symbol(class, &mut c.class);
1416+ let local = z - mv_class_base(class);
1417+ if class == 0 {
1418+ let bit = (local >> 3) & 1;
1419+ let fr = (local >> 1) & 3;
1420+ enc.symbol(bit as usize, &mut c.class0_bit);
1421+ enc.symbol(fr as usize, &mut c.class0_fr[bit as usize]);
1422+ } else {
1423+ let d = local >> 3;
1424+ let fr = (local >> 1) & 3;
1425+ for i in 0..class {
1426+ enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
1427+ }
1428+ enc.symbol(fr as usize, &mut c.fr);
1429+ }
1430+ // The eighth-pel bit itself is inferred, not coded (spec 5.11.32: "if
1431+ // (allow_high_precision_mv) mv_class0_hp ... else mv_class0_hp = 1").
1432+ Ok(())
1433+}
1434+
1435+/// Writes a motion vector as a residual against `pred` (spec 5.11.32
1436+/// `read_mv`): the joint symbol naming which components differ, then each
1437+/// differing component.
1438+fn write_mv(
1439+ enc: &mut SymbolEncoder,
1440+ mv_comp: &mut [MvComponentCdfs; 2],
1441+ mv_joint: &mut [u16; 5],
1442+ mv: (i32, i32),
1443+ pred: (i32, i32),
1444+) -> Result<()> {
1445+ let diff = (mv.0 - pred.0, mv.1 - pred.1);
1446+ let joint = match (diff.0 != 0, diff.1 != 0) {
1447+ (false, false) => 0, // MV_JOINT_ZERO
1448+ (false, true) => 1, // MV_JOINT_HNZVZ: column only
1449+ (true, false) => 2, // MV_JOINT_HZVNZ: row only
1450+ (true, true) => 3, // MV_JOINT_HNZVNZ
1451+ };
1452+ enc.symbol(joint, mv_joint);
1453+ if diff.0 != 0 {
1454+ write_mv_component(enc, &mut mv_comp[0], diff.0)?;
1455+ }
1456+ if diff.1 != 0 {
1457+ write_mv_component(enc, &mut mv_comp[1], diff.1)?;
1458+ }
1459+ Ok(())
1460+}
1461+
1462+/// Writes the payload of a one-tile inter frame built from `blocks`, one
1463+/// 32x32 block per entry in raster order across the frame — every superblock
1464+/// is split into its four quadrants the way [`split_coeff_key_frame_tile`]
1465+/// codes a key frame, because a mixed-size partition tree buys this writer's
1466+/// gate nothing a flat grid does not already prove: the CDF state, the
1467+/// neighbour contexts and the single-reference/MV-stack machinery below are
1468+/// exactly as size-sensitive whether the tree recurses or not, and recursing
1469+/// it would be undirected scaffolding — see `sb_coeff_key_frame_tile` for
1470+/// where that tree already lives, ready to graft this block's mode reads
1471+/// onto once a real partition search needs it.
1472+///
1473+/// A block whose [`BlockCoeffs::inter`] is `Some` is coded inter: `skip`,
1474+/// then `is_inter`, then a single-reference chain that always names `LAST`
1475+/// (spec 5.11.25 `single_ref_p1`/`p3`/`p4`, this crate's only reference so
1476+/// far), then the two-mode `read_inter_mode` chain (spec 5.11.24) and, for
1477+/// [`InterMode::NewMv`], a DRL index (always zero) and a coded motion vector
1478+/// residual. A block whose `inter` is `None` codes intra, through the
1479+/// *inter*-frame intra path (spec 5.11.16's `intra_frame_mode_info` is the
1480+/// key frame writers' path; this is `inter_frame_mode_info`'s intra branch):
1481+/// `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour context, since
1482+/// an inter frame's intra blocks do not read their neighbours' modes.
1483+///
1484+/// # Errors
1485+/// Returns an error when the frame is not a whole number of 64x64
1486+/// superblocks, when `blocks` does not carry exactly one entry per 32x32
1487+/// block, when an intra block names a mode a key frame does not code, when a
1488+/// coefficient sits outside its transform or is one the writer cannot code,
1489+/// when a `NEWMV` block's motion vector needs eighth-pel precision, or when
1490+/// `base_q_idx` is outside the q-context band whose default CDFs this crate
1491+/// carries.
1492+pub fn sb_coeff_inter_frame_tile(
1493+ mi_cols: u32,
1494+ mi_rows: u32,
1495+ base_q_idx: u8,
1496+ blocks: &[BlockCoeffs],
1497+) -> Result<Vec<u8>> {
1498+ check_superblocks(mi_cols, mi_rows)?;
1499+ if !Q_CTX_2.contains(&base_q_idx) {
1500+ return Err(Error::unsupported(
1501+ "AV1 tile",
1502+ "the coefficient CDFs of only one q context are known, so \
1503+ base_q_idx must be 61..=120",
1504+ ));
1505+ }
1506+ let (cols, rows) = (mi_cols / BLOCK_MI, mi_rows / BLOCK_MI);
1507+ if blocks.len() != (cols * rows) as usize {
1508+ return Err(Error::unsupported(
1509+ "AV1 tile",
1510+ "an inter frame needs one entry per 32x32 block",
1511+ ));
1512+ }
1513+ if let Some(bad) = blocks
1514+ .iter()
1515+ .find(|b| b.inter.is_none() && usize::from(b.mode) >= INTRA_MODES)
1516+ {
1517+ return Err(Error::unsupported(
1518+ "AV1 tile",
1519+ format!(
1520+ "intra mode {} is not one of the thirteen this writer codes",
1521+ bad.mode
1522+ ),
1523+ ));
1524+ }
1525+
1526+ /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block, the only
1527+ /// size this writer's intra branch codes.
1528+ const SIZE_GROUP_32: usize = 3;
1529+ /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference this
1530+ /// writer's single-reference chain ever names.
1531+ const LAST_FRAME: i8 = 1;
1532+
1533+ let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
1534+ let mut neighbours = Neighbours::new(cols as usize * 2, rows as usize * 2);
1535+ let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
1536+ let mut cdfs = Cdfs::new();
1537+ let mut enc = SymbolEncoder::new();
1538+ let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
1539+ let scan32 = default_scan(TX32);
1540+ let scan16 = default_scan(TX16);
1541+ let zero_grids = [
1542+ vec![0i32; TX32 * TX32],
1543+ vec![0i32; TX16 * TX16],
1544+ vec![0i32; TX16 * TX16],
1545+ ];
1546+
1547+ for sb_r in 0..sb_rows {
1548+ neighbours.start_row();
1549+ for sb_c in 0..sb_cols {
1550+ let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
1551+ let sb_ctx = neighbours.partition_ctx(sb_at, SB);
1552+ enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[sb_ctx]);
1553+
1554+ for quadrant in 0..4 {
1555+ let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
1556+ let block = &blocks[(r32 * cols + c32) as usize];
1557+ let at = (r32 as usize * 2, c32 as usize * 2);
1558+ let (r, c) = at;
1559+ let ctx32 = neighbours.partition_ctx(at, BLOCK);
1560+ enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[ctx32]);
1561+
1562+ let has_above = r32 > 0;
1563+ let has_left = c32 > 0;
1564+ let skip_ctx =
1565+ usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
1566+ enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
1567+
1568+ let is_inter = block.inter.is_some();
1569+ let (above_inter, left_inter) =
1570+ (neighbours.above_inter[c], neighbours.left_inter[r]);
1571+ let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
1572+ enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]);
1573+
1574+ let mode_for_tx;
1575+ if let Some(info) = block.inter {
1576+ let sr_ctx = single_ref_ctx(above_inter || left_inter);
1577+ enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward
1578+ enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2
1579+ enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST
1580+
1581+ let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
1582+ let stack = find_mv_stack(
1583+ &grid,
1584+ mi_row,
1585+ mi_col,
1586+ 8,
1587+ 8,
1588+ LAST_FRAME,
1589+ mi_cols as usize,
1590+ mi_rows as usize,
1591+ );
1592+
1593+ let is_new_mv = matches!(info.mode, InterMode::NewMv);
1594+ if is_new_mv {
1595+ enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV
1596+ } else {
1597+ enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new
1598+ enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero
1599+ enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
1600+ }
1601+ // This writer always keeps the first DRL candidate, so the
1602+ // loop (spec 5.11.24 `read_drl_idx`) only ever runs its
1603+ // first, breaking iteration.
1604+ if is_new_mv && stack.entries.len() > 1 {
1605+ enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]);
1606+ }
1607+ let mv = if is_new_mv {
1608+ write_mv(
1609+ &mut enc,
1610+ &mut cdfs.mv_comp,
1611+ &mut cdfs.mv_joint,
1612+ info.mv,
1613+ stack.pred_mv,
1614+ )?;
1615+ info.mv
1616+ } else {
1617+ stack.nearest_mv
1618+ };
1619+ grid.set(
1620+ mi_row,
1621+ mi_col,
1622+ MiInfo {
1623+ is_inter: true,
1624+ ref_frame: LAST_FRAME,
1625+ mv,
1626+ is_new_mv,
1627+ },
1628+ );
1629+ for dr in 0..8 {
1630+ for dc in 0..8 {
1631+ if dr == 0 && dc == 0 {
1632+ continue;
1633+ }
1634+ grid.set(
1635+ mi_row + dr,
1636+ mi_col + dc,
1637+ MiInfo {
1638+ is_inter: true,
1639+ ref_frame: LAST_FRAME,
1640+ mv,
1641+ is_new_mv,
1642+ },
1643+ );
1644+ }
1645+ }
1646+ mode_for_tx = 0;
1647+ } else {
1648+ let mode = usize::from(block.mode);
1649+ enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);
1650+ if (V_PRED..=D67_PRED).contains(&mode) {
1651+ enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
1652+ }
1653+ enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]);
1654+ mode_for_tx = mode;
1655+ }
1656+
1657+ if block.skip {
1658+ neighbours.record(at, BLOCK, mode_for_tx, &zero_grids);
1659+ } else {
1660+ let grids = [
1661+ level_grid(&block.luma, TX32)?,
1662+ level_grid(&block.u, TX16)?,
1663+ level_grid(&block.v, TX16)?,
1664+ ];
1665+ write_block_planes(
1666+ &mut enc,
1667+ &mut cdfs,
1668+ &split_planes,
1669+ &grids,
1670+ &[&scan32, &scan16, &scan16],
1671+ &neighbours.around(at, BLOCK),
1672+ mode_for_tx,
1673+ );
1674+ neighbours.record(at, BLOCK, mode_for_tx, &grids);
1675+ }
1676+ neighbours.record_inter(at, BLOCK, block.skip, is_inter);
1677+ }
1678+ }
1679+ }
1680+ Ok(enc.finish())
1681+}
1682+
1286 #[cfg(test)]1683 #[cfg(test)]
1287 mod tests {1684 mod tests {
1288 use super::*;1685 use super::*;
@@ -1291,8 +1688,8 @@ mod tests {
1291 use crate::sequence::sequence_header_obu;1688 use crate::sequence::sequence_header_obu;
1292 use ec_av1_syntax::sequence::SequenceHeader;1689 use ec_av1_syntax::sequence::SequenceHeader;
1293 use ec_av1_syntax::{1690 use ec_av1_syntax::{
1294- FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo,1691+ FrameHeader, FrameType, LoopFilterParams, QuantizationParams, TileInfo, TxMode,
1295- TxMode,1692+ PRIMARY_REF_NONE,
1296 };1693 };
1297 use std::io::Write;1694 use std::io::Write;
1298 use std::process::{Command, Stdio};1695 use std::process::{Command, Stdio};
@@ -3315,4 +3712,314 @@ mod tests {
3315 "the decoded picture is {rmse} off, a step being {step}"3712 "the decoded picture is {rmse} off, a step being {step}"
3316 );3713 );
3317 }3714 }
3715+
3716+ /// The inverse of [`write_mv_component`], mirroring [`SymbolDecoder`]
3717+ /// against the spec's own `read_mv_component` pseudocode.
3718+ fn decode_mv_component(
3719+ dec: &mut crate::msac::tests::SymbolDecoder,
3720+ c: &mut MvComponentCdfs,
3721+ ) -> i32 {
3722+ let sign = dec.symbol(&mut c.sign);
3723+ let class = dec.symbol(&mut c.class);
3724+ let local = if class == 0 {
3725+ let bit = dec.symbol(&mut c.class0_bit);
3726+ let fr = dec.symbol(&mut c.class0_fr[bit]);
3727+ (bit << 3) | (fr << 1) | 1
3728+ } else {
3729+ let mut d = 0;
3730+ for i in 0..class {
3731+ d |= dec.symbol(&mut c.bit[i]) << i;
3732+ }
3733+ let fr = dec.symbol(&mut c.fr);
3734+ (d << 3) | (fr << 1) | 1
3735+ };
3736+ let mag = mv_class_base(class) + local as i32 + 1;
3737+ if sign == 1 {
3738+ -mag
3739+ } else {
3740+ mag
3741+ }
3742+ }
3743+
3744+ /// Decodes one superblock a [`sb_coeff_inter_frame_tile`] payload wrote,
3745+ /// mirroring the writer's own context tracking (partition, skip,
3746+ /// is_inter, and the MV stack) symbol for symbol against a fresh
3747+ /// [`Cdfs`], so a desync between the two shows up as a wrong decoded
3748+ /// value rather than a silent pass. Every block here is skipped, so no
3749+ /// coefficient symbols are read. `wrong_y_mode` swaps in `KF_Y_MODE`'s
3750+ /// (0, 0) row for an intra block's mode read, to show that reading the
3751+ /// wrong table decodes the wrong mode rather than the one that was
3752+ /// written.
3753+ ///
3754+ /// One decoded block's `(skip, is_inter, mode, mv)` — `mode` is `None`
3755+ /// for an inter block, `mv` is `(0, 0)` for an intra one.
3756+ type DecodedBlock = (bool, bool, Option<usize>, (i32, i32));
3757+
3758+ /// Returns the number of symbols and literals read, and each block's
3759+ /// decoded state.
3760+ fn decode_inter_sb(
3761+ data: &[u8],
3762+ mi_cols: u32,
3763+ mi_rows: u32,
3764+ wrong_y_mode: bool,
3765+ ) -> (usize, Vec<DecodedBlock>) {
3766+ let mut dec = crate::msac::tests::SymbolDecoder::new(data);
3767+ let mut cdfs = Cdfs::new();
3768+ let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
3769+ let mut above_skip = [false; 2];
3770+ let mut left_skip = [false; 2];
3771+ let mut above_inter = [false; 2];
3772+ let mut left_inter = [false; 2];
3773+ let mut count = 0usize;
3774+
3775+ count += 1;
3776+ dec.symbol(&mut cdfs.partition_w64[0]);
3777+
3778+ let mut results = Vec::new();
3779+ for quadrant in 0..4usize {
3780+ let (r32, c32) = (quadrant / 2, quadrant % 2);
3781+ count += 1;
3782+ dec.symbol(&mut cdfs.partition_w32[0]);
3783+
3784+ let (has_above, has_left) = (r32 > 0, c32 > 0);
3785+ let skip_ctx = usize::from(above_skip[c32]) + usize::from(left_skip[r32]);
3786+ count += 1;
3787+ let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
3788+
3789+ let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter[c32], left_inter[r32]);
3790+ count += 1;
3791+ let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
3792+
3793+ let (mode, mv) = if is_inter {
3794+ let sr_ctx = single_ref_ctx(above_inter[c32] || left_inter[r32]);
3795+ count += 3;
3796+ assert_eq!(
3797+ dec.symbol(&mut cdfs.single_ref[sr_ctx][0]),
3798+ 0,
3799+ "single_ref p1"
3800+ );
3801+ assert_eq!(
3802+ dec.symbol(&mut cdfs.single_ref[sr_ctx][2]),
3803+ 0,
3804+ "single_ref p3"
3805+ );
3806+ assert_eq!(
3807+ dec.symbol(&mut cdfs.single_ref[sr_ctx][3]),
3808+ 0,
3809+ "single_ref p4"
3810+ );
3811+
3812+ let (mi_row, mi_col) = (r32 * 8, c32 * 8);
3813+ let stack = find_mv_stack(
3814+ &grid,
3815+ mi_row,
3816+ mi_col,
3817+ 8,
3818+ 8,
3819+ 1,
3820+ mi_cols as usize,
3821+ mi_rows as usize,
3822+ );
3823+
3824+ count += 1;
3825+ let new_mv = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 0;
3826+ let (mv, is_new_mv) = if new_mv {
3827+ if stack.entries.len() > 1 {
3828+ count += 1;
3829+ dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
3830+ }
3831+ count += 1;
3832+ let joint = dec.symbol(&mut cdfs.mv_joint);
3833+ let mut diff = (0, 0);
3834+ if joint == 2 || joint == 3 {
3835+ // sign, class, class0_bit, class0_fr for this test's
3836+ // small (class 0) components.
3837+ count += 4;
3838+ diff.0 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[0]);
3839+ }
3840+ if joint == 1 || joint == 3 {
3841+ count += 4;
3842+ diff.1 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[1]);
3843+ }
3844+ ((stack.pred_mv.0 + diff.0, stack.pred_mv.1 + diff.1), true)
3845+ } else {
3846+ count += 2;
3847+ assert_eq!(
3848+ dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]),
3849+ 1,
3850+ "zero_mv"
3851+ );
3852+ assert_eq!(dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]), 0, "ref_mv");
3853+ (stack.nearest_mv, false)
3854+ };
3855+ for dr in 0..8 {
3856+ for dc in 0..8 {
3857+ grid.set(
3858+ mi_row + dr,
3859+ mi_col + dc,
3860+ MiInfo {
3861+ is_inter: true,
3862+ ref_frame: 1,
3863+ mv,
3864+ is_new_mv,
3865+ },
3866+ );
3867+ }
3868+ }
3869+ (None, mv)
3870+ } else {
3871+ count += 1;
3872+ let m = if wrong_y_mode {
3873+ dec.symbol(&mut cdfs.kf_y_mode[0][0])
3874+ } else {
3875+ dec.symbol(&mut cdfs.y_mode[3])
3876+ };
3877+ if (V_PRED..=D67_PRED).contains(&m) {
3878+ count += 1;
3879+ dec.symbol(&mut cdfs.angle_delta[m - V_PRED]);
3880+ }
3881+ count += 1;
3882+ dec.symbol(&mut cdfs.uv_mode_cfl[m]);
3883+ (Some(m), (0, 0))
3884+ };
3885+
3886+ above_skip[c32] = skip;
3887+ left_skip[r32] = skip;
3888+ above_inter[c32] = is_inter;
3889+ left_inter[r32] = is_inter;
3890+ results.push((skip, is_inter, mode, mv));
3891+ }
3892+ (count, results)
3893+ }
3894+
3895+ /// Every superblock here skips: no residual, so the only symbols are the
3896+ /// mode chain, and the byte count and the symbol count both come out
3897+ /// small enough to hand-check.
3898+ #[test]
3899+ fn an_all_skip_inter_superblock_is_small_and_reads_back() {
3900+ let block = BlockCoeffs {
3901+ inter: Some(InterInfo {
3902+ mode: InterMode::NearestMv,
3903+ mv: (0, 0),
3904+ }),
3905+ skip: true,
3906+ ..BlockCoeffs::default()
3907+ };
3908+ let blocks = vec![block.clone(), block.clone(), block.clone(), block];
3909+ let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
3910+ // Hand count: one partition_w64, then per block partition_w32 + skip +
3911+ // is_inter + 3 single_ref + new_mv + zero_mv + ref_mv = 9, times four.
3912+ assert!(
3913+ data.len() <= 16,
3914+ "an all-skip NEARESTMV superblock took {} bytes",
3915+ data.len()
3916+ );
3917+
3918+ let (count, results) = decode_inter_sb(&data, 16, 16, false);
3919+ assert_eq!(count, 1 + 4 * 9, "symbol count against the hand count");
3920+ for (skip, is_inter, mode, mv) in results {
3921+ assert!(skip);
3922+ assert!(is_inter);
3923+ assert_eq!(mode, None);
3924+ // Every block's only inter neighbours carry (0, 0), so the stack's
3925+ // nearest candidate is (0, 0) throughout.
3926+ assert_eq!(mv, (0, 0));
3927+ }
3928+ }
3929+
3930+ /// The fourth block codes NEWMV against a (0, 0) predictor with a coded
3931+ /// column component: the symbol sequence a decoder reads back has to be
3932+ /// exactly what [`write_mv`] wrote, not a residual that merely decodes
3933+ /// to *some* valid vector.
3934+ #[test]
3935+ fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {
3936+ let nearest = BlockCoeffs {
3937+ inter: Some(InterInfo {
3938+ mode: InterMode::NearestMv,
3939+ mv: (0, 0),
3940+ }),
3941+ skip: true,
3942+ ..BlockCoeffs::default()
3943+ };
3944+ let newmv = BlockCoeffs {
3945+ inter: Some(InterInfo {
3946+ mode: InterMode::NewMv,
3947+ mv: (0, 2),
3948+ }),
3949+ skip: true,
3950+ ..BlockCoeffs::default()
3951+ };
3952+ let blocks = vec![nearest.clone(), nearest.clone(), nearest, newmv];
3953+ let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
3954+
3955+ let (count, results) = decode_inter_sb(&data, 16, 16, false);
3956+ // Three NEARESTMV blocks at 9 symbols each, one NEWMV block at
3957+ // partition + skip + is_inter + 3 single_ref + new_mv + mv_joint +
3958+ // (sign, class, class0_bit, class0_fr for the one nonzero component)
3959+ // = 12, plus the superblock's partition_w64.
3960+ assert_eq!(count, 1 + 3 * 9 + 12, "symbol count against the hand count");
3961+ let (skip, is_inter, mode, mv) = results[3];
3962+ assert!(skip);
3963+ assert!(is_inter);
3964+ assert_eq!(mode, None);
3965+ assert_eq!(
3966+ mv,
3967+ (0, 2),
3968+ "the decoded motion vector must be exactly what was written"
3969+ );
3970+ }
3971+
3972+ /// Decodes only the first 32x32 block's mode symbol of a superblock: the
3973+ /// tile's own first block always reads partition, skip and is_inter at
3974+ /// context zero, so this needs none of [`decode_inter_sb`]'s neighbour
3975+ /// bookkeeping — which matters here because the mutation this feeds
3976+ /// desyncs everything after the one symbol it is testing, and a decoder
3977+ /// that kept reading past it would be asserting on garbage.
3978+ fn decode_first_block_mode(data: &[u8], wrong_y_mode: bool) -> usize {
3979+ let mut dec = crate::msac::tests::SymbolDecoder::new(data);
3980+ let mut cdfs = Cdfs::new();
3981+ dec.symbol(&mut cdfs.partition_w64[0]);
3982+ dec.symbol(&mut cdfs.partition_w32[0]);
3983+ dec.symbol(&mut cdfs.skip[0]);
3984+ dec.symbol(&mut cdfs.intra_inter[0]);
3985+ if wrong_y_mode {
3986+ dec.symbol(&mut cdfs.kf_y_mode[0][0])
3987+ } else {
3988+ dec.symbol(&mut cdfs.y_mode[3])
3989+ }
3990+ }
3991+
3992+ /// An inter frame's intra block reads its mode against `Y_MODE`'s size
3993+ /// group, not `KF_Y_MODE`'s neighbour-context table a key frame's block
3994+ /// reads. Reading the wrong table back — `KF_Y_MODE`'s `(0, 0)` row —
3995+ /// decodes a different mode than the one [`sb_coeff_inter_frame_tile`]
3996+ /// wrote, because the two tables carry different default probabilities
3997+ /// even though a row of each is the same fourteen-entry width. (The swap
3998+ /// this test's name warns of does not typecheck as a one-line
3999+ /// substitution at the write site either — `cdfs.kf_y_mode[3]` is a
4000+ /// `[[u16; 14]; 5]` row, not the single `[u16; 14]` `Y_MODE` indexing
4001+ /// needs — so a mutation that got the *outer* shape wrong would be
4002+ /// caught by `cargo check` before it ever reached a test; this test is
4003+ /// what catches getting the *right* leaf shape from the *wrong* table.)
4004+ #[test]
4005+ fn an_intra_block_in_an_inter_frame_is_caught_reading_kf_y_mode() {
4006+ let block = BlockCoeffs {
4007+ mode: H_PRED as u8,
4008+ skip: true,
4009+ ..BlockCoeffs::default()
4010+ };
4011+ let blocks = vec![block; 4];
4012+ let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
4013+
4014+ assert_eq!(
4015+ decode_first_block_mode(&data, false),
4016+ H_PRED,
4017+ "the right table reads the mode back exactly"
4018+ );
4019+ assert_ne!(
4020+ decode_first_block_mode(&data, true),
4021+ H_PRED,
4022+ "KF_Y_MODE's different probabilities must decode a different mode"
4023+ );
4024+ }
3318 }4025 }