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(
2653 eight: None,2653 eight: None,
2654 tx_depth,2654 tx_depth,
2655 inter: Some(InterInfo {2655 inter: Some(InterInfo {
2656+ ref1: None,
2657+ mv1: (0, 0),
2656 ref_frame: crate::mvstack::LAST_FRAME,2658 ref_frame: crate::mvstack::LAST_FRAME,
2657 mode: InterMode::NewMv,2659 mode: InterMode::NewMv,
2658 mv: new_mv,2660 mv: new_mv,
@@ -2687,6 +2689,8 @@ fn code_square_inter(
2687 eight: None,2689 eight: None,
2688 tx_depth,2690 tx_depth,
2689 inter: Some(InterInfo {2691 inter: Some(InterInfo {
2692+ ref1: None,
2693+ mv1: (0, 0),
2690 ref_frame: crate::mvstack::LAST_FRAME,2694 ref_frame: crate::mvstack::LAST_FRAME,
2691 mode: InterMode::NearestMv,2695 mode: InterMode::NearestMv,
2692 mv,2696 mv,
@@ -3874,6 +3878,56 @@ fn mc_trial(
3874 plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set)3878 plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set)
3875 }3879 }
3876 3880
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+
3877 /// Codes one 32x32 block of an inter frame as whichever costs least of: each3931 /// Codes one 32x32 block of an inter frame as whichever costs least of: each
3878 /// intra mode [`Search::modes`] offers (predicted exactly as a key frame's3932 /// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
3879 /// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by3933 /// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
@@ -3906,7 +3960,11 @@ fn search_inter_block(
3906 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a3960 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
3907 // second motion search would double the wall of the stage that already3961 // second motion search would double the wall of the stage that already
3908 // owns most of it.3962 // 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,
3910 ) -> (BlockCoeffs, f64) {3968 ) -> (BlockCoeffs, f64) {
3911 // `luma_set` is the INTRA candidates' table; the two inter candidates3969 // `luma_set` is the INTRA candidates' table; the two inter candidates
3912 // below price their coefficients through `TxbSet::Luma32Inter`, which is3970 // below price their coefficients through `TxbSet::Luma32Inter`, which is
@@ -4083,6 +4141,8 @@ fn search_inter_block(
4083 stack.nearest_mv,4141 stack.nearest_mv,
4084 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),4142 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
4085 InterInfo {4143 InterInfo {
4144+ ref1: None,
4145+ mv1: (0, 0),
4086 ref_frame: crate::mvstack::LAST_FRAME,4146 ref_frame: crate::mvstack::LAST_FRAME,
4087 mode: InterMode::NearestMv,4147 mode: InterMode::NearestMv,
4088 mv: stack.nearest_mv,4148 mv: stack.nearest_mv,
@@ -4096,6 +4156,8 @@ fn search_inter_block(
4096 (0, 0),4156 (0, 0),
4097 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),4157 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
4098 InterInfo {4158 InterInfo {
4159+ ref1: None,
4160+ mv1: (0, 0),
4099 ref_frame: crate::mvstack::LAST_FRAME,4161 ref_frame: crate::mvstack::LAST_FRAME,
4100 mode: InterMode::GlobalMv,4162 mode: InterMode::GlobalMv,
4101 mv: (0, 0),4163 mv: (0, 0),
@@ -4111,6 +4173,8 @@ fn search_inter_block(
4111 e.mv,4173 e.mv,
4112 near_bits + drl_bits(1, idx),4174 near_bits + drl_bits(1, idx),
4113 InterInfo {4175 InterInfo {
4176+ ref1: None,
4177+ mv1: (0, 0),
4114 ref_frame: crate::mvstack::LAST_FRAME,4178 ref_frame: crate::mvstack::LAST_FRAME,
4115 mode: InterMode::NearMv,4179 mode: InterMode::NearMv,
4116 mv: e.mv,4180 mv: e.mv,
@@ -4149,6 +4213,8 @@ fn search_inter_block(
4149 mv,4213 mv,
4150 last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,4214 last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,
4151 InterInfo {4215 InterInfo {
4216+ ref1: None,
4217+ mv1: (0, 0),
4152 ref_frame: crate::mvstack::LAST_FRAME,4218 ref_frame: crate::mvstack::LAST_FRAME,
4153 mode: InterMode::NewMv,4219 mode: InterMode::NewMv,
4154 mv,4220 mv,
@@ -4157,6 +4223,9 @@ fn search_inter_block(
4157 ));4223 ));
4158 }4224 }
4159 4225
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();
4160 for &(ref_frame, g, gstack) in extra {4229 for &(ref_frame, g, gstack) in extra {
4161 let g_ref_bits = single_ref_bits(ref_frame);4230 let g_ref_bits = single_ref_bits(ref_frame);
4162 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);4231 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
@@ -4167,6 +4236,8 @@ fn search_inter_block(
4167 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)4236 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
4168 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),4237 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
4169 InterInfo {4238 InterInfo {
4239+ ref1: None,
4240+ mv1: (0, 0),
4170 ref_frame,4241 ref_frame,
4171 mode: InterMode::NearestMv,4242 mode: InterMode::NearestMv,
4172 mv: gstack.nearest_mv,4243 mv: gstack.nearest_mv,
@@ -4177,6 +4248,8 @@ fn search_inter_block(
4177 (0, 0),4248 (0, 0),
4178 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),4249 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
4179 InterInfo {4250 InterInfo {
4251+ ref1: None,
4252+ mv1: (0, 0),
4180 ref_frame,4253 ref_frame,
4181 mode: InterMode::GlobalMv,4254 mode: InterMode::GlobalMv,
4182 mv: (0, 0),4255 mv: (0, 0),
@@ -4231,11 +4304,14 @@ fn search_inter_block(
4231 #[cfg(test)]4304 #[cfg(test)]
4232 stage_add(0, t.elapsed());4305 stage_add(0, t.elapsed());
4233 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);4306 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
4307+ extra_new_mvs.push((ref_frame, gmv));
4234 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {4308 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
4235 cands.push((4309 cands.push((
4236 gmv,4310 gmv,
4237 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,4311 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
4238 InterInfo {4312 InterInfo {
4313+ ref1: None,
4314+ mv1: (0, 0),
4239 ref_frame,4315 ref_frame,
4240 mode: InterMode::NewMv,4316 mode: InterMode::NewMv,
4241 mv: gmv,4317 mv: gmv,
@@ -4246,6 +4322,131 @@ fn search_inter_block(
4246 }4322 }
4247 }4323 }
4248 4324
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+
4249 // One trial set per distinct (reference, vector) pair: sort, cheapest4450 // One trial set per distinct (reference, vector) pair: sort, cheapest
4250 // syntax first, and drop the rest of each pair's run.4451 // syntax first, and drop the rest of each pair's run.
4251 cands.sort_by(|a, b| {4452 cands.sort_by(|a, b| {
@@ -4616,6 +4817,37 @@ pub(crate) fn encode_inter_frame(
4616 .iter()4817 .iter()
4617 .map(|(r, p, st)| (*r, *p, st))4818 .map(|(r, p, st)| (*r, *p, st))
4618 .collect();4819 .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+ };
4619 4851
4620 let base = snapshot(&luma, &chroma, (x, y), BLOCK);4852 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
4621 let (block, mut cost_whole) = search_inter_block(4853 let (block, mut cost_whole) = search_inter_block(
@@ -4626,7 +4858,8 @@ pub(crate) fn encode_inter_frame(
4626 &mode_bits_table,4858 &mode_bits_table,
4627 reference,4859 reference,
4628 &stack,4860 &stack,
4629- &extra, fctx,4861+ &extra,
4862+ &compound, fctx,
4630 );4863 );
4631 cost_whole += search.lambda * partition_bits(BLOCK, false);4864 cost_whole += search.lambda * partition_bits(BLOCK, false);
4632 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);4865 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
@@ -4965,6 +5198,7 @@ pub(crate) fn encode_inter_frame(
4965 let start_cdfs = CdfSnapshot(cdfs.clone());5198 let start_cdfs = CdfSnapshot(cdfs.clone());
4966 crate::tile::arm_sign_bias(sign_bias);5199 crate::tile::arm_sign_bias(sign_bias);
4967 crate::tile::arm_reference_select(header.reference_select);5200 crate::tile::arm_reference_select(header.reference_select);
5201+ crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
4968 let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(5202 let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs(
4969 mi_cols,5203 mi_cols,
4970 mi_rows,5204 mi_rows,
@@ -5056,6 +5290,7 @@ pub(crate) fn encode_inter_frame(
5056 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());5290 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
5057 crate::tile::arm_sign_bias(sign_bias);5291 crate::tile::arm_sign_bias(sign_bias);
5058 crate::tile::arm_reference_select(reference_select());5292 crate::tile::arm_reference_select(reference_select());
5293+ crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
5059 let mut cdfs = start_cdfs.0.clone();5294 let mut cdfs = start_cdfs.0.clone();
5060 let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(5295 let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs(
5061 mi_cols,5296 mi_cols,
@@ -5630,6 +5865,8 @@ mod tests {
5630 eight: None,5865 eight: None,
5631 tx_depth: 0,5866 tx_depth: 0,
5632 inter: Some(InterInfo {5867 inter: Some(InterInfo {
5868+ ref1: None,
5869+ mv1: (0, 0),
5633 ref_frame: crate::mvstack::LAST_FRAME,5870 ref_frame: crate::mvstack::LAST_FRAME,
5634 mode: InterMode::NearestMv,5871 mode: InterMode::NearestMv,
5635 mv: (0, 0),5872 mv: (0, 0),
@@ -5639,6 +5876,8 @@ mod tests {
5639 let skipped_block = BlockCoeffs {5876 let skipped_block = BlockCoeffs {
5640 skip: true,5877 skip: true,
5641 inter: Some(InterInfo {5878 inter: Some(InterInfo {
5879+ ref1: None,
5880+ mv1: (0, 0),
5642 ref_frame: crate::mvstack::LAST_FRAME,5881 ref_frame: crate::mvstack::LAST_FRAME,
5643 mode: InterMode::NearestMv,5882 mode: InterMode::NearestMv,
5644 mv: (0, 0),5883 mv: (0, 0),
@@ -8220,6 +8459,8 @@ mod tests {
8220 let _ = crate::tile::take_inter_mode_hits();8459 let _ = crate::tile::take_inter_mode_hits();
8221 let _ = crate::tile::take_drl_hits();8460 let _ = crate::tile::take_drl_hits();
8222 let _ = crate::tile::take_ref_hits();8461 let _ = crate::tile::take_ref_hits();
8462+ let _ = crate::tile::take_compound_mode_hits();
8463+ let _ = crate::tile::take_compound_pair_hits();
8223 let _ = crate::motion::take_census();8464 let _ = crate::motion::take_census();
8224 let (ours, ours_wall) = match pyramid_from_env() {8465 let (ours, ours_wall) = match pyramid_from_env() {
8225 None => our_ladder(&source, width, height, fctx),8466 None => our_ladder(&source, width, height, fctx),
@@ -8255,6 +8496,22 @@ mod tests {
8255 100.0 * global as f64 / modes_total as f64,8496 100.0 * global as f64 / modes_total as f64,
8256 100.0 * new as f64 / modes_total as f64,8497 100.0 * new as f64 / modes_total as f64,
8257 );8498 );
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+ );
8258 // Where the wall-owning stage actually goes: how many candidate8515 // Where the wall-owning stage actually goes: how many candidate
8259 // evaluations (one `mc::predict` + SAD each) a search spends, how8516 // evaluations (one `mc::predict` + SAD each) a search spends, how
8260 // many of them are subpel, and how often the winner is the seed8517 // 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 {
284 }284 }
285 285
286 /// Sets this frame's `ref_frame_sign_bias` (see the field).286 /// 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.
287 pub fn set_sign_bias(&mut self, sign_bias: SignBiasTable) {295 pub fn set_sign_bias(&mut self, sign_bias: SignBiasTable) {
288 self.sign_bias = sign_bias;296 self.sign_bias = sign_bias;
289 }297 }
crates/ec-av1/src/tile.rsmodified+459 -18
@@ -176,15 +176,253 @@ pub(crate) fn arm_reference_select(on: bool) {
176 REFERENCE_SELECT.with(|c| c.set(on));176 REFERENCE_SELECT.with(|c| c.set(on));
177 }177 }
178 178
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+
179 /// Writer-side counterpart of decode.rs `read_comp_mode` (spec 5.11.25's420 /// Writer-side counterpart of decode.rs `read_comp_mode` (spec 5.11.25's
180 /// `comp_mode`): on a `reference_select` frame every inter block whose size421 /// `comp_mode`): on a `reference_select` frame every inter block whose size
181 /// allows compound (`is_comp_ref_allowed`, always true here -- this writer's422 /// allows compound (`is_comp_ref_allowed`, always true here -- this writer's
182 /// smallest leaf is 8x8) names SINGLE or COMPOUND, at423 /// smallest leaf is 8x8) names SINGLE or COMPOUND, at
183 /// `mvstack::reference_mode_ctx`'s own context off the same two neighbour424 /// `mvstack::reference_mode_ctx`'s own context off the same two neighbour
184-/// bands decode.rs builds its `NeighbourRef` pair from. No neighbour carries a425+/// bands decode.rs builds its `NeighbourRef` pair from.
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.
188 fn write_comp_mode(426 fn write_comp_mode(
189 enc: &mut SymbolEncoder,427 enc: &mut SymbolEncoder,
190 cdfs: &mut Cdfs,428 cdfs: &mut Cdfs,
@@ -196,14 +434,8 @@ fn write_comp_mode(
196 if !REFERENCE_SELECT.with(std::cell::Cell::get) {434 if !REFERENCE_SELECT.with(std::cell::Cell::get) {
197 return;435 return;
198 }436 }
199- let nbr = |is_inter: bool, r: i8| crate::mvstack::NeighbourRef {437+ let above = has_above.then(|| neighbours.above_nbr(mi_c));
200- is_inter,438+ let left = has_left.then(|| neighbours.left_nbr(mi_r));
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]));
207 let ctx = crate::mvstack::reference_mode_ctx(above, left);439 let ctx = crate::mvstack::reference_mode_ctx(above, left);
208 enc.symbol(usize::from(compound), &mut cdfs.comp_mode[ctx]);440 enc.symbol(usize::from(compound), &mut cdfs.comp_mode[ctx]);
209 }441 }
@@ -217,6 +449,7 @@ impl Drop for CdefIdxGuard {
217 LR_PLAN.with(|c| *c.borrow_mut() = None);449 LR_PLAN.with(|c| *c.borrow_mut() = None);
218 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));450 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
219 REFERENCE_SELECT.with(|c| c.set(false));451 REFERENCE_SELECT.with(|c| c.set(false));
452+ ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));
220 }453 }
221 }454 }
222 455
@@ -727,6 +960,29 @@ pub enum InterMode {
727 /// `NEWMV`: codes `mv` as a residual against the stack entry960 /// `NEWMV`: codes `mv` as a residual against the stack entry
728 /// [`InterInfo::ref_mv_idx`] names.961 /// [`InterInfo::ref_mv_idx`] names.
729 NewMv,962 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+ }
730 }986 }
731 987
732 /// An inter-coded block's mode and motion vector, `mv` in the spec's 1/8-pel988 /// An inter-coded block's mode and motion vector, `mv` in the spec's 1/8-pel
@@ -747,6 +1003,13 @@ pub struct InterInfo {
747 /// `NEARMV` takes outright. Ignored by the two modes that code no DRL1003 /// `NEARMV` takes outright. Ignored by the two modes that code no DRL
748 /// index (`NEARESTMV`, `GLOBALMV`).1004 /// index (`NEARESTMV`, `GLOBALMV`).
749 pub ref_mv_idx: u8,1005 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),
750 }1013 }
751 1014
752 impl From<Vec<Coeff>> for BlockCoeffs {1015 impl From<Vec<Coeff>> for BlockCoeffs {
@@ -918,6 +1181,23 @@ struct Neighbours {
918 above_ref: Vec<i8>,1181 above_ref: Vec<i8>,
919 /// The same, down the left edge.1182 /// The same, down the left edge.
920 left_ref: Vec<i8>,1183 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>,
921 /// The frame's true (unpadded) width and height, in 4x4 mode-info units,1201 /// The frame's true (unpadded) width and height, in 4x4 mode-info units,
922 /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec1202 /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec
923 /// `av1_set_entropy_contexts`): a block whose row or column run spills1203 /// `av1_set_entropy_contexts`): a block whose row or column run spills
@@ -963,6 +1243,12 @@ impl Neighbours {
963 left_inter: vec![false; rows * (SUB / MI)],1243 left_inter: vec![false; rows * (SUB / MI)],
964 above_ref: vec![-1; cols * (SUB / MI)],1244 above_ref: vec![-1; cols * (SUB / MI)],
965 left_ref: vec![-1; rows * (SUB / MI)],1245 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)],
966 above_tx: vec![0; cols * (SUB / MI)],1252 above_tx: vec![0; cols * (SUB / MI)],
967 left_tx: vec![0; rows * (SUB / MI)],1253 left_tx: vec![0; rows * (SUB / MI)],
968 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],1254 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
@@ -981,6 +1267,9 @@ impl Neighbours {
981 self.left_skip.iter_mut().for_each(|s| *s = false);1267 self.left_skip.iter_mut().for_each(|s| *s = false);
982 self.left_inter.iter_mut().for_each(|i| *i = false);1268 self.left_inter.iter_mut().for_each(|i| *i = false);
983 self.left_ref.iter_mut().for_each(|r| *r = -1);1269 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);
984 self.left_tx.iter_mut().for_each(|t| *t = 0);1273 self.left_tx.iter_mut().for_each(|t| *t = 0);
985 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);1274 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
986 }1275 }
@@ -1185,6 +1474,29 @@ impl Neighbours {
1185 self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame);1474 self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame);
1186 }1475 }
1187 1476
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+
1188 /// [`Self::record_inter`] taking the block's position directly in 4x41500 /// [`Self::record_inter`] taking the block's position directly in 4x4
1189 /// mode-info units, for a block finer than one [`SUB`] slot.1501 /// mode-info units, for a block finer than one [`SUB`] slot.
1190 fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) {1502 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 {
1195 self.left_inter[mi_r + cell] = is_inter;1507 self.left_inter[mi_r + cell] = is_inter;
1196 self.above_ref[mi_c + cell] = ref_frame;1508 self.above_ref[mi_c + cell] = ref_frame;
1197 self.left_ref[mi_r + cell] = ref_frame;1509 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)),
1198 }1549 }
1199 }1550 }
1200 1551
@@ -3129,6 +3480,12 @@ fn write_inter_mode(
3129 stack: &crate::mvstack::MvStack,3480 stack: &crate::mvstack::MvStack,
3130 ) -> Result<((i32, i32), bool)> {3481 ) -> Result<((i32, i32), bool)> {
3131 let idx = usize::from(info.ref_mv_idx);3482 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+ }
3132 match info.mode {3489 match info.mode {
3133 InterMode::NewMv => {3490 InterMode::NewMv => {
3134 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]);3491 enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]);
@@ -3162,6 +3519,7 @@ fn write_inter_mode(
3162 note_inter_mode(1, idx);3519 note_inter_mode(1, idx);
3163 Ok((mv, false))3520 Ok((mv, false))
3164 }3521 }
3522+ _ => unreachable!("compound modes are refused above"),
3165 }3523 }
3166 }3524 }
3167 3525
@@ -3563,10 +3921,33 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3563 3921
3564 let mode_for_tx;3922 let mode_for_tx;
3565 if let Some(info) = block.inter {3923 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 {
3567 write_single_ref(&mut enc, &mut cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]);3949 write_single_ref(&mut enc, &mut cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]);
3568 3950
3569- let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
3570 let stack = find_mv_stack(3951 let stack = find_mv_stack(
3571 &grid,3952 &grid,
3572 mi_row,3953 mi_row,
@@ -3619,6 +4000,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3619 }4000 }
3620 }4001 }
3621 mode_for_tx = 0;4002 mode_for_tx = 0;
4003+ }
3622 } else {4004 } else {
3623 let mode = usize::from(block.mode);4005 let mode = usize::from(block.mode);
3624 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);4006 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]);
@@ -3711,6 +4093,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
3711 neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);4093 neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);
3712 }4094 }
3713 neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block));4095 neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block));
4096+ record_block_compound(&mut neighbours, (mi_r, mi_c), BLOCK, block);
3714 }4097 }
3715 }4098 }
3716 }4099 }
@@ -3769,10 +4152,34 @@ fn write_inter_frame_leaf(
3769 4152
3770 let mode_for_tx;4153 let mode_for_tx;
3771 if let Some(info) = block.inter {4154 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 {
3773 write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]);4181 write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]);
3774 4182
3775- let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
3776 let stack = find_mv_stack(4183 let stack = find_mv_stack(
3777 grid,4184 grid,
3778 mi_row,4185 mi_row,
@@ -3806,6 +4213,7 @@ fn write_inter_frame_leaf(
3806 }4213 }
3807 }4214 }
3808 mode_for_tx = 0;4215 mode_for_tx = 0;
4216+ }
3809 } else {4217 } else {
3810 let mode = usize::from(block.mode);4218 let mode = usize::from(block.mode);
3811 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]);4219 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]);
@@ -3894,6 +4302,7 @@ fn write_inter_frame_leaf(
3894 neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);4302 neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);
3895 }4303 }
3896 neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block));4304 neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block));
4305+ record_block_compound(neighbours, (mi_r, mi_c), SUB, block);
3897 Ok(())4306 Ok(())
3898 }4307 }
3899 4308
@@ -3963,10 +4372,33 @@ fn write_inter_frame_leaf8(
3963 4372
3964 let mode_for_tx;4373 let mode_for_tx;
3965 if let Some(info) = block.inter {4374 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 {
3967 write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[leaf_mi.1], neighbours.left_ref[leaf_mi.0]);4400 write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[leaf_mi.1], neighbours.left_ref[leaf_mi.0]);
3968 4401
3969- let (mi_row, mi_col) = leaf_mi;
3970 let stack = find_mv_stack(4402 let stack = find_mv_stack(
3971 grid,4403 grid,
3972 mi_row,4404 mi_row,
@@ -4000,6 +4432,7 @@ fn write_inter_frame_leaf8(
4000 }4432 }
4001 }4433 }
4002 mode_for_tx = 0;4434 mode_for_tx = 0;
4435+ }
4003 } else {4436 } else {
4004 let mode = usize::from(block.mode);4437 let mode = usize::from(block.mode);
4005 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]);4438 enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]);
@@ -4065,6 +4498,7 @@ fn write_inter_frame_leaf8(
4065 ];4498 ];
4066 neighbours.record_mi(leaf_mi, 8, &zero_grids);4499 neighbours.record_mi(leaf_mi, 8, &zero_grids);
4067 neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some(), block_ref(block));4500 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);
4068 } else {4502 } else {
4069 let grids = [4503 let grids = [
4070 level_grid(&block.luma, TX8)?,4504 level_grid(&block.luma, TX8)?,
@@ -4088,6 +4522,7 @@ fn write_inter_frame_leaf8(
4088 );4522 );
4089 neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);4523 neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);
4090 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block));4524 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block));
4525+ record_block_compound(neighbours, leaf_mi, 8, block);
4091 }4526 }
4092 Ok((block.skip, is_inter))4527 Ok((block.skip, is_inter))
4093 }4528 }
@@ -6369,6 +6804,8 @@ mod tests {
6369 fn an_all_skip_inter_superblock_is_small_and_reads_back() {6804 fn an_all_skip_inter_superblock_is_small_and_reads_back() {
6370 let block = BlockCoeffs {6805 let block = BlockCoeffs {
6371 inter: Some(InterInfo {6806 inter: Some(InterInfo {
6807+ ref1: None,
6808+ mv1: (0, 0),
6372 ref_frame: crate::mvstack::LAST_FRAME,6809 ref_frame: crate::mvstack::LAST_FRAME,
6373 mode: InterMode::NearestMv,6810 mode: InterMode::NearestMv,
6374 mv: (0, 0),6811 mv: (0, 0),
@@ -6412,6 +6849,8 @@ mod tests {
6412 fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {6849 fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {
6413 let nearest = BlockCoeffs {6850 let nearest = BlockCoeffs {
6414 inter: Some(InterInfo {6851 inter: Some(InterInfo {
6852+ ref1: None,
6853+ mv1: (0, 0),
6415 ref_frame: crate::mvstack::LAST_FRAME,6854 ref_frame: crate::mvstack::LAST_FRAME,
6416 mode: InterMode::NearestMv,6855 mode: InterMode::NearestMv,
6417 mv: (0, 0),6856 mv: (0, 0),
@@ -6422,6 +6861,8 @@ mod tests {
6422 };6861 };
6423 let newmv = BlockCoeffs {6862 let newmv = BlockCoeffs {
6424 inter: Some(InterInfo {6863 inter: Some(InterInfo {
6864+ ref1: None,
6865+ mv1: (0, 0),
6425 ref_frame: crate::mvstack::LAST_FRAME,6866 ref_frame: crate::mvstack::LAST_FRAME,
6426 mode: InterMode::NewMv,6867 mode: InterMode::NewMv,
6427 mv: (0, 2),6868 mv: (0, 2),