forge
Explore
Log in

Don't you dare go Hollow

The tile adapts its CDFs as it writes

Browse files at this commit

8a54f53612bb1aeef7c192bf29ab06f9046f1b08Ahmet Kaan GümüşParent: 7f0bc2a
  • feat
    • the tile adapts its CDFs as it writes
Show full message
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.rsadded+255 -0
@@ -0,0 +1,255 @@
1+//! The CDFs a tile adapts as it is written.
2+//!
3+//! AV1's symbol decoder updates every non-literal CDF it reads (spec 8.3.2),
4+//! so an encoder that wants `disable_cdf_update` off has to keep the same
5+//! state and update it in the same order. What lives here is that state: one
6+//! owned copy of each table the tile writer touches, seeded from the defaults
7+//! in [`crate::cdf`].
8+//!
9+//! The tables are owned once, not once per use: two coefficient table sets
10+//! that share a table -- a 64x64 luma transform reads the 32x32 base-range
11+//! rows, and both luma sets read the same DC sign table -- share the *adapted*
12+//! table too, which is what the decoder does.
13+
14+use crate::cdf;
15+
16+/// Which of the four coefficient table sets a transform block is coded with.
17+#[derive(Clone, Copy)]
18+pub(crate) enum TxbSet {
19+ /// The 32x32 luma transform of a 32x32 block.
20+ Luma32,
21+ /// The 64x64 luma transform of a whole superblock, scanned as a 32x32.
22+ Luma64,
23+ /// The 16x16 transform of a chroma plane of a 32x32 block.
24+ Chroma16,
25+ /// The 32x32 transform of a chroma plane of a whole superblock.
26+ Chroma32,
27+}
28+
29+/// The tables one transform block is coded with, borrowed from the state for
30+/// as long as that block is being written.
31+pub(crate) struct TxbTables<'a> {
32+ /// Side of the transform, in coefficients.
33+ pub side: usize,
34+ /// The all-zero flag, indexed by its own context.
35+ pub txb_skip: &'a mut [[u16; 3]],
36+ /// The end-of-block group, whose alphabet the transform size sets.
37+ pub eob_pt: &'a mut [u16],
38+ /// The top bit of the offset inside that group.
39+ pub eob_extra: &'a mut [[u16; 3]; 9],
40+ /// A coefficient's base level.
41+ pub base: &'a mut [[u16; 5]; 42],
42+ /// The base level of the last coefficient in the scan.
43+ pub base_eob: &'a mut [[u16; 4]; 4],
44+ /// The base-range tail above level two.
45+ pub br: &'a mut [[u16; 5]; 21],
46+ /// The sign of the DC.
47+ pub dc_sign: &'a mut [[u16; 3]; 3],
48+}
49+
50+/// Every table a key frame's tile writer adapts.
51+pub(crate) struct Cdfs {
52+ /// The partition symbol of a 64x64 superblock.
53+ pub partition_w64: [[u16; 11]; 4],
54+ /// The partition symbol of a 32x32 block.
55+ pub partition_w32: [[u16; 11]; 4],
56+ /// Whether a block carries no residual at all.
57+ pub skip: [[u16; 3]; 3],
58+ /// The luma mode of a key frame's block, under the two neighbours' modes.
59+ pub kf_y_mode: [[[u16; 14]; 5]; 5],
60+ /// The chroma mode of a block too big to be offered chroma from luma.
61+ pub uv_mode_no_cfl: [[u16; 14]; 13],
62+ /// The chroma mode of a block that is offered it.
63+ pub uv_mode_cfl: [[u16; 15]; 13],
64+ /// The angle a directional mode is nudged by.
65+ pub angle_delta: [[u16; 8]; 8],
66+ /// The one-context all-zero flag of a 32x32 luma transform.
67+ pub txb_skip_luma_32: [[u16; 3]; 1],
68+ /// The same, for a 64x64 luma transform.
69+ pub txb_skip_luma_64: [[u16; 3]; 1],
70+ /// The all-zero flag of a 16x16 chroma transform.
71+ pub txb_skip_chroma_16: [[u16; 3]; 3],
72+ /// The all-zero flag of a 32x32 chroma transform.
73+ pub txb_skip_chroma_32: [[u16; 3]; 3],
74+ /// The end-of-block group of a luma transform of 1024 positions.
75+ pub eob_pt_1024_luma: [u16; 12],
76+ /// The same, for chroma.
77+ pub eob_pt_1024_chroma: [u16; 12],
78+ /// The end-of-block group of a 16x16 chroma transform.
79+ pub eob_pt_256_chroma: [u16; 10],
80+ /// The end-of-block offset bit, per table set.
81+ pub eob_extra_luma_32: [[u16; 3]; 9],
82+ /// The same, for a 64x64 luma transform.
83+ pub eob_extra_luma_64: [[u16; 3]; 9],
84+ /// The same, for a 16x16 chroma transform.
85+ pub eob_extra_chroma_16: [[u16; 3]; 9],
86+ /// The same, for a 32x32 chroma transform.
87+ pub eob_extra_chroma_32: [[u16; 3]; 9],
88+ /// The base level of a 32x32 luma coefficient.
89+ pub base_luma_32: [[u16; 5]; 42],
90+ /// The base level of a 64x64 luma coefficient.
91+ pub base_luma_64: [[u16; 5]; 42],
92+ /// The base level of a 16x16 chroma coefficient.
93+ pub base_chroma_16: [[u16; 5]; 42],
94+ /// The base level of a 32x32 chroma coefficient.
95+ pub base_chroma_32: [[u16; 5]; 42],
96+ /// The last coefficient's base level, per table set.
97+ pub base_eob_luma_32: [[u16; 4]; 4],
98+ /// The same, for a 64x64 luma transform.
99+ pub base_eob_luma_64: [[u16; 4]; 4],
100+ /// The same, for a 16x16 chroma transform.
101+ pub base_eob_chroma_16: [[u16; 4]; 4],
102+ /// The same, for a 32x32 chroma transform.
103+ pub base_eob_chroma_32: [[u16; 4]; 4],
104+ /// The base-range tail of a luma coefficient, which a 64x64 transform
105+ /// reads too because its index is clamped at the 32x32 size.
106+ pub br_luma_32: [[u16; 5]; 21],
107+ /// The base-range tail of a 16x16 chroma coefficient.
108+ pub br_chroma_16: [[u16; 5]; 21],
109+ /// The base-range tail of a 32x32 chroma coefficient.
110+ pub br_chroma_32: [[u16; 5]; 21],
111+ /// The DC sign of a luma coefficient, shared by both luma sets.
112+ pub dc_sign_luma: [[u16; 3]; 3],
113+ /// The DC sign of a chroma coefficient, shared by both chroma sets.
114+ pub dc_sign_chroma: [[u16; 3]; 3],
115+}
116+
117+impl Cdfs {
118+ /// The defaults a key frame starts from (spec 8.4, `init_coeff_cdfs` and
119+ /// `init_non_coeff_cdfs`), for the one quantizer context whose tables this
120+ /// crate carries.
121+ pub fn new() -> Cdfs {
122+ Cdfs {
123+ partition_w64: cdf::PARTITION_W64,
124+ partition_w32: cdf::PARTITION_W32,
125+ skip: cdf::SKIP,
126+ kf_y_mode: cdf::KF_Y_MODE,
127+ uv_mode_no_cfl: cdf::UV_MODE_NO_CFL,
128+ uv_mode_cfl: cdf::UV_MODE_CFL,
129+ angle_delta: cdf::ANGLE_DELTA,
130+ txb_skip_luma_32: [cdf::TXB_SKIP_LUMA_32],
131+ txb_skip_luma_64: [cdf::TXB_SKIP_LUMA_64],
132+ txb_skip_chroma_16: cdf::TXB_SKIP_CHROMA_16,
133+ txb_skip_chroma_32: cdf::TXB_SKIP_CHROMA_32,
134+ eob_pt_1024_luma: cdf::EOB_PT_1024_LUMA,
135+ eob_pt_1024_chroma: cdf::EOB_PT_1024_CHROMA,
136+ eob_pt_256_chroma: cdf::EOB_PT_256_CHROMA,
137+ eob_extra_luma_32: cdf::EOB_EXTRA_LUMA_32,
138+ eob_extra_luma_64: cdf::EOB_EXTRA_LUMA_64,
139+ eob_extra_chroma_16: cdf::EOB_EXTRA_CHROMA_16,
140+ eob_extra_chroma_32: cdf::EOB_EXTRA_CHROMA_32,
141+ base_luma_32: cdf::COEFF_BASE_LUMA_32,
142+ base_luma_64: cdf::COEFF_BASE_LUMA_64,
143+ base_chroma_16: cdf::COEFF_BASE_CHROMA_16,
144+ base_chroma_32: cdf::COEFF_BASE_CHROMA_32,
145+ base_eob_luma_32: cdf::COEFF_BASE_EOB_LUMA_32,
146+ base_eob_luma_64: cdf::COEFF_BASE_EOB_LUMA_64,
147+ base_eob_chroma_16: cdf::COEFF_BASE_EOB_CHROMA_16,
148+ base_eob_chroma_32: cdf::COEFF_BASE_EOB_CHROMA_32,
149+ br_luma_32: cdf::COEFF_BR_LUMA_32,
150+ br_chroma_16: cdf::COEFF_BR_CHROMA_16,
151+ br_chroma_32: cdf::COEFF_BR_CHROMA_32,
152+ dc_sign_luma: cdf::DC_SIGN_LUMA,
153+ dc_sign_chroma: cdf::DC_SIGN_CHROMA,
154+ }
155+ }
156+
157+ /// The tables one table set is coded with, borrowed out of the state.
158+ pub fn txb(&mut self, set: TxbSet) -> TxbTables<'_> {
159+ match set {
160+ TxbSet::Luma32 => TxbTables {
161+ side: 32,
162+ txb_skip: &mut self.txb_skip_luma_32,
163+ eob_pt: &mut self.eob_pt_1024_luma,
164+ eob_extra: &mut self.eob_extra_luma_32,
165+ base: &mut self.base_luma_32,
166+ base_eob: &mut self.base_eob_luma_32,
167+ br: &mut self.br_luma_32,
168+ dc_sign: &mut self.dc_sign_luma,
169+ },
170+ TxbSet::Luma64 => TxbTables {
171+ side: 32,
172+ txb_skip: &mut self.txb_skip_luma_64,
173+ eob_pt: &mut self.eob_pt_1024_luma,
174+ eob_extra: &mut self.eob_extra_luma_64,
175+ base: &mut self.base_luma_64,
176+ base_eob: &mut self.base_eob_luma_64,
177+ br: &mut self.br_luma_32,
178+ dc_sign: &mut self.dc_sign_luma,
179+ },
180+ TxbSet::Chroma16 => TxbTables {
181+ side: 16,
182+ txb_skip: &mut self.txb_skip_chroma_16,
183+ eob_pt: &mut self.eob_pt_256_chroma,
184+ eob_extra: &mut self.eob_extra_chroma_16,
185+ base: &mut self.base_chroma_16,
186+ base_eob: &mut self.base_eob_chroma_16,
187+ br: &mut self.br_chroma_16,
188+ dc_sign: &mut self.dc_sign_chroma,
189+ },
190+ TxbSet::Chroma32 => TxbTables {
191+ side: 32,
192+ txb_skip: &mut self.txb_skip_chroma_32,
193+ eob_pt: &mut self.eob_pt_1024_chroma,
194+ eob_extra: &mut self.eob_extra_chroma_32,
195+ base: &mut self.base_chroma_32,
196+ base_eob: &mut self.base_eob_chroma_32,
197+ br: &mut self.br_chroma_32,
198+ dc_sign: &mut self.dc_sign_chroma,
199+ },
200+ }
201+ }
202+}
203+
204+#[cfg(test)]
205+mod tests {
206+ use super::*;
207+
208+ /// A 64x64 luma transform reads the 32x32 base-range rows, so the two sets
209+ /// have to adapt the same table: a decoder keeps one copy, and an encoder
210+ /// that kept two would drift away from it the first time a level above two
211+ /// was coded.
212+ #[test]
213+ fn the_two_luma_sets_share_the_base_range_table() {
214+ let mut cdfs = Cdfs::new();
215+ cdfs.txb(TxbSet::Luma64).br[0][0] = 1;
216+ assert_eq!(cdfs.txb(TxbSet::Luma32).br[0][0], 1);
217+ }
218+
219+ /// Both luma sets read one DC sign table, and both chroma sets another;
220+ /// what a luma block adapts must not reach the chroma one.
221+ #[test]
222+ fn the_sign_tables_are_shared_within_a_plane_type_and_not_across() {
223+ let mut cdfs = Cdfs::new();
224+ cdfs.txb(TxbSet::Luma32).dc_sign[1][0] = 1;
225+ cdfs.txb(TxbSet::Chroma16).dc_sign[2][0] = 2;
226+ assert_eq!(cdfs.txb(TxbSet::Luma64).dc_sign[1][0], 1);
227+ assert_eq!(cdfs.txb(TxbSet::Chroma32).dc_sign[2][0], 2);
228+ assert_ne!(cdfs.txb(TxbSet::Chroma32).dc_sign[1][0], 1);
229+ assert_ne!(cdfs.txb(TxbSet::Luma64).dc_sign[2][0], 2);
230+ }
231+
232+ /// The end-of-block table a 1024-position transform reads is shared by both
233+ /// luma sets and separate from chroma's, which is the same hazard one table
234+ /// further along.
235+ #[test]
236+ fn the_luma_end_of_block_table_is_shared_and_chromas_is_not() {
237+ let mut cdfs = Cdfs::new();
238+ cdfs.txb(TxbSet::Luma32).eob_pt[0] = 7;
239+ assert_eq!(cdfs.txb(TxbSet::Luma64).eob_pt[0], 7);
240+ assert_ne!(cdfs.txb(TxbSet::Chroma32).eob_pt[0], 7);
241+ }
242+
243+ /// Every set starts from the spec's defaults, so a tile that adapts nothing
244+ /// writes exactly what a non-adapting one does.
245+ #[test]
246+ fn the_state_starts_at_the_defaults() {
247+ let mut cdfs = Cdfs::new();
248+ assert_eq!(cdfs.txb(TxbSet::Luma32).base[3], cdf::COEFF_BASE_LUMA_32[3]);
249+ assert_eq!(
250+ cdfs.txb(TxbSet::Chroma16).eob_extra[2],
251+ cdf::EOB_EXTRA_CHROMA_16[2]
252+ );
253+ assert_eq!(cdfs.partition_w64[2], cdf::PARTITION_W64[2]);
254+ }
255+}
crates/ec-av1/src/encode.rsmodified+6 -1
@@ -199,7 +199,12 @@ pub fn key_frame_headers(
199199 frame_is_intra: true,
200200 show_frame: true,
201201 error_resilient_mode: true,
202- disable_cdf_update: true,
202+ // The tile writer keeps the same CDF state the decoder does and
203+ // updates it in the same order, so the frame lets the decoder adapt.
204+ disable_cdf_update: false,
205+ // Nothing reads the state this frame leaves behind: a key frame always
206+ // starts from the defaults, and this encoder emits one frame.
207+ disable_frame_end_update_cdf: true,
203208 force_integer_mv: true,
204209 refresh_frame_flags: 0xFF,
205210 primary_ref_frame: PRIMARY_REF_NONE,
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -14,6 +14,7 @@
1414
1515 pub mod bits;
1616 pub mod cdf;
17+mod cdf_state;
1718 pub mod encode;
1819 pub mod frame;
1920 pub mod intra;
crates/ec-av1/src/tile.rsmodified+83 -116
@@ -14,6 +14,7 @@ use std::sync::LazyLock;
1414 use ec_core::{Error, Result};
1515
1616 use crate::cdf;
17+use crate::cdf_state::{Cdfs, TxbSet, TxbTables};
1718 use crate::msac::SymbolEncoder;
1819
1920 /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
@@ -365,90 +366,6 @@ const TX32: usize = 32;
365366 /// Side of the chroma transform beside it at 4:2:0.
366367 const TX16: usize = 16;
367368
368-/// The shapes and default CDFs one plane's transform blocks are coded with.
369-/// The two differ in every coefficient table because the CDFs are indexed by
370-/// plane type and transform size, and in the end-of-block alphabet because a
371-/// 16x16 transform has a quarter of the positions to point at.
372-struct TxbCoding {
373- /// Side of the transform, in coefficients.
374- side: usize,
375- /// The all-zero flag, indexed by its own context.
376- txb_skip: &'static [[u16; 3]],
377- /// The end-of-block group, whose alphabet the transform size sets.
378- eob_pt: &'static [u16],
379- /// The top bit of the offset inside that group.
380- eob_extra: &'static [[u16; 3]; 9],
381- /// A coefficient's base level.
382- base: &'static [[u16; 5]; 42],
383- /// The base level of the last coefficient in the scan.
384- base_eob: &'static [[u16; 4]; 4],
385- /// The base-range tail above level two.
386- br: &'static [[u16; 5]; 21],
387- /// The sign of the DC.
388- dc_sign: &'static [[u16; 3]; 3],
389-}
390-
391-/// The luma all-zero flag has one context here: the transform covers its whole
392-/// block, which fixes it at zero.
393-const TXB_SKIP_LUMA_32_CTX: [[u16; 3]; 1] = [cdf::TXB_SKIP_LUMA_32];
394-
395-/// The 32x32 luma transform of a 32x32 block.
396-const LUMA_32: TxbCoding = TxbCoding {
397- side: TX32,
398- txb_skip: &TXB_SKIP_LUMA_32_CTX,
399- eob_pt: &cdf::EOB_PT_1024_LUMA,
400- eob_extra: &cdf::EOB_EXTRA_LUMA_32,
401- base: &cdf::COEFF_BASE_LUMA_32,
402- base_eob: &cdf::COEFF_BASE_EOB_LUMA_32,
403- br: &cdf::COEFF_BR_LUMA_32,
404- dc_sign: &cdf::DC_SIGN_LUMA,
405-};
406-
407-/// The 16x16 transform of either chroma plane of that block at 4:2:0.
408-const CHROMA_16: TxbCoding = TxbCoding {
409- side: TX16,
410- txb_skip: &cdf::TXB_SKIP_CHROMA_16,
411- eob_pt: &cdf::EOB_PT_256_CHROMA,
412- eob_extra: &cdf::EOB_EXTRA_CHROMA_16,
413- base: &cdf::COEFF_BASE_CHROMA_16,
414- base_eob: &cdf::COEFF_BASE_EOB_CHROMA_16,
415- br: &cdf::COEFF_BR_CHROMA_16,
416- dc_sign: &cdf::DC_SIGN_CHROMA,
417-};
418-
419-/// The luma all-zero flag of a 64x64 transform, whose one context is fixed the
420-/// way [`TXB_SKIP_LUMA_32_CTX`] is.
421-const TXB_SKIP_LUMA_64_CTX: [[u16; 3]; 1] = [cdf::TXB_SKIP_LUMA_64];
422-
423-/// The 64x64 luma transform of a whole superblock. Only its top-left 32x32
424-/// carries coefficients, so it is scanned and its end-of-block position read
425-/// as a 32x32 transform is; what it does not share with [`LUMA_32`] is every
426-/// coefficient CDF, which is indexed by the transform size.
427-const LUMA_64: TxbCoding = TxbCoding {
428- side: TX32,
429- txb_skip: &TXB_SKIP_LUMA_64_CTX,
430- eob_pt: &cdf::EOB_PT_1024_LUMA,
431- eob_extra: &cdf::EOB_EXTRA_LUMA_64,
432- base: &cdf::COEFF_BASE_LUMA_64,
433- base_eob: &cdf::COEFF_BASE_EOB_LUMA_64,
434- // The base-range tail is the one table a 64x64 transform does not have of
435- // its own: the index is clamped at the 32x32 size, so it reads that row.
436- br: &cdf::COEFF_BR_LUMA_32,
437- dc_sign: &cdf::DC_SIGN_LUMA,
438-};
439-
440-/// The 32x32 transform of either chroma plane of that superblock at 4:2:0.
441-const CHROMA_32: TxbCoding = TxbCoding {
442- side: TX32,
443- txb_skip: &cdf::TXB_SKIP_CHROMA_32,
444- eob_pt: &cdf::EOB_PT_1024_CHROMA,
445- eob_extra: &cdf::EOB_EXTRA_CHROMA_32,
446- base: &cdf::COEFF_BASE_CHROMA_32,
447- base_eob: &cdf::COEFF_BASE_EOB_CHROMA_32,
448- br: &cdf::COEFF_BR_CHROMA_32,
449- dc_sign: &cdf::DC_SIGN_CHROMA,
450-};
451-
452369 /// What one coded block leaves behind for the blocks that read it as a
453370 /// neighbour: whether it coded anything at all, and the sign of its DC.
454371 #[derive(Clone, Copy, Default)]
@@ -556,8 +473,8 @@ pub fn sb_coeff_key_frame_tile(
556473 ));
557474 }
558475
559- let split_planes = [&LUMA_32, &CHROMA_16, &CHROMA_16];
560- let whole_planes = [&LUMA_64, &CHROMA_32, &CHROMA_32];
476+ let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
477+ let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
561478 let scans = [default_scan(TX32), default_scan(TX16)];
562479 // What the blocks above and to the left of the one being coded left
563480 // behind, per plane, one entry per 32x32 column and row. The left column
@@ -579,6 +496,10 @@ pub fn sb_coeff_key_frame_tile(
579496 let mut above_split = vec![false; cols as usize];
580497 let mut left_split = vec![false; rows as usize];
581498
499+ // The tile adapts every non-literal CDF it writes, exactly as the decoder
500+ // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
501+ // off.
502+ let mut cdfs = Cdfs::new();
582503 let mut enc = SymbolEncoder::new();
583504 for sb_r in 0..sb_rows {
584505 left.iter_mut().for_each(|l| *l = Default::default());
@@ -611,15 +532,16 @@ pub fn sb_coeff_key_frame_tile(
611532 "a superblock that is half outside the frame cannot be left whole",
612533 ));
613534 }
614- enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[ctx]);
535+ enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]);
615536 let mode = write_intra_mode(
616537 &mut enc,
538+ &mut cdfs,
617539 block,
618540 above_mode[c0],
619541 left_mode[r0],
620542 // A 64x64 block is too big to be offered chroma from
621543 // luma, so its chroma mode reads the table without it.
622- &cdf::UV_MODE_NO_CFL[usize::from(block.mode)],
544+ false,
623545 );
624546 let grids = [
625547 level_grid(&block.luma, TX32)?,
@@ -628,6 +550,7 @@ pub fn sb_coeff_key_frame_tile(
628550 ];
629551 write_block_planes(
630552 &mut enc,
553+ &mut cdfs,
631554 &whole_planes,
632555 &grids,
633556 &[&scans[0], &scans[0], &scans[0]],
@@ -650,12 +573,15 @@ pub fn sb_coeff_key_frame_tile(
650573 }
651574 Superblock::Split(blocks) => {
652575 match (has_cols, has_rows) {
653- (true, true) => enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]),
576+ (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w64[ctx]),
577+ // The gathered CDF an edge superblock reads is built
578+ // for the read and thrown away: the decoder never
579+ // stores it back, so nothing adapts here.
654580 (true, false) => {
655- enc.symbol_fixed(1, &gather(&cdf::PARTITION_W64[ctx], VERT_ALIKE));
581+ enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
656582 }
657583 (false, true) => {
658- enc.symbol_fixed(1, &gather(&cdf::PARTITION_W64[ctx], HORZ_ALIKE));
584+ enc.symbol_fixed(1, &gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
659585 }
660586 (false, false) => {}
661587 }
@@ -666,13 +592,14 @@ pub fn sb_coeff_key_frame_tile(
666592 ));
667593 }
668594 for (block, (r, c)) in blocks.iter().zip(quadrants) {
669- enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]);
595+ enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
670596 let mode = write_intra_mode(
671597 &mut enc,
598+ &mut cdfs,
672599 block,
673600 above_mode[c],
674601 left_mode[r],
675- &cdf::UV_MODE_CFL[usize::from(block.mode)],
602+ true,
676603 );
677604 let grids = [
678605 level_grid(&block.luma, TX32)?,
@@ -681,6 +608,7 @@ pub fn sb_coeff_key_frame_tile(
681608 ];
682609 write_block_planes(
683610 &mut enc,
611+ &mut cdfs,
684612 &split_planes,
685613 &grids,
686614 &[&scans[0], &scans[1], &scans[1]],
@@ -710,21 +638,28 @@ pub fn sb_coeff_key_frame_tile(
710638 /// the luma mode, which is what the blocks beside it read.
711639 fn write_intra_mode(
712640 enc: &mut SymbolEncoder,
641+ cdfs: &mut Cdfs,
713642 block: &BlockCoeffs,
714643 above_mode: usize,
715644 left_mode: usize,
716- uv_cdf: &[u16],
645+ cfl: bool,
717646 ) -> usize {
718647 let mode = usize::from(block.mode);
719- enc.symbol_fixed(0, &cdf::SKIP[0]);
720- enc.symbol_fixed(
648+ enc.symbol(0, &mut cdfs.skip[0]);
649+ enc.symbol(
721650 mode,
722- &cdf::KF_Y_MODE[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
651+ &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]],
723652 );
724653 if (V_PRED..=D67_PRED).contains(&mode) {
725- enc.symbol_fixed(ANGLE_DELTA_ZERO, &cdf::ANGLE_DELTA[mode - V_PRED]);
654+ enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]);
655+ }
656+ // A block small enough to be offered chroma from luma reads the wider
657+ // table even when it does not take the mode.
658+ if cfl {
659+ enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]);
660+ } else {
661+ enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[mode]);
726662 }
727- enc.symbol_fixed(DC_PRED, uv_cdf);
728663 mode
729664 }
730665
@@ -732,7 +667,8 @@ fn write_intra_mode(
732667 /// decoder reads them.
733668 fn write_block_planes(
734669 enc: &mut SymbolEncoder,
735- planes: &[&TxbCoding; 3],
670+ cdfs: &mut Cdfs,
671+ planes: &[TxbSet; 3],
736672 grids: &[Vec<i32>; 3],
737673 scans: &[&Vec<u16>; 3],
738674 above: &[Neighbour; 3],
@@ -750,7 +686,7 @@ fn write_block_planes(
750686 };
751687 write_coeffs(
752688 enc,
753- planes[plane],
689+ &mut cdfs.txb(planes[plane]),
754690 grid,
755691 scans[plane],
756692 skip_ctx,
@@ -878,7 +814,17 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
878814 static SCAN: LazyLock<Vec<u16>> = LazyLock::new(|| default_scan(TX32));
879815 let mut enc = SymbolEncoder::new();
880816 enc.reset_bits();
881- write_coeffs(&mut enc, &LUMA_32, grid, &SCAN, 0, 0);
817+ // The search runs before the tile is written, so the adapted state the
818+ // block will really be coded against does not exist yet: the price is
819+ // taken against the defaults every tile starts from.
820+ write_coeffs(
821+ &mut enc,
822+ &mut Cdfs::new().txb(TxbSet::Luma32),
823+ grid,
824+ &SCAN,
825+ 0,
826+ 0,
827+ );
882828 enc.bits()
883829 }
884830
@@ -891,7 +837,7 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
891837 /// already has.
892838 fn write_coeffs(
893839 enc: &mut SymbolEncoder,
894- coding: &TxbCoding,
840+ coding: &mut TxbTables,
895841 grid: &[i32],
896842 scan: &[u16],
897843 skip_ctx: usize,
@@ -902,7 +848,7 @@ fn write_coeffs(
902848 .iter()
903849 .rposition(|&pos| grid[pos as usize] != 0)
904850 .map_or(0, |i| i + 1);
905- enc.symbol_fixed(usize::from(eob == 0), &coding.txb_skip[skip_ctx]);
851+ enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]);
906852 if eob == 0 {
907853 return;
908854 }
@@ -915,13 +861,16 @@ fn write_coeffs(
915861 let level = grid[pos].abs();
916862 if scan_idx == eob - 1 {
917863 let ctx = eob_coeff_ctx(scan_idx, side * side);
918- enc.symbol_fixed(
864+ enc.symbol(
919865 (level.min(NUM_BASE_LEVELS + 1) - 1) as usize,
920- &coding.base_eob[ctx],
866+ &mut coding.base_eob[ctx],
921867 );
922868 } else {
923869 let ctx = base_ctx(grid, side, row, col);
924- enc.symbol_fixed(level.min(NUM_BASE_LEVELS + 1) as usize, &coding.base[ctx]);
870+ enc.symbol(
871+ level.min(NUM_BASE_LEVELS + 1) as usize,
872+ &mut coding.base[ctx],
873+ );
925874 }
926875 if level > NUM_BASE_LEVELS {
927876 let ctx = br_ctx(grid, side, row, col);
@@ -929,7 +878,7 @@ fn write_coeffs(
929878 let mut sent = 0;
930879 while sent < COEFF_BASE_RANGE {
931880 let k = remaining.min(BR_STEP);
932- enc.symbol_fixed(k as usize, &coding.br[ctx]);
881+ enc.symbol(k as usize, &mut coding.br[ctx]);
933882 if k < BR_STEP {
934883 break;
935884 }
@@ -947,7 +896,7 @@ fn write_coeffs(
947896 continue;
948897 }
949898 if pos == 0 {
950- enc.symbol_fixed(usize::from(level < 0), &coding.dc_sign[sign_ctx]);
899+ enc.symbol(usize::from(level < 0), &mut coding.dc_sign[sign_ctx]);
951900 } else {
952901 enc.literal(u32::from(level < 0), 1);
953902 }
@@ -962,7 +911,7 @@ fn write_coeffs(
962911 /// The end-of-block position (spec 5.11.39): which group of scan positions the
963912 /// last coded coefficient falls in, then its offset inside that group — the
964913 /// offset's top bit from a CDF and the rest as raw bits.
965-fn write_eob(enc: &mut SymbolEncoder, coding: &TxbCoding, eob: usize) {
914+fn write_eob(enc: &mut SymbolEncoder, coding: &mut TxbTables, eob: usize) {
966915 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of
967916 /// end-of-block positions covers, indexed by the group's own number.
968917 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) {
975924 .expect("the first group starts at zero");
976925 // The groups are numbered from one, and how many of them the transform
977926 // reaches is the size of its own end-of-block alphabet.
978- enc.symbol_fixed(group - 1, coding.eob_pt);
927+ enc.symbol(group - 1, coding.eob_pt);
979928
980929 let bits = OFFSET_BITS[group];
981930 if bits > 0 {
982931 let offset = (eob - GROUP_START[group]) as u32;
983932 let top = (offset >> (bits - 1)) & 1;
984- enc.symbol_fixed(top as usize, &coding.eob_extra[group - 3]);
933+ enc.symbol(top as usize, &mut coding.eob_extra[group - 3]);
985934 if bits > 1 {
986935 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);
987936 }
@@ -1387,7 +1336,10 @@ mod tests {
13871336 /// hand back the decoded planes.
13881337 fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
13891338 let (w, h) = (64 * sb_cols, 64 * sb_rows);
1390- let (seq, header) = frame_of(w, h);
1339+ let (seq, mut header) = frame_of(w, h);
1340+ // The DC fixture writers code against the default CDFs and never
1341+ // update them, so their frames say so.
1342+ header.disable_cdf_update = true;
13911343 let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
13921344 let mut stream = temporal_delimiter();
13931345 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
@@ -1402,6 +1354,8 @@ mod tests {
14021354 seq.max_frame_width = w;
14031355 seq.max_frame_height = h;
14041356 let mut header = flat_key_frame();
1357+ // Every tile these headers carry is written by the adapting writer.
1358+ header.disable_cdf_update = false;
14051359 header.frame_width = w;
14061360 header.frame_height = h;
14071361 header.upscaled_width = w;
@@ -1580,7 +1534,10 @@ mod tests {
15801534 /// Encode a grid of 32x32 blocks, each carrying its own DC level.
15811535 fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
15821536 let (w, h) = (64 * sb_cols, 64 * sb_rows);
1583- let (seq, header) = frame_of(w, h);
1537+ let (seq, mut header) = frame_of(w, h);
1538+ // The DC fixture writers code against the default CDFs and never
1539+ // update them, so their frames say so.
1540+ header.disable_cdf_update = true;
15841541 let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
15851542 let mut stream = temporal_delimiter();
15861543 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
@@ -1836,7 +1793,14 @@ mod tests {
18361793 let mut enc = SymbolEncoder::new();
18371794 let mut priced = 0.0;
18381795 for grid in &grids {
1839- write_coeffs(&mut enc, &LUMA_32, grid, &scan, 0, 0);
1796+ write_coeffs(
1797+ &mut enc,
1798+ &mut Cdfs::new().txb(TxbSet::Luma32),
1799+ grid,
1800+ &scan,
1801+ 0,
1802+ 0,
1803+ );
18401804 priced += luma_32_coeff_bits(grid);
18411805 }
18421806 let spent = enc.finish().len() as f64 * 8.0;
@@ -1872,7 +1836,10 @@ mod tests {
18721836 // An empty block is one symbol -- an expensive one, because a block
18731837 // with no coefficients at all is the rarer of the two under the
18741838 // neutral context -- and nothing else.
1875- assert!(empty < 6.0, "an empty block is one skip symbol, not {empty}");
1839+ assert!(
1840+ empty < 6.0,
1841+ "an empty block is one skip symbol, not {empty}"
1842+ );
18761843 }
18771844
18781845 /// Neighbouring blocks that each carry coefficients read their DC sign
lanes/av1-cdf-r1.report.mdadded+63 -0
@@ -0,0 +1,63 @@
1+# lane-av1-cdf r1 — the tile adapts its CDFs
2+
3+## What changed
4+`crates/ec-av1/src/cdf_state.rs` (new) holds the CDF state a key frame's tile
5+adapts: one owned copy of every table the writer touches, seeded from the
6+defaults in `crate::cdf`, plus the four coefficient table sets (`TxbSet`) a
7+transform block is coded with. `sb_coeff_key_frame_tile` now writes every
8+non-literal symbol through `SymbolEncoder::symbol` against that state instead
9+of `symbol_fixed` against the static defaults, and `encode_key_frame`'s header
10+carries `disable_cdf_update: false` (with `disable_frame_end_update_cdf: true`,
11+since nothing reads what one frame leaves behind).
12+
13+Tables that a decoder keeps one copy of are one copy here too: a 64x64 luma
14+transform reads the 32x32 base-range rows, both luma sets read one DC sign
15+table and one 1024-position end-of-block table, and both chroma sets share
16+their own DC sign table.
17+
18+Not adapted: the gathered partition CDF an edge superblock reads, which the
19+decoder builds for the read and throws away.
20+
21+## Gates
22+- `cargo test --release -p ec-av1`: 82 passed, 0 failed, 3 ignored. The
23+ ffmpeg/dav1d bit-exact roundtrips are the real gate — a decoder that adapts
24+ its own tables desyncs the moment our order or our sharing differs.
25+- `cargo clippy --release -p ec-av1 --all-targets`: 0 warnings. `cargo fmt`
26+ clean.
27+- New unit tests in `cdf_state`: the two luma sets share the base-range table;
28+ the sign tables are shared within a plane type and not across; the luma
29+ end-of-block table is shared and chroma's is not; the state starts at the
30+ defaults.
31+
32+## Mutation kills
33+| Mutation | Killed by |
34+|---|---|
35+| DC sign written with `symbol_fixed` (stops adapting) | 4 tests, incl. both ffmpeg roundtrips |
36+| `Luma64` given the chroma base-range table (breaks sharing) | 3 tests, incl. the 64x64 ffmpeg roundtrip |
37+
38+## Rate, against the merged baseline
39+Same encoder, same decisions; adaptation on vs off, BD-rate over the
40+three-point ladder (`probe_ladder`, `EC_AV1_CLIPS` on his files).
41+
42+| Picture | BD-rate |
43+|---|---|
44+| ReelC 1080p AV1 (frame at 600 s) | **-3.52%** |
45+| OBS screen capture 2026-08-25 (frame at 5 s) | **-5.63%** |
46+| test card | -11.25% |
47+| stripes | -37.67% |
48+| diagonal | -3.54% |
49+
50+## Dispositions
51+- The coefficient rate term (`luma_32_coeff_bits`) still prices against the
52+ **default** tables: the mode search runs before the tile is written, so the
53+ adapted state the block will really be coded against does not exist yet —
54+ **accepted**; pricing against a running copy needs the search and the writer
55+ interleaved, which is its own lane.
56+- The DC fixture writers (`flat_key_frame_tile`, `dc_key_frame_tile_levels`,
57+ `split_dc_key_frame_tile`) still code against the defaults; their test frames
58+ now say `disable_cdf_update: true` — **accepted**, they are fixtures the
59+ encoder does not use.
60+
61+## Not in this lane
62+Block sizes below 32x32, transform types beyond DCT_DCT, inter frames, angle
63+deltas other than zero, trellis of levels.