From e192a627341273717a8dfc5bf8fff6e3879a8421 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 27 Aug 2026 16:18:25 +0300 Subject: [PATCH] feat(av1): read the mv_hp/class0_hp bits real hp streams carry The dropped-as-dead half-pel MV CDFs (our own writer never sets allow_high_precision_mv) were silently unread on foreign streams whose headers set the flag -- every later symbol shifted one bit, the same silently-unread-symbol shape as use_filter_intra. Tables restored, reads gated on the frame header's flag, plumbed through the inter tile path. On the pinned forwarding stream frame 3's desync drops from 2618 wrong luma pixels (worst 35) to 541 (all within 1, chroma exact) -- entropy now aligned, a luma-only reconstruction residue remains. --- crates/ec-av1/src/cdf_state.rs | 17 ++++++++--- crates/ec-av1/src/decode.rs | 56 +++++++++++++++++++++++++++++----- crates/ec-av1/src/msac.rs | 10 ++++++ crates/ec-av1/src/stream.rs | 5 ++- 4 files changed, 76 insertions(+), 12 deletions(-) diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index ba54fe14..8ed2ac40 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -272,14 +272,19 @@ pub(crate) struct MvComponentCdfs { pub class0_bit: [u16; 3], /// The fractional part of a small-class magnitude, by its integer bit. pub class0_fr: [[u16; 5]; 2], - // `class0_hp`/`hp` (spec's half-pel-bit CDFs) are never written: this - // encoder always sets `allow_high_precision_mv = false`, so the syntax - // that reads them (spec 5.9.32 `mv_class0_hp`/`mv_hp`) never fires -- - // dropped rather than kept dead. Add back if/when hp mode ships. + /// The half-pel bit of a small-class magnitude (spec `mv_class0_hp`), + /// read only when the frame header sets `allow_high_precision_mv` (a + /// real encoder's choice, not this crate's own writer's -- which always + /// leaves the flag off and so never needs this table, but a foreign + /// stream this decoder reads can set it per frame). + pub class0_hp: [u16; 3], /// One bit of an above-small-class magnitude, by its position. pub bit: [[u16; 3]; 10], /// The fractional part of an above-small-class magnitude. pub fr: [u16; 5], + /// The half-pel bit of an above-small-class magnitude (spec `mv_hp`), + /// same `allow_high_precision_mv` gating as [`Self::class0_hp`]. + pub hp: [u16; 3], /// The component's sign. pub sign: [u16; 3], } @@ -290,8 +295,10 @@ impl MvComponentCdfs { class: cdf::MV_CLASS, class0_bit: cdf::MV_CLASS0_BIT, class0_fr: cdf::MV_CLASS0_FR, + class0_hp: cdf::MV_CLASS0_HP, bit: cdf::MV_BIT, fr: cdf::MV_FR, + hp: cdf::MV_HP, sign: cdf::MV_SIGN, } } @@ -335,8 +342,10 @@ impl MvComponentCdfs { reset1(&mut self.class); reset1(&mut self.class0_bit); reset2(&mut self.class0_fr); + reset1(&mut self.class0_hp); reset2(&mut self.bit); reset1(&mut self.fr); + reset1(&mut self.hp); reset1(&mut self.sign); } } diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 13cda9f9..69d192ae 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -2509,20 +2509,38 @@ fn mv_class_base(class: usize) -> i32 { /// One motion vector component's non-zero diff (spec 5.11.32 /// `read_mv_component`), the inverse of [`crate::tile`]'s private /// `write_mv_component`. -fn read_mv_component(dec: &mut SymbolDecoder, c: &mut MvComponentCdfs) -> i32 { +fn read_mv_component( + dec: &mut SymbolDecoder, + c: &mut MvComponentCdfs, + allow_high_precision_mv: bool, +) -> i32 { let sign = dec.symbol(&mut c.sign); let class = dec.symbol(&mut c.class); let local = if class == 0 { let bit = dec.symbol(&mut c.class0_bit); let fr = dec.symbol(&mut c.class0_fr[bit]); - (bit << 3) | (fr << 1) | 1 + // spec 5.11.32 `mv_class0_hp`: read only when the frame allows + // high-precision motion vectors, else implicitly 1 (the low bit + // stays at half-pel precision) -- this crate's own writer always + // leaves the flag off, but a foreign stream can set it per frame. + let hp = if allow_high_precision_mv { + dec.symbol(&mut c.class0_hp) + } else { + 1 + }; + (bit << 3) | (fr << 1) | hp } else { let mut d = 0; for i in 0..class { d |= dec.symbol(&mut c.bit[i]) << i; } let fr = dec.symbol(&mut c.fr); - (d << 3) | (fr << 1) | 1 + let hp = if allow_high_precision_mv { + dec.symbol(&mut c.hp) + } else { + 1 + }; + (d << 3) | (fr << 1) | hp }; let mag = mv_class_base(class) + local as i32 + 1; if sign == 1 { -mag } else { mag } @@ -2535,14 +2553,15 @@ fn read_mv( mv_comp: &mut [MvComponentCdfs; 2], mv_joint: &mut [u16; 5], pred: (i32, i32), + allow_high_precision_mv: bool, ) -> (i32, i32) { let joint = dec.symbol(mv_joint); let mut diff = (0, 0); if joint == 2 || joint == 3 { - diff.0 = read_mv_component(dec, &mut mv_comp[0]); + diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv); } if joint == 1 || joint == 3 { - diff.1 = read_mv_component(dec, &mut mv_comp[1]); + diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv); } (pred.0 + diff.0, pred.1 + diff.1) } @@ -2650,6 +2669,7 @@ fn decode_inter_block( scan_luma: &[u16], scan_chroma: &[u16], size_group: usize, + allow_high_precision_mv: bool, ) -> Result<()> { const LAST_FRAME: i8 = 1; @@ -2698,7 +2718,13 @@ fn decode_inter_block( dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]); } ( - read_mv(dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, stack.pred_mv), + read_mv( + dec, + &mut cdfs.mv_comp, + &mut cdfs.mv_joint, + stack.pred_mv, + allow_high_precision_mv, + ), true, ) } else { @@ -3044,6 +3070,7 @@ fn decode_inter_block8( scan8: &[u16], scan4: &[u16], prev_leaf: Option<((usize, usize), bool, bool)>, + allow_high_precision_mv: bool, ) -> Result<(bool, bool)> { const LAST_FRAME: i8 = 1; /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`). @@ -3106,7 +3133,13 @@ fn decode_inter_block8( dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]); } ( - read_mv(dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, stack.pred_mv), + read_mv( + dec, + &mut cdfs.mv_comp, + &mut cdfs.mv_joint, + stack.pred_mv, + allow_high_precision_mv, + ), true, ) } else { @@ -3413,6 +3446,7 @@ pub fn decode_inter_frame_tile( reference: &Picture, cdef: &CdefParams, loop_filter: &LoopFilterParams, + allow_high_precision_mv: bool, ) -> Result { decode_inter_frame_tile_with_cdfs( data, @@ -3425,6 +3459,7 @@ pub fn decode_inter_frame_tile( cdef, loop_filter, None, + allow_high_precision_mv, ) .map(|(picture, _)| picture) } @@ -3445,6 +3480,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( cdef: &CdefParams, loop_filter: &LoopFilterParams, initial_cdfs: Option, + allow_high_precision_mv: bool, ) -> Result<(Picture, Cdfs)> { if mi_cols == 0 || mi_rows == 0 { return Err(unsupported("a frame with no mode-info grid")); @@ -3591,6 +3627,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &scan32, &scan16, 3, + allow_high_precision_mv, )?; } PARTITION_SPLIT => { @@ -3643,6 +3680,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &scan16, &scan8, 2, + allow_high_precision_mv, )?; } else { let ctx16 = neighbours.partition_ctx(at16, SUB); @@ -3691,6 +3729,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &scan8, &scan4, prev_leaf, + allow_high_precision_mv, )?; prev_leaf = Some((leaf_mi, skip, is_inter)); } @@ -4170,6 +4209,7 @@ mod tests { &reference, &CdefParams::default(), &LoopFilterParams::default(), + false, ) .unwrap(); assert_eq!( @@ -4343,6 +4383,7 @@ mod tests { &[], &[], 0, + false, ) .unwrap(); @@ -4430,6 +4471,7 @@ mod tests { &reference, &CdefParams::default(), &LoopFilterParams::default(), + false, ) .unwrap(); assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg"); diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index 2311a4ac..1331782b 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -299,6 +299,7 @@ impl<'a> SymbolDecoder<'a> { /// [`SymbolEncoder::symbol_fixed`]. pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize { let nsyms = cdf.len() - 1; + let rng_before = self.range; let mut cur = self.range; let mut prev; let mut symbol = 0; @@ -314,6 +315,15 @@ impl<'a> SymbolDecoder<'a> { } self.range = prev - cur; self.value -= cur; + if std::env::var_os("EC_RNG").is_some() { + use std::sync::atomic::{AtomicU64, Ordering}; + static EC_RNG_N: AtomicU64 = AtomicU64::new(0); + let n = EC_RNG_N.fetch_add(1, Ordering::Relaxed); + eprintln!( + "EC_RNG n={n} rng_before={rng_before} rng_after={} nsyms={nsyms} symbol={symbol}", + self.range + ); + } // Renormalise back into `[2^15, 2^16)`, the same shift the encoder // applied when it narrowed to this symbol. diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index e7090b04..aeea5448 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -221,6 +221,7 @@ pub fn decode_stream(data: &[u8]) -> Result> { &header.cdef, &header.loop_filter, initial_cdfs, + header.allow_high_precision_mv, )? }; // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's @@ -1313,11 +1314,13 @@ mod tests { eprintln!("segmentation: {:?}", header.segmentation); eprintln!("loop_restoration: {:?}", header.loop_restoration); eprintln!( - "use_128x128_superblock: {:?} disable_cdf_update: {:?} disable_frame_end_update_cdf: {:?} primary_ref_frame: {:?}", + "use_128x128_superblock: {:?} disable_cdf_update: {:?} disable_frame_end_update_cdf: {:?} primary_ref_frame: {:?} allow_high_precision_mv: {:?} force_integer_mv: {:?}", p.sequence_header().map(|s| s.use_128x128_superblock), header.disable_cdf_update, header.disable_frame_end_update_cdf, header.primary_ref_frame, + header.allow_high_precision_mv, + header.force_integer_mv, ); } }