forge
Explore
Log in

Don't you dare go Hollow

Compound candidates at the 16x16 and 8x8 inter leaves

Browse files at this commit

9dbe40f23454c768252043a8901ac67b9f564c47Ahmet Kaan GümüşParent: fa932fb
  • feat
    • compound candidates at the 16x16 and 8x8 inter leaves
Show full message
feat(av1): compound candidates at the 16x16 and 8x8 inter leaves

The two straddling-leaf mi publications spelled their vote out by hand
with ref_frame pinned to LAST and mv1 to (0,0) -- the encoder-grid-drift
class, correct only for as long as a leaf could never be compound. Both
now go through record_mi, byte-identically.

A leaf is then offered the compound candidates a whole 32x32 block is:
NEAREST_NEARESTMV, GLOBAL_GLOBALMV and NEW_NEARESTMV off the vector the
leaf already searched, against the compound stack built at the leaf's
own bw4/bh4. The tile writer already codes a compound block at any leaf
size, so no writer change was needed.
crates/ec-av1/src/encode.rsmodified+257 -90
@@ -190,6 +190,21 @@ fn extra_new_skip_margin() -> f64 {
190190 }
191191 }
192192
193+/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
194+/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
195+/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
196+/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
197+/// was missing was the encoder ever forming one below 32x32.
198+const LEAF_COMPOUND: bool = true;
199+
200+/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
201+fn leaf_compound() -> bool {
202+ match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
203+ Some(v) => v != "0",
204+ None => LEAF_COMPOUND,
205+ }
206+}
207+
193208 /// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
194209 fn leaf_new_mv() -> bool {
195210 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
@@ -2730,7 +2745,12 @@ fn code_square_inter(
27302745 search: &Search,
27312746 mode_bits: &[f64; 13],
27322747 reference: &Picture,
2733- stack: &MvStack, fctx: &crate::decode::FrameCtx,
2748+ stack: &MvStack,
2749+ // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
2750+ // leaf's own `bw4`/`bh4` (empty on a frame that does not code
2751+ // `reference_select`, and at the straddling call sites).
2752+ compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
2753+ fctx: &crate::decode::FrameCtx,
27342754 ) -> (BlockCoeffs, f64) {
27352755 let (intra_block, intra_cost) =
27362756 code_square(
@@ -2867,7 +2887,12 @@ fn code_square_inter(
28672887 // not code the movement it split for. Same candidate `search_inter_block`
28682888 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
28692889 // a vector the residual syntax can name -- at this leaf's own side.
2870- let mut best = (inter_cost, None);
2890+ let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
2891+ // This leaf's own `NEWMV` vector, kept whether or not it won the
2892+ // single-reference comparison: it seeds the compound half-new candidate
2893+ // below, exactly as `search_inter_block` seeds its own from the searches
2894+ // it already ran.
2895+ let mut searched_new: Option<(i32, i32)> = None;
28712896 if leaf_new_mv() {
28722897 let source_block = luma.source_block(x, y, side);
28732898 let (seeds, seed_n) = mv_seeds(stack);
@@ -2888,6 +2913,7 @@ fn code_square_inter(
28882913 );
28892914 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
28902915 if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) {
2916+ searched_new = Some(new_mv);
28912917 // Same reuse as `search_inter_block`: a NEWMV equal to the
28922918 // stack's NEARESTMV is the same three trials, already run above.
28932919 let (luma_new, u_new, v_new) = if new_mv == mv {
@@ -2934,15 +2960,170 @@ fn code_square_inter(
29342960 luma_new.bits + u_new.bits + v_new.bits
29352961 });
29362962 if cost_new < best.0 {
2937- best = (cost_new, Some((luma_new, u_new, v_new, skip_new, new_mv)));
2963+ best = (
2964+ cost_new,
2965+ Some((
2966+ luma_new,
2967+ u_new,
2968+ v_new,
2969+ skip_new,
2970+ InterInfo {
2971+ ref1: None,
2972+ mv1: (0, 0),
2973+ ref_frame: crate::mvstack::LAST_FRAME,
2974+ mode: InterMode::NewMv,
2975+ mv: new_mv,
2976+ ref_mv_idx: 0,
2977+ },
2978+ )),
2979+ );
29382980 }
29392981 }
29402982 }
2941- if let (cost, Some((luma_new, u_new, v_new, skip_new, new_mv))) = best {
2942- if cost < intra_cost {
2943- let (levels, tx_depth, dcost) = commit_inter_luma(
2944- luma, (x, y), side, new_mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_new, skip_new, fctx,
2983+
2984+ // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
2985+ // `search_inter_block` prices for a whole 32x32 block minus the two that
2986+ // need a motion search against the SECOND reference: a leaf never runs
2987+ // one (`NEAREST_NEWMV`/`NEW_NEWMV` would each cost another
2988+ // `motion::search` per extra reference per leaf), so the set here is
2989+ // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` off the
2990+ // vector this leaf already searched. Priced with the same static-CDF
2991+ // approximation, plus the compound-only syntax the writer emits.
2992+ for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) {
2993+ let (ref1, g) = (*ref1, *g);
2994+ let uni =
2995+ (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1);
2996+ let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
2997+ + if uni {
2998+ symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
2999+ + symbol_bits(&cdf::COMP_REF[0][0], 0)
3000+ + symbol_bits(&cdf::COMP_REF[0][1], 0)
3001+ + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
3002+ } else {
3003+ symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
3004+ + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
3005+ + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
3006+ + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
3007+ };
3008+ let mode_ctx =
3009+ cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
3010+ let mode_bits_of =
3011+ |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
3012+ let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
3013+ (
3014+ cstack.nearest_mv,
3015+ mode_bits_of(0),
3016+ InterInfo {
3017+ ref_frame: crate::mvstack::LAST_FRAME,
3018+ mode: InterMode::NearestNearestMv,
3019+ mv: cstack.nearest_mv.0,
3020+ mv1: cstack.nearest_mv.1,
3021+ ref1: Some(ref1),
3022+ ref_mv_idx: 0,
3023+ },
3024+ ),
3025+ (
3026+ ((0, 0), (0, 0)),
3027+ mode_bits_of(6),
3028+ InterInfo {
3029+ ref_frame: crate::mvstack::LAST_FRAME,
3030+ mode: InterMode::GlobalGlobalMv,
3031+ mv: (0, 0),
3032+ mv1: (0, 0),
3033+ ref1: Some(ref1),
3034+ ref_mv_idx: 0,
3035+ },
3036+ ),
3037+ ];
3038+ // `NEW_NEARESTMV`: the NEW half is this leaf's own searched vector,
3039+ // its residual priced against compound stack entry 0 (what
3040+ // `assign_compound_mv` predicts from at `ref_mv_idx = 0`).
3041+ let cbase = cstack
3042+ .entries
3043+ .first()
3044+ .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
3045+ if let Some(new_mv) = searched_new {
3046+ if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
3047+ ccands.push((
3048+ (new_mv, cstack.nearest_mv.1),
3049+ mode_bits_of(3) + b0,
3050+ InterInfo {
3051+ ref_frame: crate::mvstack::LAST_FRAME,
3052+ mode: InterMode::NewNearestMv,
3053+ mv: new_mv,
3054+ mv1: cstack.nearest_mv.1,
3055+ ref1: Some(ref1),
3056+ ref_mv_idx: 0,
3057+ },
3058+ ));
3059+ }
3060+ }
3061+ ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
3062+ ccands.dedup_by_key(|c| c.0);
3063+ let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
3064+ let g_u = (
3065+ g.u.as_slice(),
3066+ g.width / 2,
3067+ chroma[0].true_width,
3068+ chroma[0].true_height,
3069+ );
3070+ let g_v = (
3071+ g.v.as_slice(),
3072+ g.width / 2,
3073+ chroma[1].true_width,
3074+ chroma[1].true_height,
3075+ );
3076+ for (mvs, bits, info) in ccands {
3077+ let luma_c = mc_trial_compound(
3078+ luma, x, y, side, mvs, true,
3079+ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
3080+ search.base_q_idx, search.deadzone, luma_set, fctx,
3081+ );
3082+ let u_c = mc_trial_compound(
3083+ &chroma[0], x / 2, y / 2, side / 2, mvs, false,
3084+ (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
3085+ search.base_q_idx, search.deadzone, chroma_set, fctx,
3086+ );
3087+ let v_c = mc_trial_compound(
3088+ &chroma[1], x / 2, y / 2, side / 2, mvs, false,
3089+ (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
3090+ search.base_q_idx, search.deadzone, chroma_set, fctx,
29453091 );
3092+ let skip_c = luma_c.levels.iter().all(|&l| l == 0)
3093+ && u_c.levels.iter().all(|&l| l == 0)
3094+ && v_c.levels.iter().all(|&l| l == 0);
3095+ let cost_c = luma_c.sse
3096+ + u_c.sse
3097+ + v_c.sse
3098+ + search.lambda
3099+ * (skip_bits(skip_c)
3100+ + intra_inter_bits(true)
3101+ + bits
3102+ + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
3103+ if cost_c < best.0 {
3104+ best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
3105+ }
3106+ }
3107+ }
3108+
3109+ if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
3110+ if cost < intra_cost {
3111+ // A compound winner commits the flat trial it was priced from:
3112+ // `commit_inter_luma`'s var-tx trial set is single-reference
3113+ // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
3114+ // corner-cut: no var-tx split for a compound leaf -- ceiling is
3115+ // the split gain on 16x16 compound blocks; upgrade path is a
3116+ // compound `commit_inter_luma` taking both references.
3117+ let (levels, tx_depth, dcost) = if info.ref1.is_some() {
3118+ luma.commit(x, y, side, &luma_new);
3119+ (luma_new.levels.clone(), 0, 0.0)
3120+ } else {
3121+ commit_inter_luma(
3122+ luma, (x, y), side, info.mv,
3123+ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
3124+ search, &luma_new, skip_new, fctx,
3125+ )
3126+ };
29463127 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
29473128 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
29483129 return (
@@ -2956,14 +3137,7 @@ fn code_square_inter(
29563137 eight: None,
29573138 palette: None,
29583139 tx_depth,
2959- inter: Some(InterInfo {
2960- ref1: None,
2961- mv1: (0, 0),
2962- ref_frame: crate::mvstack::LAST_FRAME,
2963- mode: InterMode::NewMv,
2964- mv: new_mv,
2965- ref_mv_idx: 0,
2966- }),
3140+ inter: Some(info),
29673141 },
29683142 cost + dcost,
29693143 );
@@ -5703,6 +5877,30 @@ pub(crate) fn encode_inter_frame(
57035877 let stack = find_mv_stack(
57045878 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
57055879 );
5880+ let cstacks: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
5881+ if header.reference_select && leaf_compound() {
5882+ [
5883+ (crate::mvstack::GOLDEN_FRAME, golden),
5884+ (crate::mvstack::ALTREF_FRAME, altref),
5885+ ]
5886+ .into_iter()
5887+ .filter_map(|(r, pic)| {
5888+ pic.map(|p| {
5889+ (
5890+ r,
5891+ p,
5892+ crate::mvstack::find_mv_stack_compound(
5893+ &grid, mi_row, mi_col, 4, 4,
5894+ (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
5895+ grid.sign_bias_table(), &[(0, 0); 7], None,
5896+ ),
5897+ )
5898+ })
5899+ })
5900+ .collect()
5901+ } else {
5902+ Vec::new()
5903+ };
57065904 let (leaf, leaf_cost) = code_square_inter(
57075905 &mut luma,
57085906 &mut chroma,
@@ -5711,7 +5909,7 @@ pub(crate) fn encode_inter_frame(
57115909 &search,
57125910 &mode_bits_table,
57135911 reference,
5714- &stack, fctx,
5912+ &stack, &cstacks, fctx,
57155913 );
57165914 let leaf_cost = leaf_cost
57175915 + search.lambda * partition_bits(SUB, false);
@@ -5740,6 +5938,30 @@ pub(crate) fn encode_inter_frame(
57405938 let stack8 = find_mv_stack(
57415939 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
57425940 );
5941+ let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
5942+ if header.reference_select && leaf_compound() {
5943+ [
5944+ (crate::mvstack::GOLDEN_FRAME, golden),
5945+ (crate::mvstack::ALTREF_FRAME, altref),
5946+ ]
5947+ .into_iter()
5948+ .filter_map(|(r, pic)| {
5949+ pic.map(|p| {
5950+ (
5951+ r,
5952+ p,
5953+ crate::mvstack::find_mv_stack_compound(
5954+ &grid, mr, mc, 2, 2,
5955+ (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
5956+ grid.sign_bias_table(), &[(0, 0); 7], None,
5957+ ),
5958+ )
5959+ })
5960+ })
5961+ .collect()
5962+ } else {
5963+ Vec::new()
5964+ };
57435965 let (leaf8, cost) = code_square_inter(
57445966 &mut luma,
57455967 &mut chroma,
@@ -5748,7 +5970,7 @@ pub(crate) fn encode_inter_frame(
57485970 &search,
57495971 &mode_bits_table,
57505972 reference,
5751- &stack8, fctx,
5973+ &stack8, &cstacks8, fctx,
57525974 );
57535975 cost8 += cost;
57545976 record_mi(&mut grid, mr, mc, 2, leaf8.inter);
@@ -5849,42 +6071,15 @@ pub(crate) fn encode_inter_frame(
58496071 &search,
58506072 &mode_bits_table,
58516073 reference,
5852- &stack, fctx,
6074+ &stack, &[], fctx,
58536075 );
5854- for dr in 0..4 {
5855- for dc in 0..4 {
5856- grid.set(
5857- mi_row + dr,
5858- mi_col + dc,
5859- match block.inter {
5860- Some(info) => MiInfo {
5861- is_inter: true,
5862- ref_frame: LAST_FRAME,
5863- ref_frame1: NO_REF1,
5864- mv1: (0, 0),
5865- mv: mv16(info.mv),
5866- is_new_mv: matches!(info.mode, InterMode::NewMv),
5867- size: 4,
5868- size_h: 4,
5869- is_global_mv0: false,
5870- is_global_mv1: false,
5871- },
5872- None => MiInfo {
5873- is_inter: false,
5874- ref_frame: -1,
5875- ref_frame1: NO_REF1,
5876- mv1: (0, 0),
5877- mv: (0, 0),
5878- is_new_mv: false,
5879- size: 4,
5880- size_h: 4,
5881- is_global_mv0: false,
5882- is_global_mv1: false,
5883- },
5884- },
5885- );
5886- }
5887- }
6076+ // One publication point for every coded leaf
6077+ // (`record_mi`): this site used to spell the vote
6078+ // out with `ref_frame` pinned to LAST and `mv1`
6079+ // to (0,0), which is the encoder-grid-drift class
6080+ // -- correct only for as long as a leaf can never
6081+ // be compound.
6082+ record_mi(&mut grid, mi_row, mi_col, 4, block.inter);
58886083 leaves.push(block);
58896084 } else {
58906085 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
@@ -5909,45 +6104,11 @@ pub(crate) fn encode_inter_frame(
59096104 &search,
59106105 &mode_bits_table,
59116106 reference,
5912- &stack, fctx,
6107+ &stack, &[], fctx,
59136108 );
5914- for dr in 0..2 {
5915- for dc in 0..2 {
5916- grid.set(
5917- mi_row + dr,
5918- mi_col + dc,
5919- match leaf.inter {
5920- Some(info) => MiInfo {
5921- is_inter: true,
5922- ref_frame: LAST_FRAME,
5923- ref_frame1: NO_REF1,
5924- mv1: (0, 0),
5925- mv: mv16(info.mv),
5926- is_new_mv: matches!(
5927- info.mode,
5928- InterMode::NewMv
5929- ),
5930- size: 2,
5931- size_h: 2,
5932- is_global_mv0: false,
5933- is_global_mv1: false,
5934- },
5935- None => MiInfo {
5936- is_inter: false,
5937- ref_frame: -1,
5938- ref_frame1: NO_REF1,
5939- mv1: (0, 0),
5940- mv: (0, 0),
5941- is_new_mv: false,
5942- size: 2,
5943- size_h: 2,
5944- is_global_mv0: false,
5945- is_global_mv1: false,
5946- },
5947- },
5948- );
5949- }
5950- }
6109+ // Same publication point as the 16x16
6110+ // straddling leaf above (`record_mi`).
6111+ record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter);
59516112 eight.push(leaf);
59526113 }
59536114 leaves.push(BlockCoeffs {
@@ -9492,6 +9653,7 @@ mod tests {
94929653 let _ = crate::tile::take_ref_hits();
94939654 let _ = crate::tile::take_compound_mode_hits();
94949655 let _ = crate::tile::take_compound_pair_hits();
9656+ let _ = crate::tile::take_compound_size_hits();
94959657 let _ = crate::motion::take_census();
94969658 let (ours, ours_wall) = match pyramid_from_env() {
94979659 None => our_ladder(&source, width, height, fctx),
@@ -9533,6 +9695,7 @@ mod tests {
95339695 // picks cannot be what a BD number credits).
95349696 let comp_modes = crate::tile::take_compound_mode_hits();
95359697 let comp_pairs = crate::tile::take_compound_pair_hits();
9698+ let comp_sizes = crate::tile::take_compound_size_hits();
95369699 let comp_total: usize = comp_modes.iter().sum();
95379700 eprintln!(
95389701 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
@@ -9544,6 +9707,10 @@ mod tests {
95449707 comp_modes[6], comp_modes[7],
95459708 comp_pairs[3], comp_pairs[6],
95469709 );
9710+ eprintln!(
9711+ "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
9712+ comp_sizes[1], comp_sizes[2], comp_sizes[3],
9713+ );
95479714 // Where the wall-owning stage actually goes: how many candidate
95489715 // evaluations (one `mc::predict` + SAD each) a search spends, how
95499716 // many of them are subpel, and how often the winner is the seed
crates/ec-av1/src/tile.rsmodified+15 -0
@@ -478,6 +478,19 @@ pub(crate) fn take_compound_pair_hits() -> [usize; 7] {
478478 std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
479479 }
480480
481+/// Per-SIZE fire counts of [`write_compound_block`], indexed by
482+/// `log2(bw4)` (1 = 8x8, 2 = 16x16, 3 = 32x32 and up): compound started as a
483+/// 32x32-only tool, so the share by size is what says whether the leaf
484+/// candidates fire at all (gate-blind-to-feature).
485+static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] =
486+ [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
487+
488+/// Takes and clears the compound size histogram.
489+#[cfg(test)]
490+pub(crate) fn take_compound_size_hits() -> [usize; 4] {
491+ std::array::from_fn(|i| COMPOUND_SIZE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
492+}
493+
481494 /// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side
482495 /// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /
483496 /// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that
@@ -615,6 +628,8 @@ fn write_compound_block(
615628 COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
616629 COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7]
617630 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
631+ COMPOUND_SIZE_HITS[(bw4.max(1).trailing_zeros() as usize).min(3)]
632+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
618633 if crate::envflags::env_flag!("EC_COMP_MISMATCH") && (mvs.0 != info.mv || mvs.1 != info.mv1) {
619634 eprintln!(
620635 "EC_COMP_MISMATCH mode={mode} enc=({:?},{:?}) wrote=({:?},{:?})",