From 8a54f53612bb1aeef7c192bf29ab06f9046f1b08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 03:05:50 +0300 Subject: [PATCH] feat(av1): the tile adapts its CDFs as it writes AV1's symbol decoder updates every non-literal CDF it reads, so an encoder that leaves `disable_cdf_update` off has to keep the same state and update it in the same order. This adds that state and writes the key frame's tile through it. Tables the decoder keeps one copy of are one copy here too: a 64x64 luma transform reads the 32x32 base-range rows, both luma sets share one DC sign and one 1024-position end-of-block table, and both chroma sets share their own sign table. The gathered partition CDF an edge superblock reads is built for the read and thrown away, so nothing adapts there. The coefficient rate term still prices against the defaults: the mode search runs before the tile is written, so the adapted state does not exist yet. BD-rate against the same encoder with adaptation off, over a three-point ladder: -3.52% on a 1080p film frame, -5.63% on a screen capture, -11.25% on the test card. The ffmpeg/dav1d roundtrips are the gate -- a decoder adapting its own tables desyncs the moment the order or the sharing differs. --- crates/ec-av1/src/cdf_state.rs | 255 +++++++++++++++++++++++++++++++++ crates/ec-av1/src/encode.rs | 7 +- crates/ec-av1/src/lib.rs | 1 + crates/ec-av1/src/tile.rs | 199 +++++++++++-------------- lanes/av1-cdf-r1.report.md | 63 ++++++++ 5 files changed, 408 insertions(+), 117 deletions(-) create mode 100644 crates/ec-av1/src/cdf_state.rs create mode 100644 lanes/av1-cdf-r1.report.md diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs new file mode 100644 index 00000000..20c15643 --- /dev/null +++ b/crates/ec-av1/src/cdf_state.rs @@ -0,0 +1,255 @@ +//! The CDFs a tile adapts as it is written. +//! +//! AV1's symbol decoder updates every non-literal CDF it reads (spec 8.3.2), +//! so an encoder that wants `disable_cdf_update` off has to keep the same +//! state and update it in the same order. What lives here is that state: one +//! owned copy of each table the tile writer touches, seeded from the defaults +//! in [`crate::cdf`]. +//! +//! The tables are owned once, not once per use: two coefficient table sets +//! that share a table -- a 64x64 luma transform reads the 32x32 base-range +//! rows, and both luma sets read the same DC sign table -- share the *adapted* +//! table too, which is what the decoder does. + +use crate::cdf; + +/// Which of the four coefficient table sets a transform block is coded with. +#[derive(Clone, Copy)] +pub(crate) enum TxbSet { + /// The 32x32 luma transform of a 32x32 block. + Luma32, + /// The 64x64 luma transform of a whole superblock, scanned as a 32x32. + Luma64, + /// The 16x16 transform of a chroma plane of a 32x32 block. + Chroma16, + /// The 32x32 transform of a chroma plane of a whole superblock. + Chroma32, +} + +/// The tables one transform block is coded with, borrowed from the state for +/// as long as that block is being written. +pub(crate) struct TxbTables<'a> { + /// Side of the transform, in coefficients. + pub side: usize, + /// The all-zero flag, indexed by its own context. + pub txb_skip: &'a mut [[u16; 3]], + /// The end-of-block group, whose alphabet the transform size sets. + pub eob_pt: &'a mut [u16], + /// The top bit of the offset inside that group. + pub eob_extra: &'a mut [[u16; 3]; 9], + /// A coefficient's base level. + pub base: &'a mut [[u16; 5]; 42], + /// The base level of the last coefficient in the scan. + pub base_eob: &'a mut [[u16; 4]; 4], + /// The base-range tail above level two. + pub br: &'a mut [[u16; 5]; 21], + /// The sign of the DC. + pub dc_sign: &'a mut [[u16; 3]; 3], +} + +/// Every table a key frame's tile writer adapts. +pub(crate) struct Cdfs { + /// The partition symbol of a 64x64 superblock. + pub partition_w64: [[u16; 11]; 4], + /// The partition symbol of a 32x32 block. + pub partition_w32: [[u16; 11]; 4], + /// Whether a block carries no residual at all. + pub skip: [[u16; 3]; 3], + /// The luma mode of a key frame's block, under the two neighbours' modes. + pub kf_y_mode: [[[u16; 14]; 5]; 5], + /// The chroma mode of a block too big to be offered chroma from luma. + pub uv_mode_no_cfl: [[u16; 14]; 13], + /// The chroma mode of a block that is offered it. + pub uv_mode_cfl: [[u16; 15]; 13], + /// The angle a directional mode is nudged by. + pub angle_delta: [[u16; 8]; 8], + /// The one-context all-zero flag of a 32x32 luma transform. + pub txb_skip_luma_32: [[u16; 3]; 1], + /// The same, for a 64x64 luma transform. + pub txb_skip_luma_64: [[u16; 3]; 1], + /// The all-zero flag of a 16x16 chroma transform. + pub txb_skip_chroma_16: [[u16; 3]; 3], + /// The all-zero flag of a 32x32 chroma transform. + pub txb_skip_chroma_32: [[u16; 3]; 3], + /// The end-of-block group of a luma transform of 1024 positions. + pub eob_pt_1024_luma: [u16; 12], + /// The same, for chroma. + pub eob_pt_1024_chroma: [u16; 12], + /// The end-of-block group of a 16x16 chroma transform. + pub eob_pt_256_chroma: [u16; 10], + /// The end-of-block offset bit, per table set. + pub eob_extra_luma_32: [[u16; 3]; 9], + /// The same, for a 64x64 luma transform. + pub eob_extra_luma_64: [[u16; 3]; 9], + /// The same, for a 16x16 chroma transform. + pub eob_extra_chroma_16: [[u16; 3]; 9], + /// The same, for a 32x32 chroma transform. + pub eob_extra_chroma_32: [[u16; 3]; 9], + /// The base level of a 32x32 luma coefficient. + pub base_luma_32: [[u16; 5]; 42], + /// The base level of a 64x64 luma coefficient. + pub base_luma_64: [[u16; 5]; 42], + /// The base level of a 16x16 chroma coefficient. + pub base_chroma_16: [[u16; 5]; 42], + /// The base level of a 32x32 chroma coefficient. + pub base_chroma_32: [[u16; 5]; 42], + /// The last coefficient's base level, per table set. + pub base_eob_luma_32: [[u16; 4]; 4], + /// The same, for a 64x64 luma transform. + pub base_eob_luma_64: [[u16; 4]; 4], + /// The same, for a 16x16 chroma transform. + pub base_eob_chroma_16: [[u16; 4]; 4], + /// The same, for a 32x32 chroma transform. + pub base_eob_chroma_32: [[u16; 4]; 4], + /// The base-range tail of a luma coefficient, which a 64x64 transform + /// reads too because its index is clamped at the 32x32 size. + pub br_luma_32: [[u16; 5]; 21], + /// The base-range tail of a 16x16 chroma coefficient. + pub br_chroma_16: [[u16; 5]; 21], + /// The base-range tail of a 32x32 chroma coefficient. + pub br_chroma_32: [[u16; 5]; 21], + /// The DC sign of a luma coefficient, shared by both luma sets. + pub dc_sign_luma: [[u16; 3]; 3], + /// The DC sign of a chroma coefficient, shared by both chroma sets. + pub dc_sign_chroma: [[u16; 3]; 3], +} + +impl Cdfs { + /// The defaults a key frame starts from (spec 8.4, `init_coeff_cdfs` and + /// `init_non_coeff_cdfs`), for the one quantizer context whose tables this + /// crate carries. + pub fn new() -> Cdfs { + Cdfs { + partition_w64: cdf::PARTITION_W64, + partition_w32: cdf::PARTITION_W32, + skip: cdf::SKIP, + kf_y_mode: cdf::KF_Y_MODE, + uv_mode_no_cfl: cdf::UV_MODE_NO_CFL, + uv_mode_cfl: cdf::UV_MODE_CFL, + angle_delta: cdf::ANGLE_DELTA, + txb_skip_luma_32: [cdf::TXB_SKIP_LUMA_32], + txb_skip_luma_64: [cdf::TXB_SKIP_LUMA_64], + txb_skip_chroma_16: cdf::TXB_SKIP_CHROMA_16, + txb_skip_chroma_32: cdf::TXB_SKIP_CHROMA_32, + eob_pt_1024_luma: cdf::EOB_PT_1024_LUMA, + eob_pt_1024_chroma: cdf::EOB_PT_1024_CHROMA, + eob_pt_256_chroma: cdf::EOB_PT_256_CHROMA, + eob_extra_luma_32: cdf::EOB_EXTRA_LUMA_32, + eob_extra_luma_64: cdf::EOB_EXTRA_LUMA_64, + eob_extra_chroma_16: cdf::EOB_EXTRA_CHROMA_16, + eob_extra_chroma_32: cdf::EOB_EXTRA_CHROMA_32, + base_luma_32: cdf::COEFF_BASE_LUMA_32, + base_luma_64: cdf::COEFF_BASE_LUMA_64, + base_chroma_16: cdf::COEFF_BASE_CHROMA_16, + base_chroma_32: cdf::COEFF_BASE_CHROMA_32, + base_eob_luma_32: cdf::COEFF_BASE_EOB_LUMA_32, + base_eob_luma_64: cdf::COEFF_BASE_EOB_LUMA_64, + base_eob_chroma_16: cdf::COEFF_BASE_EOB_CHROMA_16, + base_eob_chroma_32: cdf::COEFF_BASE_EOB_CHROMA_32, + br_luma_32: cdf::COEFF_BR_LUMA_32, + br_chroma_16: cdf::COEFF_BR_CHROMA_16, + br_chroma_32: cdf::COEFF_BR_CHROMA_32, + dc_sign_luma: cdf::DC_SIGN_LUMA, + dc_sign_chroma: cdf::DC_SIGN_CHROMA, + } + } + + /// The tables one table set is coded with, borrowed out of the state. + pub fn txb(&mut self, set: TxbSet) -> TxbTables<'_> { + match set { + TxbSet::Luma32 => TxbTables { + side: 32, + txb_skip: &mut self.txb_skip_luma_32, + eob_pt: &mut self.eob_pt_1024_luma, + eob_extra: &mut self.eob_extra_luma_32, + base: &mut self.base_luma_32, + base_eob: &mut self.base_eob_luma_32, + br: &mut self.br_luma_32, + dc_sign: &mut self.dc_sign_luma, + }, + TxbSet::Luma64 => TxbTables { + side: 32, + txb_skip: &mut self.txb_skip_luma_64, + eob_pt: &mut self.eob_pt_1024_luma, + eob_extra: &mut self.eob_extra_luma_64, + base: &mut self.base_luma_64, + base_eob: &mut self.base_eob_luma_64, + br: &mut self.br_luma_32, + dc_sign: &mut self.dc_sign_luma, + }, + TxbSet::Chroma16 => TxbTables { + side: 16, + txb_skip: &mut self.txb_skip_chroma_16, + eob_pt: &mut self.eob_pt_256_chroma, + eob_extra: &mut self.eob_extra_chroma_16, + base: &mut self.base_chroma_16, + base_eob: &mut self.base_eob_chroma_16, + br: &mut self.br_chroma_16, + dc_sign: &mut self.dc_sign_chroma, + }, + TxbSet::Chroma32 => TxbTables { + side: 32, + txb_skip: &mut self.txb_skip_chroma_32, + eob_pt: &mut self.eob_pt_1024_chroma, + eob_extra: &mut self.eob_extra_chroma_32, + base: &mut self.base_chroma_32, + base_eob: &mut self.base_eob_chroma_32, + br: &mut self.br_chroma_32, + dc_sign: &mut self.dc_sign_chroma, + }, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A 64x64 luma transform reads the 32x32 base-range rows, so the two sets + /// have to adapt the same table: a decoder keeps one copy, and an encoder + /// that kept two would drift away from it the first time a level above two + /// was coded. + #[test] + fn the_two_luma_sets_share_the_base_range_table() { + let mut cdfs = Cdfs::new(); + cdfs.txb(TxbSet::Luma64).br[0][0] = 1; + assert_eq!(cdfs.txb(TxbSet::Luma32).br[0][0], 1); + } + + /// Both luma sets read one DC sign table, and both chroma sets another; + /// what a luma block adapts must not reach the chroma one. + #[test] + fn the_sign_tables_are_shared_within_a_plane_type_and_not_across() { + let mut cdfs = Cdfs::new(); + cdfs.txb(TxbSet::Luma32).dc_sign[1][0] = 1; + cdfs.txb(TxbSet::Chroma16).dc_sign[2][0] = 2; + assert_eq!(cdfs.txb(TxbSet::Luma64).dc_sign[1][0], 1); + assert_eq!(cdfs.txb(TxbSet::Chroma32).dc_sign[2][0], 2); + assert_ne!(cdfs.txb(TxbSet::Chroma32).dc_sign[1][0], 1); + assert_ne!(cdfs.txb(TxbSet::Luma64).dc_sign[2][0], 2); + } + + /// The end-of-block table a 1024-position transform reads is shared by both + /// luma sets and separate from chroma's, which is the same hazard one table + /// further along. + #[test] + fn the_luma_end_of_block_table_is_shared_and_chromas_is_not() { + let mut cdfs = Cdfs::new(); + cdfs.txb(TxbSet::Luma32).eob_pt[0] = 7; + assert_eq!(cdfs.txb(TxbSet::Luma64).eob_pt[0], 7); + assert_ne!(cdfs.txb(TxbSet::Chroma32).eob_pt[0], 7); + } + + /// Every set starts from the spec's defaults, so a tile that adapts nothing + /// writes exactly what a non-adapting one does. + #[test] + fn the_state_starts_at_the_defaults() { + let mut cdfs = Cdfs::new(); + assert_eq!(cdfs.txb(TxbSet::Luma32).base[3], cdf::COEFF_BASE_LUMA_32[3]); + assert_eq!( + cdfs.txb(TxbSet::Chroma16).eob_extra[2], + cdf::EOB_EXTRA_CHROMA_16[2] + ); + assert_eq!(cdfs.partition_w64[2], cdf::PARTITION_W64[2]); + } +} diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 92653b42..4230d895 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -199,7 +199,12 @@ pub fn key_frame_headers( frame_is_intra: true, show_frame: true, error_resilient_mode: true, - disable_cdf_update: true, + // The tile writer keeps the same CDF state the decoder does and + // updates it in the same order, so the frame lets the decoder adapt. + disable_cdf_update: false, + // Nothing reads the state this frame leaves behind: a key frame always + // starts from the defaults, and this encoder emits one frame. + disable_frame_end_update_cdf: true, force_integer_mv: true, refresh_frame_flags: 0xFF, primary_ref_frame: PRIMARY_REF_NONE, diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index b4753a8e..0d8e4e1e 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -14,6 +14,7 @@ pub mod bits; pub mod cdf; +mod cdf_state; pub mod encode; pub mod frame; pub mod intra; diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 7d043e61..4635ccb8 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -14,6 +14,7 @@ use std::sync::LazyLock; use ec_core::{Error, Result}; use crate::cdf; +use crate::cdf_state::{Cdfs, TxbSet, TxbTables}; use crate::msac::SymbolEncoder; /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided. @@ -365,90 +366,6 @@ const TX32: usize = 32; /// Side of the chroma transform beside it at 4:2:0. const TX16: usize = 16; -/// The shapes and default CDFs one plane's transform blocks are coded with. -/// The two differ in every coefficient table because the CDFs are indexed by -/// plane type and transform size, and in the end-of-block alphabet because a -/// 16x16 transform has a quarter of the positions to point at. -struct TxbCoding { - /// Side of the transform, in coefficients. - side: usize, - /// The all-zero flag, indexed by its own context. - txb_skip: &'static [[u16; 3]], - /// The end-of-block group, whose alphabet the transform size sets. - eob_pt: &'static [u16], - /// The top bit of the offset inside that group. - eob_extra: &'static [[u16; 3]; 9], - /// A coefficient's base level. - base: &'static [[u16; 5]; 42], - /// The base level of the last coefficient in the scan. - base_eob: &'static [[u16; 4]; 4], - /// The base-range tail above level two. - br: &'static [[u16; 5]; 21], - /// The sign of the DC. - dc_sign: &'static [[u16; 3]; 3], -} - -/// The luma all-zero flag has one context here: the transform covers its whole -/// block, which fixes it at zero. -const TXB_SKIP_LUMA_32_CTX: [[u16; 3]; 1] = [cdf::TXB_SKIP_LUMA_32]; - -/// The 32x32 luma transform of a 32x32 block. -const LUMA_32: TxbCoding = TxbCoding { - side: TX32, - txb_skip: &TXB_SKIP_LUMA_32_CTX, - eob_pt: &cdf::EOB_PT_1024_LUMA, - eob_extra: &cdf::EOB_EXTRA_LUMA_32, - base: &cdf::COEFF_BASE_LUMA_32, - base_eob: &cdf::COEFF_BASE_EOB_LUMA_32, - br: &cdf::COEFF_BR_LUMA_32, - dc_sign: &cdf::DC_SIGN_LUMA, -}; - -/// The 16x16 transform of either chroma plane of that block at 4:2:0. -const CHROMA_16: TxbCoding = TxbCoding { - side: TX16, - txb_skip: &cdf::TXB_SKIP_CHROMA_16, - eob_pt: &cdf::EOB_PT_256_CHROMA, - eob_extra: &cdf::EOB_EXTRA_CHROMA_16, - base: &cdf::COEFF_BASE_CHROMA_16, - base_eob: &cdf::COEFF_BASE_EOB_CHROMA_16, - br: &cdf::COEFF_BR_CHROMA_16, - dc_sign: &cdf::DC_SIGN_CHROMA, -}; - -/// The luma all-zero flag of a 64x64 transform, whose one context is fixed the -/// way [`TXB_SKIP_LUMA_32_CTX`] is. -const TXB_SKIP_LUMA_64_CTX: [[u16; 3]; 1] = [cdf::TXB_SKIP_LUMA_64]; - -/// The 64x64 luma transform of a whole superblock. Only its top-left 32x32 -/// carries coefficients, so it is scanned and its end-of-block position read -/// as a 32x32 transform is; what it does not share with [`LUMA_32`] is every -/// coefficient CDF, which is indexed by the transform size. -const LUMA_64: TxbCoding = TxbCoding { - side: TX32, - txb_skip: &TXB_SKIP_LUMA_64_CTX, - eob_pt: &cdf::EOB_PT_1024_LUMA, - eob_extra: &cdf::EOB_EXTRA_LUMA_64, - base: &cdf::COEFF_BASE_LUMA_64, - base_eob: &cdf::COEFF_BASE_EOB_LUMA_64, - // The base-range tail is the one table a 64x64 transform does not have of - // its own: the index is clamped at the 32x32 size, so it reads that row. - br: &cdf::COEFF_BR_LUMA_32, - dc_sign: &cdf::DC_SIGN_LUMA, -}; - -/// The 32x32 transform of either chroma plane of that superblock at 4:2:0. -const CHROMA_32: TxbCoding = TxbCoding { - side: TX32, - txb_skip: &cdf::TXB_SKIP_CHROMA_32, - eob_pt: &cdf::EOB_PT_1024_CHROMA, - eob_extra: &cdf::EOB_EXTRA_CHROMA_32, - base: &cdf::COEFF_BASE_CHROMA_32, - base_eob: &cdf::COEFF_BASE_EOB_CHROMA_32, - br: &cdf::COEFF_BR_CHROMA_32, - dc_sign: &cdf::DC_SIGN_CHROMA, -}; - /// What one coded block leaves behind for the blocks that read it as a /// neighbour: whether it coded anything at all, and the sign of its DC. #[derive(Clone, Copy, Default)] @@ -556,8 +473,8 @@ pub fn sb_coeff_key_frame_tile( )); } - let split_planes = [&LUMA_32, &CHROMA_16, &CHROMA_16]; - let whole_planes = [&LUMA_64, &CHROMA_32, &CHROMA_32]; + let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16]; + let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32]; let scans = [default_scan(TX32), default_scan(TX16)]; // What the blocks above and to the left of the one being coded left // behind, per plane, one entry per 32x32 column and row. The left column @@ -579,6 +496,10 @@ pub fn sb_coeff_key_frame_tile( let mut above_split = vec![false; cols as usize]; let mut left_split = vec![false; rows as usize]; + // The tile adapts every non-literal CDF it writes, exactly as the decoder + // adapts the ones it reads, so the frame header leaves `disable_cdf_update` + // off. + let mut cdfs = Cdfs::new(); let mut enc = SymbolEncoder::new(); for sb_r in 0..sb_rows { left.iter_mut().for_each(|l| *l = Default::default()); @@ -611,15 +532,16 @@ pub fn sb_coeff_key_frame_tile( "a superblock that is half outside the frame cannot be left whole", )); } - enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[ctx]); + enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]); let mode = write_intra_mode( &mut enc, + &mut cdfs, block, above_mode[c0], left_mode[r0], // A 64x64 block is too big to be offered chroma from // luma, so its chroma mode reads the table without it. - &cdf::UV_MODE_NO_CFL[usize::from(block.mode)], + false, ); let grids = [ level_grid(&block.luma, TX32)?, @@ -628,6 +550,7 @@ pub fn sb_coeff_key_frame_tile( ]; write_block_planes( &mut enc, + &mut cdfs, &whole_planes, &grids, &[&scans[0], &scans[0], &scans[0]], @@ -650,12 +573,15 @@ pub fn sb_coeff_key_frame_tile( } Superblock::Split(blocks) => { match (has_cols, has_rows) { - (true, true) => enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]), + (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]), + // The gathered CDF an edge superblock reads is built + // for the read and thrown away: the decoder never + // stores it back, so nothing adapts here. (true, false) => { - enc.symbol_fixed(1, &gather(&cdf::PARTITION_W64[ctx], VERT_ALIKE)); + enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], VERT_ALIKE)); } (false, true) => { - enc.symbol_fixed(1, &gather(&cdf::PARTITION_W64[ctx], HORZ_ALIKE)); + enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], HORZ_ALIKE)); } (false, false) => {} } @@ -666,13 +592,14 @@ pub fn sb_coeff_key_frame_tile( )); } for (block, (r, c)) in blocks.iter().zip(quadrants) { - enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]); + enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]); let mode = write_intra_mode( &mut enc, + &mut cdfs, block, above_mode[c], left_mode[r], - &cdf::UV_MODE_CFL[usize::from(block.mode)], + true, ); let grids = [ level_grid(&block.luma, TX32)?, @@ -681,6 +608,7 @@ pub fn sb_coeff_key_frame_tile( ]; write_block_planes( &mut enc, + &mut cdfs, &split_planes, &grids, &[&scans[0], &scans[1], &scans[1]], @@ -710,21 +638,28 @@ pub fn sb_coeff_key_frame_tile( /// the luma mode, which is what the blocks beside it read. fn write_intra_mode( enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, block: &BlockCoeffs, above_mode: usize, left_mode: usize, - uv_cdf: &[u16], + cfl: bool, ) -> usize { let mode = usize::from(block.mode); - enc.symbol_fixed(0, &cdf::SKIP[0]); - enc.symbol_fixed( + enc.symbol(0, &mut cdfs.skip[0]); + enc.symbol( mode, - &cdf::KF_Y_MODE[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]], + &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]], ); if (V_PRED..=D67_PRED).contains(&mode) { - enc.symbol_fixed(ANGLE_DELTA_ZERO, &cdf::ANGLE_DELTA[mode - V_PRED]); + enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]); + } + // A block small enough to be offered chroma from luma reads the wider + // table even when it does not take the mode. + if cfl { + enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]); + } else { + enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[mode]); } - enc.symbol_fixed(DC_PRED, uv_cdf); mode } @@ -732,7 +667,8 @@ fn write_intra_mode( /// decoder reads them. fn write_block_planes( enc: &mut SymbolEncoder, - planes: &[&TxbCoding; 3], + cdfs: &mut Cdfs, + planes: &[TxbSet; 3], grids: &[Vec; 3], scans: &[&Vec; 3], above: &[Neighbour; 3], @@ -750,7 +686,7 @@ fn write_block_planes( }; write_coeffs( enc, - planes[plane], + &mut cdfs.txb(planes[plane]), grid, scans[plane], skip_ctx, @@ -878,7 +814,17 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { static SCAN: LazyLock> = LazyLock::new(|| default_scan(TX32)); let mut enc = SymbolEncoder::new(); enc.reset_bits(); - write_coeffs(&mut enc, &LUMA_32, grid, &SCAN, 0, 0); + // The search runs before the tile is written, so the adapted state the + // block will really be coded against does not exist yet: the price is + // taken against the defaults every tile starts from. + write_coeffs( + &mut enc, + &mut Cdfs::new().txb(TxbSet::Luma32), + grid, + &SCAN, + 0, + 0, + ); enc.bits() } @@ -891,7 +837,7 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { /// already has. fn write_coeffs( enc: &mut SymbolEncoder, - coding: &TxbCoding, + coding: &mut TxbTables, grid: &[i32], scan: &[u16], skip_ctx: usize, @@ -902,7 +848,7 @@ fn write_coeffs( .iter() .rposition(|&pos| grid[pos as usize] != 0) .map_or(0, |i| i + 1); - enc.symbol_fixed(usize::from(eob == 0), &coding.txb_skip[skip_ctx]); + enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]); if eob == 0 { return; } @@ -915,13 +861,16 @@ fn write_coeffs( let level = grid[pos].abs(); if scan_idx == eob - 1 { let ctx = eob_coeff_ctx(scan_idx, side * side); - enc.symbol_fixed( + enc.symbol( (level.min(NUM_BASE_LEVELS + 1) - 1) as usize, - &coding.base_eob[ctx], + &mut coding.base_eob[ctx], ); } else { let ctx = base_ctx(grid, side, row, col); - enc.symbol_fixed(level.min(NUM_BASE_LEVELS + 1) as usize, &coding.base[ctx]); + enc.symbol( + level.min(NUM_BASE_LEVELS + 1) as usize, + &mut coding.base[ctx], + ); } if level > NUM_BASE_LEVELS { let ctx = br_ctx(grid, side, row, col); @@ -929,7 +878,7 @@ fn write_coeffs( let mut sent = 0; while sent < COEFF_BASE_RANGE { let k = remaining.min(BR_STEP); - enc.symbol_fixed(k as usize, &coding.br[ctx]); + enc.symbol(k as usize, &mut coding.br[ctx]); if k < BR_STEP { break; } @@ -947,7 +896,7 @@ fn write_coeffs( continue; } if pos == 0 { - enc.symbol_fixed(usize::from(level < 0), &coding.dc_sign[sign_ctx]); + enc.symbol(usize::from(level < 0), &mut coding.dc_sign[sign_ctx]); } else { enc.literal(u32::from(level < 0), 1); } @@ -962,7 +911,7 @@ fn write_coeffs( /// The end-of-block position (spec 5.11.39): which group of scan positions the /// last coded coefficient falls in, then its offset inside that group — the /// offset's top bit from a CDF and the rest as raw bits. -fn write_eob(enc: &mut SymbolEncoder, coding: &TxbCoding, eob: usize) { +fn write_eob(enc: &mut SymbolEncoder, coding: &mut TxbTables, eob: usize) { /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of /// end-of-block positions covers, indexed by the group's own number. const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513]; @@ -975,13 +924,13 @@ fn write_eob(enc: &mut SymbolEncoder, coding: &TxbCoding, eob: usize) { .expect("the first group starts at zero"); // The groups are numbered from one, and how many of them the transform // reaches is the size of its own end-of-block alphabet. - enc.symbol_fixed(group - 1, coding.eob_pt); + enc.symbol(group - 1, coding.eob_pt); let bits = OFFSET_BITS[group]; if bits > 0 { let offset = (eob - GROUP_START[group]) as u32; let top = (offset >> (bits - 1)) & 1; - enc.symbol_fixed(top as usize, &coding.eob_extra[group - 3]); + enc.symbol(top as usize, &mut coding.eob_extra[group - 3]); if bits > 1 { enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1); } @@ -1387,7 +1336,10 @@ mod tests { /// hand back the decoded planes. fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec { let (w, h) = (64 * sb_cols, 64 * sb_rows); - let (seq, header) = frame_of(w, h); + let (seq, mut header) = frame_of(w, h); + // The DC fixture writers code against the default CDFs and never + // update them, so their frames say so. + header.disable_cdf_update = true; let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap(); let mut stream = temporal_delimiter(); stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); @@ -1402,6 +1354,8 @@ mod tests { seq.max_frame_width = w; seq.max_frame_height = h; let mut header = flat_key_frame(); + // Every tile these headers carry is written by the adapting writer. + header.disable_cdf_update = false; header.frame_width = w; header.frame_height = h; header.upscaled_width = w; @@ -1580,7 +1534,10 @@ mod tests { /// Encode a grid of 32x32 blocks, each carrying its own DC level. fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec { let (w, h) = (64 * sb_cols, 64 * sb_rows); - let (seq, header) = frame_of(w, h); + let (seq, mut header) = frame_of(w, h); + // The DC fixture writers code against the default CDFs and never + // update them, so their frames say so. + header.disable_cdf_update = true; let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap(); let mut stream = temporal_delimiter(); stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); @@ -1836,7 +1793,14 @@ mod tests { let mut enc = SymbolEncoder::new(); let mut priced = 0.0; for grid in &grids { - write_coeffs(&mut enc, &LUMA_32, grid, &scan, 0, 0); + write_coeffs( + &mut enc, + &mut Cdfs::new().txb(TxbSet::Luma32), + grid, + &scan, + 0, + 0, + ); priced += luma_32_coeff_bits(grid); } let spent = enc.finish().len() as f64 * 8.0; @@ -1872,7 +1836,10 @@ mod tests { // An empty block is one symbol -- an expensive one, because a block // with no coefficients at all is the rarer of the two under the // neutral context -- and nothing else. - assert!(empty < 6.0, "an empty block is one skip symbol, not {empty}"); + assert!( + empty < 6.0, + "an empty block is one skip symbol, not {empty}" + ); } /// Neighbouring blocks that each carry coefficients read their DC sign diff --git a/lanes/av1-cdf-r1.report.md b/lanes/av1-cdf-r1.report.md new file mode 100644 index 00000000..9ce18b10 --- /dev/null +++ b/lanes/av1-cdf-r1.report.md @@ -0,0 +1,63 @@ +# lane-av1-cdf r1 — the tile adapts its CDFs + +## What changed +`crates/ec-av1/src/cdf_state.rs` (new) holds the CDF state a key frame's tile +adapts: one owned copy of every table the writer touches, seeded from the +defaults in `crate::cdf`, plus the four coefficient table sets (`TxbSet`) a +transform block is coded with. `sb_coeff_key_frame_tile` now writes every +non-literal symbol through `SymbolEncoder::symbol` against that state instead +of `symbol_fixed` against the static defaults, and `encode_key_frame`'s header +carries `disable_cdf_update: false` (with `disable_frame_end_update_cdf: true`, +since nothing reads what one frame leaves behind). + +Tables that a decoder keeps one copy of are one copy here too: a 64x64 luma +transform reads the 32x32 base-range rows, both luma sets read one DC sign +table and one 1024-position end-of-block table, and both chroma sets share +their own DC sign table. + +Not adapted: the gathered partition CDF an edge superblock reads, which the +decoder builds for the read and throws away. + +## Gates +- `cargo test --release -p ec-av1`: 82 passed, 0 failed, 3 ignored. The + ffmpeg/dav1d bit-exact roundtrips are the real gate — a decoder that adapts + its own tables desyncs the moment our order or our sharing differs. +- `cargo clippy --release -p ec-av1 --all-targets`: 0 warnings. `cargo fmt` + clean. +- New unit tests in `cdf_state`: the two luma sets share the base-range table; + the sign tables are shared within a plane type and not across; the luma + end-of-block table is shared and chroma's is not; the state starts at the + defaults. + +## Mutation kills +| Mutation | Killed by | +|---|---| +| DC sign written with `symbol_fixed` (stops adapting) | 4 tests, incl. both ffmpeg roundtrips | +| `Luma64` given the chroma base-range table (breaks sharing) | 3 tests, incl. the 64x64 ffmpeg roundtrip | + +## Rate, against the merged baseline +Same encoder, same decisions; adaptation on vs off, BD-rate over the +three-point ladder (`probe_ladder`, `EC_AV1_CLIPS` on his files). + +| Picture | BD-rate | +|---|---| +| ReelC 1080p AV1 (frame at 600 s) | **-3.52%** | +| OBS screen capture 2026-08-25 (frame at 5 s) | **-5.63%** | +| test card | -11.25% | +| stripes | -37.67% | +| diagonal | -3.54% | + +## Dispositions +- The coefficient rate term (`luma_32_coeff_bits`) still prices against the + **default** tables: the mode search runs before the tile is written, so the + adapted state the block will really be coded against does not exist yet — + **accepted**; pricing against a running copy needs the search and the writer + interleaved, which is its own lane. +- The DC fixture writers (`flat_key_frame_tile`, `dc_key_frame_tile_levels`, + `split_dc_key_frame_tile`) still code against the defaults; their test frames + now say `disable_cdf_update: true` — **accepted**, they are fixtures the + encoder does not use. + +## Not in this lane +Block sizes below 32x32, transform types beyond DCT_DCT, inter frames, angle +deltas other than zero, trellis of levels.