forge
Explore
Log in

Don't you dare go Hollow

wip(av1): compound syntax writers, snapshot at the agent cap (may not compile)

Browse files at this commit

b22678ddf1feb8a95c6f8cd29e88fb5e8ffc37fcAhmet Kaan GümüşParent: 14a71ba
crates/ec-av1/src/encode.rsmodified+259 -2
@@ -2653,6 +2653,8 @@ fn code_square_inter(
26532653 eight: None,
26542654 tx_depth,
26552655 inter: Some(InterInfo {
2656+ ref1: None,
2657+ mv1: (0, 0),
26562658 ref_frame: crate::mvstack::LAST_FRAME,
26572659 mode: InterMode::NewMv,
26582660 mv: new_mv,
@@ -2687,6 +2689,8 @@ fn code_square_inter(
26872689 eight: None,
26882690 tx_depth,
26892691 inter: Some(InterInfo {
2692+ ref1: None,
2693+ mv1: (0, 0),
26902694 ref_frame: crate::mvstack::LAST_FRAME,
26912695 mode: InterMode::NearestMv,
26922696 mv,
@@ -3874,6 +3878,56 @@ fn mc_trial(
38743878 plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set)
38753879 }
38763880
3881+/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
3882+/// references predict into the `CONV_BUF` intermediate domain
3883+/// ([`mc::predict_compound_intermediate`]) and are blended by
3884+/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
3885+/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
3886+/// block, so the encoder's reconstruction is the decoder's.
3887+#[allow(clippy::too_many_arguments)]
3888+fn mc_trial_compound(
3889+ plane: &Plane,
3890+ x: usize,
3891+ y: usize,
3892+ side: usize,
3893+ (mv0, mv1): ((i32, i32), (i32, i32)),
3894+ luma: bool,
3895+ ref0: (&[u16], usize, usize, usize),
3896+ ref1: (&[u16], usize, usize, usize),
3897+ base_q_idx: u8,
3898+ deadzone: f64,
3899+ set: TxbSet, fctx: &crate::decode::FrameCtx,
3900+) -> Trial {
3901+ let mut inter0 = [0i32; BLOCK * BLOCK];
3902+ let mut inter1 = [0i32; BLOCK * BLOCK];
3903+ let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
3904+ for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
3905+ mc::predict_compound_intermediate(
3906+ r.0,
3907+ r.1,
3908+ r.2,
3909+ r.3,
3910+ mv_to_q4(x, mv.1, luma),
3911+ mv_to_q4(y, mv.0, luma),
3912+ mc::REF_NO_SCALE,
3913+ side,
3914+ side,
3915+ mc::InterpFilterKind::Regular,
3916+ mc::InterpFilterKind::Regular,
3917+ dst,
3918+ );
3919+ }
3920+ let mut blended16 = [0u16; BLOCK * BLOCK];
3921+ let blended16 = &mut blended16[..side * side];
3922+ mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
3923+ let mut prediction = [0u8; BLOCK * BLOCK];
3924+ let prediction = &mut prediction[..side * side];
3925+ for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
3926+ *dst = src as u8;
3927+ }
3928+ plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set)
3929+}
3930+
38773931 /// Codes one 32x32 block of an inter frame as whichever costs least of: each
38783932 /// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
38793933 /// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
@@ -3906,7 +3960,11 @@ fn search_inter_block(
39063960 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
39073961 // second motion search would double the wall of the stage that already
39083962 // owns most of it.
3909- extra: &[(i8, &Picture, &MvStack)], fctx: &crate::decode::FrameCtx,
3963+ extra: &[(i8, &Picture, &MvStack)],
3964+ // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
3965+ // the caller off the same MI grid the tile writer will (empty unless the
3966+ // frame carries `reference_select`).
3967+ compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], fctx: &crate::decode::FrameCtx,
39103968 ) -> (BlockCoeffs, f64) {
39113969 // `luma_set` is the INTRA candidates' table; the two inter candidates
39123970 // below price their coefficients through `TxbSet::Luma32Inter`, which is
@@ -4083,6 +4141,8 @@ fn search_inter_block(
40834141 stack.nearest_mv,
40844142 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
40854143 InterInfo {
4144+ ref1: None,
4145+ mv1: (0, 0),
40864146 ref_frame: crate::mvstack::LAST_FRAME,
40874147 mode: InterMode::NearestMv,
40884148 mv: stack.nearest_mv,
@@ -4096,6 +4156,8 @@ fn search_inter_block(
40964156 (0, 0),
40974157 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
40984158 InterInfo {
4159+ ref1: None,
4160+ mv1: (0, 0),
40994161 ref_frame: crate::mvstack::LAST_FRAME,
41004162 mode: InterMode::GlobalMv,
41014163 mv: (0, 0),
@@ -4111,6 +4173,8 @@ fn search_inter_block(
41114173 e.mv,
41124174 near_bits + drl_bits(1, idx),
41134175 InterInfo {
4176+ ref1: None,
4177+ mv1: (0, 0),
41144178 ref_frame: crate::mvstack::LAST_FRAME,
41154179 mode: InterMode::NearMv,
41164180 mv: e.mv,
@@ -4149,6 +4213,8 @@ fn search_inter_block(
41494213 mv,
41504214 last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,
41514215 InterInfo {
4216+ ref1: None,
4217+ mv1: (0, 0),
41524218 ref_frame: crate::mvstack::LAST_FRAME,
41534219 mode: InterMode::NewMv,
41544220 mv,
@@ -4157,6 +4223,9 @@ fn search_inter_block(
41574223 ));
41584224 }
41594225
4226+ // Each extra reference's own `NEWMV` vector, for the compound
4227+ // `NEW_NEWMV` candidate below to pair with `LAST`'s.
4228+ let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
41604229 for &(ref_frame, g, gstack) in extra {
41614230 let g_ref_bits = single_ref_bits(ref_frame);
41624231 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
@@ -4167,6 +4236,8 @@ fn search_inter_block(
41674236 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
41684237 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
41694238 InterInfo {
4239+ ref1: None,
4240+ mv1: (0, 0),
41704241 ref_frame,
41714242 mode: InterMode::NearestMv,
41724243 mv: gstack.nearest_mv,
@@ -4177,6 +4248,8 @@ fn search_inter_block(
41774248 (0, 0),
41784249 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
41794250 InterInfo {
4251+ ref1: None,
4252+ mv1: (0, 0),
41804253 ref_frame,
41814254 mode: InterMode::GlobalMv,
41824255 mv: (0, 0),
@@ -4231,11 +4304,14 @@ fn search_inter_block(
42314304 #[cfg(test)]
42324305 stage_add(0, t.elapsed());
42334306 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
4307+ extra_new_mvs.push((ref_frame, gmv));
42344308 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
42354309 cands.push((
42364310 gmv,
42374311 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
42384312 InterInfo {
4313+ ref1: None,
4314+ mv1: (0, 0),
42394315 ref_frame,
42404316 mode: InterMode::NewMv,
42414317 mv: gmv,
@@ -4246,6 +4322,131 @@ fn search_inter_block(
42464322 }
42474323 }
42484324
4325+ // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
4326+ // trial set each: both references predict the block and the two
4327+ // predictions are averaged, which is what pays on content where neither
4328+ // reference alone is right. Priced with the same static-CDF approximation
4329+ // the single-reference candidates use, plus the compound-only symbols
4330+ // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
4331+ for (ref1, g, cstack) in compound {
4332+ let (ref1, g) = (*ref1, *g);
4333+ let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME)
4334+ .contains(&ref1);
4335+ let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
4336+ + if uni {
4337+ // LAST + a backward reference: `comp_ref_type` = bidirectional,
4338+ // `comp_ref` LAST, `comp_bwdref` ALTREF.
4339+ symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
4340+ + symbol_bits(&cdf::COMP_REF[0][0], 0)
4341+ + symbol_bits(&cdf::COMP_REF[0][1], 0)
4342+ + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
4343+ } else {
4344+ // LAST + GOLDEN: unidirectional, `uni_comp_ref` p0/p1/p2.
4345+ symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
4346+ + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
4347+ + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
4348+ + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
4349+ };
4350+ let mode_ctx =
4351+ cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
4352+ let mode_bits_of =
4353+ |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
4354+ let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
4355+ #[cfg(any())]
4356+ (
4357+ cstack.nearest_mv,
4358+ mode_bits_of(0),
4359+ InterInfo {
4360+ ref_frame: crate::mvstack::LAST_FRAME,
4361+ mode: InterMode::NearestNearestMv,
4362+ mv: cstack.nearest_mv.0,
4363+ mv1: cstack.nearest_mv.1,
4364+ ref1: Some(ref1),
4365+ ref_mv_idx: 0,
4366+ },
4367+ ),
4368+ (
4369+ ((0, 0), (0, 0)),
4370+ mode_bits_of(6),
4371+ InterInfo {
4372+ ref_frame: crate::mvstack::LAST_FRAME,
4373+ mode: InterMode::GlobalGlobalMv,
4374+ mv: (0, 0),
4375+ mv1: (0, 0),
4376+ ref1: Some(ref1),
4377+ ref_mv_idx: 0,
4378+ },
4379+ ),
4380+ ];
4381+ // `NEW_NEWMV` seeded from the two single-reference searches this
4382+ // block already ran -- no joint search of its own.
4383+ if false && let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
4384+ let base = cstack
4385+ .entries
4386+ .first()
4387+ .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
4388+ if let (Some(b0), Some(b1)) = (
4389+ mv_residual_bits(mv, base.0),
4390+ mv_residual_bits(mv1, base.1),
4391+ ) {
4392+ ccands.push((
4393+ (mv, mv1),
4394+ mode_bits_of(7) + b0 + b1,
4395+ InterInfo {
4396+ ref_frame: crate::mvstack::LAST_FRAME,
4397+ mode: InterMode::NewNewMv,
4398+ mv,
4399+ mv1,
4400+ ref1: Some(ref1),
4401+ ref_mv_idx: 0,
4402+ },
4403+ ));
4404+ }
4405+ }
4406+ ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
4407+ ccands.dedup_by_key(|c| c.0);
4408+ let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
4409+ let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height);
4410+ let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height);
4411+ for (mvs, bits, info) in ccands {
4412+ let luma_trial = mc_trial_compound(
4413+ luma, x, y, BLOCK, mvs, true,
4414+ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
4415+ search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx,
4416+ );
4417+ let u = mc_trial_compound(
4418+ &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false,
4419+ (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
4420+ search.base_q_idx, search.deadzone, chroma_set, fctx,
4421+ );
4422+ let v = mc_trial_compound(
4423+ &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false,
4424+ (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
4425+ search.base_q_idx, search.deadzone, chroma_set, fctx,
4426+ );
4427+ let skip = luma_trial.levels.iter().all(|&l| l == 0)
4428+ && u.levels.iter().all(|&l| l == 0)
4429+ && v.levels.iter().all(|&l| l == 0);
4430+ let cost = luma_trial.sse
4431+ + u.sse
4432+ + v.sse
4433+ + search.lambda
4434+ * (skip_bits(skip)
4435+ + intra_inter_bits(true)
4436+ + bits
4437+ + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
4438+ consider(Candidate {
4439+ cost,
4440+ luma: luma_trial,
4441+ u,
4442+ v,
4443+ mode: DC_PRED,
4444+ skip,
4445+ inter: Some(info),
4446+ });
4447+ }
4448+ }
4449+
42494450 // One trial set per distinct (reference, vector) pair: sort, cheapest
42504451 // syntax first, and drop the rest of each pair's run.
42514452 cands.sort_by(|a, b| {
@@ -4616,6 +4817,37 @@ pub(crate) fn encode_inter_frame(
46164817 .iter()
46174818 .map(|(r, p, st)| (*r, *p, st))
46184819 .collect();
4820+ // The COMPOUND stack of each `LAST` + extra pair, off the
4821+ // same grid (and the same armed sign bias) the tile writer
4822+ // rebuilds it from. Empty unless this frame codes
4823+ // `reference_select`, which is what gates the syntax.
4824+ let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
4825+ if header.reference_select {
4826+ extra_stacks
4827+ .iter()
4828+ .map(|&(r, p, _)| {
4829+ (
4830+ r,
4831+ p,
4832+ crate::mvstack::find_mv_stack_compound(
4833+ &grid,
4834+ mi_row,
4835+ mi_col,
4836+ 8,
4837+ 8,
4838+ (crate::mvstack::LAST_FRAME, r),
4839+ mi_cols,
4840+ mi_rows,
4841+ grid.sign_bias_table(),
4842+ &[(0, 0); 7],
4843+ None,
4844+ ),
4845+ )
4846+ })
4847+ .collect()
4848+ } else {
4849+ Vec::new()
4850+ };
46194851
46204852 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
46214853 let (block, mut cost_whole) = search_inter_block(
@@ -4626,7 +4858,8 @@ pub(crate) fn encode_inter_frame(
46264858 &mode_bits_table,
46274859 reference,
46284860 &stack,
4629- &extra, fctx,
4861+ &extra,
4862+ &compound, fctx,
46304863 );
46314864 cost_whole += search.lambda * partition_bits(BLOCK, false);
46324865 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
@@ -4965,6 +5198,7 @@ pub(crate) fn encode_inter_frame(
49655198 let start_cdfs = CdfSnapshot(cdfs.clone());
49665199 crate::tile::arm_sign_bias(sign_bias);
49675200 crate::tile::arm_reference_select(header.reference_select);
5201+ crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
49685202 let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(
49695203 mi_cols,
49705204 mi_rows,
@@ -5056,6 +5290,7 @@ pub(crate) fn encode_inter_frame(
50565290 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
50575291 crate::tile::arm_sign_bias(sign_bias);
50585292 crate::tile::arm_reference_select(reference_select());
5293+ crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
50595294 let mut cdfs = start_cdfs.0.clone();
50605295 let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(
50615296 mi_cols,
@@ -5630,6 +5865,8 @@ mod tests {
56305865 eight: None,
56315866 tx_depth: 0,
56325867 inter: Some(InterInfo {
5868+ ref1: None,
5869+ mv1: (0, 0),
56335870 ref_frame: crate::mvstack::LAST_FRAME,
56345871 mode: InterMode::NearestMv,
56355872 mv: (0, 0),
@@ -5639,6 +5876,8 @@ mod tests {
56395876 let skipped_block = BlockCoeffs {
56405877 skip: true,
56415878 inter: Some(InterInfo {
5879+ ref1: None,
5880+ mv1: (0, 0),
56425881 ref_frame: crate::mvstack::LAST_FRAME,
56435882 mode: InterMode::NearestMv,
56445883 mv: (0, 0),
@@ -8220,6 +8459,8 @@ mod tests {
82208459 let _ = crate::tile::take_inter_mode_hits();
82218460 let _ = crate::tile::take_drl_hits();
82228461 let _ = crate::tile::take_ref_hits();
8462+ let _ = crate::tile::take_compound_mode_hits();
8463+ let _ = crate::tile::take_compound_pair_hits();
82238464 let _ = crate::motion::take_census();
82248465 let (ours, ours_wall) = match pyramid_from_env() {
82258466 None => our_ladder(&source, width, height, fctx),
@@ -8255,6 +8496,22 @@ mod tests {
82558496 100.0 * global as f64 / modes_total as f64,
82568497 100.0 * new as f64 / modes_total as f64,
82578498 );
8499+ // The compound census: what share of the coded inter blocks took
8500+ // a compound reference at all, which compound mode they took, and
8501+ // which pair (gate-blind-to-feature -- a compound mode nobody
8502+ // picks cannot be what a BD number credits).
8503+ let comp_modes = crate::tile::take_compound_mode_hits();
8504+ let comp_pairs = crate::tile::take_compound_pair_hits();
8505+ let comp_total: usize = comp_modes.iter().sum();
8506+ eprintln!(
8507+ "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
8508+ NEAREST_NEAREST {} NEAR_NEAR {} GLOBAL_GLOBAL {} NEW_NEW {}; pairs \
8509+ LAST+GOLDEN {} LAST+ALTREF {}",
8510+ modes_total + comp_total,
8511+ 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
8512+ comp_modes[0], comp_modes[1], comp_modes[6], comp_modes[7],
8513+ comp_pairs[3], comp_pairs[6],
8514+ );
82588515 // Where the wall-owning stage actually goes: how many candidate
82598516 // evaluations (one `mc::predict` + SAD each) a search spends, how
82608517 // many of them are subpel, and how often the winner is the seed
crates/ec-av1/src/mvstack.rsmodified+8 -0
@@ -284,6 +284,14 @@ impl MiGrid {
284284 }
285285
286286 /// Sets this frame's `ref_frame_sign_bias` (see the field).
287+ /// This grid's armed `ref_frame_sign_bias`, for the callers that build a
288+ /// COMPOUND stack (which takes the table explicitly, unlike
289+ /// [`find_mv_stack`]).
290+ pub fn sign_bias_table(&self) -> &SignBiasTable {
291+ &self.sign_bias
292+ }
293+
294+ /// Arms this grid's `ref_frame_sign_bias` for every stack built off it.
287295 pub fn set_sign_bias(&mut self, sign_bias: SignBiasTable) {
288296 self.sign_bias = sign_bias;
289297 }
crates/ec-av1/src/tile.rsmodified+459 -18
@@ -176,15 +176,253 @@ pub(crate) fn arm_reference_select(on: bool) {
176176 REFERENCE_SELECT.with(|c| c.set(on));
177177 }
178178
179+/// The compound half of a block's end-of-block neighbour record: nothing for
180+/// a single-reference or intra block, and `record_compound_mi`'s overwrite of
181+/// the ALTREF default for a compound one (this writer only codes
182+/// `comp_group_idx == 0`, `compound_idx == 1`).
183+fn record_block_compound(neighbours: &mut Neighbours, at_mi: (usize, usize), side: usize, block: &BlockCoeffs) {
184+ if let Some(r1) = block.inter.and_then(|i| i.ref1) {
185+ neighbours.record_compound_mi(at_mi, side, r1, 0, 1);
186+ }
187+}
188+
189+/// decode.rs' own `is_uni_comp_ref`: a pair is `UNIDIR_COMP_REFERENCE`
190+/// exactly when both references sit on the same temporal side.
191+fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
192+ let backward =
193+ |r: i8| (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&r);
194+ backward(ref0) == backward(ref1)
195+}
196+
197+thread_local! {
198+ /// `(order_hint_bits, this frame's order hint, each reference's order
199+ /// hint)` -- what `get_comp_index_context` (decode.rs) needs to context
200+ /// the `compound_idx` symbol, armed the same way the sign-bias table is.
201+ static ORDER_HINTS: std::cell::Cell<(u32, u32, [u32; 7])> =
202+ const { std::cell::Cell::new((7, 0, [0; 7])) };
203+}
204+
205+/// Arms this frame's order hints for the next tile written on this thread.
206+pub(crate) fn arm_order_hints(bits: u32, order_hint: u32, hints: [u32; 7]) {
207+ ORDER_HINTS.with(|c| c.set((bits, order_hint, hints)));
208+}
209+
210+/// Writer-side counterpart of decode.rs `read_compound_ref_frames` (spec
211+/// 5.11.25's `comp_reference_type`/`uni_comp_ref`/`comp_ref`/`comp_bwdref`
212+/// trees), symbol for symbol at the same contexts -- which are, as that
213+/// function's own doc records, `single_ref_p1_ctx`..`single_ref_p6_ctx`/
214+/// `uni_comp_ref_p1_ctx` under libaom's compound names.
215+///
216+/// # Errors
217+/// A pair this writer never forms (its `ref0` is not `LAST_FRAME`).
218+fn write_compound_ref_frames(
219+ enc: &mut SymbolEncoder,
220+ cdfs: &mut Cdfs,
221+ above: Option<crate::mvstack::NeighbourRef>,
222+ left: Option<crate::mvstack::NeighbourRef>,
223+ above_ref: i8,
224+ left_ref: i8,
225+ (ref0, ref1): (i8, i8),
226+) -> Result<()> {
227+ use crate::mvstack::{
228+ ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
229+ LAST_FRAME, comp_reference_type_ctx, single_ref_p1_ctx, single_ref_p2_ctx,
230+ single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
231+ uni_comp_ref_p1_ctx,
232+ };
233+ let a = (above_ref > 0).then_some(above_ref);
234+ let l = (left_ref > 0).then_some(left_ref);
235+ let a1 = above.and_then(|n| n.ref1);
236+ let l1 = left.and_then(|n| n.ref1);
237+ let unidir = is_uni_comp_ref(ref0, ref1);
238+ enc.symbol(
239+ usize::from(!unidir),
240+ &mut cdfs.comp_ref_type[comp_reference_type_ctx(above, left)],
241+ );
242+ if unidir {
243+ let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
244+ enc.symbol(
245+ usize::from(both_backward),
246+ &mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0],
247+ );
248+ if both_backward {
249+ return Ok(());
250+ }
251+ if ref0 != LAST_FRAME {
252+ return Err(Error::unsupported(
253+ "AV1 tile",
254+ "a unidirectional compound pair this writer does not form",
255+ ));
256+ }
257+ let past_last2 = ref1 != LAST2_FRAME;
258+ enc.symbol(
259+ usize::from(past_last2),
260+ &mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
261+ );
262+ if past_last2 {
263+ enc.symbol(
264+ usize::from(ref1 == GOLDEN_FRAME),
265+ &mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
266+ );
267+ }
268+ return Ok(());
269+ }
270+ let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
271+ enc.symbol(
272+ usize::from(far),
273+ &mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0],
274+ );
275+ if far {
276+ enc.symbol(
277+ usize::from(ref0 == GOLDEN_FRAME),
278+ &mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2],
279+ );
280+ } else {
281+ enc.symbol(
282+ usize::from(ref0 == LAST2_FRAME),
283+ &mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1],
284+ );
285+ }
286+ let is_altref = ref1 == ALTREF_FRAME;
287+ enc.symbol(
288+ usize::from(is_altref),
289+ &mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0],
290+ );
291+ if !is_altref {
292+ enc.symbol(
293+ usize::from(ref1 == ALTREF2_FRAME),
294+ &mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1],
295+ );
296+ }
297+ Ok(())
298+}
299+
300+/// Per-mode and per-pair fire counts of [`write_compound_block`], for the
301+/// gate's own census (gate-blind-to-feature): modes indexed by the spec's
302+/// `INTER_COMPOUND_MODES`, pairs by `ref1` (`LAST`..`ALTREF`).
303+static COMPOUND_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
304+ [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
305+static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] =
306+ [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
307+
308+/// Takes and clears the compound mode histogram.
309+#[cfg(test)]
310+pub(crate) fn take_compound_mode_hits() -> [usize; 8] {
311+ std::array::from_fn(|i| COMPOUND_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
312+}
313+
314+/// Takes and clears the compound pair histogram, indexed by the SECOND
315+/// reference (`LAST` = 0 .. `ALTREF` = 6).
316+#[cfg(test)]
317+pub(crate) fn take_compound_pair_hits() -> [usize; 7] {
318+ std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
319+}
320+
321+/// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side
322+/// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /
323+/// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that
324+/// order. Returns the two motion vectors the decoder derives (what the MI
325+/// grid must record) and whether the mode was a `NEW*` one.
326+///
327+/// Only the three modes [`InterMode::compound_index`] names are written, and
328+/// only the `comp_group_idx == 0`, `compound_idx == 1` blend (spec
329+/// `COMPOUND_AVERAGE`) -- masked compound and the distance-weighted blend are
330+/// not searched.
331+///
332+/// # Errors
333+/// As [`write_mv`], or a pair/mode this writer does not form.
334+#[allow(clippy::too_many_arguments)]
335+fn write_compound_block(
336+ enc: &mut SymbolEncoder,
337+ cdfs: &mut Cdfs,
338+ neighbours: &Neighbours,
339+ grid: &crate::mvstack::MiGrid,
340+ (mi_row, mi_col): (usize, usize),
341+ (bw4, bh4): (usize, usize),
342+ (has_above, has_left): (bool, bool),
343+ info: InterInfo,
344+ (mi_cols, mi_rows): (usize, usize),
345+) -> Result<((i32, i32), (i32, i32), bool)> {
346+ let (Some(ref1), Some(mode)) = (info.ref1, info.mode.compound_index()) else {
347+ return Err(Error::unsupported(
348+ "AV1 tile",
349+ "a compound block needs a second reference and a compound mode",
350+ ));
351+ };
352+ let above = has_above.then(|| neighbours.above_nbr(mi_col));
353+ let left = has_left.then(|| neighbours.left_nbr(mi_row));
354+ write_compound_ref_frames(
355+ enc,
356+ cdfs,
357+ above,
358+ left,
359+ neighbours.above_ref[mi_col],
360+ neighbours.left_ref[mi_row],
361+ (info.ref_frame, ref1),
362+ )?;
363+ let stack = crate::mvstack::find_mv_stack_compound(
364+ grid,
365+ mi_row,
366+ mi_col,
367+ bw4,
368+ bh4,
369+ (info.ref_frame, ref1),
370+ mi_cols,
371+ mi_rows,
372+ grid.sign_bias_table(),
373+ &[(0, 0); 7],
374+ None,
375+ );
376+ let ctx = crate::cdf::COMPOUND_MODE_CTX_MAP[stack.ref_mv_ctx >> 1][stack.new_mv_ctx.min(4)];
377+ enc.symbol(mode, &mut cdfs.inter_compound_mode[ctx]);
378+ // `assign_compound_mv`'s own DRL half: `NEW_NEWMV` walks from index 0,
379+ // the two derived modes code no index at all.
380+ let mvs = match info.mode {
381+ InterMode::NearestNearestMv => stack.nearest_mv,
382+ InterMode::GlobalGlobalMv => ((0, 0), (0, 0)),
383+ _ => {
384+ let idx = usize::from(info.ref_mv_idx);
385+ let mut walk = 0usize;
386+ while walk < 2 && stack.entries.len() > walk + 1 {
387+ let advance = walk < idx;
388+ enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[walk]]);
389+ if !advance {
390+ break;
391+ }
392+ walk += 1;
393+ }
394+ let base = stack
395+ .entries
396+ .get(idx)
397+ .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1));
398+ write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
399+ write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
400+ (info.mv, info.mv1)
401+ }
402+ };
403+ // spec 5.11.25's `comp_group_idx`/`compound_idx` are NOT coded: this
404+ // crate's sequence header carries `enable_masked_compound = false` and
405+ // `enable_jnt_comp = false` (encode.rs), and decode.rs reads neither
406+ // symbol under those bits -- it infers `comp_group_idx = 0`,
407+ // `compound_idx = 1` (the simple average), which is the only blend this
408+ // writer forms anyway. A lane that turns either sequence bit on has to
409+ // write the matching symbol here, at
410+ // `get_comp_group_idx_context`/`get_comp_index_context`'s contexts (which
411+ // is what `Neighbours::above_comp_group_idx`/`above_compound_idx` and the
412+ // armed order hints below are already kept for).
413+ let _ = ORDER_HINTS.with(std::cell::Cell::get);
414+ COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
415+ COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7]
416+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
417+ Ok((mvs.0, mvs.1, matches!(info.mode, InterMode::NewNewMv)))
418+}
419+
179420 /// Writer-side counterpart of decode.rs `read_comp_mode` (spec 5.11.25's
180421 /// `comp_mode`): on a `reference_select` frame every inter block whose size
181422 /// allows compound (`is_comp_ref_allowed`, always true here -- this writer's
182423 /// smallest leaf is 8x8) names SINGLE or COMPOUND, at
183424 /// `mvstack::reference_mode_ctx`'s own context off the same two neighbour
184-/// bands decode.rs builds its `NeighbourRef` pair from. No neighbour carries a
185-/// second reference yet (`ref1: None`), because every block this writer codes
186-/// is single-reference; a compound-writing lane fills that in from its own
187-/// `ref1` band.
425+/// bands decode.rs builds its `NeighbourRef` pair from.
188426 fn write_comp_mode(
189427 enc: &mut SymbolEncoder,
190428 cdfs: &mut Cdfs,
@@ -196,14 +434,8 @@ fn write_comp_mode(
196434 if !REFERENCE_SELECT.with(std::cell::Cell::get) {
197435 return;
198436 }
199- let nbr = |is_inter: bool, r: i8| crate::mvstack::NeighbourRef {
200- is_inter,
201- ref0: if is_inter { r } else { 0 },
202- ref1: None,
203- uni: false,
204- };
205- let above = has_above.then(|| nbr(neighbours.above_inter[mi_c], neighbours.above_ref[mi_c]));
206- let left = has_left.then(|| nbr(neighbours.left_inter[mi_r], neighbours.left_ref[mi_r]));
437+ let above = has_above.then(|| neighbours.above_nbr(mi_c));
438+ let left = has_left.then(|| neighbours.left_nbr(mi_r));
207439 let ctx = crate::mvstack::reference_mode_ctx(above, left);
208440 enc.symbol(usize::from(compound), &mut cdfs.comp_mode[ctx]);
209441 }
@@ -217,6 +449,7 @@ impl Drop for CdefIdxGuard {
217449 LR_PLAN.with(|c| *c.borrow_mut() = None);
218450 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
219451 REFERENCE_SELECT.with(|c| c.set(false));
452+ ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));
220453 }
221454 }
222455
@@ -727,6 +960,29 @@ pub enum InterMode {
727960 /// `NEWMV`: codes `mv` as a residual against the stack entry
728961 /// [`InterInfo::ref_mv_idx`] names.
729962 NewMv,
963+ /// `NEAREST_NEARESTMV`: both sides take the compound stack's own nearest
964+ /// pair, no residual, no DRL.
965+ NearestNearestMv,
966+ /// `GLOBAL_GLOBALMV`: both sides take the identity global model's zero
967+ /// vector.
968+ GlobalGlobalMv,
969+ /// `NEW_NEWMV`: both sides code a residual against the compound stack
970+ /// entry [`InterInfo::ref_mv_idx`] names.
971+ NewNewMv,
972+}
973+
974+impl InterMode {
975+ /// The spec's `INTER_COMPOUND_MODES` index (libaom `enums.h` order,
976+ /// `NEAREST_NEARESTMV = 0`..`NEW_NEWMV = 7`) for a compound mode, `None`
977+ /// for a single-reference one.
978+ fn compound_index(self) -> Option<usize> {
979+ match self {
980+ InterMode::NearestNearestMv => Some(0),
981+ InterMode::GlobalGlobalMv => Some(6),
982+ InterMode::NewNewMv => Some(7),
983+ _ => None,
984+ }
985+ }
730986 }
731987
732988 /// An inter-coded block's mode and motion vector, `mv` in the spec's 1/8-pel
@@ -747,6 +1003,13 @@ pub struct InterInfo {
7471003 /// `NEARMV` takes outright. Ignored by the two modes that code no DRL
7481004 /// index (`NEARESTMV`, `GLOBALMV`).
7491005 pub ref_mv_idx: u8,
1006+ /// The block's second reference (spec `RefFrames[1]`), `None` for a
1007+ /// single-reference block. `Some` only on a `reference_select` frame, and
1008+ /// only beside one of [`InterMode`]'s compound modes.
1009+ pub ref1: Option<i8>,
1010+ /// The motion vector into `ref1`, for the compound modes that code one
1011+ /// (`NEW_NEWMV`); the other two derive both sides.
1012+ pub mv1: (i32, i32),
7501013 }
7511014
7521015 impl From<Vec<Coeff>> for BlockCoeffs {
@@ -918,6 +1181,23 @@ struct Neighbours {
9181181 above_ref: Vec<i8>,
9191182 /// The same, down the left edge.
9201183 left_ref: Vec<i8>,
1184+ /// Each neighbour's SECOND reference, `None` for a single-reference or
1185+ /// intra one -- decode.rs `Neighbours::above_ref1`, read by every compound
1186+ /// context function (`reference_mode_ctx`, `comp_reference_type_ctx`, the
1187+ /// `comp_ref`/`comp_bwdref` votes).
1188+ above_ref1: Vec<Option<i8>>,
1189+ /// The same, down the left edge.
1190+ left_ref1: Vec<Option<i8>>,
1191+ /// What decode.rs `Neighbours::above_comp_group_idx` holds: a compound
1192+ /// neighbour's own `comp_group_idx`, or libaom's single-reference special
1193+ /// case (`3` for an ALTREF block, `0` otherwise).
1194+ above_comp_group_idx: Vec<u8>,
1195+ /// The same, down the left edge.
1196+ left_comp_group_idx: Vec<u8>,
1197+ /// The same for `compound_idx` (`1` for a single-ref ALTREF block).
1198+ above_compound_idx: Vec<u8>,
1199+ /// The same, down the left edge.
1200+ left_compound_idx: Vec<u8>,
9211201 /// The frame's true (unpadded) width and height, in 4x4 mode-info units,
9221202 /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec
9231203 /// `av1_set_entropy_contexts`): a block whose row or column run spills
@@ -963,6 +1243,12 @@ impl Neighbours {
9631243 left_inter: vec![false; rows * (SUB / MI)],
9641244 above_ref: vec![-1; cols * (SUB / MI)],
9651245 left_ref: vec![-1; rows * (SUB / MI)],
1246+ above_ref1: vec![None; cols * (SUB / MI)],
1247+ left_ref1: vec![None; rows * (SUB / MI)],
1248+ above_comp_group_idx: vec![0; cols * (SUB / MI)],
1249+ left_comp_group_idx: vec![0; rows * (SUB / MI)],
1250+ above_compound_idx: vec![0; cols * (SUB / MI)],
1251+ left_compound_idx: vec![0; rows * (SUB / MI)],
9661252 above_tx: vec![0; cols * (SUB / MI)],
9671253 left_tx: vec![0; rows * (SUB / MI)],
9681254 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
@@ -981,6 +1267,9 @@ impl Neighbours {
9811267 self.left_skip.iter_mut().for_each(|s| *s = false);
9821268 self.left_inter.iter_mut().for_each(|i| *i = false);
9831269 self.left_ref.iter_mut().for_each(|r| *r = -1);
1270+ self.left_ref1.iter_mut().for_each(|r| *r = None);
1271+ self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
1272+ self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
9841273 self.left_tx.iter_mut().for_each(|t| *t = 0);
9851274 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
9861275 }
@@ -1185,6 +1474,29 @@ impl Neighbours {
11851474 self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame);
11861475 }
11871476
1477+ /// [`Self::record_inter_mi`]'s compound half (decode.rs
1478+ /// `Neighbours::record_compound_ctx_rect_mi`): overwrites the ALTREF
1479+ /// single-reference default with a real compound block's own second
1480+ /// reference and `comp_group_idx`/`compound_idx` bits, called right after
1481+ /// it for every compound-coded block.
1482+ fn record_compound_mi(
1483+ &mut self,
1484+ (mi_r, mi_c): (usize, usize),
1485+ side: usize,
1486+ ref1: i8,
1487+ comp_group_idx: u8,
1488+ compound_idx: u8,
1489+ ) {
1490+ for cell in 0..side / MI {
1491+ self.above_ref1[mi_c + cell] = Some(ref1);
1492+ self.left_ref1[mi_r + cell] = Some(ref1);
1493+ self.above_comp_group_idx[mi_c + cell] = comp_group_idx;
1494+ self.left_comp_group_idx[mi_r + cell] = comp_group_idx;
1495+ self.above_compound_idx[mi_c + cell] = compound_idx;
1496+ self.left_compound_idx[mi_r + cell] = compound_idx;
1497+ }
1498+ }
1499+
11881500 /// [`Self::record_inter`] taking the block's position directly in 4x4
11891501 /// mode-info units, for a block finer than one [`SUB`] slot.
11901502 fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) {
@@ -1195,6 +1507,45 @@ impl Neighbours {
11951507 self.left_inter[mi_r + cell] = is_inter;
11961508 self.above_ref[mi_c + cell] = ref_frame;
11971509 self.left_ref[mi_r + cell] = ref_frame;
1510+ // decode.rs `record_inter`'s single-reference default: no second
1511+ // reference, and libaom's ALTREF special case in the two compound
1512+ // context bands. `record_compound_mi` overwrites both for a real
1513+ // compound block.
1514+ let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
1515+ self.above_ref1[mi_c + cell] = None;
1516+ self.left_ref1[mi_r + cell] = None;
1517+ self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 };
1518+ self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 };
1519+ self.above_compound_idx[mi_c + cell] = u8::from(altref);
1520+ self.left_compound_idx[mi_r + cell] = u8::from(altref);
1521+ }
1522+ }
1523+
1524+ /// The above neighbour as decode.rs' own `NeighbourRef`, for every
1525+ /// compound context function (`reference_mode_ctx`,
1526+ /// `comp_reference_type_ctx`, the `comp_ref`/`comp_bwdref` votes).
1527+ fn above_nbr(&self, mi_c: usize) -> crate::mvstack::NeighbourRef {
1528+ let is_inter = self.above_inter[mi_c];
1529+ let ref0 = if is_inter { self.above_ref[mi_c] } else { 0 };
1530+ let ref1 = self.above_ref1[mi_c];
1531+ crate::mvstack::NeighbourRef {
1532+ is_inter,
1533+ ref0,
1534+ ref1,
1535+ uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
1536+ }
1537+ }
1538+
1539+ /// [`Self::above_nbr`], down the left edge.
1540+ fn left_nbr(&self, mi_r: usize) -> crate::mvstack::NeighbourRef {
1541+ let is_inter = self.left_inter[mi_r];
1542+ let ref0 = if is_inter { self.left_ref[mi_r] } else { 0 };
1543+ let ref1 = self.left_ref1[mi_r];
1544+ crate::mvstack::NeighbourRef {
1545+ is_inter,
1546+ ref0,
1547+ ref1,
1548+ uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)),
11981549 }
11991550 }
12001551
@@ -3129,6 +3480,12 @@ fn write_inter_mode(
31293480 stack: &crate::mvstack::MvStack,
31303481 ) -> Result<((i32, i32), bool)> {
31313482 let idx = usize::from(info.ref_mv_idx);
3483+ if info.mode.compound_index().is_some() {
3484+ return Err(Error::unsupported(
3485+ "AV1 tile",
3486+ "a compound mode is written by `write_compound_block`, not here",
3487+ ));
3488+ }
31323489 match info.mode {
31333490 InterMode::NewMv => {
31343491 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]);
@@ -3162,6 +3519,7 @@ fn write_inter_mode(
31623519 note_inter_mode(1, idx);
31633520 Ok((mv, false))
31643521 }
3522+ _ => unreachable!("compound modes are refused above"),
31653523 }
31663524 }
31673525
@@ -3563,10 +3921,33 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
35633921
35643922 let mode_for_tx;
35653923 if let Some(info) = block.inter {
3566- write_comp_mode(&mut enc, &mut cdfs, &neighbours, (mi_r, mi_c), (has_above, has_left), false);
3924+ write_comp_mode(&mut enc, &mut cdfs, &neighbours, (mi_r, mi_c), (has_above, has_left), info.ref1.is_some());
3925+ let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
3926+ if info.ref1.is_some() {
3927+ let (mv, mv1, is_new_mv) = write_compound_block(
3928+ &mut enc, &mut cdfs, &neighbours, &grid, (mi_row, mi_col), (8, 8),
3929+ (has_above, has_left), info, (mi_cols as usize, mi_rows as usize),
3930+ )?;
3931+ for dr in 0..8 {
3932+ for dc in 0..8 {
3933+ grid.set(mi_row + dr, mi_col + dc, MiInfo {
3934+ is_inter: true,
3935+ ref_frame: info.ref_frame,
3936+ ref_frame1: info.ref1.unwrap_or(NO_REF1),
3937+ mv1: mv16(mv1),
3938+ mv: mv16(mv),
3939+ is_new_mv,
3940+ size: 8,
3941+ size_h: 8,
3942+ is_global_mv0: false,
3943+ is_global_mv1: false,
3944+ });
3945+ }
3946+ }
3947+ mode_for_tx = 0;
3948+ } else {
35673949 write_single_ref(&mut enc, &mut cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]);
35683950
3569- let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
35703951 let stack = find_mv_stack(
35713952 &grid,
35723953 mi_row,
@@ -3619,6 +4000,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
36194000 }
36204001 }
36214002 mode_for_tx = 0;
4003+ }
36224004 } else {
36234005 let mode = usize::from(block.mode);
36244006 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);
@@ -3711,6 +4093,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
37114093 neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);
37124094 }
37134095 neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block));
4096+ record_block_compound(&mut neighbours, (mi_r, mi_c), BLOCK, block);
37144097 }
37154098 }
37164099 }
@@ -3769,10 +4152,34 @@ fn write_inter_frame_leaf(
37694152
37704153 let mode_for_tx;
37714154 if let Some(info) = block.inter {
3772- write_comp_mode(enc, cdfs, neighbours, (mi_r, mi_c), (has_above, has_left), false);
4155+ write_comp_mode(enc, cdfs, neighbours, (mi_r, mi_c), (has_above, has_left), info.ref1.is_some());
4156+ let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
4157+ if info.ref1.is_some() {
4158+ let n = SUB_MI as usize;
4159+ let (mv, mv1, is_new_mv) = write_compound_block(
4160+ enc, cdfs, neighbours, grid, (mi_row, mi_col), (n, n),
4161+ (has_above, has_left), info, (mi_cols as usize, mi_rows as usize),
4162+ )?;
4163+ for dr in 0..n {
4164+ for dc in 0..n {
4165+ grid.set(mi_row + dr, mi_col + dc, MiInfo {
4166+ is_inter: true,
4167+ ref_frame: info.ref_frame,
4168+ ref_frame1: info.ref1.unwrap_or(NO_REF1),
4169+ mv1: mv16(mv1),
4170+ mv: mv16(mv),
4171+ is_new_mv,
4172+ size: n as u8,
4173+ size_h: n as u8,
4174+ is_global_mv0: false,
4175+ is_global_mv1: false,
4176+ });
4177+ }
4178+ }
4179+ mode_for_tx = 0;
4180+ } else {
37734181 write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]);
37744182
3775- let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
37764183 let stack = find_mv_stack(
37774184 grid,
37784185 mi_row,
@@ -3806,6 +4213,7 @@ fn write_inter_frame_leaf(
38064213 }
38074214 }
38084215 mode_for_tx = 0;
4216+ }
38094217 } else {
38104218 let mode = usize::from(block.mode);
38114219 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]);
@@ -3894,6 +4302,7 @@ fn write_inter_frame_leaf(
38944302 neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);
38954303 }
38964304 neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block));
4305+ record_block_compound(neighbours, (mi_r, mi_c), SUB, block);
38974306 Ok(())
38984307 }
38994308
@@ -3963,10 +4372,33 @@ fn write_inter_frame_leaf8(
39634372
39644373 let mode_for_tx;
39654374 if let Some(info) = block.inter {
3966- write_comp_mode(enc, cdfs, neighbours, leaf_mi, (has_above, has_left), false);
4375+ write_comp_mode(enc, cdfs, neighbours, leaf_mi, (has_above, has_left), info.ref1.is_some());
4376+ let (mi_row, mi_col) = leaf_mi;
4377+ if info.ref1.is_some() {
4378+ let (mv, mv1, is_new_mv) = write_compound_block(
4379+ enc, cdfs, neighbours, grid, (mi_row, mi_col), (2, 2),
4380+ (has_above, has_left), info, (mi_cols as usize, mi_rows as usize),
4381+ )?;
4382+ for dr in 0..2 {
4383+ for dc in 0..2 {
4384+ grid.set(mi_row + dr, mi_col + dc, MiInfo {
4385+ is_inter: true,
4386+ ref_frame: info.ref_frame,
4387+ ref_frame1: info.ref1.unwrap_or(NO_REF1),
4388+ mv1: mv16(mv1),
4389+ mv: mv16(mv),
4390+ is_new_mv,
4391+ size: 2,
4392+ size_h: 2,
4393+ is_global_mv0: false,
4394+ is_global_mv1: false,
4395+ });
4396+ }
4397+ }
4398+ mode_for_tx = 0;
4399+ } else {
39674400 write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[leaf_mi.1], neighbours.left_ref[leaf_mi.0]);
39684401
3969- let (mi_row, mi_col) = leaf_mi;
39704402 let stack = find_mv_stack(
39714403 grid,
39724404 mi_row,
@@ -4000,6 +4432,7 @@ fn write_inter_frame_leaf8(
40004432 }
40014433 }
40024434 mode_for_tx = 0;
4435+ }
40034436 } else {
40044437 let mode = usize::from(block.mode);
40054438 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]);
@@ -4065,6 +4498,7 @@ fn write_inter_frame_leaf8(
40654498 ];
40664499 neighbours.record_mi(leaf_mi, 8, &zero_grids);
40674500 neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some(), block_ref(block));
4501+ record_block_compound(neighbours, leaf_mi, 8, block);
40684502 } else {
40694503 let grids = [
40704504 level_grid(&block.luma, TX8)?,
@@ -4088,6 +4522,7 @@ fn write_inter_frame_leaf8(
40884522 );
40894523 neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);
40904524 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block));
4525+ record_block_compound(neighbours, leaf_mi, 8, block);
40914526 }
40924527 Ok((block.skip, is_inter))
40934528 }
@@ -6369,6 +6804,8 @@ mod tests {
63696804 fn an_all_skip_inter_superblock_is_small_and_reads_back() {
63706805 let block = BlockCoeffs {
63716806 inter: Some(InterInfo {
6807+ ref1: None,
6808+ mv1: (0, 0),
63726809 ref_frame: crate::mvstack::LAST_FRAME,
63736810 mode: InterMode::NearestMv,
63746811 mv: (0, 0),
@@ -6412,6 +6849,8 @@ mod tests {
64126849 fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {
64136850 let nearest = BlockCoeffs {
64146851 inter: Some(InterInfo {
6852+ ref1: None,
6853+ mv1: (0, 0),
64156854 ref_frame: crate::mvstack::LAST_FRAME,
64166855 mode: InterMode::NearestMv,
64176856 mv: (0, 0),
@@ -6422,6 +6861,8 @@ mod tests {
64226861 };
64236862 let newmv = BlockCoeffs {
64246863 inter: Some(InterInfo {
6864+ ref1: None,
6865+ mv1: (0, 0),
64256866 ref_frame: crate::mvstack::LAST_FRAME,
64266867 mode: InterMode::NewMv,
64276868 mv: (0, 2),