From b22678ddf1feb8a95c6f8cd29e88fb5e8ffc37fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 10:46:48 +0300 Subject: [PATCH] wip(av1): compound syntax writers, snapshot at the agent cap (may not compile) --- crates/ec-av1/src/encode.rs | 261 ++++++++++++++++++- crates/ec-av1/src/mvstack.rs | 8 + crates/ec-av1/src/tile.rs | 477 +++++++++++++++++++++++++++++++++-- 3 files changed, 726 insertions(+), 20 deletions(-) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index b649c44a..9cc98c33 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -2653,6 +2653,8 @@ fn code_square_inter( eight: None, tx_depth, inter: Some(InterInfo { + ref1: None, + mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewMv, mv: new_mv, @@ -2687,6 +2689,8 @@ fn code_square_inter( eight: None, tx_depth, inter: Some(InterInfo { + ref1: None, + mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv, @@ -3874,6 +3878,56 @@ fn mc_trial( plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set) } +/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both +/// references predict into the `CONV_BUF` intermediate domain +/// ([`mc::predict_compound_intermediate`]) and are blended by +/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly +/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1` +/// block, so the encoder's reconstruction is the decoder's. +#[allow(clippy::too_many_arguments)] +fn mc_trial_compound( + plane: &Plane, + x: usize, + y: usize, + side: usize, + (mv0, mv1): ((i32, i32), (i32, i32)), + luma: bool, + ref0: (&[u16], usize, usize, usize), + ref1: (&[u16], usize, usize, usize), + base_q_idx: u8, + deadzone: f64, + set: TxbSet, fctx: &crate::decode::FrameCtx, +) -> Trial { + let mut inter0 = [0i32; BLOCK * BLOCK]; + let mut inter1 = [0i32; BLOCK * BLOCK]; + let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]); + for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] { + mc::predict_compound_intermediate( + r.0, + r.1, + r.2, + r.3, + mv_to_q4(x, mv.1, luma), + mv_to_q4(y, mv.0, luma), + mc::REF_NO_SCALE, + side, + side, + mc::InterpFilterKind::Regular, + mc::InterpFilterKind::Regular, + dst, + ); + } + let mut blended16 = [0u16; BLOCK * BLOCK]; + let blended16 = &mut blended16[..side * side]; + mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx); + let mut prediction = [0u8; BLOCK * BLOCK]; + let prediction = &mut prediction[..side * side]; + for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) { + *dst = src as u8; + } + plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set) +} + /// Codes one 32x32 block of an inter frame as whichever costs least of: each /// intra mode [`Search::modes`] offers (predicted exactly as a key frame's /// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by @@ -3906,7 +3960,11 @@ fn search_inter_block( // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a // second motion search would double the wall of the stage that already // owns most of it. - extra: &[(i8, &Picture, &MvStack)], fctx: &crate::decode::FrameCtx, + extra: &[(i8, &Picture, &MvStack)], + // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by + // the caller off the same MI grid the tile writer will (empty unless the + // frame carries `reference_select`). + compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], fctx: &crate::decode::FrameCtx, ) -> (BlockCoeffs, f64) { // `luma_set` is the INTRA candidates' table; the two inter candidates // below price their coefficients through `TxbSet::Luma32Inter`, which is @@ -4083,6 +4141,8 @@ fn search_inter_block( stack.nearest_mv, last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0), InterInfo { + ref1: None, + mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: stack.nearest_mv, @@ -4096,6 +4156,8 @@ fn search_inter_block( (0, 0), last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0), InterInfo { + ref1: None, + mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::GlobalMv, mv: (0, 0), @@ -4111,6 +4173,8 @@ fn search_inter_block( e.mv, near_bits + drl_bits(1, idx), InterInfo { + ref1: None, + mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearMv, mv: e.mv, @@ -4149,6 +4213,8 @@ fn search_inter_block( mv, last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits, InterInfo { + ref1: None, + mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewMv, mv, @@ -4157,6 +4223,9 @@ fn search_inter_block( )); } + // Each extra reference's own `NEWMV` vector, for the compound + // `NEW_NEWMV` candidate below to pair with `LAST`'s. + let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new(); for &(ref_frame, g, gstack) in extra { let g_ref_bits = single_ref_bits(ref_frame); let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1); @@ -4167,6 +4236,8 @@ fn search_inter_block( + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1) + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0), InterInfo { + ref1: None, + mv1: (0, 0), ref_frame, mode: InterMode::NearestMv, mv: gstack.nearest_mv, @@ -4177,6 +4248,8 @@ fn search_inter_block( (0, 0), g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0), InterInfo { + ref1: None, + mv1: (0, 0), ref_frame, mode: InterMode::GlobalMv, mv: (0, 0), @@ -4231,11 +4304,14 @@ fn search_inter_block( #[cfg(test)] stage_add(0, t.elapsed()); let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv); + extra_new_mvs.push((ref_frame, gmv)); if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) { cands.push(( gmv, g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits, InterInfo { + ref1: None, + mv1: (0, 0), ref_frame, mode: InterMode::NewMv, mv: gmv, @@ -4246,6 +4322,131 @@ fn search_inter_block( } } + // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one + // trial set each: both references predict the block and the two + // predictions are averaged, which is what pays on content where neither + // reference alone is right. Priced with the same static-CDF approximation + // the single-reference candidates use, plus the compound-only symbols + // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`). + for (ref1, g, cstack) in compound { + let (ref1, g) = (*ref1, *g); + let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME) + .contains(&ref1); + let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1) + + if uni { + // LAST + a backward reference: `comp_ref_type` = bidirectional, + // `comp_ref` LAST, `comp_bwdref` ALTREF. + symbol_bits(&cdf::COMP_REF_TYPE[0], 1) + + symbol_bits(&cdf::COMP_REF[0][0], 0) + + symbol_bits(&cdf::COMP_REF[0][1], 0) + + symbol_bits(&cdf::COMP_BWDREF[0][0], 1) + } else { + // LAST + GOLDEN: unidirectional, `uni_comp_ref` p0/p1/p2. + symbol_bits(&cdf::COMP_REF_TYPE[0], 0) + + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0) + + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1) + + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1) + }; + let mode_ctx = + cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; + let mode_bits_of = + |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); + let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![ + #[cfg(any())] + ( + cstack.nearest_mv, + mode_bits_of(0), + InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, + mode: InterMode::NearestNearestMv, + mv: cstack.nearest_mv.0, + mv1: cstack.nearest_mv.1, + ref1: Some(ref1), + ref_mv_idx: 0, + }, + ), + ( + ((0, 0), (0, 0)), + mode_bits_of(6), + InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, + mode: InterMode::GlobalGlobalMv, + mv: (0, 0), + mv1: (0, 0), + ref1: Some(ref1), + ref_mv_idx: 0, + }, + ), + ]; + // `NEW_NEWMV` seeded from the two single-reference searches this + // block already ran -- no joint search of its own. + if false && let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) { + let base = cstack + .entries + .first() + .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); + if let (Some(b0), Some(b1)) = ( + mv_residual_bits(mv, base.0), + mv_residual_bits(mv1, base.1), + ) { + ccands.push(( + (mv, mv1), + mode_bits_of(7) + b0 + b1, + InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, + mode: InterMode::NewNewMv, + mv, + mv1, + ref1: Some(ref1), + ref_mv_idx: 0, + }, + )); + } + } + ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); + ccands.dedup_by_key(|c| c.0); + let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height); + let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height); + let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height); + for (mvs, bits, info) in ccands { + let luma_trial = mc_trial_compound( + luma, x, y, BLOCK, mvs, true, + (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma, + search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx, + ); + let u = mc_trial_compound( + &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false, + (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u, + search.base_q_idx, search.deadzone, chroma_set, fctx, + ); + let v = mc_trial_compound( + &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false, + (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v, + search.base_q_idx, search.deadzone, chroma_set, fctx, + ); + let skip = luma_trial.levels.iter().all(|&l| l == 0) + && u.levels.iter().all(|&l| l == 0) + && v.levels.iter().all(|&l| l == 0); + let cost = luma_trial.sse + + u.sse + + v.sse + + search.lambda + * (skip_bits(skip) + + intra_inter_bits(true) + + bits + + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits }); + consider(Candidate { + cost, + luma: luma_trial, + u, + v, + mode: DC_PRED, + skip, + inter: Some(info), + }); + } + } + // One trial set per distinct (reference, vector) pair: sort, cheapest // syntax first, and drop the rest of each pair's run. cands.sort_by(|a, b| { @@ -4616,6 +4817,37 @@ pub(crate) fn encode_inter_frame( .iter() .map(|(r, p, st)| (*r, *p, st)) .collect(); + // The COMPOUND stack of each `LAST` + extra pair, off the + // same grid (and the same armed sign bias) the tile writer + // rebuilds it from. Empty unless this frame codes + // `reference_select`, which is what gates the syntax. + let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = + if header.reference_select { + extra_stacks + .iter() + .map(|&(r, p, _)| { + ( + r, + p, + crate::mvstack::find_mv_stack_compound( + &grid, + mi_row, + mi_col, + 8, + 8, + (crate::mvstack::LAST_FRAME, r), + mi_cols, + mi_rows, + grid.sign_bias_table(), + &[(0, 0); 7], + None, + ), + ) + }) + .collect() + } else { + Vec::new() + }; let base = snapshot(&luma, &chroma, (x, y), BLOCK); let (block, mut cost_whole) = search_inter_block( @@ -4626,7 +4858,8 @@ pub(crate) fn encode_inter_frame( &mode_bits_table, reference, &stack, - &extra, fctx, + &extra, + &compound, fctx, ); cost_whole += search.lambda * partition_bits(BLOCK, false); let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); @@ -4965,6 +5198,7 @@ pub(crate) fn encode_inter_frame( let start_cdfs = CdfSnapshot(cdfs.clone()); crate::tile::arm_sign_bias(sign_bias); crate::tile::arm_reference_select(header.reference_select); + crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs( mi_cols, mi_rows, @@ -5056,6 +5290,7 @@ pub(crate) fn encode_inter_frame( crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); crate::tile::arm_sign_bias(sign_bias); crate::tile::arm_reference_select(reference_select()); + crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); let mut cdfs = start_cdfs.0.clone(); let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs( mi_cols, @@ -5630,6 +5865,8 @@ mod tests { eight: None, tx_depth: 0, inter: Some(InterInfo { + ref1: None, + mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: (0, 0), @@ -5639,6 +5876,8 @@ mod tests { let skipped_block = BlockCoeffs { skip: true, inter: Some(InterInfo { + ref1: None, + mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: (0, 0), @@ -8220,6 +8459,8 @@ mod tests { let _ = crate::tile::take_inter_mode_hits(); let _ = crate::tile::take_drl_hits(); let _ = crate::tile::take_ref_hits(); + let _ = crate::tile::take_compound_mode_hits(); + let _ = crate::tile::take_compound_pair_hits(); let _ = crate::motion::take_census(); let (ours, ours_wall) = match pyramid_from_env() { None => our_ladder(&source, width, height, fctx), @@ -8255,6 +8496,22 @@ mod tests { 100.0 * global as f64 / modes_total as f64, 100.0 * new as f64 / modes_total as f64, ); + // The compound census: what share of the coded inter blocks took + // a compound reference at all, which compound mode they took, and + // which pair (gate-blind-to-feature -- a compound mode nobody + // picks cannot be what a BD number credits). + let comp_modes = crate::tile::take_compound_mode_hits(); + let comp_pairs = crate::tile::take_compound_pair_hits(); + let comp_total: usize = comp_modes.iter().sum(); + eprintln!( + "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \ + NEAREST_NEAREST {} NEAR_NEAR {} GLOBAL_GLOBAL {} NEW_NEW {}; pairs \ + LAST+GOLDEN {} LAST+ALTREF {}", + modes_total + comp_total, + 100.0 * comp_total as f64 / (modes_total + comp_total) as f64, + comp_modes[0], comp_modes[1], comp_modes[6], comp_modes[7], + comp_pairs[3], comp_pairs[6], + ); // Where the wall-owning stage actually goes: how many candidate // evaluations (one `mc::predict` + SAD each) a search spends, how // many of them are subpel, and how often the winner is the seed diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index a13ee546..f061fe3e 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -284,6 +284,14 @@ impl MiGrid { } /// Sets this frame's `ref_frame_sign_bias` (see the field). + /// This grid's armed `ref_frame_sign_bias`, for the callers that build a + /// COMPOUND stack (which takes the table explicitly, unlike + /// [`find_mv_stack`]). + pub fn sign_bias_table(&self) -> &SignBiasTable { + &self.sign_bias + } + + /// Arms this grid's `ref_frame_sign_bias` for every stack built off it. pub fn set_sign_bias(&mut self, sign_bias: SignBiasTable) { self.sign_bias = sign_bias; } diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 65330600..54e0c6fd 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -176,15 +176,253 @@ pub(crate) fn arm_reference_select(on: bool) { REFERENCE_SELECT.with(|c| c.set(on)); } +/// The compound half of a block's end-of-block neighbour record: nothing for +/// a single-reference or intra block, and `record_compound_mi`'s overwrite of +/// the ALTREF default for a compound one (this writer only codes +/// `comp_group_idx == 0`, `compound_idx == 1`). +fn record_block_compound(neighbours: &mut Neighbours, at_mi: (usize, usize), side: usize, block: &BlockCoeffs) { + if let Some(r1) = block.inter.and_then(|i| i.ref1) { + neighbours.record_compound_mi(at_mi, side, r1, 0, 1); + } +} + +/// decode.rs' own `is_uni_comp_ref`: a pair is `UNIDIR_COMP_REFERENCE` +/// exactly when both references sit on the same temporal side. +fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool { + let backward = + |r: i8| (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&r); + backward(ref0) == backward(ref1) +} + +thread_local! { + /// `(order_hint_bits, this frame's order hint, each reference's order + /// hint)` -- what `get_comp_index_context` (decode.rs) needs to context + /// the `compound_idx` symbol, armed the same way the sign-bias table is. + static ORDER_HINTS: std::cell::Cell<(u32, u32, [u32; 7])> = + const { std::cell::Cell::new((7, 0, [0; 7])) }; +} + +/// Arms this frame's order hints for the next tile written on this thread. +pub(crate) fn arm_order_hints(bits: u32, order_hint: u32, hints: [u32; 7]) { + ORDER_HINTS.with(|c| c.set((bits, order_hint, hints))); +} + +/// Writer-side counterpart of decode.rs `read_compound_ref_frames` (spec +/// 5.11.25's `comp_reference_type`/`uni_comp_ref`/`comp_ref`/`comp_bwdref` +/// trees), symbol for symbol at the same contexts -- which are, as that +/// function's own doc records, `single_ref_p1_ctx`..`single_ref_p6_ctx`/ +/// `uni_comp_ref_p1_ctx` under libaom's compound names. +/// +/// # Errors +/// A pair this writer never forms (its `ref0` is not `LAST_FRAME`). +fn write_compound_ref_frames( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + above: Option, + left: Option, + above_ref: i8, + left_ref: i8, + (ref0, ref1): (i8, i8), +) -> Result<()> { + use crate::mvstack::{ + ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME, + LAST_FRAME, comp_reference_type_ctx, single_ref_p1_ctx, single_ref_p2_ctx, + single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, + uni_comp_ref_p1_ctx, + }; + let a = (above_ref > 0).then_some(above_ref); + let l = (left_ref > 0).then_some(left_ref); + let a1 = above.and_then(|n| n.ref1); + let l1 = left.and_then(|n| n.ref1); + let unidir = is_uni_comp_ref(ref0, ref1); + enc.symbol( + usize::from(!unidir), + &mut cdfs.comp_ref_type[comp_reference_type_ctx(above, left)], + ); + if unidir { + let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME); + enc.symbol( + usize::from(both_backward), + &mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0], + ); + if both_backward { + return Ok(()); + } + if ref0 != LAST_FRAME { + return Err(Error::unsupported( + "AV1 tile", + "a unidirectional compound pair this writer does not form", + )); + } + let past_last2 = ref1 != LAST2_FRAME; + enc.symbol( + usize::from(past_last2), + &mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1], + ); + if past_last2 { + enc.symbol( + usize::from(ref1 == GOLDEN_FRAME), + &mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2], + ); + } + return Ok(()); + } + let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME; + enc.symbol( + usize::from(far), + &mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0], + ); + if far { + enc.symbol( + usize::from(ref0 == GOLDEN_FRAME), + &mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2], + ); + } else { + enc.symbol( + usize::from(ref0 == LAST2_FRAME), + &mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1], + ); + } + let is_altref = ref1 == ALTREF_FRAME; + enc.symbol( + usize::from(is_altref), + &mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0], + ); + if !is_altref { + enc.symbol( + usize::from(ref1 == ALTREF2_FRAME), + &mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1], + ); + } + Ok(()) +} + +/// Per-mode and per-pair fire counts of [`write_compound_block`], for the +/// gate's own census (gate-blind-to-feature): modes indexed by the spec's +/// `INTER_COMPOUND_MODES`, pairs by `ref1` (`LAST`..`ALTREF`). +static COMPOUND_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; +static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; + +/// Takes and clears the compound mode histogram. +#[cfg(test)] +pub(crate) fn take_compound_mode_hits() -> [usize; 8] { + std::array::from_fn(|i| COMPOUND_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// Takes and clears the compound pair histogram, indexed by the SECOND +/// reference (`LAST` = 0 .. `ALTREF` = 6). +#[cfg(test)] +pub(crate) fn take_compound_pair_hits() -> [usize; 7] { + std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side +/// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` / +/// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that +/// order. Returns the two motion vectors the decoder derives (what the MI +/// grid must record) and whether the mode was a `NEW*` one. +/// +/// Only the three modes [`InterMode::compound_index`] names are written, and +/// only the `comp_group_idx == 0`, `compound_idx == 1` blend (spec +/// `COMPOUND_AVERAGE`) -- masked compound and the distance-weighted blend are +/// not searched. +/// +/// # Errors +/// As [`write_mv`], or a pair/mode this writer does not form. +#[allow(clippy::too_many_arguments)] +fn write_compound_block( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + neighbours: &Neighbours, + grid: &crate::mvstack::MiGrid, + (mi_row, mi_col): (usize, usize), + (bw4, bh4): (usize, usize), + (has_above, has_left): (bool, bool), + info: InterInfo, + (mi_cols, mi_rows): (usize, usize), +) -> Result<((i32, i32), (i32, i32), bool)> { + let (Some(ref1), Some(mode)) = (info.ref1, info.mode.compound_index()) else { + return Err(Error::unsupported( + "AV1 tile", + "a compound block needs a second reference and a compound mode", + )); + }; + let above = has_above.then(|| neighbours.above_nbr(mi_col)); + let left = has_left.then(|| neighbours.left_nbr(mi_row)); + write_compound_ref_frames( + enc, + cdfs, + above, + left, + neighbours.above_ref[mi_col], + neighbours.left_ref[mi_row], + (info.ref_frame, ref1), + )?; + let stack = crate::mvstack::find_mv_stack_compound( + grid, + mi_row, + mi_col, + bw4, + bh4, + (info.ref_frame, ref1), + mi_cols, + mi_rows, + grid.sign_bias_table(), + &[(0, 0); 7], + None, + ); + let ctx = crate::cdf::COMPOUND_MODE_CTX_MAP[stack.ref_mv_ctx >> 1][stack.new_mv_ctx.min(4)]; + enc.symbol(mode, &mut cdfs.inter_compound_mode[ctx]); + // `assign_compound_mv`'s own DRL half: `NEW_NEWMV` walks from index 0, + // the two derived modes code no index at all. + let mvs = match info.mode { + InterMode::NearestNearestMv => stack.nearest_mv, + InterMode::GlobalGlobalMv => ((0, 0), (0, 0)), + _ => { + let idx = usize::from(info.ref_mv_idx); + let mut walk = 0usize; + while walk < 2 && stack.entries.len() > walk + 1 { + let advance = walk < idx; + enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[walk]]); + if !advance { + break; + } + walk += 1; + } + let base = stack + .entries + .get(idx) + .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1)); + write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?; + write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?; + (info.mv, info.mv1) + } + }; + // spec 5.11.25's `comp_group_idx`/`compound_idx` are NOT coded: this + // crate's sequence header carries `enable_masked_compound = false` and + // `enable_jnt_comp = false` (encode.rs), and decode.rs reads neither + // symbol under those bits -- it infers `comp_group_idx = 0`, + // `compound_idx = 1` (the simple average), which is the only blend this + // writer forms anyway. A lane that turns either sequence bit on has to + // write the matching symbol here, at + // `get_comp_group_idx_context`/`get_comp_index_context`'s contexts (which + // is what `Neighbours::above_comp_group_idx`/`above_compound_idx` and the + // armed order hints below are already kept for). + let _ = ORDER_HINTS.with(std::cell::Cell::get); + COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7] + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Ok((mvs.0, mvs.1, matches!(info.mode, InterMode::NewNewMv))) +} + /// Writer-side counterpart of decode.rs `read_comp_mode` (spec 5.11.25's /// `comp_mode`): on a `reference_select` frame every inter block whose size /// allows compound (`is_comp_ref_allowed`, always true here -- this writer's /// smallest leaf is 8x8) names SINGLE or COMPOUND, at /// `mvstack::reference_mode_ctx`'s own context off the same two neighbour -/// bands decode.rs builds its `NeighbourRef` pair from. No neighbour carries a -/// second reference yet (`ref1: None`), because every block this writer codes -/// is single-reference; a compound-writing lane fills that in from its own -/// `ref1` band. +/// bands decode.rs builds its `NeighbourRef` pair from. fn write_comp_mode( enc: &mut SymbolEncoder, cdfs: &mut Cdfs, @@ -196,14 +434,8 @@ fn write_comp_mode( if !REFERENCE_SELECT.with(std::cell::Cell::get) { return; } - let nbr = |is_inter: bool, r: i8| crate::mvstack::NeighbourRef { - is_inter, - ref0: if is_inter { r } else { 0 }, - ref1: None, - uni: false, - }; - let above = has_above.then(|| nbr(neighbours.above_inter[mi_c], neighbours.above_ref[mi_c])); - let left = has_left.then(|| nbr(neighbours.left_inter[mi_r], neighbours.left_ref[mi_r])); + let above = has_above.then(|| neighbours.above_nbr(mi_c)); + let left = has_left.then(|| neighbours.left_nbr(mi_r)); let ctx = crate::mvstack::reference_mode_ctx(above, left); enc.symbol(usize::from(compound), &mut cdfs.comp_mode[ctx]); } @@ -217,6 +449,7 @@ impl Drop for CdefIdxGuard { LR_PLAN.with(|c| *c.borrow_mut() = None); SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS)); REFERENCE_SELECT.with(|c| c.set(false)); + ORDER_HINTS.with(|c| c.set((7, 0, [0; 7]))); } } @@ -727,6 +960,29 @@ pub enum InterMode { /// `NEWMV`: codes `mv` as a residual against the stack entry /// [`InterInfo::ref_mv_idx`] names. NewMv, + /// `NEAREST_NEARESTMV`: both sides take the compound stack's own nearest + /// pair, no residual, no DRL. + NearestNearestMv, + /// `GLOBAL_GLOBALMV`: both sides take the identity global model's zero + /// vector. + GlobalGlobalMv, + /// `NEW_NEWMV`: both sides code a residual against the compound stack + /// entry [`InterInfo::ref_mv_idx`] names. + NewNewMv, +} + +impl InterMode { + /// The spec's `INTER_COMPOUND_MODES` index (libaom `enums.h` order, + /// `NEAREST_NEARESTMV = 0`..`NEW_NEWMV = 7`) for a compound mode, `None` + /// for a single-reference one. + fn compound_index(self) -> Option { + match self { + InterMode::NearestNearestMv => Some(0), + InterMode::GlobalGlobalMv => Some(6), + InterMode::NewNewMv => Some(7), + _ => None, + } + } } /// An inter-coded block's mode and motion vector, `mv` in the spec's 1/8-pel @@ -747,6 +1003,13 @@ pub struct InterInfo { /// `NEARMV` takes outright. Ignored by the two modes that code no DRL /// index (`NEARESTMV`, `GLOBALMV`). pub ref_mv_idx: u8, + /// The block's second reference (spec `RefFrames[1]`), `None` for a + /// single-reference block. `Some` only on a `reference_select` frame, and + /// only beside one of [`InterMode`]'s compound modes. + pub ref1: Option, + /// The motion vector into `ref1`, for the compound modes that code one + /// (`NEW_NEWMV`); the other two derive both sides. + pub mv1: (i32, i32), } impl From> for BlockCoeffs { @@ -918,6 +1181,23 @@ struct Neighbours { above_ref: Vec, /// The same, down the left edge. left_ref: Vec, + /// Each neighbour's SECOND reference, `None` for a single-reference or + /// intra one -- decode.rs `Neighbours::above_ref1`, read by every compound + /// context function (`reference_mode_ctx`, `comp_reference_type_ctx`, the + /// `comp_ref`/`comp_bwdref` votes). + above_ref1: Vec>, + /// The same, down the left edge. + left_ref1: Vec>, + /// What decode.rs `Neighbours::above_comp_group_idx` holds: a compound + /// neighbour's own `comp_group_idx`, or libaom's single-reference special + /// case (`3` for an ALTREF block, `0` otherwise). + above_comp_group_idx: Vec, + /// The same, down the left edge. + left_comp_group_idx: Vec, + /// The same for `compound_idx` (`1` for a single-ref ALTREF block). + above_compound_idx: Vec, + /// The same, down the left edge. + left_compound_idx: Vec, /// The frame's true (unpadded) width and height, in 4x4 mode-info units, /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec /// `av1_set_entropy_contexts`): a block whose row or column run spills @@ -963,6 +1243,12 @@ impl Neighbours { left_inter: vec![false; rows * (SUB / MI)], above_ref: vec![-1; cols * (SUB / MI)], left_ref: vec![-1; rows * (SUB / MI)], + above_ref1: vec![None; cols * (SUB / MI)], + left_ref1: vec![None; rows * (SUB / MI)], + above_comp_group_idx: vec![0; cols * (SUB / MI)], + left_comp_group_idx: vec![0; rows * (SUB / MI)], + above_compound_idx: vec![0; cols * (SUB / MI)], + left_compound_idx: vec![0; rows * (SUB / MI)], above_tx: vec![0; cols * (SUB / MI)], left_tx: vec![0; rows * (SUB / MI)], above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], @@ -981,6 +1267,9 @@ impl Neighbours { self.left_skip.iter_mut().for_each(|s| *s = false); self.left_inter.iter_mut().for_each(|i| *i = false); self.left_ref.iter_mut().for_each(|r| *r = -1); + self.left_ref1.iter_mut().for_each(|r| *r = None); + self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0); + self.left_compound_idx.iter_mut().for_each(|r| *r = 0); self.left_tx.iter_mut().for_each(|t| *t = 0); self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); } @@ -1185,6 +1474,29 @@ impl Neighbours { self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame); } + /// [`Self::record_inter_mi`]'s compound half (decode.rs + /// `Neighbours::record_compound_ctx_rect_mi`): overwrites the ALTREF + /// single-reference default with a real compound block's own second + /// reference and `comp_group_idx`/`compound_idx` bits, called right after + /// it for every compound-coded block. + fn record_compound_mi( + &mut self, + (mi_r, mi_c): (usize, usize), + side: usize, + ref1: i8, + comp_group_idx: u8, + compound_idx: u8, + ) { + for cell in 0..side / MI { + self.above_ref1[mi_c + cell] = Some(ref1); + self.left_ref1[mi_r + cell] = Some(ref1); + self.above_comp_group_idx[mi_c + cell] = comp_group_idx; + self.left_comp_group_idx[mi_r + cell] = comp_group_idx; + self.above_compound_idx[mi_c + cell] = compound_idx; + self.left_compound_idx[mi_r + cell] = compound_idx; + } + } + /// [`Self::record_inter`] taking the block's position directly in 4x4 /// mode-info units, for a block finer than one [`SUB`] slot. 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 { self.left_inter[mi_r + cell] = is_inter; self.above_ref[mi_c + cell] = ref_frame; self.left_ref[mi_r + cell] = ref_frame; + // decode.rs `record_inter`'s single-reference default: no second + // reference, and libaom's ALTREF special case in the two compound + // context bands. `record_compound_mi` overwrites both for a real + // compound block. + let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME; + self.above_ref1[mi_c + cell] = None; + self.left_ref1[mi_r + cell] = None; + self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 }; + self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 }; + self.above_compound_idx[mi_c + cell] = u8::from(altref); + self.left_compound_idx[mi_r + cell] = u8::from(altref); + } + } + + /// The above neighbour as decode.rs' own `NeighbourRef`, for every + /// compound context function (`reference_mode_ctx`, + /// `comp_reference_type_ctx`, the `comp_ref`/`comp_bwdref` votes). + fn above_nbr(&self, mi_c: usize) -> crate::mvstack::NeighbourRef { + let is_inter = self.above_inter[mi_c]; + let ref0 = if is_inter { self.above_ref[mi_c] } else { 0 }; + let ref1 = self.above_ref1[mi_c]; + crate::mvstack::NeighbourRef { + is_inter, + ref0, + ref1, + uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)), + } + } + + /// [`Self::above_nbr`], down the left edge. + fn left_nbr(&self, mi_r: usize) -> crate::mvstack::NeighbourRef { + let is_inter = self.left_inter[mi_r]; + let ref0 = if is_inter { self.left_ref[mi_r] } else { 0 }; + let ref1 = self.left_ref1[mi_r]; + crate::mvstack::NeighbourRef { + is_inter, + ref0, + ref1, + uni: ref1.is_some_and(|r1| is_uni_comp_ref(ref0, r1)), } } @@ -3129,6 +3480,12 @@ fn write_inter_mode( stack: &crate::mvstack::MvStack, ) -> Result<((i32, i32), bool)> { let idx = usize::from(info.ref_mv_idx); + if info.mode.compound_index().is_some() { + return Err(Error::unsupported( + "AV1 tile", + "a compound mode is written by `write_compound_block`, not here", + )); + } match info.mode { InterMode::NewMv => { enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); @@ -3162,6 +3519,7 @@ fn write_inter_mode( note_inter_mode(1, idx); Ok((mv, false)) } + _ => unreachable!("compound modes are refused above"), } } @@ -3563,10 +3921,33 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( let mode_for_tx; if let Some(info) = block.inter { - write_comp_mode(&mut enc, &mut cdfs, &neighbours, (mi_r, mi_c), (has_above, has_left), false); + write_comp_mode(&mut enc, &mut cdfs, &neighbours, (mi_r, mi_c), (has_above, has_left), info.ref1.is_some()); + let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8); + if info.ref1.is_some() { + let (mv, mv1, is_new_mv) = write_compound_block( + &mut enc, &mut cdfs, &neighbours, &grid, (mi_row, mi_col), (8, 8), + (has_above, has_left), info, (mi_cols as usize, mi_rows as usize), + )?; + for dr in 0..8 { + for dc in 0..8 { + grid.set(mi_row + dr, mi_col + dc, MiInfo { + is_inter: true, + ref_frame: info.ref_frame, + ref_frame1: info.ref1.unwrap_or(NO_REF1), + mv1: mv16(mv1), + mv: mv16(mv), + is_new_mv, + size: 8, + size_h: 8, + is_global_mv0: false, + is_global_mv1: false, + }); + } + } + mode_for_tx = 0; + } else { write_single_ref(&mut enc, &mut cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]); - let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8); let stack = find_mv_stack( &grid, mi_row, @@ -3619,6 +4000,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( } } mode_for_tx = 0; + } } else { let mode = usize::from(block.mode); enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_32]); @@ -3711,6 +4093,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split); } neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block)); + record_block_compound(&mut neighbours, (mi_r, mi_c), BLOCK, block); } } } @@ -3769,10 +4152,34 @@ fn write_inter_frame_leaf( let mode_for_tx; if let Some(info) = block.inter { - write_comp_mode(enc, cdfs, neighbours, (mi_r, mi_c), (has_above, has_left), false); + write_comp_mode(enc, cdfs, neighbours, (mi_r, mi_c), (has_above, has_left), info.ref1.is_some()); + let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + if info.ref1.is_some() { + let n = SUB_MI as usize; + let (mv, mv1, is_new_mv) = write_compound_block( + enc, cdfs, neighbours, grid, (mi_row, mi_col), (n, n), + (has_above, has_left), info, (mi_cols as usize, mi_rows as usize), + )?; + for dr in 0..n { + for dc in 0..n { + grid.set(mi_row + dr, mi_col + dc, MiInfo { + is_inter: true, + ref_frame: info.ref_frame, + ref_frame1: info.ref1.unwrap_or(NO_REF1), + mv1: mv16(mv1), + mv: mv16(mv), + is_new_mv, + size: n as u8, + size_h: n as u8, + is_global_mv0: false, + is_global_mv1: false, + }); + } + } + mode_for_tx = 0; + } else { write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]); - let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); let stack = find_mv_stack( grid, mi_row, @@ -3806,6 +4213,7 @@ fn write_inter_frame_leaf( } } mode_for_tx = 0; + } } else { let mode = usize::from(block.mode); enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_16]); @@ -3894,6 +4302,7 @@ fn write_inter_frame_leaf( neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split); } neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block)); + record_block_compound(neighbours, (mi_r, mi_c), SUB, block); Ok(()) } @@ -3963,10 +4372,33 @@ fn write_inter_frame_leaf8( let mode_for_tx; if let Some(info) = block.inter { - write_comp_mode(enc, cdfs, neighbours, leaf_mi, (has_above, has_left), false); + write_comp_mode(enc, cdfs, neighbours, leaf_mi, (has_above, has_left), info.ref1.is_some()); + let (mi_row, mi_col) = leaf_mi; + if info.ref1.is_some() { + let (mv, mv1, is_new_mv) = write_compound_block( + enc, cdfs, neighbours, grid, (mi_row, mi_col), (2, 2), + (has_above, has_left), info, (mi_cols as usize, mi_rows as usize), + )?; + for dr in 0..2 { + for dc in 0..2 { + grid.set(mi_row + dr, mi_col + dc, MiInfo { + is_inter: true, + ref_frame: info.ref_frame, + ref_frame1: info.ref1.unwrap_or(NO_REF1), + mv1: mv16(mv1), + mv: mv16(mv), + is_new_mv, + size: 2, + size_h: 2, + is_global_mv0: false, + is_global_mv1: false, + }); + } + } + mode_for_tx = 0; + } else { write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[leaf_mi.1], neighbours.left_ref[leaf_mi.0]); - let (mi_row, mi_col) = leaf_mi; let stack = find_mv_stack( grid, mi_row, @@ -4000,6 +4432,7 @@ fn write_inter_frame_leaf8( } } mode_for_tx = 0; + } } else { let mode = usize::from(block.mode); enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]); @@ -4065,6 +4498,7 @@ fn write_inter_frame_leaf8( ]; neighbours.record_mi(leaf_mi, 8, &zero_grids); neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some(), block_ref(block)); + record_block_compound(neighbours, leaf_mi, 8, block); } else { let grids = [ level_grid(&block.luma, TX8)?, @@ -4088,6 +4522,7 @@ fn write_inter_frame_leaf8( ); neighbours.record_mi_planes(leaf_mi, 8, &grids, !split); neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block)); + record_block_compound(neighbours, leaf_mi, 8, block); } Ok((block.skip, is_inter)) } @@ -6369,6 +6804,8 @@ mod tests { fn an_all_skip_inter_superblock_is_small_and_reads_back() { let block = BlockCoeffs { inter: Some(InterInfo { + ref1: None, + mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: (0, 0), @@ -6412,6 +6849,8 @@ mod tests { fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() { let nearest = BlockCoeffs { inter: Some(InterInfo { + ref1: None, + mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: (0, 0), @@ -6422,6 +6861,8 @@ mod tests { }; let newmv = BlockCoeffs { inter: Some(InterInfo { + ref1: None, + mv1: (0, 0), ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewMv, mv: (0, 2),