forge
Explore
Log in

Don't you dare go Hollow

Carry the CDF state across frames (spec 7.20)

Browse files at this commit

e1619168c8a2506486370ddd15f98abed0420921Ahmet Kaan GümüşParent: 52ec542
  • feat
    • carry the CDF state across frames (spec 7.20)
Show full message
feat(av1): carry the CDF state across frames (spec 7.20)

Inter frames now leave `disable_frame_end_update_cdf` off, so each one
stores its end-of-tile tables with the counts reset and the next frame's
writer starts from them -- the encoder mirrors `stream::stored_cdfs_for`
exactly, and the key frame keeps the bit set, so what it stores is the
defaults it started from and the first inter frame is unchanged.

`sb_coeff_{key,inter}_frame_tile_cdfs` are the writers that take and leave
the caller's `Cdfs`; the old entry points wrap them with a fresh one.
`Encoded` carries `start_cdfs`/`next_cdfs`, `Av1Encoder` carries the state
between `encode` calls, and `decode_inter_frame_tile` takes an
`initial_cdfs` -- the same threading the frame's `tx_select` bit needed,
third instance of that class, and the three GOP tests (one of which checks
ffmpeg against us) now pass the frame's own start state.

BD-rate vs libaom 210.1/218.7/167.4 -> 202.6/206.6/159.0, vs rav1e
151.8/164.7/72.7 -> 144.5/153.2/65.9; wall unchanged at 7.9/7.4/7.6 s.
crates/ec-av1/src/decode.rsmodified+9 -1
@@ -32638,6 +32638,11 @@ pub(crate) fn decode_inter_frame_tile(
3263832638 // inter frames coded Select by default (class: test asserts against a
3263932639 // stale header, second instance).
3264032640 tx_select: bool,
32641+ // The CDF state this frame's tile was WRITTEN from (`Encoded::start_cdfs`):
32642+ // an inter frame whose header leaves `disable_frame_end_update_cdf` off
32643+ // starts from what the previous frame stored, not from the defaults. Same
32644+ // class as `tx_select` above, third instance.
32645+ initial_cdfs: Option<Cdfs>,
3264132646 fctx: &crate::decode::FrameCtx,
3264232647 ) -> Result<Picture> {
3264332648 let single_tile = TileInfo {
@@ -32658,7 +32663,7 @@ pub(crate) fn decode_inter_frame_tile(
3265832663 cdef,
3265932664 loop_filter,
3266032665 &LoopRestorationParams::default(),
32661- None,
32666+ initial_cdfs,
3266232667 allow_high_precision_mv,
3266332668 force_integer_mv,
3266432669 NO_SIGN_BIAS,
@@ -36769,6 +36774,7 @@ mod tests {
3676936774 false,
3677036775 false,
3677136776 false,
36777+ None,
3677236778 fctx,
3677336779 )
3677436780 .unwrap_err();
@@ -37165,6 +37171,7 @@ mod tests {
3716537171 false,
3716637172 false,
3716737173 frame.tx_select,
37174+ Some(frame.start_cdfs.0.clone()),
3716837175 fctx,
3716937176 )
3717037177 .unwrap();
@@ -37476,6 +37483,7 @@ mod tests {
3747637483 false,
3747737484 false,
3747837485 frame.tx_select,
37486+ Some(frame.start_cdfs.0.clone()),
3747937487 fctx,
3748037488 )
3748137489 .unwrap();
crates/ec-av1/src/encode.rsmodified+68 -9
@@ -477,6 +477,19 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
477477 mi_rows: encoded.mi_rows,
478478 base_q_idx: encoded.base_q_idx,
479479 tx_select: encoded.tx_select,
480+ start_cdfs: encoded.start_cdfs.clone(),
481+ next_cdfs: encoded.next_cdfs.clone(),
482+ }
483+}
484+
485+/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
486+/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
487+#[derive(Clone)]
488+pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
489+
490+impl std::fmt::Debug for CdfSnapshot {
491+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
492+ f.write_str("CdfSnapshot")
480493 }
481494 }
482495
@@ -513,6 +526,18 @@ pub struct Encoded {
513526 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
514527 /// block.
515528 pub(crate) tx_select: bool,
529+ /// The CDF state this frame's tile writer started from -- the defaults
530+ /// for a key frame and for the first inter frame, and the previous
531+ /// frame's stored tables after that. A test that decodes `tile` directly
532+ /// must feed the decoder this, exactly as `decode_stream` feeds it what
533+ /// the frame's `primary_ref_frame` slot holds (same class as
534+ /// `tx_select`: a header bit a raw tile decode cannot guess).
535+ pub(crate) start_cdfs: CdfSnapshot,
536+ /// What this frame stores into the slots it refreshes (spec 7.20,
537+ /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
538+ /// counts reset when `disable_frame_end_update_cdf` is off, and what it
539+ /// started from when it is on.
540+ pub(crate) next_cdfs: CdfSnapshot,
516541 }
517542
518543 /// The sequence and frame headers a picture of this size is coded under: one
@@ -691,7 +716,10 @@ pub fn inter_frame_headers(
691716 show_frame: true,
692717 error_resilient_mode: false,
693718 disable_cdf_update: false,
694- disable_frame_end_update_cdf: true,
719+ // The tile writer hands its end-of-tile tables to the next frame
720+ // (`encode_sequence_with_ctx`), so the frame stores them the way the
721+ // decoder will load them (spec 7.20).
722+ disable_frame_end_update_cdf: false,
695723 force_integer_mv: false,
696724 order_hint,
697725 primary_ref_frame: 0,
@@ -3008,12 +3036,20 @@ pub(crate) fn encode_key_frame_inner(
30083036
30093037 #[cfg(test)]
30103038 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
3011- let tile = crate::tile::sb_coeff_key_frame_tile_tx(
3039+ // A key frame always starts from the defaults (`primary_ref_frame` is
3040+ // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
3041+ // set, so what it stores into the slots it refreshes is exactly those
3042+ // defaults again (spec 7.20's `started_from` arm) -- the first inter
3043+ // frame after it therefore starts from the defaults too.
3044+ let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
3045+ let start_cdfs = CdfSnapshot(cdfs.clone());
3046+ let tile = crate::tile::sb_coeff_key_frame_tile_cdfs(
30123047 header.mi_cols,
30133048 header.mi_rows,
30143049 base_q_idx,
30153050 &superblocks,
30163051 tx_select,
3052+ &mut cdfs,
30173053 )?;
30183054 let mut stream = temporal_delimiter();
30193055 stream.extend_from_slice(&sequence_header_obu(&seq)?);
@@ -3036,6 +3072,8 @@ pub(crate) fn encode_key_frame_inner(
30363072 mi_rows: header.mi_rows,
30373073 base_q_idx,
30383074 tx_select,
3075+ next_cdfs: start_cdfs.clone(),
3076+ start_cdfs,
30393077 })
30403078 }
30413079
@@ -3620,7 +3658,12 @@ pub(crate) fn encode_inter_frame(
36203658 base_q_idx: u8,
36213659 deadzone: f64,
36223660 order_hint: u32,
3623- render: (usize, usize), fctx: &crate::decode::FrameCtx,
3661+ render: (usize, usize),
3662+ // The tables this frame's writer starts from: what the previous frame
3663+ // stored into the slot this one's `primary_ref_frame` names. `None`
3664+ // starts from the defaults, which is right only for the frame straight
3665+ // after a key frame.
3666+ start_cdfs: Option<&crate::cdf_state::Cdfs>, fctx: &crate::decode::FrameCtx,
36243667 ) -> Result<Encoded> {
36253668 picture.check()?;
36263669 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
@@ -4084,13 +4127,24 @@ pub(crate) fn encode_inter_frame(
40844127 / modes.len() as f64;
40854128 #[cfg(test)]
40864129 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
4087- let tile = crate::tile::sb_coeff_inter_frame_tile_tx(
4130+ // This frame's header leaves `disable_frame_end_update_cdf` off, so it
4131+ // stores its end-of-tile tables with the counts reset (spec 7.20) and the
4132+ // next frame's writer starts from them -- exactly what
4133+ // `crate::stream::stored_cdfs_for` hands the decoder.
4134+ let mut cdfs = start_cdfs
4135+ .cloned()
4136+ .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
4137+ let start_cdfs = CdfSnapshot(cdfs.clone());
4138+ let tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(
40884139 header.mi_cols,
40894140 header.mi_rows,
40904141 base_q_idx,
40914142 &blocks,
40924143 tx_select,
4144+ &mut cdfs,
40934145 )?;
4146+ cdfs.reset_counts();
4147+ let next_cdfs = CdfSnapshot(cdfs);
40944148 let mut stream = temporal_delimiter();
40954149 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
40964150
@@ -4111,6 +4165,8 @@ pub(crate) fn encode_inter_frame(
41114165 mi_rows: header.mi_rows,
41124166 base_q_idx,
41134167 tx_select,
4168+ start_cdfs,
4169+ next_cdfs,
41144170 })
41154171 }
41164172
@@ -4169,6 +4225,7 @@ pub(crate) fn encode_sequence_with_ctx(
41694225 unspecified_color_config(), fctx,
41704226 )?;
41714227 let mut stream = key.stream.clone();
4228+ let mut carried = key.next_cdfs.clone();
41724229 let mut reference = key.reconstruction.clone();
41734230 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
41744231 for (i, picture) in rest.iter().enumerate() {
@@ -4186,9 +4243,11 @@ pub(crate) fn encode_sequence_with_ctx(
41864243 base_q_idx,
41874244 deadzone,
41884245 order_hint,
4189- render, fctx,
4246+ render,
4247+ Some(&carried.0), fctx,
41904248 )?;
41914249 stream.extend_from_slice(&inter.stream);
4250+ carried = inter.next_cdfs.clone();
41924251 reference = inter.reconstruction.clone();
41934252 frames.push(crop_encoded(&inter, render.0, render.1));
41944253 }
@@ -6180,7 +6239,7 @@ mod tests {
61806239 let padded_pic = picture.padded_to(SUPERBLOCK);
61816240 let t = Instant::now();
61826241 let inter =
6183- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), fctx).unwrap();
6242+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, fctx).unwrap();
61846243 let inter_t = t.elapsed();
61856244 eprintln!(
61866245 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
@@ -6278,7 +6337,7 @@ mod tests {
62786337 stage_reset();
62796338 let t = Instant::now();
62806339 let inter =
6281- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), fctx).unwrap();
6340+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, fctx).unwrap();
62826341 let total_t = t.elapsed();
62836342 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
62846343 let accounted = motion_search + transform_quant + entropy;
@@ -6455,7 +6514,7 @@ mod tests {
64556514 q,
64566515 0.5,
64576516 1,
6458- (width, height), fctx,
6517+ (width, height), None, fctx,
64596518 )
64606519 .unwrap();
64616520 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
@@ -6472,7 +6531,7 @@ mod tests {
64726531 q,
64736532 0.5,
64746533 1,
6475- (width, height), fctx,
6534+ (width, height), None, fctx,
64766535 )
64776536 .unwrap();
64786537 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
crates/ec-av1/src/encoder.rsmodified+8 -0
@@ -226,6 +226,11 @@ pub struct Av1Encoder {
226226 /// thread-local. One per encoder, never per frame: several of its fields
227227 /// (the inter-frame inheritance guards) carry state ACROSS frames.
228228 fctx: crate::decode::FrameCtx,
229+ /// What the last coded frame stored into the reference slot the next
230+ /// inter frame reads (spec 7.20): the tables that frame's tile writer
231+ /// must start from, since the header leaves
232+ /// `disable_frame_end_update_cdf` off. `None` before the first frame.
233+ carried_cdfs: Option<crate::encode::CdfSnapshot>,
229234 }
230235
231236 /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are
@@ -251,6 +256,7 @@ impl Av1Encoder {
251256 // then.
252257 Picture::grey(config.width, config.height).check_even()?;
253258 Ok(Self {
259+ carried_cdfs: None,
254260 color_config: config.colour.color_config(),
255261 config,
256262 reference: None,
@@ -355,10 +361,12 @@ impl Av1Encoder {
355361 DEADZONE,
356362 order as u32,
357363 render,
364+ self.carried_cdfs.as_ref().map(|c| &c.0),
358365 &self.fctx,
359366 )?
360367 };
361368
369+ self.carried_cdfs = Some(encoded.next_cdfs.clone());
362370 self.reference = Some(encoded.reconstruction.clone());
363371 self.next_index += 1;
364372 let cropped = crop_encoded(&encoded, render.0, render.1);
crates/ec-av1/src/tile.rsmodified+40 -3
@@ -135,7 +135,7 @@ const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19);
135135 /// The coefficient q-context (spec 8.3.2's `Get_Qctx`, `Default_..._Cdf`'s
136136 /// leading index) a frame's `base_q_idx` picks its default CDFs from.
137137 /// [`crate::cdf`] carries all four, one constant set per context.
138-fn q_ctx_of(base_q_idx: u8) -> usize {
138+pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
139139 match base_q_idx {
140140 0..=20 => 0,
141141 21..=60 => 1,
@@ -1049,6 +1049,26 @@ pub fn sb_coeff_key_frame_tile_tx(
10491049 base_q_idx: u8,
10501050 superblocks: &[Superblock],
10511051 tx_select: bool,
1052+) -> Result<Vec<u8>> {
1053+ let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1054+ sb_coeff_key_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, superblocks, tx_select, &mut cdfs)
1055+}
1056+
1057+/// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the
1058+/// caller's own CDF state, which is what a frame whose
1059+/// `disable_frame_end_update_cdf` is off needs: the next frame's writer must
1060+/// start where this tile ended (spec 7.20, mirrored by
1061+/// `crate::stream::stored_cdfs_for`).
1062+///
1063+/// # Errors
1064+/// As [`sb_coeff_key_frame_tile_tx`].
1065+pub(crate) fn sb_coeff_key_frame_tile_cdfs(
1066+ mi_cols: u32,
1067+ mi_rows: u32,
1068+ _base_q_idx: u8,
1069+ superblocks: &[Superblock],
1070+ tx_select: bool,
1071+ cdfs: &mut Cdfs,
10521072 ) -> Result<Vec<u8>> {
10531073 check_blocks(mi_cols, mi_rows)?;
10541074 let (cols, rows) = block_grid(mi_cols, mi_rows);
@@ -1108,7 +1128,7 @@ pub fn sb_coeff_key_frame_tile_tx(
11081128 // The tile adapts every non-literal CDF it writes, exactly as the decoder
11091129 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
11101130 // off.
1111- let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1131+ let mut cdfs = cdfs;
11121132 let mut enc = SymbolEncoder::new();
11131133 for sb_r in 0..sb_rows {
11141134 neighbours.start_row();
@@ -2811,6 +2831,23 @@ pub fn sb_coeff_inter_frame_tile_tx(
28112831 base_q_idx: u8,
28122832 blocks: &[Quadrant],
28132833 tx_select: bool,
2834+) -> Result<Vec<u8>> {
2835+ let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
2836+ sb_coeff_inter_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, blocks, tx_select, &mut cdfs)
2837+}
2838+
2839+/// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
2840+/// the caller's own CDF state; see [`sb_coeff_key_frame_tile_cdfs`].
2841+///
2842+/// # Errors
2843+/// As [`sb_coeff_inter_frame_tile_tx`].
2844+pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
2845+ mi_cols: u32,
2846+ mi_rows: u32,
2847+ _base_q_idx: u8,
2848+ blocks: &[Quadrant],
2849+ tx_select: bool,
2850+ cdfs: &mut Cdfs,
28142851 ) -> Result<Vec<u8>> {
28152852 check_blocks(mi_cols, mi_rows)?;
28162853 // `block_grid`'s ceiling, not a plain division: a true frame size that is
@@ -2853,7 +2890,7 @@ pub fn sb_coeff_inter_frame_tile_tx(
28532890 mi_rows as usize,
28542891 );
28552892 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
2856- let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
2893+ let mut cdfs = cdfs;
28572894 let mut enc = SymbolEncoder::new();
28582895 // An `is_inter` block's 32x32 luma transform reads a different
28592896 // `tx_type` set than an intra block's (`get_tx_set`, spec 5.11.48; see