forge
Explore
Log in

Don't you dare go Hollow

Inter tile writer sb_coeff_inter_frame_tile

Browse files at this commit

302d3c4e0bd21f4edc7dada0f80dc59d7c84baf2Ahmet Kaan GümüşParent: 23d548c
  • feat
    • inter tile writer sb_coeff_inter_frame_tile
Show full message
feat(av1): inter tile writer sb_coeff_inter_frame_tile

Flat 32x32-block-grid writer for inter frames: skip -> is_inter (ctx
from above/left skip+inter tracking) -> intra path (Y_MODE by size
group, not KF_Y_MODE) or inter path (single_ref chain, find_mv_stack,
read_inter_mode NEWMV/NEARESTMV, DRL idx 0 only, mv_joint + per
component symbols) -> existing coefficient path. Widens
SymbolDecoder::symbol to pub(crate) for cross-module roundtrip tests.

One-line encode.rs fix required for BlockCoeffs' two new fields
(skip, inter) via ..BlockCoeffs::default() at its one non-spread
construction site.

Corner-cuts (documented in tile.rs): whole-superblock frames only,
DRL always index 0, allow_high_precision_mv=0 assumed (validated,
not silently rounded), InterMode limited to NearestMv/NewMv.
crates/ec-av1/src/encode.rsmodified+2 -1
@@ -609,6 +609,7 @@ fn code_square(
609609 v,
610610 luma: luma_coeffs,
611611 mode,
612+ ..BlockCoeffs::default()
612613 },
613614 cost,
614615 )
@@ -872,7 +873,7 @@ fn encode_key_frame_inner(
872873 #[cfg(test)]
873874 mod tests {
874875 use super::*;
875- use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
876+ use crate::intra::{D135_PRED, D45_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
876877 use std::io::Write;
877878 use std::process::{Command, Stdio};
878879
crates/ec-av1/src/msac.rsmodified+1 -1
@@ -272,7 +272,7 @@ pub(crate) mod tests {
272272 }
273273
274274 /// `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 {
276276 let s = self.symbol_fixed(cdf);
277277 update_cdf(cdf, s);
278278 s
crates/ec-av1/src/tile.rsmodified+710 -3
@@ -14,8 +14,9 @@ use std::sync::LazyLock;
1414 use ec_core::{Error, Result};
1515
1616 use crate::cdf;
17-use crate::cdf_state::{Cdfs, TxbSet, TxbTables};
17+use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
1818 use crate::msac::SymbolEncoder;
19+use crate::mvstack::{find_mv_stack, single_ref_ctx, MiGrid, MiInfo};
1920
2021 /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
2122 const PARTITION_NONE: usize = 0;
@@ -352,6 +353,39 @@ pub struct BlockCoeffs {
352353 /// [`Default`] and a plain coefficient list give). Chroma stays on
353354 /// `DC_PRED`.
354355 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),
355389 }
356390
357391 impl From<Vec<Coeff>> for BlockCoeffs {
@@ -468,6 +502,16 @@ struct Neighbours {
468502 above_side: Vec<usize>,
469503 /// The same, down the left edge.
470504 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>,
471515 }
472516
473517 /// What one plane's neighbours leave for a block, gathered across every cell
@@ -496,6 +540,10 @@ impl Neighbours {
496540 left_mode: vec![DC_PRED; rows],
497541 above_side: vec![SB; cols],
498542 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],
499547 }
500548 }
501549
@@ -504,6 +552,8 @@ impl Neighbours {
504552 self.left.iter_mut().for_each(|l| *l = Default::default());
505553 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
506554 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);
507557 }
508558
509559 /// Writes one coded block into every 16x16 column and row it covers.
@@ -520,6 +570,19 @@ impl Neighbours {
520570 }
521571 }
522572
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+
523586 /// The context of a block's partition symbol (spec 9.3): whether the
524587 /// blocks above it and to its left were split finer than it is.
525588 /// 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 {
12831346 }
12841347 }
12851348
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+
12861683 #[cfg(test)]
12871684 mod tests {
12881685 use super::*;
@@ -1291,8 +1688,8 @@ mod tests {
12911688 use crate::sequence::sequence_header_obu;
12921689 use ec_av1_syntax::sequence::SequenceHeader;
12931690 use ec_av1_syntax::{
1294- FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
1295- TxMode,
1691+ FrameHeader, FrameType, LoopFilterParams, QuantizationParams, TileInfo, TxMode,
1692+ PRIMARY_REF_NONE,
12961693 };
12971694 use std::io::Write;
12981695 use std::process::{Command, Stdio};
@@ -3315,4 +3712,314 @@ mod tests {
33153712 "the decoded picture is {rmse} off, a step being {step}"
33163713 );
33173714 }
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+ }
33184025 }