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(
199 frame_is_intra: true,199 frame_is_intra: true,
200 show_frame: true,200 show_frame: true,
201 error_resilient_mode: true,201 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,
203 force_integer_mv: true,208 force_integer_mv: true,
204 refresh_frame_flags: 0xFF,209 refresh_frame_flags: 0xFF,
205 primary_ref_frame: PRIMARY_REF_NONE,210 primary_ref_frame: PRIMARY_REF_NONE,
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -14,6 +14,7 @@
14 14
15 pub mod bits;15 pub mod bits;
16 pub mod cdf;16 pub mod cdf;
17+mod cdf_state;
17 pub mod encode;18 pub mod encode;
18 pub mod frame;19 pub mod frame;
19 pub mod intra;20 pub mod intra;
crates/ec-av1/src/tile.rsmodified+83 -116
@@ -14,6 +14,7 @@ use std::sync::LazyLock;
14 use ec_core::{Error, Result};14 use ec_core::{Error, Result};
15 15
16 use crate::cdf;16 use crate::cdf;
17+use crate::cdf_state::{Cdfs, TxbSet, TxbTables};
17 use crate::msac::SymbolEncoder;18 use crate::msac::SymbolEncoder;
18 19
19 /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.20 /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
@@ -365,90 +366,6 @@ const TX32: usize = 32;
365 /// Side of the chroma transform beside it at 4:2:0.366 /// Side of the chroma transform beside it at 4:2:0.
366 const TX16: usize = 16;367 const TX16: usize = 16;
367 368
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-
452 /// What one coded block leaves behind for the blocks that read it as a369 /// What one coded block leaves behind for the blocks that read it as a
453 /// neighbour: whether it coded anything at all, and the sign of its DC.370 /// neighbour: whether it coded anything at all, and the sign of its DC.
454 #[derive(Clone, Copy, Default)]371 #[derive(Clone, Copy, Default)]
@@ -556,8 +473,8 @@ pub fn sb_coeff_key_frame_tile(
556 ));473 ));
557 }474 }
558 475
559- let split_planes = [&LUMA_32, &CHROMA_16, &CHROMA_16];476+ let split_planes = [TxbSet::Luma32, TxbSet::Chroma16, TxbSet::Chroma16];
560- let whole_planes = [&LUMA_64, &CHROMA_32, &CHROMA_32];477+ let whole_planes = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
561 let scans = [default_scan(TX32), default_scan(TX16)];478 let scans = [default_scan(TX32), default_scan(TX16)];
562 // What the blocks above and to the left of the one being coded left479 // What the blocks above and to the left of the one being coded left
563 // behind, per plane, one entry per 32x32 column and row. The left column480 // behind, per plane, one entry per 32x32 column and row. The left column
@@ -579,6 +496,10 @@ pub fn sb_coeff_key_frame_tile(
579 let mut above_split = vec![false; cols as usize];496 let mut above_split = vec![false; cols as usize];
580 let mut left_split = vec![false; rows as usize];497 let mut left_split = vec![false; rows as usize];
581 498
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();
582 let mut enc = SymbolEncoder::new();503 let mut enc = SymbolEncoder::new();
583 for sb_r in 0..sb_rows {504 for sb_r in 0..sb_rows {
584 left.iter_mut().for_each(|l| *l = Default::default());505 left.iter_mut().for_each(|l| *l = Default::default());
@@ -611,15 +532,16 @@ pub fn sb_coeff_key_frame_tile(
611 "a superblock that is half outside the frame cannot be left whole",532 "a superblock that is half outside the frame cannot be left whole",
612 ));533 ));
613 }534 }
614- enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[ctx]);535+ enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[ctx]);
615 let mode = write_intra_mode(536 let mode = write_intra_mode(
616 &mut enc,537 &mut enc,
538+ &mut cdfs,
617 block,539 block,
618 above_mode[c0],540 above_mode[c0],
619 left_mode[r0],541 left_mode[r0],
620 // A 64x64 block is too big to be offered chroma from542 // A 64x64 block is too big to be offered chroma from
621 // luma, so its chroma mode reads the table without it.543 // luma, so its chroma mode reads the table without it.
622- &cdf::UV_MODE_NO_CFL[usize::from(block.mode)],544+ false,
623 );545 );
624 let grids = [546 let grids = [
625 level_grid(&block.luma, TX32)?,547 level_grid(&block.luma, TX32)?,
@@ -628,6 +550,7 @@ pub fn sb_coeff_key_frame_tile(
628 ];550 ];
629 write_block_planes(551 write_block_planes(
630 &mut enc,552 &mut enc,
553+ &mut cdfs,
631 &whole_planes,554 &whole_planes,
632 &grids,555 &grids,
633 &[&scans[0], &scans[0], &scans[0]],556 &[&scans[0], &scans[0], &scans[0]],
@@ -650,12 +573,15 @@ pub fn sb_coeff_key_frame_tile(
650 }573 }
651 Superblock::Split(blocks) => {574 Superblock::Split(blocks) => {
652 match (has_cols, has_rows) {575 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.
654 (true, false) => {580 (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));
656 }582 }
657 (false, true) => {583 (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));
659 }585 }
660 (false, false) => {}586 (false, false) => {}
661 }587 }
@@ -666,13 +592,14 @@ pub fn sb_coeff_key_frame_tile(
666 ));592 ));
667 }593 }
668 for (block, (r, c)) in blocks.iter().zip(quadrants) {594 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]);
670 let mode = write_intra_mode(596 let mode = write_intra_mode(
671 &mut enc,597 &mut enc,
598+ &mut cdfs,
672 block,599 block,
673 above_mode[c],600 above_mode[c],
674 left_mode[r],601 left_mode[r],
675- &cdf::UV_MODE_CFL[usize::from(block.mode)],602+ true,
676 );603 );
677 let grids = [604 let grids = [
678 level_grid(&block.luma, TX32)?,605 level_grid(&block.luma, TX32)?,
@@ -681,6 +608,7 @@ pub fn sb_coeff_key_frame_tile(
681 ];608 ];
682 write_block_planes(609 write_block_planes(
683 &mut enc,610 &mut enc,
611+ &mut cdfs,
684 &split_planes,612 &split_planes,
685 &grids,613 &grids,
686 &[&scans[0], &scans[1], &scans[1]],614 &[&scans[0], &scans[1], &scans[1]],
@@ -710,21 +638,28 @@ pub fn sb_coeff_key_frame_tile(
710 /// the luma mode, which is what the blocks beside it read.638 /// the luma mode, which is what the blocks beside it read.
711 fn write_intra_mode(639 fn write_intra_mode(
712 enc: &mut SymbolEncoder,640 enc: &mut SymbolEncoder,
641+ cdfs: &mut Cdfs,
713 block: &BlockCoeffs,642 block: &BlockCoeffs,
714 above_mode: usize,643 above_mode: usize,
715 left_mode: usize,644 left_mode: usize,
716- uv_cdf: &[u16],645+ cfl: bool,
717 ) -> usize {646 ) -> usize {
718 let mode = usize::from(block.mode);647 let mode = usize::from(block.mode);
719- enc.symbol_fixed(0, &cdf::SKIP[0]);648+ enc.symbol(0, &mut cdfs.skip[0]);
720- enc.symbol_fixed(649+ enc.symbol(
721 mode,650 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]],
723 );652 );
724 if (V_PRED..=D67_PRED).contains(&mode) {653 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]);
726 }662 }
727- enc.symbol_fixed(DC_PRED, uv_cdf);
728 mode663 mode
729 }664 }
730 665
@@ -732,7 +667,8 @@ fn write_intra_mode(
732 /// decoder reads them.667 /// decoder reads them.
733 fn write_block_planes(668 fn write_block_planes(
734 enc: &mut SymbolEncoder,669 enc: &mut SymbolEncoder,
735- planes: &[&TxbCoding; 3],670+ cdfs: &mut Cdfs,
671+ planes: &[TxbSet; 3],
736 grids: &[Vec<i32>; 3],672 grids: &[Vec<i32>; 3],
737 scans: &[&Vec<u16>; 3],673 scans: &[&Vec<u16>; 3],
738 above: &[Neighbour; 3],674 above: &[Neighbour; 3],
@@ -750,7 +686,7 @@ fn write_block_planes(
750 };686 };
751 write_coeffs(687 write_coeffs(
752 enc,688 enc,
753- planes[plane],689+ &mut cdfs.txb(planes[plane]),
754 grid,690 grid,
755 scans[plane],691 scans[plane],
756 skip_ctx,692 skip_ctx,
@@ -878,7 +814,17 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
878 static SCAN: LazyLock<Vec<u16>> = LazyLock::new(|| default_scan(TX32));814 static SCAN: LazyLock<Vec<u16>> = LazyLock::new(|| default_scan(TX32));
879 let mut enc = SymbolEncoder::new();815 let mut enc = SymbolEncoder::new();
880 enc.reset_bits();816 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+ );
882 enc.bits()828 enc.bits()
883 }829 }
884 830
@@ -891,7 +837,7 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
891 /// already has.837 /// already has.
892 fn write_coeffs(838 fn write_coeffs(
893 enc: &mut SymbolEncoder,839 enc: &mut SymbolEncoder,
894- coding: &TxbCoding,840+ coding: &mut TxbTables,
895 grid: &[i32],841 grid: &[i32],
896 scan: &[u16],842 scan: &[u16],
897 skip_ctx: usize,843 skip_ctx: usize,
@@ -902,7 +848,7 @@ fn write_coeffs(
902 .iter()848 .iter()
903 .rposition(|&pos| grid[pos as usize] != 0)849 .rposition(|&pos| grid[pos as usize] != 0)
904 .map_or(0, |i| i + 1);850 .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]);
906 if eob == 0 {852 if eob == 0 {
907 return;853 return;
908 }854 }
@@ -915,13 +861,16 @@ fn write_coeffs(
915 let level = grid[pos].abs();861 let level = grid[pos].abs();
916 if scan_idx == eob - 1 {862 if scan_idx == eob - 1 {
917 let ctx = eob_coeff_ctx(scan_idx, side * side);863 let ctx = eob_coeff_ctx(scan_idx, side * side);
918- enc.symbol_fixed(864+ enc.symbol(
919 (level.min(NUM_BASE_LEVELS + 1) - 1) as usize,865 (level.min(NUM_BASE_LEVELS + 1) - 1) as usize,
920- &coding.base_eob[ctx],866+ &mut coding.base_eob[ctx],
921 );867 );
922 } else {868 } else {
923 let ctx = base_ctx(grid, side, row, col);869 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+ );
925 }874 }
926 if level > NUM_BASE_LEVELS {875 if level > NUM_BASE_LEVELS {
927 let ctx = br_ctx(grid, side, row, col);876 let ctx = br_ctx(grid, side, row, col);
@@ -929,7 +878,7 @@ fn write_coeffs(
929 let mut sent = 0;878 let mut sent = 0;
930 while sent < COEFF_BASE_RANGE {879 while sent < COEFF_BASE_RANGE {
931 let k = remaining.min(BR_STEP);880 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]);
933 if k < BR_STEP {882 if k < BR_STEP {
934 break;883 break;
935 }884 }
@@ -947,7 +896,7 @@ fn write_coeffs(
947 continue;896 continue;
948 }897 }
949 if pos == 0 {898 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]);
951 } else {900 } else {
952 enc.literal(u32::from(level < 0), 1);901 enc.literal(u32::from(level < 0), 1);
953 }902 }
@@ -962,7 +911,7 @@ fn write_coeffs(
962 /// The end-of-block position (spec 5.11.39): which group of scan positions the911 /// The end-of-block position (spec 5.11.39): which group of scan positions the
963 /// last coded coefficient falls in, then its offset inside that group — the912 /// last coded coefficient falls in, then its offset inside that group — the
964 /// offset's top bit from a CDF and the rest as raw bits.913 /// 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) {
966 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of915 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of
967 /// end-of-block positions covers, indexed by the group's own number.916 /// end-of-block positions covers, indexed by the group's own number.
968 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];917 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) {
975 .expect("the first group starts at zero");924 .expect("the first group starts at zero");
976 // The groups are numbered from one, and how many of them the transform925 // The groups are numbered from one, and how many of them the transform
977 // reaches is the size of its own end-of-block alphabet.926 // 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);
979 928
980 let bits = OFFSET_BITS[group];929 let bits = OFFSET_BITS[group];
981 if bits > 0 {930 if bits > 0 {
982 let offset = (eob - GROUP_START[group]) as u32;931 let offset = (eob - GROUP_START[group]) as u32;
983 let top = (offset >> (bits - 1)) & 1;932 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]);
985 if bits > 1 {934 if bits > 1 {
986 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);935 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);
987 }936 }
@@ -1387,7 +1336,10 @@ mod tests {
1387 /// hand back the decoded planes.1336 /// hand back the decoded planes.
1388 fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {1337 fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
1389 let (w, h) = (64 * sb_cols, 64 * sb_rows);1338 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;
1391 let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();1343 let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
1392 let mut stream = temporal_delimiter();1344 let mut stream = temporal_delimiter();
1393 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());1345 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
@@ -1402,6 +1354,8 @@ mod tests {
1402 seq.max_frame_width = w;1354 seq.max_frame_width = w;
1403 seq.max_frame_height = h;1355 seq.max_frame_height = h;
1404 let mut header = flat_key_frame();1356 let mut header = flat_key_frame();
1357+ // Every tile these headers carry is written by the adapting writer.
1358+ header.disable_cdf_update = false;
1405 header.frame_width = w;1359 header.frame_width = w;
1406 header.frame_height = h;1360 header.frame_height = h;
1407 header.upscaled_width = w;1361 header.upscaled_width = w;
@@ -1580,7 +1534,10 @@ mod tests {
1580 /// Encode a grid of 32x32 blocks, each carrying its own DC level.1534 /// Encode a grid of 32x32 blocks, each carrying its own DC level.
1581 fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {1535 fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
1582 let (w, h) = (64 * sb_cols, 64 * sb_rows);1536 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;
1584 let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();1541 let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
1585 let mut stream = temporal_delimiter();1542 let mut stream = temporal_delimiter();
1586 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());1543 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
@@ -1836,7 +1793,14 @@ mod tests {
1836 let mut enc = SymbolEncoder::new();1793 let mut enc = SymbolEncoder::new();
1837 let mut priced = 0.0;1794 let mut priced = 0.0;
1838 for grid in &grids {1795 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+ );
1840 priced += luma_32_coeff_bits(grid);1804 priced += luma_32_coeff_bits(grid);
1841 }1805 }
1842 let spent = enc.finish().len() as f64 * 8.0;1806 let spent = enc.finish().len() as f64 * 8.0;
@@ -1872,7 +1836,10 @@ mod tests {
1872 // An empty block is one symbol -- an expensive one, because a block1836 // An empty block is one symbol -- an expensive one, because a block
1873 // with no coefficients at all is the rarer of the two under the1837 // with no coefficients at all is the rarer of the two under the
1874 // neutral context -- and nothing else.1838 // 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+ );
1876 }1843 }
1877 1844
1878 /// Neighbouring blocks that each carry coefficients read their DC sign1845 /// 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.