diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 5a82f5b3..8ed2ac40 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -96,6 +96,7 @@ pub(crate) struct TxbTables<'a> { } /// Every table a key frame's tile writer adapts. +#[derive(Clone)] pub(crate) struct Cdfs { /// The partition symbol of a 64x64 superblock. pub partition_w64: [[u16; 11]; 4], @@ -271,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], } @@ -289,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, } } @@ -308,7 +316,126 @@ pub(crate) fn pick(q_ctx: usize, q0: T, q1: T, q2: T, q3: T) -> T { } } +/// `reset_cdf_symbol_counter` (spec 7.20's `save_cdfs`, libaom +/// `av1_reset_cdf_symbol_counters`, `entropy.c`): every adapting table's last +/// entry is a symbol counter that slows [`update_cdf`](crate::msac)'s rate +/// down for a table's first 32 observations. A tile decoded with +/// `disable_frame_end_update_cdf == false` saves its *adapted* table into the +/// reference slots the frame refreshes, but the counters go back to zero +/// first -- forwarding the raw counts (this crate's bug until it was found: +/// the counts climbed unchecked, so every table forwarded across two or more +/// frames adapted *faster* than the real decoder's, a divergence too small to +/// flip any one symbol in a single hop but compounding into a visible +/// mismatch by the third). +fn reset1(a: &mut [u16; N]) { + a[N - 1] = 0; +} +fn reset2(a: &mut [[u16; N]; M]) { + a.iter_mut().for_each(reset1); +} +fn reset3(a: &mut [[[u16; N]; M]; K]) { + a.iter_mut().for_each(reset2); +} + +impl MvComponentCdfs { + fn reset_counts(&mut self) { + 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); + } +} + impl Cdfs { + /// Zeroes every table's symbol counter (its last entry), leaving the + /// probabilities themselves untouched -- spec 7.20's `save_cdfs`. Call + /// this on the tile's own end-of-tile adapted state before storing it + /// into a reference slot for cross-frame forwarding; never on a table + /// still being read within the same tile. + pub(crate) fn reset_counts(&mut self) { + reset2(&mut self.partition_w64); + reset2(&mut self.partition_w32); + reset2(&mut self.skip); + reset3(&mut self.kf_y_mode); + reset2(&mut self.uv_mode_no_cfl); + reset2(&mut self.uv_mode_cfl); + reset1(&mut self.cfl_sign); + reset2(&mut self.cfl_alpha); + reset2(&mut self.angle_delta); + reset2(&mut self.txb_skip_luma_16); + reset2(&mut self.txb_skip_luma_8); + reset2(&mut self.txb_skip_chroma_8); + reset2(&mut self.txb_skip_chroma_4); + reset1(&mut self.eob_pt_256_luma); + reset1(&mut self.eob_pt_64_luma); + reset1(&mut self.eob_pt_64_chroma); + reset1(&mut self.eob_pt_16_chroma); + reset2(&mut self.eob_extra_luma_16); + reset2(&mut self.eob_extra_luma_8); + reset2(&mut self.eob_extra_chroma_8); + reset2(&mut self.eob_extra_chroma_4); + reset2(&mut self.base_luma_16); + reset2(&mut self.base_luma_8); + reset2(&mut self.base_chroma_8); + reset2(&mut self.base_chroma_4); + reset2(&mut self.base_eob_luma_16); + reset2(&mut self.base_eob_luma_8); + reset2(&mut self.base_eob_chroma_8); + reset2(&mut self.base_eob_chroma_4); + reset2(&mut self.br_luma_16); + reset2(&mut self.br_luma_8); + reset2(&mut self.br_chroma_8); + reset2(&mut self.br_chroma_4); + reset2(&mut self.partition_w16); + reset2(&mut self.partition_w8); + reset2(&mut self.txb_skip_luma_32); + reset2(&mut self.txb_skip_luma_64); + reset2(&mut self.txb_skip_chroma_16); + reset2(&mut self.txb_skip_chroma_32); + reset1(&mut self.eob_pt_1024_luma); + reset1(&mut self.eob_pt_1024_chroma); + reset1(&mut self.eob_pt_256_chroma); + reset2(&mut self.eob_extra_luma_32); + reset2(&mut self.eob_extra_luma_64); + reset2(&mut self.eob_extra_chroma_16); + reset2(&mut self.eob_extra_chroma_32); + reset2(&mut self.base_luma_32); + reset2(&mut self.base_luma_64); + reset2(&mut self.base_chroma_16); + reset2(&mut self.base_chroma_32); + reset2(&mut self.base_eob_luma_32); + reset2(&mut self.base_eob_luma_64); + reset2(&mut self.base_eob_chroma_16); + reset2(&mut self.base_eob_chroma_32); + reset2(&mut self.br_luma_32); + reset2(&mut self.br_chroma_16); + reset2(&mut self.br_chroma_32); + reset2(&mut self.dc_sign_luma); + reset2(&mut self.intra_tx_type_16); + reset2(&mut self.intra_tx_type_8); + reset1(&mut self.inter_tx_type_32); + reset1(&mut self.inter_tx_type_16); + reset1(&mut self.inter_tx_type_8); + reset2(&mut self.dc_sign_chroma); + reset2(&mut self.intra_inter); + reset3(&mut self.single_ref); + reset2(&mut self.y_mode); + reset2(&mut self.new_mv); + reset2(&mut self.zero_mv); + reset2(&mut self.ref_mv); + reset2(&mut self.drl_mode); + reset1(&mut self.mv_joint); + self.mv_comp + .iter_mut() + .for_each(MvComponentCdfs::reset_counts); + reset2(&mut self.filter_intra); + reset1(&mut self.filter_intra_mode); + } + /// The defaults a key frame starts from (spec 8.4, `init_coeff_cdfs` and /// `init_non_coeff_cdfs`), for coefficient q-context `q_ctx` (0..=3, spec /// 8.3.2's `Get_Qctx`). The non-coefficient tables do not vary with the diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index c8249094..69d192ae 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -115,7 +115,7 @@ fn unsupported(what: impl Into) -> Error { /// The coefficient q-context a frame's `base_q_idx` picks its default CDFs /// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the /// same rule. -fn q_ctx_of(base_q_idx: u8) -> usize { +pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize { match base_q_idx { 0..=20 => 0, 21..=60 => 1, @@ -2078,6 +2078,41 @@ pub fn decode_key_frame_tile( cdef: &CdefParams, loop_filter: &LoopFilterParams, ) -> Result { + decode_key_frame_tile_with_cdfs( + data, + mi_cols, + mi_rows, + base_q_idx, + frame_width, + frame_height, + enable_filter_intra, + cdef, + loop_filter, + None, + ) + .map(|(picture, _)| picture) +} + +/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec +/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from +/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults +/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs, +/// since a key frame's own header always forces `primary_ref_frame == +/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table +/// alongside the picture, for the caller to save into whichever reference +/// slots this frame's `refresh_frame_flags` names. +pub(crate) fn decode_key_frame_tile_with_cdfs( + data: &[u8], + mi_cols: u32, + mi_rows: u32, + base_q_idx: u8, + frame_width: u32, + frame_height: u32, + enable_filter_intra: bool, + cdef: &CdefParams, + loop_filter: &LoopFilterParams, + initial_cdfs: Option, +) -> Result<(Picture, Cdfs)> { if mi_cols == 0 || mi_rows == 0 { return Err(unsupported("a frame with no mode-info grid")); } @@ -2113,7 +2148,7 @@ pub fn decode_key_frame_tile( let scan8 = default_scan(TX8); let scan4 = default_scan(TX4); - let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); + let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx))); if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( "TRACE key_tile_bytes len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}", @@ -2416,13 +2451,16 @@ pub fn decode_key_frame_tile( let (fw, fh) = (frame_width as usize, frame_height as usize); if fw == width && fh == height { - return Ok(Picture { - width, - height, - y: y.data, - u: u.data, - v: v.data, - }); + return Ok(( + Picture { + width, + height, + y: y.data, + u: u.data, + v: v.data, + }, + cdfs, + )); } let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec { let mut out = Vec::with_capacity(w * h); @@ -2431,13 +2469,16 @@ pub fn decode_key_frame_tile( } out }; - Ok(Picture { - width: fw, - height: fh, - y: crop(&y, fw, fh), - u: crop(&u, fw / 2, fh / 2), - v: crop(&v, fw / 2, fh / 2), - }) + Ok(( + Picture { + width: fw, + height: fh, + y: crop(&y, fw, fh), + u: crop(&u, fw / 2, fh / 2), + v: crop(&v, fw / 2, fh / 2), + }, + cdfs, + )) } /// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`), @@ -2468,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 } @@ -2494,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) } @@ -2609,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; @@ -2657,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 { @@ -2691,6 +2758,12 @@ fn decode_inter_block( }; (mv, false) }; + if std::env::var_os("EC_AV1_TRACE").is_some() { + eprintln!( + "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side}", + skip as u8, mv.0, mv.1 + ); + } for dr in 0..bw4 { for dc in 0..bw4 { grid.set( @@ -2997,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]`). @@ -3059,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 { @@ -3366,7 +3446,42 @@ 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, + mi_cols, + mi_rows, + base_q_idx, + frame_width, + frame_height, + reference, + cdef, + loop_filter, + None, + allow_high_precision_mv, + ) + .map(|(picture, _)| picture) +} + +/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see +/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned +/// end-of-tile table. An inter frame's own header can name +/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream), +/// so `None` is a real case here, not only a convenience default. +pub(crate) fn decode_inter_frame_tile_with_cdfs( + data: &[u8], + mi_cols: u32, + mi_rows: u32, + base_q_idx: u8, + frame_width: u32, + frame_height: u32, + reference: &Picture, + 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")); } @@ -3429,7 +3544,7 @@ pub fn decode_inter_frame_tile( let scan8 = default_scan(TX8); let scan4 = default_scan(TX4); - let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); + let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx))); let mut dec = SymbolDecoder::new(data); let mut neighbours = Neighbours::new( cols as usize * 2, @@ -3512,6 +3627,7 @@ pub fn decode_inter_frame_tile( &scan32, &scan16, 3, + allow_high_precision_mv, )?; } PARTITION_SPLIT => { @@ -3564,6 +3680,7 @@ pub fn decode_inter_frame_tile( &scan16, &scan8, 2, + allow_high_precision_mv, )?; } else { let ctx16 = neighbours.partition_ctx(at16, SUB); @@ -3612,6 +3729,7 @@ pub fn decode_inter_frame_tile( &scan8, &scan4, prev_leaf, + allow_high_precision_mv, )?; prev_leaf = Some((leaf_mi, skip, is_inter)); } @@ -3634,13 +3752,16 @@ pub fn decode_inter_frame_tile( let (fw, fh) = (frame_width as usize, frame_height as usize); if fw == width && fh == height { - return Ok(Picture { - width, - height, - y: y.data, - u: u.data, - v: v.data, - }); + return Ok(( + Picture { + width, + height, + y: y.data, + u: u.data, + v: v.data, + }, + cdfs, + )); } let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec { let mut out = Vec::with_capacity(w * h); @@ -3649,13 +3770,16 @@ pub fn decode_inter_frame_tile( } out }; - Ok(Picture { - width: fw, - height: fh, - y: crop(&y, fw, fh), - u: crop(&u, fw / 2, fh / 2), - v: crop(&v, fw / 2, fh / 2), - }) + Ok(( + Picture { + width: fw, + height: fh, + y: crop(&y, fw, fh), + u: crop(&u, fw / 2, fh / 2), + v: crop(&v, fw / 2, fh / 2), + }, + cdfs, + )) } #[cfg(test)] @@ -4085,6 +4209,7 @@ mod tests { &reference, &CdefParams::default(), &LoopFilterParams::default(), + false, ) .unwrap(); assert_eq!( @@ -4258,6 +4383,7 @@ mod tests { &[], &[], 0, + false, ) .unwrap(); @@ -4345,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 3f690203..cd0c8197 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -1,20 +1,31 @@ //! The stream-level entry point a real decoder needs: walk a raw AV1 OBU //! stream (`Encoded::stream`, or any low-overhead-format bitstream this //! crate's own writers produce) via [`ec_av1_syntax::Av1Parser`] and dispatch -//! each frame's tile payload to [`crate::decode::decode_key_frame_tile`] / -//! [`crate::decode::decode_inter_frame_tile`], threading a single-slot DPB -//! exactly as [`crate::encode::encode_sequence`] does on the write side. +//! each frame's tile payload to [`crate::decode::decode_key_frame_tile_with_cdfs`] / +//! [`crate::decode::decode_inter_frame_tile_with_cdfs`], threading a +//! single-slot picture DPB exactly as [`crate::encode::encode_sequence`] does +//! on the write side, plus the full 8-slot *CDF* reference bank spec 7.20 +//! (`load_cdfs`) and 7.4 (the reference frame update) describe: a frame whose +//! header names `primary_ref_frame != PRIMARY_REF_NONE` resumes from the +//! adapted table a previous frame's `refresh_frame_flags` left in that slot, +//! rather than the spec 8.4 defaults. //! //! This is the only reachable path for a caller that does not have the //! encoder's own `Encoded::tile`/`mi_cols`/`mi_rows`/`base_q_idx` fields (they //! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is //! an implementation detail of how this crate happens to build it). -use ec_av1_syntax::{Av1Parser, FrameType, ObuKind, TxMode, WarpModel}; +use ec_av1_syntax::{ + Av1Parser, FrameType, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE, TxMode, WarpModel, +}; use ec_core::{Error, Result}; +use crate::cdf_state::Cdfs; use crate::decode; -use crate::decode::{decode_inter_frame_tile, decode_key_frame_tile}; +use crate::decode::{ + decode_inter_frame_tile_with_cdfs, decode_key_frame_tile, decode_key_frame_tile_with_cdfs, + q_ctx_of, +}; use crate::encode::Picture; /// Decode every frame in a raw AV1 OBU stream, in coding order. @@ -35,7 +46,24 @@ use crate::encode::Picture; pub fn decode_stream(data: &[u8]) -> Result> { let mut parser = Av1Parser::new(); let mut pictures = Vec::new(); - let mut reference: Option = None; + // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a + // previous frame's `refresh_frame_flags` stored into it, exactly like the + // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`, + // not simply "the previous frame decoded"; a frame whose own predecessor + // didn't refresh that slot (an altref/hidden frame, or any GOP with more + // than one live reference) must keep predicting from whatever picture is + // still sitting there. Round 7's cdffwd hunt: a global `reference` + // overwritten every frame silently always used "the most recent decode" + // instead, producing a bit-exact motion vector into the WRONG picture -- + // luma-only (chroma coincidentally shares this fixture's flat regions) + // and small-magnitude (the two pictures mostly agree), which is exactly + // what made it look like a rounding bug rather than a wrong reference. + let mut ref_slots: [Option; NUM_REF_FRAMES] = std::array::from_fn(|_| None); + // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a + // previous frame's `refresh_frame_flags` stored into it -- the frame's + // own end-of-tile adapted table, or (when the frame set + // `disable_frame_end_update_cdf`) the table it started from, unchanged. + let mut cdf_slots: [Option; NUM_REF_FRAMES] = std::array::from_fn(|_| None); let mut pos = 0usize; while pos < data.len() { @@ -110,6 +138,18 @@ pub fn decode_stream(data: &[u8]) -> Result> { "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)", )); } + // Loop restoration carries per-restoration-unit symbols in the tile + // (spec 5.11.57 `read_lr`, one group per LR unit reached from the + // superblock walk) that this decoder never reads -- same + // silent-desync shape as the refusals above. Traced live 2026-08-27: + // an aomenc inter frame with `Sgrproj` on the V plane desynced the + // partition walk into out-of-alphabet garbage. + if header.loop_restoration.uses_lr { + return Err(Error::unsupported( + "AV1 decode_stream", + "a frame with loop restoration enabled (this decoder never reads the per-unit lr symbols)", + )); + } // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV` // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the @@ -125,6 +165,17 @@ pub fn decode_stream(data: &[u8]) -> Result> { "an inter frame whose LAST_FRAME global motion is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)", )); } + // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names + // which tile's end-of-tile adapted CDFs become the frame's own; this + // decoder only ever decodes tile 0 (`tiles.first()` above), so a + // multi-tile frame is refused rather than silently forwarding the + // wrong tile's table (or leaving the rest of the picture undecoded). + if header.tile_info.cols > 1 || header.tile_info.rows > 1 { + return Err(Error::unsupported( + "AV1 decode_stream", + "a frame with more than one tile (this decoder only ever decodes tile 0)", + )); + } // `Tile::offset` is relative to the buffer `parse_obu` was handed // (`&data[pos..]` at the time this OBU was parsed), so it is relative // to `obu_offset`, not to `data` as a whole. @@ -134,8 +185,25 @@ pub fn decode_stream(data: &[u8]) -> Result> { .sequence_header() .is_some_and(|seq| seq.enable_filter_intra); - let picture = if header.frame_type == FrameType::Key { - decode_key_frame_tile( + // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes + // from that reference slot's saved CDF state instead of the spec 8.4 + // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case + // builds. + let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE { + None + } else { + let slot = header.ref_frame_idx[header.primary_ref_frame as usize] as usize; + Some(cdf_slots[slot].clone().ok_or_else(|| { + Error::unsupported( + "AV1 decode_stream", + "a frame naming primary_ref_frame at a reference slot with no saved CDF state", + ) + })?) + }; + let started_from = initial_cdfs.clone(); + + let (picture, end_cdfs) = if header.frame_type == FrameType::Key { + decode_key_frame_tile_with_cdfs( tile_bytes, header.mi_cols, header.mi_rows, @@ -145,15 +213,17 @@ pub fn decode_stream(data: &[u8]) -> Result> { enable_filter_intra, &header.cdef, &header.loop_filter, + initial_cdfs, )? } else { - let reference = reference.as_ref().ok_or_else(|| { + let last_slot = header.ref_frame_idx[0] as usize; + let reference = ref_slots[last_slot].as_ref().ok_or_else(|| { Error::unsupported( "AV1 decode_stream", "an inter frame with no key frame before it", ) })?; - decode_inter_frame_tile( + decode_inter_frame_tile_with_cdfs( tile_bytes, header.mi_cols, header.mi_rows, @@ -163,9 +233,47 @@ pub fn decode_stream(data: &[u8]) -> Result> { reference, &header.cdef, &header.loop_filter, + initial_cdfs, + header.allow_high_precision_mv, )? }; - reference = Some(picture.clone()); + // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's + // *initial* table into the slots it refreshes, not the adapted + // end-of-tile one. + let stored_cdfs = if header.disable_frame_end_update_cdf { + started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx))) + } else { + // Spec 7.20 `save_cdfs` (libaom `av1_reset_cdf_symbol_counters`): + // the adapted table is saved with every symbol counter zeroed, + // not with the counts the tile's own decode left behind. + let mut end_cdfs = end_cdfs; + end_cdfs.reset_counts(); + end_cdfs + }; + if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") { + use std::io::Write; + if let Ok(mut f) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + { + let _ = writeln!(f, "=== frame idx={} ===", pictures.len()); + let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64); + let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32); + let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16); + let _ = writeln!(f, "skip {:?}", stored_cdfs.skip); + let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv); + let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv); + let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv); + let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint); + } + } + for i in 0..NUM_REF_FRAMES { + if header.refresh_frame_flags & (1 << i) != 0 { + cdf_slots[i] = Some(stored_cdfs.clone()); + ref_slots[i] = Some(picture.clone()); + } + } pictures.push(picture); } Ok(pictures) @@ -837,6 +945,10 @@ mod tests { "--enable-angle-delta=0", "--enable-tx-size-search=0", "--enable-cdef=0", + // Loop restoration is a named refusal (aomenc's RD picks + // Sgrproj on this kind of content) -- off in every recipe + // whose test targets a different surface. + "--enable-restoration=0", "--max-partition-size=32", "--enable-palette=0", "--enable-intrabc=0", @@ -964,6 +1076,10 @@ mod tests { "--enable-angle-delta=0", "--enable-tx-size-search=0", "--enable-cdef=0", + // Loop restoration is a named refusal (aomenc's RD picks + // Sgrproj on this kind of content) -- off in every recipe + // whose test targets a different surface. + "--enable-restoration=0", "--max-partition-size=32", "--enable-palette=0", "--enable-intrabc=0", @@ -1014,6 +1130,180 @@ mod tests { } } + /// The decisive cross-frame CDF forwarding test: identical to + /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`] + /// except it drops `--error-resilient=1`, so aomenc codes every inter + /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`) + /// and expects the decoder to resume from the previous frame's *adapted* + /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding, + /// frame 1's very first tile symbol desyncs (an out-of-alphabet + /// partition read); with it, every frame decodes pixel-exact. + #[test] + fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() { + if !have_ffmpeg() { + eprintln!( + "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg" + ); + return; + } + if !have_aomenc() { + eprintln!( + "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}", + aomenc_path().display() + ); + return; + } + let (width, height, frame_count) = (64usize, 64usize, 4usize); + // aomenc's RD is nondeterministic run to run even on a fixed fixture: + // most encodes of this recipe trip one of the decoder's NAMED round-2 + // refusals (a reference other than LAST_FRAME, a sub-16 partition -- + // genuine coverage gaps, separately documented), and only some produce + // a stream fully inside this decoder's declared support. So: attempt + // several seeds, and the first stream that DECODES must be pixel-exact + // -- that assertion is what guards the forwarded-CDF state (a wrong + // table decodes plausible-but-wrong pixels; the counter-reset bug this + // gate caught did exactly that). Exhausting every attempt on named + // refusals skips loudly, listing them. + let mut refusals = Vec::new(); + for attempt in 0..8u32 { + let seed = 42 + attempt; + let source = format!("gradients=size=64x64:seed={seed}:duration=0.16:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=55", + "--cpu-used=0", + "--lag-in-frames=0", + "--auto-alt-ref=0", + "--kf-max-dist=1000", + // `--threads=1` (not the default): a multithreaded RD search + // makes aomenc's screen-content-tools heuristic race (seen + // flaky under `cargo test`'s own parallelism -- the same + // fixture, same seed, occasionally sets + // `allow_screen_content_tools`, a round-2 gap unrelated to + // CDF forwarding), so pin it to one thread for a + // deterministic header. + "--threads=1", + "--row-mt=0", + // No `--error-resilient=1` here (that is the whole point of + // this test), but every other reference/compound tool this + // decoder's round-2 inter path does not model is still + // disabled the same way `--error-resilient=1` incidentally + // disabled it in the sibling test above: without + // `--enable-order-hint=0` aomenc's RD search picks a + // non-`LAST_FRAME` reference (`GOLDEN_FRAME`) for some + // blocks even in this short a sequence, which is a separate, + // already-documented round-2 gap ("a reference frame other + // than LAST_FRAME"), not a CDF-forwarding one. + "--enable-order-hint=0", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-dist-wtd-comp=0", + "--enable-diff-wtd-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + // Loop restoration is a named refusal (aomenc's RD picks + // Sgrproj on this kind of content) -- off in every recipe + // whose test targets a different surface. + "--enable-restoration=0", + "--max-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--obu", + "-o", + "-", + "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + // A named `unsupported` refusal is a documented coverage gap (each + // one carries its own test debt elsewhere), not a forwarding verdict + // -- try the next seed. Any stream that DECODES must be pixel-exact, + // and any non-refusal error is a hard failure. + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "cross-frame CDF forwarding failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + Ok(frames) => frames, + }; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + assert_eq!(frames.len(), frame_count); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); + } + return; + } + eprintln!( + "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: every \ + attempt hit a named refusal:\n{}", + refusals.join("\n") + ); + } + /// scratch: isolate a pinned mismatching stream's first divergent pixel. #[test] #[ignore] @@ -1035,51 +1325,60 @@ mod tests { ); eprintln!("delta: {:?}", header.delta); 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: {:?} 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, + ); } } } - let width = 32; - let height = 32; + let width = std::env::var("EC_AV1_PIN_W") + .map(|s| s.parse().unwrap()) + .unwrap_or(64); + let height = std::env::var("EC_AV1_PIN_H") + .map(|s| s.parse().unwrap()) + .unwrap_or(64); + let frame_count = std::env::var("EC_AV1_PIN_N") + .map(|s| s.parse().unwrap()) + .unwrap_or(4); let frames = decode_stream(&stream).expect("our decode"); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); - let ours = &frames[0]; - let theirs = &ffmpeg_frames[0]; - for (plane_name, a, b, w) in [ - ("y", &ours.y, &theirs.y, width), - ("u", &ours.u, &theirs.u, width / 2), - ("v", &ours.v, &theirs.v, width / 2), - ] { - let mut first = None; - let mut count = 0; - for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() { - if x != y { - count += 1; - if first.is_none() { - first = Some(i); + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + for f in 0..frame_count.min(frames.len()).min(ffmpeg_frames.len()) { + let ours = &frames[f]; + let theirs = &ffmpeg_frames[f]; + for (plane_name, a, b, w) in [ + ("y", &ours.y, &theirs.y, width), + ("u", &ours.u, &theirs.u, width / 2), + ("v", &ours.v, &theirs.v, width / 2), + ] { + let mut first = None; + let mut count = 0; + for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() { + if x != y { + count += 1; + if first.is_none() { + first = Some(i); + } } } + if let Some(i) = first { + eprintln!( + "frame {f} plane {plane_name}: {count} mismatches, first at offset {i} (row {}, col {}) ours={} theirs={}", + i / w, + i % w, + a[i], + b[i] + ); + } else { + eprintln!("frame {f} plane {plane_name}: MATCH"); + } } - if let Some(i) = first { - eprintln!( - "plane {plane_name}: {count} mismatches, first at offset {i} (row {}, col {}) ours={} theirs={}", - i / w, - i % w, - a[i], - b[i] - ); - } else { - eprintln!("plane {plane_name}: MATCH"); - } - } - for row in 0..8 { - eprintln!( - "ours row{row}: {:?}", - &ours.y[row * width..row * width + 8] - ); - eprintln!( - "theirs row{row}: {:?}", - &theirs.y[row * width..row * width + 8] - ); } } }