forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'main' (d5fc99e0) into lane-av1lr

Browse files at this commit

8e2799acfc87c130bf007b1fd0265a867cab45d5Ahmet Kaan GümüşParent: 3bf4b1b0f15668
Nine hunks across three files, all taken both ways.

tile.rs: that lane split each writer into a `_tx` wrapper and a
`_cdfs` worker, so this lane's arm/clear guard moves down into the
worker, where the symbols are actually written.

decode.rs: `decode_inter_frame_tile_lr` now takes `initial_cdfs`
alongside `lr` and both wrappers thread it; the two chained-decode
tests pass this frame's own `loop_restoration` AND its `start_cdfs`.

encode.rs: the tile is written through the CDF-carrying writer, and
this lane's re-codes (for the `cdef_idx` literals and the per-unit
restoration syntax) each restart from the frame's OWN `start_cdfs`
rather than from where the first write left them -- the second tile is
the first tile's symbol sequence plus new ones, so it has to adapt from
the same point the decoder will. The winning re-code publishes its
end-of-tile tables into `next_cdfs`, which is what the next frame's
writer starts from; the first write's would have been stale.

Byte pins re-measured on the merged tree: q=150 7416 -> 7458 bytes,
q=60 27927 -> 27807.
crates/ec-av1/src/decode.rsmodified+37 -4
@@ -32863,13 +32863,18 @@ pub(crate) fn decode_inter_frame_tile(
3286332863 // inter frames coded Select by default (class: test asserts against a
3286432864 // stale header, second instance).
3286532865 tx_select: bool,
32866+ // The CDF state this frame's tile was WRITTEN from (`Encoded::start_cdfs`):
32867+ // an inter frame whose header leaves `disable_frame_end_update_cdf` off
32868+ // starts from what the previous frame stored, not from the defaults. Same
32869+ // class as `tx_select` above, third instance.
32870+ initial_cdfs: Option<Cdfs>,
3286632871 fctx: &crate::decode::FrameCtx,
3286732872 ) -> Result<Picture> {
3286832873 decode_inter_frame_tile_lr(
3286932874 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef,
3287032875 loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed,
3287132876 enable_dual_filter, reference_select, tx_select,
32872- &LoopRestorationParams::default(), fctx,
32877+ &LoopRestorationParams::default(), initial_cdfs, fctx,
3287332878 )
3287432879 }
3287532880
@@ -32893,6 +32898,7 @@ pub(crate) fn decode_inter_frame_tile_lr(
3289332898 reference_select: bool,
3289432899 tx_select: bool,
3289532900 lr: &LoopRestorationParams,
32901+ initial_cdfs: Option<Cdfs>,
3289632902 fctx: &crate::decode::FrameCtx,
3289732903 ) -> Result<Picture> {
3289832904 let single_tile = TileInfo {
@@ -32913,7 +32919,7 @@ pub(crate) fn decode_inter_frame_tile_lr(
3291332919 cdef,
3291432920 loop_filter,
3291532921 lr,
32916- None,
32922+ initial_cdfs,
3291732923 allow_high_precision_mv,
3291832924 force_integer_mv,
3291932925 NO_SIGN_BIAS,
@@ -35909,6 +35915,22 @@ mod tests {
3590935915 RefPix::ready(refs)
3591035916 }
3591135917
35918+ /// [`last_only`] plus `GOLDEN_FRAME` (index 4 of the name-keyed array)
35919+ /// and `ALTREF_FRAME` (index 7, the frame two back, which the encoder
35920+ /// keeps in the slot the current frame refreshes): what a frame this
35921+ /// encoder writes needs, since its blocks may name any of the three.
35922+ fn last_golden_altref<'a>(
35923+ last: &'a Picture,
35924+ golden: &'a Picture,
35925+ altref: Option<&'a Picture>,
35926+ ) -> RefPix<'a> {
35927+ let mut refs: [Option<&Picture>; 8] = [None; 8];
35928+ refs[1] = Some(last);
35929+ refs[4] = Some(golden);
35930+ refs[7] = altref;
35931+ RefPix::ready(refs)
35932+ }
35933+
3591235934
3591335935 /// lane-perf6 step 2: the CDEF kernel now reads a pre-gathered window and
3591435936 /// a pre-resolved damping shift instead of a bounds-testing closure and a
@@ -37050,6 +37072,7 @@ mod tests {
3705037072 false,
3705137073 false,
3705237074 false,
37075+ None,
3705337076 fctx,
3705437077 )
3705537078 .unwrap_err();
@@ -37440,7 +37463,11 @@ mod tests {
3744037463 frame.base_q_idx,
3744137464 width as u32,
3744237465 height as u32,
37443- &last_only(&reference),
37466+ &last_golden_altref(
37467+ &reference,
37468+ &encoded.frames[0].reconstruction,
37469+ (i >= 2).then(|| &encoded.frames[i - 2].reconstruction),
37470+ ),
3744437471 &frame.cdef,
3744537472 &frame.loop_filter,
3744637473 false,
@@ -37450,6 +37477,7 @@ mod tests {
3745037477 false,
3745137478 frame.tx_select,
3745237479 &frame.loop_restoration,
37480+ Some(frame.start_cdfs.0.clone()),
3745337481 fctx,
3745437482 )
3745537483 .unwrap();
@@ -37753,7 +37781,11 @@ mod tests {
3775337781 frame.base_q_idx,
3775437782 coded_w,
3775537783 coded_h,
37756- &last_only(&reference),
37784+ &last_golden_altref(
37785+ &reference,
37786+ &encoded.frames[0].reconstruction,
37787+ (i >= 2).then(|| &encoded.frames[i - 2].reconstruction),
37788+ ),
3775737789 &frame.cdef,
3775837790 &frame.loop_filter,
3775937791 false,
@@ -37763,6 +37795,7 @@ mod tests {
3776337795 false,
3776437796 frame.tx_select,
3776537797 &frame.loop_restoration,
37798+ Some(frame.start_cdfs.0.clone()),
3776637799 fctx,
3776737800 )
3776837801 .unwrap();
crates/ec-av1/src/encode.rsmodified+495 -205
@@ -491,12 +491,25 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
491491 mi_rows: encoded.mi_rows,
492492 base_q_idx: encoded.base_q_idx,
493493 tx_select: encoded.tx_select,
494+ start_cdfs: encoded.start_cdfs.clone(),
495+ next_cdfs: encoded.next_cdfs.clone(),
494496 loop_filter: encoded.loop_filter,
495497 loop_restoration: encoded.loop_restoration,
496498 cdef: encoded.cdef,
497499 }
498500 }
499501
502+/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
503+/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
504+#[derive(Clone)]
505+pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
506+
507+impl std::fmt::Debug for CdfSnapshot {
508+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
509+ f.write_str("CdfSnapshot")
510+ }
511+}
512+
500513 /// What one call to [`encode_key_frame`] produced.
501514 #[derive(Clone, Debug)]
502515 pub struct Encoded {
@@ -530,6 +543,18 @@ pub struct Encoded {
530543 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
531544 /// block.
532545 pub(crate) tx_select: bool,
546+ /// The CDF state this frame's tile writer started from -- the defaults
547+ /// for a key frame and for the first inter frame, and the previous
548+ /// frame's stored tables after that. A test that decodes `tile` directly
549+ /// must feed the decoder this, exactly as `decode_stream` feeds it what
550+ /// the frame's `primary_ref_frame` slot holds (same class as
551+ /// `tx_select`: a header bit a raw tile decode cannot guess).
552+ pub(crate) start_cdfs: CdfSnapshot,
553+ /// What this frame stores into the slots it refreshes (spec 7.20,
554+ /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
555+ /// counts reset when `disable_frame_end_update_cdf` is off, and what it
556+ /// started from when it is on.
557+ pub(crate) next_cdfs: CdfSnapshot,
533558 /// This frame header's chosen deblocking parameters
534559 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
535560 /// picture the decoder produces UNDER them, so a test that decodes
@@ -708,6 +733,11 @@ pub(crate) fn key_frame_headers_colour(
708733 Ok((seq, header))
709734 }
710735
736+/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
737+/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
738+/// 1 still holds the key frame however long the GOP runs.
739+pub const GOLDEN_SLOT: u8 = 1;
740+
711741 /// The frame header for a shown inter frame that predicts from the single
712742 /// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
713743 /// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
@@ -721,6 +751,26 @@ pub fn inter_frame_headers(
721751 base_q_idx: u8,
722752 order_hint: u32,
723753 last_slot: u8,
754+) -> Result<(SequenceHeader, FrameHeader)> {
755+ inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
756+}
757+
758+/// [`inter_frame_headers`] with the three slots named apart: the one read as
759+/// `LAST_FRAME`, the one this frame refreshes, and the one read as
760+/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
761+/// so that the frame two back is still intact in the slot this one is about
762+/// to overwrite -- read before write, spec 7.20's decode order.
763+///
764+/// # Errors
765+/// As [`inter_frame_headers`].
766+pub fn inter_frame_headers_slots(
767+ width: usize,
768+ height: usize,
769+ base_q_idx: u8,
770+ order_hint: u32,
771+ last_slot: u8,
772+ self_slot: u8,
773+ altref_slot: u8,
724774 ) -> Result<(SequenceHeader, FrameHeader)> {
725775 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
726776 let header = FrameHeader {
@@ -729,12 +779,25 @@ pub fn inter_frame_headers(
729779 show_frame: true,
730780 error_resilient_mode: false,
731781 disable_cdf_update: false,
732- disable_frame_end_update_cdf: true,
782+ // The tile writer hands its end-of-tile tables to the next frame
783+ // (`encode_sequence_with_ctx`), so the frame stores them the way the
784+ // decoder will load them (spec 7.20).
785+ disable_frame_end_update_cdf: false,
733786 force_integer_mv: false,
734787 order_hint,
735788 primary_ref_frame: 0,
736- refresh_frame_flags: 1 << last_slot,
737- ref_frame_idx: [last_slot; ec_av1_syntax::REFS_PER_FRAME],
789+ refresh_frame_flags: 1 << self_slot,
790+ // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
791+ // names the slot this frame both predicts from and refreshes;
792+ // GOLDEN names slot 1, which the key frame wrote when it refreshed
793+ // all eight and which no inter frame ever overwrites, so it holds
794+ // the key frame's own picture for the whole GOP.
795+ ref_frame_idx: {
796+ let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
797+ idx[3] = GOLDEN_SLOT;
798+ idx[6] = altref_slot;
799+ idx
800+ },
738801 allow_high_precision_mv: false,
739802 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
740803 is_motion_mode_switchable: false,
@@ -2357,8 +2420,10 @@ fn code_square_inter(
23572420 eight: None,
23582421 tx_depth,
23592422 inter: Some(InterInfo {
2423+ ref_frame: crate::mvstack::LAST_FRAME,
23602424 mode: InterMode::NewMv,
23612425 mv: new_mv,
2426+ ref_mv_idx: 0,
23622427 }),
23632428 },
23642429 cost + dcost,
@@ -2382,8 +2447,10 @@ fn code_square_inter(
23822447 eight: None,
23832448 tx_depth,
23842449 inter: Some(InterInfo {
2450+ ref_frame: crate::mvstack::LAST_FRAME,
23852451 mode: InterMode::NearestMv,
23862452 mv,
2453+ ref_mv_idx: 0,
23872454 }),
23882455 }, inter_cost + dcost)
23892456 } else {
@@ -2399,7 +2466,7 @@ fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: O
23992466 let info = match inter {
24002467 Some(info) => MiInfo {
24012468 is_inter: true,
2402- ref_frame: LAST_FRAME,
2469+ ref_frame: info.ref_frame,
24032470 ref_frame1: NO_REF1,
24042471 mv1: (0, 0),
24052472 mv: mv16(info.mv),
@@ -3044,13 +3111,21 @@ pub(crate) fn encode_key_frame_inner(
30443111
30453112 #[cfg(test)]
30463113 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
3114+ // A key frame always starts from the defaults (`primary_ref_frame` is
3115+ // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
3116+ // set, so what it stores into the slots it refreshes is exactly those
3117+ // defaults again (spec 7.20's `started_from` arm) -- the first inter
3118+ // frame after it therefore starts from the defaults too.
30473119 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
3048- let mut tile = crate::tile::sb_coeff_key_frame_tile_tx(
3120+ let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
3121+ let start_cdfs = CdfSnapshot(cdfs.clone());
3122+ let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs(
30493123 mi_cols,
30503124 mi_rows,
30513125 base_q_idx,
30523126 &superblocks,
30533127 tx_select,
3128+ &mut cdfs,
30543129 )?;
30553130 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
30563131 // the tile just coded back to the decoder under each candidate (see
@@ -3072,15 +3147,21 @@ pub(crate) fn encode_key_frame_inner(
30723147 &mut tile,
30733148 search.lambda,
30743149 fctx,
3150+ // Every re-code starts from this frame's OWN starting tables, never
3151+ // from where the first write left them: the second tile is the same
3152+ // symbol sequence plus new ones, so it must adapt from the same
3153+ // point the decoder will.
30753154 |bits, sb_cols, grid, units| {
30763155 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
30773156 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3078- crate::tile::sb_coeff_key_frame_tile_tx(
3157+ let mut cdfs = start_cdfs.0.clone();
3158+ crate::tile::sb_coeff_key_frame_tile_cdfs(
30793159 mi_cols,
30803160 mi_rows,
30813161 base_q_idx,
30823162 &superblocks,
30833163 tx_select,
3164+ &mut cdfs,
30843165 )
30853166 },
30863167 |lf, cdef, h, tile, lr| {
@@ -3124,6 +3205,8 @@ pub(crate) fn encode_key_frame_inner(
31243205 mi_rows: header.mi_rows,
31253206 base_q_idx,
31263207 tx_select,
3208+ next_cdfs: start_cdfs.clone(),
3209+ start_cdfs,
31273210 loop_filter: header.loop_filter,
31283211 cdef: header.cdef,
31293212 loop_restoration: header.loop_restoration,
@@ -3483,7 +3566,13 @@ fn search_inter_block(
34833566 search: &Search,
34843567 mode_bits: &[f64; 13],
34853568 reference: &Picture,
3486- stack: &MvStack, fctx: &crate::decode::FrameCtx,
3569+ stack: &MvStack,
3570+ // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
3571+ // for the whole GOP, with the stack this block derives against it. Only
3572+ // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
3573+ // second motion search would double the wall of the stage that already
3574+ // owns most of it.
3575+ extra: &[(i8, &Picture, &MvStack)], fctx: &crate::decode::FrameCtx,
34873576 ) -> (BlockCoeffs, f64) {
34883577 // `luma_set` is the INTRA candidates' table; the two inter candidates
34893578 // below price their coefficients through `TxbSet::Luma32Inter`, which is
@@ -3496,9 +3585,17 @@ fn search_inter_block(
34963585 // function's doc comment.
34973586 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
34983587 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
3499- let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0)
3500- + symbol_bits(&cdf::SINGLE_REF[0][2], 0)
3501- + symbol_bits(&cdf::SINGLE_REF[0][3], 0);
3588+ // `write_single_ref`'s own tree, at the fixed context this pricer uses
3589+ // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0 and GOLDEN
3590+ // p1=0,p3=1,p5=1.
3591+ let single_ref_bits = |ref_frame: i8| {
3592+ symbol_bits(&cdf::SINGLE_REF[0][0], 0)
3593+ + if ref_frame == crate::mvstack::GOLDEN_FRAME {
3594+ symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1)
3595+ } else {
3596+ symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0)
3597+ }
3598+ };
35023599
35033600 struct Candidate {
35043601 cost: f64,
@@ -3631,100 +3728,72 @@ fn search_inter_block(
36313728 chroma[1].true_width,
36323729 chroma[1].true_height,
36333730 );
3634- let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
3635- + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
3636- + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
3637-
3638- // The NEARESTMV candidate: `skip` is decided below from whether its
3639- // trial actually found a nonzero level, once its residual is priced
3640- // against the same CDFs the tile writer codes it with.
3641- //
3642- // lane-av1speed: its three trials are kept (rather than moved straight
3643- // into the candidate) so that a NEWMV landing on the very same vector --
3644- // common on static content, where the stack's nearest vector is also
3645- // what the search finds -- reuses them instead of running the same
3646- // motion compensation, transform, quantize and reconstruct again. The
3647- // reused trials are the same values, so the choice is bit-identical.
3648- let nearest_trials;
3649- {
3650- let mv = stack.nearest_mv;
3651- let luma_trial = mc_trial(
3652- luma,
3653- x,
3654- y,
3655- BLOCK,
3656- mv,
3657- true,
3658- ref_luma.0,
3659- ref_luma.1,
3660- ref_luma.2,
3661- ref_luma.3,
3662- false,
3663- search.base_q_idx,
3664- search.deadzone,
3665- TxbSet::Luma32Inter, fctx,
3666- );
3667- let u = mc_trial(
3668- &chroma[0],
3669- x / 2,
3670- y / 2,
3671- BLOCK / 2,
3672- mv,
3673- false,
3674- ref_u.0,
3675- ref_u.1,
3676- ref_u.2,
3677- ref_u.3,
3678- false,
3679- search.base_q_idx,
3680- search.deadzone,
3681- chroma_set, fctx,
3682- );
3683- let v = mc_trial(
3684- &chroma[1],
3685- x / 2,
3686- y / 2,
3687- BLOCK / 2,
3688- mv,
3689- false,
3690- ref_v.0,
3691- ref_v.1,
3692- ref_v.2,
3693- ref_v.3,
3694- false,
3695- search.base_q_idx,
3696- search.deadzone,
3697- chroma_set, fctx,
3698- );
3699- let skip = luma_trial.levels.iter().all(|&l| l == 0)
3700- && u.levels.iter().all(|&l| l == 0)
3701- && v.levels.iter().all(|&l| l == 0);
3702- let cost = luma_trial.sse
3703- + u.sse
3704- + v.sse
3705- + search.lambda
3706- * (skip_bits(skip)
3707- + intra_inter_bits(true)
3708- + single_ref_bits
3709- + mode_bits_inter
3710- + if skip {
3711- 0.0
3712- } else {
3713- luma_trial.bits + u.bits + v.bits
3714- });
3715- nearest_trials = (luma_trial.clone(), u.clone(), v.clone());
3716- consider(Candidate {
3717- cost,
3718- luma: luma_trial,
3719- u,
3720- v,
3721- mode: DC_PRED,
3722- skip,
3723- inter: Some(InterInfo {
3731+ // Every single-reference mode the writer can code (spec 5.11.24's symbol
3732+ // chain, mirrored by `tile::write_inter_mode`), priced with the static
3733+ // CDFs at this block's own stack contexts. A candidate is a motion
3734+ // vector plus the cheapest syntax that reaches it, so two modes landing
3735+ // on the same vector share one set of trials: the added modes cost
3736+ // mode-bit arithmetic, not another motion compensation.
3737+ let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
3738+ let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
3739+ // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
3740+ // past `start`, `1` to advance and `0` to stop, at most two. A `target`
3741+ // the loop cannot reach is never offered below -- every candidate's
3742+ // index is one this same loop walks to.
3743+ let drl_bits = |start: usize, target: usize| {
3744+ let mut bits = 0.0;
3745+ let mut idx = start;
3746+ while idx < start + 2 && stack.entries.len() > idx + 1 {
3747+ let advance = idx < target;
3748+ bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
3749+ if !advance {
3750+ break;
3751+ }
3752+ idx += 1;
3753+ }
3754+ bits
3755+ };
3756+ let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME);
3757+ let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
3758+ (
3759+ stack.nearest_mv,
3760+ last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
3761+ InterInfo {
3762+ ref_frame: crate::mvstack::LAST_FRAME,
37243763 mode: InterMode::NearestMv,
3725- mv,
3726- }),
3727- });
3764+ mv: stack.nearest_mv,
3765+ ref_mv_idx: 0,
3766+ },
3767+ ),
3768+ // GLOBALMV is the identity model's zero vector -- this encoder writes
3769+ // no `gm_params` -- and the cheapest syntax of the four on the static
3770+ // content where that vector is also the right one.
3771+ (
3772+ (0, 0),
3773+ last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
3774+ InterInfo {
3775+ ref_frame: crate::mvstack::LAST_FRAME,
3776+ mode: InterMode::GlobalMv,
3777+ mv: (0, 0),
3778+ ref_mv_idx: 0,
3779+ },
3780+ ),
3781+ ];
3782+ let near_bits =
3783+ last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
3784+ for idx in 1..=2usize {
3785+ if let Some(e) = stack.entries.get(idx) {
3786+ cands.push((
3787+ e.mv,
3788+ near_bits + drl_bits(1, idx),
3789+ InterInfo {
3790+ ref_frame: crate::mvstack::LAST_FRAME,
3791+ mode: InterMode::NearMv,
3792+ mv: e.mv,
3793+ ref_mv_idx: idx as u8,
3794+ },
3795+ ));
3796+ }
37283797 }
37293798
37303799 let source_block = luma.source_block(x, y, BLOCK);
@@ -3746,96 +3815,157 @@ fn search_inter_block(
37463815 #[cfg(test)]
37473816 stage_add(0, t.elapsed());
37483817 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
3749- if let Some(mv_bits) = mv_residual_bits(mv, stack.pred_mv) {
3750- let (luma_trial, u, v) = if mv == stack.nearest_mv {
3751- nearest_trials
3752- } else {
3753- (
3754- mc_trial(
3755- luma,
3756- x,
3757- y,
3758- BLOCK,
3759- mv,
3760- true,
3761- ref_luma.0,
3762- ref_luma.1,
3763- ref_luma.2,
3764- ref_luma.3,
3765- false,
3766- search.base_q_idx,
3767- search.deadzone,
3768- TxbSet::Luma32Inter, fctx,
3769- ),
3770- mc_trial(
3771- &chroma[0],
3772- x / 2,
3773- y / 2,
3774- BLOCK / 2,
3775- mv,
3776- false,
3777- ref_u.0,
3778- ref_u.1,
3779- ref_u.2,
3780- ref_u.3,
3781- false,
3782- search.base_q_idx,
3783- search.deadzone,
3784- chroma_set, fctx,
3785- ),
3786- mc_trial(
3787- &chroma[1],
3788- x / 2,
3789- y / 2,
3790- BLOCK / 2,
3791- mv,
3792- false,
3793- ref_v.0,
3794- ref_v.1,
3795- ref_v.2,
3796- ref_v.3,
3797- false,
3798- search.base_q_idx,
3799- search.deadzone,
3800- chroma_set, fctx,
3801- ),
3802- )
3803- };
3804- let drl_bits = if stack.entries.len() > 1 {
3805- symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
3806- } else {
3807- 0.0
3808- };
3809- let skip = luma_trial.levels.iter().all(|&l| l == 0)
3810- && u.levels.iter().all(|&l| l == 0)
3811- && v.levels.iter().all(|&l| l == 0);
3812- let cost = luma_trial.sse
3813- + u.sse
3814- + v.sse
3815- + search.lambda
3816- * (skip_bits(skip)
3817- + intra_inter_bits(true)
3818- + single_ref_bits
3819- + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
3820- + drl_bits
3821- + mv_bits
3822- + if skip {
3823- 0.0
3824- } else {
3825- luma_trial.bits + u.bits + v.bits
3826- });
3827- consider(Candidate {
3828- cost,
3829- luma: luma_trial,
3830- u,
3831- v,
3832- mode: DC_PRED,
3833- skip,
3834- inter: Some(InterInfo {
3818+ // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
3819+ // the same vector costs a different residual from each: take the index
3820+ // whose residual plus DRL bits is cheapest, not entry 0 by default.
3821+ let mut best_new: Option<(f64, u8)> = None;
3822+ for idx in 0..3usize {
3823+ if idx > 0 && stack.entries.len() <= idx {
3824+ break;
3825+ }
3826+ let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
3827+ if let Some(b) = mv_residual_bits(mv, base) {
3828+ let total = b + drl_bits(0, idx);
3829+ if best_new.is_none_or(|(t, _)| total < t) {
3830+ best_new = Some((total, idx as u8));
3831+ }
3832+ }
3833+ }
3834+ if let Some((bits, ref_mv_idx)) = best_new {
3835+ cands.push((
3836+ mv,
3837+ last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,
3838+ InterInfo {
3839+ ref_frame: crate::mvstack::LAST_FRAME,
38353840 mode: InterMode::NewMv,
38363841 mv,
3837- }),
3838- });
3842+ ref_mv_idx,
3843+ },
3844+ ));
3845+ }
3846+
3847+ for &(ref_frame, _, gstack) in extra {
3848+ let g_ref_bits = single_ref_bits(ref_frame);
3849+ let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
3850+ cands.push((
3851+ gstack.nearest_mv,
3852+ g_ref_bits
3853+ + g_not_new
3854+ + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
3855+ + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
3856+ InterInfo {
3857+ ref_frame,
3858+ mode: InterMode::NearestMv,
3859+ mv: gstack.nearest_mv,
3860+ ref_mv_idx: 0,
3861+ },
3862+ ));
3863+ cands.push((
3864+ (0, 0),
3865+ g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
3866+ InterInfo {
3867+ ref_frame,
3868+ mode: InterMode::GlobalMv,
3869+ mv: (0, 0),
3870+ ref_mv_idx: 0,
3871+ },
3872+ ));
3873+ }
3874+
3875+ // One trial set per distinct (reference, vector) pair: sort, cheapest
3876+ // syntax first, and drop the rest of each pair's run.
3877+ cands.sort_by(|a, b| {
3878+ (a.2.ref_frame, a.0)
3879+ .cmp(&(b.2.ref_frame, b.0))
3880+ .then(a.1.total_cmp(&b.1))
3881+ });
3882+ cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
3883+ {
3884+ for (mv, mode_bits_inter, info) in cands {
3885+ let (ref_luma, ref_u, ref_v) = match extra
3886+ .iter()
3887+ .find(|(r, _, _)| *r == info.ref_frame)
3888+ {
3889+ Some(&(_, g, _)) => (
3890+ (&g.y, g.width, luma.true_width, luma.true_height),
3891+ (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
3892+ (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
3893+ ),
3894+ None => (ref_luma, ref_u, ref_v),
3895+ };
3896+ let luma_trial = mc_trial(
3897+ luma,
3898+ x,
3899+ y,
3900+ BLOCK,
3901+ mv,
3902+ true,
3903+ ref_luma.0,
3904+ ref_luma.1,
3905+ ref_luma.2,
3906+ ref_luma.3,
3907+ false,
3908+ search.base_q_idx,
3909+ search.deadzone,
3910+ TxbSet::Luma32Inter, fctx,
3911+ );
3912+ let u = mc_trial(
3913+ &chroma[0],
3914+ x / 2,
3915+ y / 2,
3916+ BLOCK / 2,
3917+ mv,
3918+ false,
3919+ ref_u.0,
3920+ ref_u.1,
3921+ ref_u.2,
3922+ ref_u.3,
3923+ false,
3924+ search.base_q_idx,
3925+ search.deadzone,
3926+ chroma_set, fctx,
3927+ );
3928+ let v = mc_trial(
3929+ &chroma[1],
3930+ x / 2,
3931+ y / 2,
3932+ BLOCK / 2,
3933+ mv,
3934+ false,
3935+ ref_v.0,
3936+ ref_v.1,
3937+ ref_v.2,
3938+ ref_v.3,
3939+ false,
3940+ search.base_q_idx,
3941+ search.deadzone,
3942+ chroma_set, fctx,
3943+ );
3944+ let skip = luma_trial.levels.iter().all(|&l| l == 0)
3945+ && u.levels.iter().all(|&l| l == 0)
3946+ && v.levels.iter().all(|&l| l == 0);
3947+ let cost = luma_trial.sse
3948+ + u.sse
3949+ + v.sse
3950+ + search.lambda
3951+ * (skip_bits(skip)
3952+ + intra_inter_bits(true)
3953+ + mode_bits_inter
3954+ + if skip {
3955+ 0.0
3956+ } else {
3957+ luma_trial.bits + u.bits + v.bits
3958+ });
3959+ consider(Candidate {
3960+ cost,
3961+ luma: luma_trial,
3962+ u,
3963+ v,
3964+ mode: DC_PRED,
3965+ skip,
3966+ inter: Some(info),
3967+ });
3968+ }
38393969 }
38403970
38413971 let best = best.expect("the search offers at least the intra modes");
@@ -3867,7 +3997,20 @@ pub(crate) fn encode_inter_frame(
38673997 base_q_idx: u8,
38683998 deadzone: f64,
38693999 order_hint: u32,
3870- render: (usize, usize), fctx: &crate::decode::FrameCtx,
4000+ render: (usize, usize),
4001+ // The tables this frame's writer starts from: what the previous frame
4002+ // stored into the slot this one's `primary_ref_frame` names. `None`
4003+ // starts from the defaults, which is right only for the frame straight
4004+ // after a key frame.
4005+ start_cdfs: Option<&crate::cdf_state::Cdfs>,
4006+ // The key frame's own (padded) reconstruction, which every frame of the
4007+ // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
4008+ // with `LAST_FRAME` alone, exactly as before.
4009+ golden: Option<&Picture>,
4010+ // The frame two back, held in the slot this frame is about to refresh
4011+ // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
4012+ // inter frames of a GOP, where the frame two back IS the key frame.
4013+ altref: Option<&Picture>, fctx: &crate::decode::FrameCtx,
38714014 ) -> Result<Encoded> {
38724015 picture.check()?;
38734016 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
@@ -3890,14 +4033,33 @@ pub(crate) fn encode_inter_frame(
38904033 // overwrites slot 0, so the frame just coded is always what the next one
38914034 // predicts against.
38924035 const LAST_SLOT: u8 = 0;
4036+ // Slot 0 and slot 2 alternate so the frame two back survives one more
4037+ // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
4038+ // and the picture this frame names as `ALTREF_FRAME` is the one sitting
4039+ // in the very slot it will overwrite.
4040+ let self_slot = if order_hint % 2 == 1 { 0 } else { 2 };
4041+ let last_slot = if order_hint <= 1 {
4042+ LAST_SLOT
4043+ } else if (order_hint - 1) % 2 == 1 {
4044+ 0
4045+ } else {
4046+ 2
4047+ };
38934048 // `render`, not `picture.width`/`picture.height`: `picture` here is
38944049 // already padded to a whole number of superblocks (`encode_sequence`'s
38954050 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
38964051 // every true-edge clamp downstream) must come from the frame's real,
38974052 // unpadded size, same as `key_frame_headers_colour` takes `render` and
38984053 // not the padded picture in `encode_key_frame_inner`.
3899- let (seq, mut header) =
3900- inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?;
4054+ let (seq, mut header) = inter_frame_headers_slots(
4055+ render.0,
4056+ render.1,
4057+ base_q_idx,
4058+ order_hint,
4059+ last_slot,
4060+ self_slot,
4061+ if altref.is_some() { self_slot } else { GOLDEN_SLOT },
4062+ )?;
39014063 header.render_width = render.0 as u32;
39024064 header.render_height = render.1 as u32;
39034065 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
@@ -4002,6 +4164,25 @@ pub(crate) fn encode_inter_frame(
40024164 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
40034165 let stack =
40044166 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
4167+ let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
4168+ (crate::mvstack::GOLDEN_FRAME, golden),
4169+ (crate::mvstack::ALTREF_FRAME, altref),
4170+ ]
4171+ .into_iter()
4172+ .filter_map(|(r, pic)| {
4173+ pic.map(|p| {
4174+ (
4175+ r,
4176+ p,
4177+ find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
4178+ )
4179+ })
4180+ })
4181+ .collect();
4182+ let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
4183+ .iter()
4184+ .map(|(r, p, st)| (*r, *p, st))
4185+ .collect();
40054186
40064187 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
40074188 let (block, mut cost_whole) = search_inter_block(
@@ -4011,7 +4192,8 @@ pub(crate) fn encode_inter_frame(
40114192 &search,
40124193 &mode_bits_table,
40134194 reference,
4014- &stack, fctx,
4195+ &stack,
4196+ &extra, fctx,
40154197 );
40164198 cost_whole += search.lambda * partition_bits(BLOCK, false);
40174199 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
@@ -4331,13 +4513,22 @@ pub(crate) fn encode_inter_frame(
43314513 / modes.len() as f64;
43324514 #[cfg(test)]
43334515 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
4516+ // This frame's header leaves `disable_frame_end_update_cdf` off, so it
4517+ // stores its end-of-tile tables with the counts reset (spec 7.20) and the
4518+ // next frame's writer starts from them -- exactly what
4519+ // `crate::stream::stored_cdfs_for` hands the decoder.
43344520 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
4335- let mut tile = crate::tile::sb_coeff_inter_frame_tile_tx(
4521+ let mut cdfs = start_cdfs
4522+ .cloned()
4523+ .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
4524+ let start_cdfs = CdfSnapshot(cdfs.clone());
4525+ let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(
43364526 mi_cols,
43374527 mi_rows,
43384528 base_q_idx,
43394529 &blocks,
43404530 tx_select,
4531+ &mut cdfs,
43414532 )?;
43424533 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
43434534 // this tile against the same single-slot reference this encoder predicted
@@ -4347,6 +4538,7 @@ pub(crate) fn encode_inter_frame(
43474538 // reference whose height is not the header's own `frame_height` (spec
43484539 // 7.9's compatible-size rule), and the chained-decode round trips prove
43494540 // the two predict identically.
4541+ let end_cdfs = std::cell::RefCell::new(cdfs);
43504542 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
43514543 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
43524544 reference.clone()
@@ -4359,8 +4551,39 @@ pub(crate) fn encode_inter_frame(
43594551 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
43604552 }
43614553 };
4554+ // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
4555+ // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
4556+ // blocks may name GOLDEN needs that plane too, cropped the same way.
4557+ let trial_golden = golden.map(|g| {
4558+ if (g.width, g.height) == (fw, fh) {
4559+ g.clone()
4560+ } else {
4561+ Picture {
4562+ width: fw,
4563+ height: fh,
4564+ y: crop_plane(&g.y, g.width, fw, fh),
4565+ u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
4566+ v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
4567+ }
4568+ }
4569+ });
4570+ let trial_altref = altref.map(|a| {
4571+ if (a.width, a.height) == (fw, fh) {
4572+ a.clone()
4573+ } else {
4574+ Picture {
4575+ width: fw,
4576+ height: fh,
4577+ y: crop_plane(&a.y, a.width, fw, fh),
4578+ u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
4579+ v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
4580+ }
4581+ }
4582+ });
43624583 let mut refs: [Option<&Picture>; 8] = [None; 8];
43634584 refs[1] = Some(&trial_ref);
4585+ refs[4] = trial_golden.as_ref();
4586+ refs[7] = trial_altref.as_ref();
43644587 let refpix = crate::decode::RefPix::ready(refs);
43654588 // The luma restoration-unit grid this frame's `lr_params` implies
43664589 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
@@ -4381,16 +4604,26 @@ pub(crate) fn encode_inter_frame(
43814604 &mut tile,
43824605 search.lambda,
43834606 fctx,
4607+ // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
4608+ // are what the NEXT frame writes from, so the winning re-code
4609+ // publishes its own into `end_cdfs` -- the first write's are stale
4610+ // the moment a second tile is coded.
43844611 |bits, sb_cols, grid, units| {
43854612 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
43864613 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
4387- crate::tile::sb_coeff_inter_frame_tile_tx(
4614+ let mut cdfs = start_cdfs.0.clone();
4615+ let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(
43884616 mi_cols,
43894617 mi_rows,
43904618 base_q_idx,
43914619 &blocks,
43924620 tx_select,
4393- )
4621+ &mut cdfs,
4622+ );
4623+ if coded.is_ok() {
4624+ *end_cdfs.borrow_mut() = cdfs;
4625+ }
4626+ coded
43944627 },
43954628 |lf, cdef, h, tile, lr| {
43964629 crate::decode::decode_inter_frame_tile_lr(
@@ -4410,10 +4643,17 @@ pub(crate) fn encode_inter_frame(
44104643 h.reference_select,
44114644 tx_select,
44124645 lr,
4646+ // The trial decode re-reads the tile the writer just wrote,
4647+ // so it starts from the same tables the writer did (this
4648+ // frame's `start_cdfs`), not from the defaults.
4649+ Some(start_cdfs.0.clone()),
44134650 fctx,
44144651 )
44154652 },
44164653 )?;
4654+ let mut cdfs = end_cdfs.into_inner();
4655+ cdfs.reset_counts();
4656+ let next_cdfs = CdfSnapshot(cdfs);
44174657 let mut stream = temporal_delimiter();
44184658 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
44194659
@@ -4434,6 +4674,8 @@ pub(crate) fn encode_inter_frame(
44344674 mi_rows: header.mi_rows,
44354675 base_q_idx,
44364676 tx_select,
4677+ start_cdfs,
4678+ next_cdfs,
44374679 loop_filter: header.loop_filter,
44384680 cdef: header.cdef,
44394681 loop_restoration: header.loop_restoration,
@@ -4495,6 +4737,14 @@ pub(crate) fn encode_sequence_with_ctx(
44954737 unspecified_color_config(), fctx,
44964738 )?;
44974739 let mut stream = key.stream.clone();
4740+ // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
4741+ // key frame refreshes every slot, each inter frame only slot 0), which is
4742+ // what `GOLDEN_FRAME` names.
4743+ let golden = key.reconstruction.clone();
4744+ // The frame two back, once there is one that is not the key frame
4745+ // itself (which `GOLDEN_FRAME` already names).
4746+ let mut prev2: Option<Picture> = None;
4747+ let mut carried = key.next_cdfs.clone();
44984748 let mut reference = key.reconstruction.clone();
44994749 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
45004750 for (i, picture) in rest.iter().enumerate() {
@@ -4512,10 +4762,17 @@ pub(crate) fn encode_sequence_with_ctx(
45124762 base_q_idx,
45134763 deadzone,
45144764 order_hint,
4515- render, fctx,
4765+ render,
4766+ Some(&carried.0),
4767+ Some(&golden),
4768+ prev2.as_ref(), fctx,
45164769 )?;
45174770 stream.extend_from_slice(&inter.stream);
4518- reference = inter.reconstruction.clone();
4771+ carried = inter.next_cdfs.clone();
4772+ prev2 = Some(std::mem::replace(
4773+ &mut reference,
4774+ inter.reconstruction.clone(),
4775+ ));
45194776 frames.push(crop_encoded(&inter, render.0, render.1));
45204777 }
45214778 Ok(EncodedSequence { stream, frames })
@@ -4925,15 +5182,19 @@ mod tests {
49255182 eight: None,
49265183 tx_depth: 0,
49275184 inter: Some(InterInfo {
5185+ ref_frame: crate::mvstack::LAST_FRAME,
49285186 mode: InterMode::NearestMv,
49295187 mv: (0, 0),
5188+ ref_mv_idx: 0,
49305189 }),
49315190 };
49325191 let skipped_block = BlockCoeffs {
49335192 skip: true,
49345193 inter: Some(InterInfo {
5194+ ref_frame: crate::mvstack::LAST_FRAME,
49355195 mode: InterMode::NearestMv,
49365196 mv: (0, 0),
5197+ ref_mv_idx: 0,
49375198 }),
49385199 ..BlockCoeffs::default()
49395200 };
@@ -6544,7 +6805,7 @@ mod tests {
65446805 let padded_pic = picture.padded_to(SUPERBLOCK);
65456806 let t = Instant::now();
65466807 let inter =
6547- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), fctx).unwrap();
6808+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap();
65486809 let inter_t = t.elapsed();
65496810 eprintln!(
65506811 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
@@ -6642,7 +6903,7 @@ mod tests {
66426903 stage_reset();
66436904 let t = Instant::now();
66446905 let inter =
6645- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), fctx).unwrap();
6906+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap();
66466907 let total_t = t.elapsed();
66476908 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
66486909 let accounted = motion_search + transform_quant + entropy;
@@ -6819,7 +7080,7 @@ mod tests {
68197080 q,
68207081 0.5,
68217082 1,
6822- (width, height), fctx,
7083+ (width, height), None, None, None, fctx,
68237084 )
68247085 .unwrap();
68257086 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
@@ -6836,7 +7097,7 @@ mod tests {
68367097 q,
68377098 0.5,
68387099 1,
6839- (width, height), fctx,
7100+ (width, height), None, None, None, fctx,
68407101 )
68417102 .unwrap();
68427103 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
@@ -7221,6 +7482,12 @@ mod tests {
72217482 ///
72227483 /// The BD gate above measures quality, which a speed lane can move by a
72237484 /// hair without failing anything; this pins the streams themselves.
7485+ /// Re-measured on the lane-av1lr merge with main d5fc99e0: the per-64x64
7486+ /// `cdef_idx` literals and the per-unit loop restoration syntax are new
7487+ /// bits in the tile, so the streams move (q=150 7416 -> 7458 bytes,
7488+ /// q=60 27927 -> 27807 -- the low-rate frame pays for the syntax, the
7489+ /// high-rate one more than earns it back).
7490+ ///
72247491 /// Every number below was measured 2026-09-06: first on lane-av1fwd
72257492 /// (whose three speed steps left them identical to `a6649c4e`'s), then
72267493 /// re-measured on the lane-av1lr merge, which legitimately moves them --
@@ -7248,7 +7515,7 @@ mod tests {
72487515 })
72497516 };
72507517 let pins: [(u8, usize, u64); 2] =
7251- [(150, 7796, 0x70db_e81d_606b_034c), (60, 28182, 0xb23d_005b_1f2e_e008)];
7518+ [(150, 7458, 0x7eb2_33c6_bd96_3baf), (60, 27807, 0xeee0_f1e5_e099_46bd)];
72527519 for (q, bytes, hash) in pins {
72537520 let encoded = encode_sequence(&source, q, 0.5).unwrap();
72547521 assert_eq!(
@@ -7409,11 +7676,34 @@ mod tests {
74097676 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
74107677 let _ = take_partition_hits();
74117678 let _ = take_uv_mode_hits();
7679+ let _ = crate::tile::take_inter_mode_hits();
7680+ let _ = crate::tile::take_drl_hits();
7681+ let _ = crate::tile::take_ref_hits();
74127682 let (ours, ours_wall) = our_ladder(&source, width, height, fctx);
74137683 // How often the inter split actually fired over this clip's four
74147684 // encodes, against the whole 32x32 that was the only outcome
74157685 // before (gate-blind-to-feature).
74167686 let [whole32, split32, whole16, split16] = take_partition_hits();
7687+ // Which inter modes actually fired over this clip's four encodes,
7688+ // and at which DRL index -- a mode nobody picks is a mode the BD
7689+ // number cannot be crediting (gate-blind-to-feature).
7690+ let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
7691+ let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
7692+ let refs = crate::tile::take_ref_hits();
7693+ let modes_total = (nearest + near + global + new).max(1);
7694+ eprintln!(
7695+ "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
7696+ GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
7697+ {drl0}/{drl1}/{drl2}/{drl3}",
7698+ 100.0 * nearest as f64 / modes_total as f64,
7699+ 100.0 * near as f64 / modes_total as f64,
7700+ 100.0 * global as f64 / modes_total as f64,
7701+ 100.0 * new as f64 / modes_total as f64,
7702+ );
7703+ eprintln!(
7704+ "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
7705+ refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
7706+ );
74177707 eprintln!(
74187708 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
74197709 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
crates/ec-av1/src/encoder.rsmodified+24 -0
@@ -226,6 +226,17 @@ 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>,
234+ /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`,
235+ /// which stays in DPB slot 1 until the next key frame refreshes it.
236+ golden: Option<Picture>,
237+ /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is
238+ /// about to refresh (`encode_inter_frame`'s 0/2 alternation).
239+ prev2: Option<Picture>,
229240 }
230241
231242 /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are
@@ -251,6 +262,9 @@ impl Av1Encoder {
251262 // then.
252263 Picture::grey(config.width, config.height).check_even()?;
253264 Ok(Self {
265+ carried_cdfs: None,
266+ golden: None,
267+ prev2: None,
254268 color_config: config.colour.color_config(),
255269 config,
256270 reference: None,
@@ -355,10 +369,20 @@ impl Av1Encoder {
355369 DEADZONE,
356370 order as u32,
357371 render,
372+ self.carried_cdfs.as_ref().map(|c| &c.0),
373+ self.golden.as_ref(),
374+ self.prev2.as_ref(),
358375 &self.fctx,
359376 )?
360377 };
361378
379+ self.carried_cdfs = Some(encoded.next_cdfs.clone());
380+ if is_key {
381+ self.golden = Some(encoded.reconstruction.clone());
382+ self.prev2 = None;
383+ } else {
384+ self.prev2 = self.reference.take();
385+ }
362386 self.reference = Some(encoded.reconstruction.clone());
363387 self.next_index += 1;
364388 let cropped = crop_encoded(&encoded, render.0, render.1);
crates/ec-av1/src/mvstack.rsmodified+1 -0
@@ -2399,6 +2399,7 @@ pub struct CompoundTplArgs<'a> {
23992399 /// two-valued test: "is there an inter neighbour at all". `has_inter`
24002400 /// gathers that over the block's whole span, the way spec 5.11.39 reads any
24012401 /// neighbour-derived context.
2402+#[cfg(test)]
24022403 pub(crate) fn single_ref_ctx(has_inter_neighbour: bool) -> usize {
24032404 if has_inter_neighbour { 2 } else { 1 }
24042405 }
crates/ec-av1/src/stream.rsmodified+8 -1
@@ -3396,7 +3396,13 @@ mod tests {
33963396
33973397 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
33983398 // 128 block (no neighbours to predict `DC_PRED` from).
3399- let (_, header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
3399+ let (_, mut header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
3400+ // These two tiles are hand-coded from a FRESH `Cdfs`, so the
3401+ // frames must not carry CDF state the way the encoder's own inter
3402+ // frames now do (spec 7.20): with the bit set, what each frame
3403+ // stores is what it started from -- the defaults -- which is
3404+ // exactly what the next hand-coded tile assumes.
3405+ header1.disable_frame_end_update_cdf = true;
34003406 let tile1 = {
34013407 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
34023408 let mut enc = SymbolEncoder::new();
@@ -3414,6 +3420,7 @@ mod tests {
34143420 // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME,
34153421 // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0).
34163422 let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap();
3423+ header2.disable_frame_end_update_cdf = true;
34173424 header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1
34183425 let tile2 = {
34193426 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
crates/ec-av1/src/tile.rsmodified+299 -120
@@ -18,7 +18,7 @@ use crate::cdf;
1818 use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
1919 use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect};
2020 use crate::msac::SymbolEncoder;
21-use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ctx};
21+use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16};
2222
2323 // ---------------------------------------------------------------------------
2424 // lane-av1lr: per-64x64 `cdef_idx` (spec 5.11.56, `read_cdef`). The decoder
@@ -293,7 +293,7 @@ const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19);
293293 /// The coefficient q-context (spec 8.3.2's `Get_Qctx`, `Default_..._Cdf`'s
294294 /// leading index) a frame's `base_q_idx` picks its default CDFs from.
295295 /// [`crate::cdf`] carries all four, one constant set per context.
296-fn q_ctx_of(base_q_idx: u8) -> usize {
296+pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
297297 match base_q_idx {
298298 0..=20 => 0,
299299 21..=60 => 1,
@@ -645,16 +645,21 @@ pub struct BlockCoeffs {
645645 pub tx_depth: u8,
646646 }
647647
648-/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take (spec
649-/// 5.11.24 `read_inter_mode`), reduced to the two branches its symbol chain
650-/// needs to prove out: the stack's own top candidate outright, or a coded
651-/// residual against it. `NEARMV`/`GLOBALMV` are never written.
648+/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
649+/// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
650+/// [`write_inter_mode`] with the decoder's own contexts.
652651 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
653652 pub enum InterMode {
654653 /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL.
655654 NearestMv,
656- /// `NEWMV`: codes `mv` as a residual against `MvStack::pred_mv`, through
657- /// a DRL index this writer always leaves at zero.
655+ /// `NEARMV`: takes the stack entry [`InterInfo::ref_mv_idx`] names
656+ /// (clamped to at least 1, the spec's own `RefMvIdx` base for this mode).
657+ NearMv,
658+ /// `GLOBALMV`: the identity global model's zero vector, two symbols and
659+ /// no MV at all.
660+ GlobalMv,
661+ /// `NEWMV`: codes `mv` as a residual against the stack entry
662+ /// [`InterInfo::ref_mv_idx`] names.
658663 NewMv,
659664 }
660665
@@ -668,6 +673,14 @@ pub struct InterInfo {
668673 pub mode: InterMode,
669674 /// The motion vector a [`InterMode::NewMv`] block's residual targets.
670675 pub mv: (i32, i32),
676+ /// The reference this block predicts from (`LAST_FRAME`..=`ALTREF_FRAME`,
677+ /// spec 6.10.24's alphabet), written by [`write_single_ref`].
678+ pub ref_frame: i8,
679+ /// The block's `RefMvIdx` (spec 5.11.24 `read_drl_idx`): which
680+ /// `MvStack::entries` slot `NEWMV` codes its residual against, or
681+ /// `NEARMV` takes outright. Ignored by the two modes that code no DRL
682+ /// index (`NEARESTMV`, `GLOBALMV`).
683+ pub ref_mv_idx: u8,
671684 }
672685
673686 impl From<Vec<Coeff>> for BlockCoeffs {
@@ -833,6 +846,12 @@ struct Neighbours {
833846 above_inter: Vec<bool>,
834847 /// The same, down the left edge.
835848 left_inter: Vec<bool>,
849+ /// The reference each neighbour named, `-1` for an intra or unavailable
850+ /// one -- what the decoder keeps in its own `Neighbours::above_ref`
851+ /// (decode.rs) and feeds `read_single_ref`'s context functions.
852+ above_ref: Vec<i8>,
853+ /// The same, down the left edge.
854+ left_ref: Vec<i8>,
836855 /// The frame's true (unpadded) width and height, in 4x4 mode-info units,
837856 /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec
838857 /// `av1_set_entropy_contexts`): a block whose row or column run spills
@@ -876,6 +895,8 @@ impl Neighbours {
876895 left_skip: vec![false; rows * (SUB / MI)],
877896 above_inter: vec![false; cols * (SUB / MI)],
878897 left_inter: vec![false; rows * (SUB / MI)],
898+ above_ref: vec![-1; cols * (SUB / MI)],
899+ left_ref: vec![-1; rows * (SUB / MI)],
879900 above_tx: vec![0; cols * (SUB / MI)],
880901 left_tx: vec![0; rows * (SUB / MI)],
881902 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
@@ -893,6 +914,7 @@ impl Neighbours {
893914 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
894915 self.left_skip.iter_mut().for_each(|s| *s = false);
895916 self.left_inter.iter_mut().for_each(|i| *i = false);
917+ self.left_ref.iter_mut().for_each(|r| *r = -1);
896918 self.left_tx.iter_mut().for_each(|t| *t = 0);
897919 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
898920 }
@@ -1092,19 +1114,21 @@ impl Neighbours {
10921114 /// Writes one inter-frame block's skip flag and inter/intra state into
10931115 /// every 16x16 column and row it covers, the same span [`Self::record`]
10941116 /// fills for the coefficient and mode state.
1095- fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool) {
1117+ fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) {
10961118 let (r, c) = at;
1097- self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter);
1119+ self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame);
10981120 }
10991121
11001122 /// [`Self::record_inter`] taking the block's position directly in 4x4
11011123 /// mode-info units, for a block finer than one [`SUB`] slot.
1102- fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool) {
1124+ fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) {
11031125 for cell in 0..side / MI {
11041126 self.above_skip[mi_c + cell] = skip;
11051127 self.left_skip[mi_r + cell] = skip;
11061128 self.above_inter[mi_c + cell] = is_inter;
11071129 self.left_inter[mi_r + cell] = is_inter;
1130+ self.above_ref[mi_c + cell] = ref_frame;
1131+ self.left_ref[mi_r + cell] = ref_frame;
11081132 }
11091133 }
11101134
@@ -1198,7 +1222,27 @@ pub fn sb_coeff_key_frame_tile_tx(
11981222 superblocks: &[Superblock],
11991223 tx_select: bool,
12001224 ) -> Result<Vec<u8>> {
1201- // Consumes whatever `arm_cdef_idx` armed, on every exit path.
1225+ let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1226+ sb_coeff_key_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, superblocks, tx_select, &mut cdfs)
1227+}
1228+
1229+/// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the
1230+/// caller's own CDF state, which is what a frame whose
1231+/// `disable_frame_end_update_cdf` is off needs: the next frame's writer must
1232+/// start where this tile ended (spec 7.20, mirrored by
1233+/// `crate::stream::stored_cdfs_for`).
1234+///
1235+/// # Errors
1236+/// As [`sb_coeff_key_frame_tile_tx`].
1237+pub(crate) fn sb_coeff_key_frame_tile_cdfs(
1238+ mi_cols: u32,
1239+ mi_rows: u32,
1240+ _base_q_idx: u8,
1241+ superblocks: &[Superblock],
1242+ tx_select: bool,
1243+ cdfs: &mut Cdfs,
1244+) -> Result<Vec<u8>> {
1245+ // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
12021246 let _cdef_idx = CdefIdxGuard;
12031247 check_blocks(mi_cols, mi_rows)?;
12041248 let (cols, rows) = block_grid(mi_cols, mi_rows);
@@ -1258,7 +1302,7 @@ pub fn sb_coeff_key_frame_tile_tx(
12581302 // The tile adapts every non-literal CDF it writes, exactly as the decoder
12591303 // adapts the ones it reads, so the frame header leaves `disable_cdf_update`
12601304 // off.
1261- let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1305+ let mut cdfs = cdfs;
12621306 let mut enc = SymbolEncoder::new();
12631307 for sb_r in 0..sb_rows {
12641308 neighbours.start_row();
@@ -2831,6 +2875,205 @@ fn write_mv(
28312875 Ok(())
28322876 }
28332877
2878+/// What a block leaves in the neighbour reference bands: its own reference,
2879+/// or `-1` when it is intra (decode.rs `Neighbours::above_ref`'s convention).
2880+fn block_ref(block: &BlockCoeffs) -> i8 {
2881+ block.inter.map_or(-1, |i| i.ref_frame)
2882+}
2883+
2884+/// Writer-side counterpart of decode.rs `read_single_ref` (spec 5.11.25's
2885+/// `single_ref_p1`..`p6` tree): codes `ref_frame` bit by bit, each symbol at
2886+/// the context its own `single_ref_p*_ctx` derives from the immediate
2887+/// above/left neighbours' references -- the same functions the decoder calls,
2888+/// with `-1` standing for an intra or unavailable neighbour and no second
2889+/// reference (this writer codes no compound block).
2890+fn write_single_ref(
2891+ enc: &mut SymbolEncoder,
2892+ cdfs: &mut Cdfs,
2893+ ref_frame: i8,
2894+ above_ref: i8,
2895+ left_ref: i8,
2896+) {
2897+ REF_HITS[(ref_frame.max(1) - 1) as usize % 7].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2898+ use crate::mvstack::{
2899+ ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
2900+ single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
2901+ single_ref_p5_ctx, single_ref_p6_ctx,
2902+ };
2903+ let above = (above_ref > 0).then_some(above_ref);
2904+ let left = (left_ref > 0).then_some(left_ref);
2905+ let backward = ref_frame >= BWDREF_FRAME;
2906+ enc.symbol(
2907+ usize::from(backward),
2908+ &mut cdfs.single_ref[single_ref_p1_ctx(above, None, left, None)][0],
2909+ );
2910+ if backward {
2911+ let is_altref = ref_frame == ALTREF_FRAME;
2912+ enc.symbol(
2913+ usize::from(is_altref),
2914+ &mut cdfs.single_ref[single_ref_p2_ctx(above, None, left, None)][1],
2915+ );
2916+ if !is_altref {
2917+ enc.symbol(
2918+ usize::from(ref_frame == ALTREF2_FRAME),
2919+ &mut cdfs.single_ref[single_ref_p6_ctx(above, None, left, None)][5],
2920+ );
2921+ }
2922+ return;
2923+ }
2924+ let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
2925+ enc.symbol(
2926+ usize::from(far),
2927+ &mut cdfs.single_ref[single_ref_p3_ctx(above, None, left, None)][2],
2928+ );
2929+ if far {
2930+ enc.symbol(
2931+ usize::from(ref_frame == GOLDEN_FRAME),
2932+ &mut cdfs.single_ref[single_ref_p5_ctx(above, None, left, None)][4],
2933+ );
2934+ } else {
2935+ enc.symbol(
2936+ usize::from(ref_frame == LAST2_FRAME),
2937+ &mut cdfs.single_ref[single_ref_p4_ctx(above, None, left, None)][3],
2938+ );
2939+ }
2940+}
2941+
2942+/// Per-mode fire counts of [`write_inter_mode`], indexed
2943+/// `NEARESTMV`/`NEARMV`/`GLOBALMV`/`NEWMV`, and the DRL index each block
2944+/// coded (bucket 3 collects any index past 2). Read by the BD gate, which
2945+/// is the only thing that proves a newly added mode ever fires
2946+/// (gate-blind-to-feature).
2947+static INTER_MODE_HITS: [std::sync::atomic::AtomicUsize; 4] = [
2948+ std::sync::atomic::AtomicUsize::new(0),
2949+ std::sync::atomic::AtomicUsize::new(0),
2950+ std::sync::atomic::AtomicUsize::new(0),
2951+ std::sync::atomic::AtomicUsize::new(0),
2952+];
2953+static DRL_HITS: [std::sync::atomic::AtomicUsize; 4] = [
2954+ std::sync::atomic::AtomicUsize::new(0),
2955+ std::sync::atomic::AtomicUsize::new(0),
2956+ std::sync::atomic::AtomicUsize::new(0),
2957+ std::sync::atomic::AtomicUsize::new(0),
2958+];
2959+
2960+/// One counter per reference name (`LAST`..`ALTREF`), for the gate's own
2961+/// census of what the encoder actually picks.
2962+static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [
2963+ std::sync::atomic::AtomicUsize::new(0),
2964+ std::sync::atomic::AtomicUsize::new(0),
2965+ std::sync::atomic::AtomicUsize::new(0),
2966+ std::sync::atomic::AtomicUsize::new(0),
2967+ std::sync::atomic::AtomicUsize::new(0),
2968+ std::sync::atomic::AtomicUsize::new(0),
2969+ std::sync::atomic::AtomicUsize::new(0),
2970+];
2971+
2972+/// Takes and clears the per-reference histogram.
2973+#[cfg(test)]
2974+pub(crate) fn take_ref_hits() -> [usize; 7] {
2975+ std::array::from_fn(|i| REF_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2976+}
2977+
2978+/// Bumps the two histograms for one coded inter block.
2979+fn note_inter_mode(mode: usize, drl: usize) {
2980+ INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2981+ DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2982+}
2983+
2984+/// Takes and clears the inter-mode histogram (NEAREST/NEAR/GLOBAL/NEW).
2985+#[cfg(test)]
2986+pub(crate) fn take_inter_mode_hits() -> [usize; 4] {
2987+ [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2988+}
2989+
2990+/// Takes and clears the DRL-index histogram (0, 1, 2, 3+).
2991+#[cfg(test)]
2992+pub(crate) fn take_drl_hits() -> [usize; 4] {
2993+ [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2994+}
2995+
2996+/// Writes the DRL index of one block: the loop the decoder runs (spec
2997+/// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one
2998+/// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to
2999+/// stop, at most two bits. `drl_ctx[idx]` is the context between
3000+/// `entries[idx]` and `entries[idx + 1]`, exactly the pair the bit chooses
3001+/// between.
3002+fn write_drl_idx(
3003+ enc: &mut SymbolEncoder,
3004+ cdfs: &mut Cdfs,
3005+ stack: &crate::mvstack::MvStack,
3006+ start: usize,
3007+ target: usize,
3008+) {
3009+ let mut idx = start;
3010+ while idx < start + 2 && stack.entries.len() > idx + 1 {
3011+ let advance = idx < target;
3012+ enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[idx]]);
3013+ if !advance {
3014+ return;
3015+ }
3016+ idx += 1;
3017+ }
3018+}
3019+
3020+/// Writer-side counterpart of the decoder's single-reference
3021+/// `read_inter_mode`/`assign_mv` chain (decode.rs ~26645): writes `info`'s
3022+/// mode symbols against `stack`'s own contexts and, for `NEWMV`, the MV
3023+/// residual against the DRL-selected predictor. Returns the motion vector
3024+/// the decoder will derive for the block (what the MI grid must record) and
3025+/// whether it is `NEWMV`.
3026+///
3027+/// `GLOBALMV` resolves to `(0, 0)` because this encoder writes no global
3028+/// motion parameters at all, so every `gm_get_motion_vector` the decoder
3029+/// runs is the identity model's zero vector; a lane that starts writing
3030+/// real `gm_params` has to feed the same vector in here.
3031+///
3032+/// # Errors
3033+/// As [`write_mv`]: a `NEWMV` residual needing eighth-pel precision.
3034+fn write_inter_mode(
3035+ enc: &mut SymbolEncoder,
3036+ cdfs: &mut Cdfs,
3037+ info: InterInfo,
3038+ stack: &crate::mvstack::MvStack,
3039+) -> Result<((i32, i32), bool)> {
3040+ let idx = usize::from(info.ref_mv_idx);
3041+ match info.mode {
3042+ InterMode::NewMv => {
3043+ enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]);
3044+ write_drl_idx(enc, cdfs, stack, 0, idx);
3045+ let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
3046+ write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?;
3047+ note_inter_mode(3, idx);
3048+ Ok((info.mv, true))
3049+ }
3050+ InterMode::GlobalMv => {
3051+ enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
3052+ enc.symbol(0, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // GLOBALMV
3053+ note_inter_mode(2, 0);
3054+ Ok(((0, 0), false))
3055+ }
3056+ InterMode::NearestMv => {
3057+ enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
3058+ enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
3059+ enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
3060+ note_inter_mode(0, 0);
3061+ Ok((stack.nearest_mv, false))
3062+ }
3063+ InterMode::NearMv => {
3064+ enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
3065+ enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
3066+ enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARMV
3067+ // `RefMvIdx` starts at 1 for NEARMV (spec 5.11.24).
3068+ let idx = idx.max(1);
3069+ write_drl_idx(enc, cdfs, stack, 1, idx);
3070+ let mv = stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv);
3071+ note_inter_mode(1, idx);
3072+ Ok((mv, false))
3073+ }
3074+ }
3075+}
3076+
28343077 /// Writes the payload of a one-tile inter frame built from `blocks`, one
28353078 /// 32x32 block per entry in raster order across the frame — every superblock
28363079 /// is split into its four quadrants the way [`split_coeff_key_frame_tile`]
@@ -2884,7 +3127,24 @@ pub fn sb_coeff_inter_frame_tile_tx(
28843127 blocks: &[Quadrant],
28853128 tx_select: bool,
28863129 ) -> Result<Vec<u8>> {
2887- // Consumes whatever `arm_cdef_idx` armed, on every exit path.
3130+ let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3131+ sb_coeff_inter_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, blocks, tx_select, &mut cdfs)
3132+}
3133+
3134+/// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind --
3135+/// the caller's own CDF state; see [`sb_coeff_key_frame_tile_cdfs`].
3136+///
3137+/// # Errors
3138+/// As [`sb_coeff_inter_frame_tile_tx`].
3139+pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3140+ mi_cols: u32,
3141+ mi_rows: u32,
3142+ _base_q_idx: u8,
3143+ blocks: &[Quadrant],
3144+ tx_select: bool,
3145+ cdfs: &mut Cdfs,
3146+) -> Result<Vec<u8>> {
3147+ // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path.
28883148 let _cdef_idx = CdefIdxGuard;
28893149 check_blocks(mi_cols, mi_rows)?;
28903150 // `block_grid`'s ceiling, not a plain division: a true frame size that is
@@ -2915,9 +3175,6 @@ pub fn sb_coeff_inter_frame_tile_tx(
29153175 /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block, the only
29163176 /// size this writer's inter branch codes.
29173177 const SIZE_GROUP_32: usize = 3;
2918- /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference this
2919- /// writer's single-reference chain ever names.
2920- const LAST_FRAME: i8 = 1;
29213178
29223179 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
29233180 let mut neighbours = Neighbours::new(
@@ -2927,7 +3184,7 @@ pub fn sb_coeff_inter_frame_tile_tx(
29273184 mi_rows as usize,
29283185 );
29293186 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
2930- let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3187+ let mut cdfs = cdfs;
29313188 let mut enc = SymbolEncoder::new();
29323189 // An `is_inter` block's 32x32 luma transform reads a different
29333190 // `tx_type` set than an intra block's (`get_tx_set`, spec 5.11.48; see
@@ -3214,10 +3471,7 @@ pub fn sb_coeff_inter_frame_tile_tx(
32143471
32153472 let mode_for_tx;
32163473 if let Some(info) = block.inter {
3217- let sr_ctx = single_ref_ctx(above_inter || left_inter);
3218- enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward
3219- enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2
3220- enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST
3474+ write_single_ref(&mut enc, &mut cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]);
32213475
32223476 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
32233477 let stack = find_mv_stack(
@@ -3226,43 +3480,18 @@ pub fn sb_coeff_inter_frame_tile_tx(
32263480 mi_col,
32273481 8,
32283482 8,
3229- LAST_FRAME,
3483+ info.ref_frame,
32303484 mi_cols as usize,
32313485 mi_rows as usize,
32323486 );
32333487
3234- let is_new_mv = matches!(info.mode, InterMode::NewMv);
3235- if is_new_mv {
3236- enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV
3237- } else {
3238- enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new
3239- enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero
3240- enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
3241- }
3242- // This writer always keeps the first DRL candidate, so the
3243- // loop (spec 5.11.24 `read_drl_idx`) only ever runs its
3244- // first, breaking iteration.
3245- if is_new_mv && stack.entries.len() > 1 {
3246- enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]);
3247- }
3248- let mv = if is_new_mv {
3249- write_mv(
3250- &mut enc,
3251- &mut cdfs.mv_comp,
3252- &mut cdfs.mv_joint,
3253- info.mv,
3254- stack.pred_mv,
3255- )?;
3256- info.mv
3257- } else {
3258- stack.nearest_mv
3259- };
3488+ let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?;
32603489 grid.set(
32613490 mi_row,
32623491 mi_col,
32633492 MiInfo {
32643493 is_inter: true,
3265- ref_frame: LAST_FRAME,
3494+ ref_frame: info.ref_frame,
32663495 ref_frame1: NO_REF1,
32673496 mv1: (0, 0),
32683497 mv: mv16(mv),
@@ -3283,7 +3512,7 @@ pub fn sb_coeff_inter_frame_tile_tx(
32833512 mi_col + dc,
32843513 MiInfo {
32853514 is_inter: true,
3286- ref_frame: LAST_FRAME,
3515+ ref_frame: info.ref_frame,
32873516 ref_frame1: NO_REF1,
32883517 mv1: (0, 0),
32893518 mv: mv16(mv),
@@ -3388,7 +3617,7 @@ pub fn sb_coeff_inter_frame_tile_tx(
33883617 );
33893618 neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);
33903619 }
3391- neighbours.record_inter(at, BLOCK, block.skip, is_inter);
3620+ neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block));
33923621 }
33933622 }
33943623 }
@@ -3432,9 +3661,6 @@ fn write_inter_frame_leaf(
34323661 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
34333662 /// `size_group_lookup[BLOCK_16X16]`) for this leaf's own size.
34343663 const SIZE_GROUP_16: usize = 2;
3435- /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference this
3436- /// writer's single-reference chain ever names, same as the 32x32 branch.
3437- const LAST_FRAME: i8 = 1;
34383664
34393665 let (r, c) = at;
34403666 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
@@ -3450,10 +3676,7 @@ fn write_inter_frame_leaf(
34503676
34513677 let mode_for_tx;
34523678 if let Some(info) = block.inter {
3453- let sr_ctx = single_ref_ctx(above_inter || left_inter);
3454- enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward
3455- enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2
3456- enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST
3679+ write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]);
34573680
34583681 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
34593682 let stack = find_mv_stack(
@@ -3462,34 +3685,12 @@ fn write_inter_frame_leaf(
34623685 mi_col,
34633686 SUB_MI as usize,
34643687 SUB_MI as usize,
3465- LAST_FRAME,
3688+ info.ref_frame,
34663689 mi_cols as usize,
34673690 mi_rows as usize,
34683691 );
34693692
3470- let is_new_mv = matches!(info.mode, InterMode::NewMv);
3471- if is_new_mv {
3472- enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV
3473- } else {
3474- enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new
3475- enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero
3476- enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
3477- }
3478- if is_new_mv && stack.entries.len() > 1 {
3479- enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]);
3480- }
3481- let mv = if is_new_mv {
3482- write_mv(
3483- enc,
3484- &mut cdfs.mv_comp,
3485- &mut cdfs.mv_joint,
3486- info.mv,
3487- stack.pred_mv,
3488- )?;
3489- info.mv
3490- } else {
3491- stack.nearest_mv
3492- };
3693+ let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
34933694 for dr in 0..SUB_MI as usize {
34943695 for dc in 0..SUB_MI as usize {
34953696 grid.set(
@@ -3497,7 +3698,7 @@ fn write_inter_frame_leaf(
34973698 mi_col + dc,
34983699 MiInfo {
34993700 is_inter: true,
3500- ref_frame: LAST_FRAME,
3701+ ref_frame: info.ref_frame,
35013702 ref_frame1: NO_REF1,
35023703 mv1: (0, 0),
35033704 mv: mv16(mv),
@@ -3598,7 +3799,7 @@ fn write_inter_frame_leaf(
35983799 );
35993800 neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);
36003801 }
3601- neighbours.record_inter(at, SUB, block.skip, is_inter);
3802+ neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block));
36023803 Ok(())
36033804 }
36043805
@@ -3646,9 +3847,6 @@ fn write_inter_frame_leaf8(
36463847 /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s
36473848 /// `size_group_lookup[BLOCK_8X8]`) for this leaf's own size.
36483849 const SIZE_GROUP_8: usize = 1;
3649- /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3), same as the 16x16/32x32
3650- /// branches.
3651- const LAST_FRAME: i8 = 1;
36523850
36533851 // This leaf's own 4x4 mode-info cells, not the enclosing 16x16 slot's:
36543852 // under a real PARTITION_SPLIT all four leaves are coded, so the
@@ -3671,10 +3869,7 @@ fn write_inter_frame_leaf8(
36713869
36723870 let mode_for_tx;
36733871 if let Some(info) = block.inter {
3674- let sr_ctx = single_ref_ctx(above_inter || left_inter);
3675- enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward
3676- enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2
3677- enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST
3872+ write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[leaf_mi.1], neighbours.left_ref[leaf_mi.0]);
36783873
36793874 let (mi_row, mi_col) = leaf_mi;
36803875 let stack = find_mv_stack(
@@ -3683,34 +3878,12 @@ fn write_inter_frame_leaf8(
36833878 mi_col,
36843879 2,
36853880 2,
3686- LAST_FRAME,
3881+ info.ref_frame,
36873882 mi_cols as usize,
36883883 mi_rows as usize,
36893884 );
36903885
3691- let is_new_mv = matches!(info.mode, InterMode::NewMv);
3692- if is_new_mv {
3693- enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV
3694- } else {
3695- enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new
3696- enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero
3697- enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
3698- }
3699- if is_new_mv && stack.entries.len() > 1 {
3700- enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]);
3701- }
3702- let mv = if is_new_mv {
3703- write_mv(
3704- enc,
3705- &mut cdfs.mv_comp,
3706- &mut cdfs.mv_joint,
3707- info.mv,
3708- stack.pred_mv,
3709- )?;
3710- info.mv
3711- } else {
3712- stack.nearest_mv
3713- };
3886+ let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
37143887 for dr in 0..2 {
37153888 for dc in 0..2 {
37163889 grid.set(
@@ -3718,7 +3891,7 @@ fn write_inter_frame_leaf8(
37183891 mi_col + dc,
37193892 MiInfo {
37203893 is_inter: true,
3721- ref_frame: LAST_FRAME,
3894+ ref_frame: info.ref_frame,
37223895 ref_frame1: NO_REF1,
37233896 mv1: (0, 0),
37243897 mv: mv16(mv),
@@ -3796,7 +3969,7 @@ fn write_inter_frame_leaf8(
37963969 vec![0i32; TX4 * TX4],
37973970 ];
37983971 neighbours.record_mi(leaf_mi, 8, &zero_grids);
3799- neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some());
3972+ neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some(), block_ref(block));
38003973 } else {
38013974 let grids = [
38023975 level_grid(&block.luma, TX8)?,
@@ -3819,7 +3992,7 @@ fn write_inter_frame_leaf8(
38193992 split,
38203993 );
38213994 neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);
3822- neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter);
3995+ neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block));
38233996 }
38243997 Ok((block.skip, is_inter))
38253998 }
@@ -5987,7 +6160,7 @@ mod tests {
59876160 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
59886161
59896162 let (mode, mv) = if is_inter {
5990- let sr_ctx = single_ref_ctx(above_inter[c32] || left_inter[r32]);
6163+ let sr_ctx = crate::mvstack::single_ref_ctx(above_inter[c32] || left_inter[r32]);
59916164 count += 3;
59926165 assert_eq!(
59936166 dec.symbol(&mut cdfs.single_ref[sr_ctx][0]),
@@ -6101,8 +6274,10 @@ mod tests {
61016274 fn an_all_skip_inter_superblock_is_small_and_reads_back() {
61026275 let block = BlockCoeffs {
61036276 inter: Some(InterInfo {
6277+ ref_frame: crate::mvstack::LAST_FRAME,
61046278 mode: InterMode::NearestMv,
61056279 mv: (0, 0),
6280+ ref_mv_idx: 0,
61066281 }),
61076282 skip: true,
61086283 ..BlockCoeffs::default()
@@ -6142,16 +6317,20 @@ mod tests {
61426317 fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {
61436318 let nearest = BlockCoeffs {
61446319 inter: Some(InterInfo {
6320+ ref_frame: crate::mvstack::LAST_FRAME,
61456321 mode: InterMode::NearestMv,
61466322 mv: (0, 0),
6323+ ref_mv_idx: 0,
61476324 }),
61486325 skip: true,
61496326 ..BlockCoeffs::default()
61506327 };
61516328 let newmv = BlockCoeffs {
61526329 inter: Some(InterInfo {
6330+ ref_frame: crate::mvstack::LAST_FRAME,
61536331 mode: InterMode::NewMv,
61546332 mv: (0, 2),
6333+ ref_mv_idx: 0,
61556334 }),
61566335 skip: true,
61576336 ..BlockCoeffs::default()