forge
Explore
Log in

Don't you dare go Hollow

Single-reference NEARMV/GLOBALMV and a real DRL index

Browse files at this commit

9147adbe4f072ae5f9747625c5a46e57d4268e51Ahmet Kaan GümüşParent: f649e1c
  • feat
    • single-reference NEARMV/GLOBALMV and a real DRL index
Show full message
feat(av1): single-reference NEARMV/GLOBALMV and a real DRL index

The writer's inter chain was NEARESTMV or NEWMV-at-DRL-0. It now codes the
whole single-reference mode set of spec 5.11.24 through one helper,
`tile::write_inter_mode`, that mirrors the decoder's `read_inter_mode` /
`read_drl_idx` / `assign_mv` reads symbol for symbol -- the three writer
sites (32x32, 16x16, 8x8 leaf) that each carried their own copy of the
two-mode chain now route through it, so a mode is added once.

`InterInfo` grows `ref_mv_idx` (the spec's `RefMvIdx`): NEWMV codes its
residual against `entries[idx]`, NEARMV takes `entries[idx]` outright.
GLOBALMV is the identity model's zero vector -- this encoder writes no
`gm_params`, so `gm_get_motion_vector` is (0,0) and `is_global_mv_block`
stays false, adding no motion-mode syntax.

The 32x32 inter RD prices every mode as (vector, cheapest syntax reaching
it) and trials one vector once, so the added modes cost mode-bit arithmetic
rather than more motion compensation; NEWMV picks the DRL index whose
residual plus DRL bits is cheapest.

BD-rate vs libaom 211.9/223.4/167.4 -> 210.1/218.7/167.4, vs rav1e
154.8/169.7/72.7 -> 151.7/164.7/72.7 (1080p/2160p/screen); wall
7.8/7.3/7.6 -> 7.9/8.7/7.6 s. Mode histogram printed by the gate.
crates/ec-av1/src/encode.rsmodified+187 -181
@@ -2321,6 +2321,7 @@ fn code_square_inter(
23212321 inter: Some(InterInfo {
23222322 mode: InterMode::NewMv,
23232323 mv: new_mv,
2324+ ref_mv_idx: 0,
23242325 }),
23252326 },
23262327 cost + dcost,
@@ -2346,6 +2347,7 @@ fn code_square_inter(
23462347 inter: Some(InterInfo {
23472348 mode: InterMode::NearestMv,
23482349 mv,
2350+ ref_mv_idx: 0,
23492351 }),
23502352 }, inter_cost + dcost)
23512353 } else {
@@ -3397,100 +3399,67 @@ fn search_inter_block(
33973399 chroma[1].true_width,
33983400 chroma[1].true_height,
33993401 );
3400- let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
3401- + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
3402- + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
3403-
3404- // The NEARESTMV candidate: `skip` is decided below from whether its
3405- // trial actually found a nonzero level, once its residual is priced
3406- // against the same CDFs the tile writer codes it with.
3407- //
3408- // lane-av1speed: its three trials are kept (rather than moved straight
3409- // into the candidate) so that a NEWMV landing on the very same vector --
3410- // common on static content, where the stack's nearest vector is also
3411- // what the search finds -- reuses them instead of running the same
3412- // motion compensation, transform, quantize and reconstruct again. The
3413- // reused trials are the same values, so the choice is bit-identical.
3414- let nearest_trials;
3415- {
3416- let mv = stack.nearest_mv;
3417- let luma_trial = mc_trial(
3418- luma,
3419- x,
3420- y,
3421- BLOCK,
3422- mv,
3423- true,
3424- ref_luma.0,
3425- ref_luma.1,
3426- ref_luma.2,
3427- ref_luma.3,
3428- false,
3429- search.base_q_idx,
3430- search.deadzone,
3431- TxbSet::Luma32Inter, fctx,
3432- );
3433- let u = mc_trial(
3434- &chroma[0],
3435- x / 2,
3436- y / 2,
3437- BLOCK / 2,
3438- mv,
3439- false,
3440- ref_u.0,
3441- ref_u.1,
3442- ref_u.2,
3443- ref_u.3,
3444- false,
3445- search.base_q_idx,
3446- search.deadzone,
3447- chroma_set, fctx,
3448- );
3449- let v = mc_trial(
3450- &chroma[1],
3451- x / 2,
3452- y / 2,
3453- BLOCK / 2,
3454- mv,
3455- false,
3456- ref_v.0,
3457- ref_v.1,
3458- ref_v.2,
3459- ref_v.3,
3460- false,
3461- search.base_q_idx,
3462- search.deadzone,
3463- chroma_set, fctx,
3464- );
3465- let skip = luma_trial.levels.iter().all(|&l| l == 0)
3466- && u.levels.iter().all(|&l| l == 0)
3467- && v.levels.iter().all(|&l| l == 0);
3468- let cost = luma_trial.sse
3469- + u.sse
3470- + v.sse
3471- + search.lambda
3472- * (skip_bits(skip)
3473- + intra_inter_bits(true)
3474- + single_ref_bits
3475- + mode_bits_inter
3476- + if skip {
3477- 0.0
3478- } else {
3479- luma_trial.bits + u.bits + v.bits
3480- });
3481- nearest_trials = (luma_trial.clone(), u.clone(), v.clone());
3482- consider(Candidate {
3483- cost,
3484- luma: luma_trial,
3485- u,
3486- v,
3487- mode: DC_PRED,
3488- skip,
3489- inter: Some(InterInfo {
3402+ // Every single-reference mode the writer can code (spec 5.11.24's symbol
3403+ // chain, mirrored by `tile::write_inter_mode`), priced with the static
3404+ // CDFs at this block's own stack contexts. A candidate is a motion
3405+ // vector plus the cheapest syntax that reaches it, so two modes landing
3406+ // on the same vector share one set of trials: the added modes cost
3407+ // mode-bit arithmetic, not another motion compensation.
3408+ let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
3409+ let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
3410+ // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
3411+ // past `start`, `1` to advance and `0` to stop, at most two. A `target`
3412+ // the loop cannot reach is never offered below -- every candidate's
3413+ // index is one this same loop walks to.
3414+ let drl_bits = |start: usize, target: usize| {
3415+ let mut bits = 0.0;
3416+ let mut idx = start;
3417+ while idx < start + 2 && stack.entries.len() > idx + 1 {
3418+ let advance = idx < target;
3419+ bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
3420+ if !advance {
3421+ break;
3422+ }
3423+ idx += 1;
3424+ }
3425+ bits
3426+ };
3427+ let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
3428+ (
3429+ stack.nearest_mv,
3430+ not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
3431+ InterInfo {
34903432 mode: InterMode::NearestMv,
3491- mv,
3492- }),
3493- });
3433+ mv: stack.nearest_mv,
3434+ ref_mv_idx: 0,
3435+ },
3436+ ),
3437+ // GLOBALMV is the identity model's zero vector -- this encoder writes
3438+ // no `gm_params` -- and the cheapest syntax of the four on the static
3439+ // content where that vector is also the right one.
3440+ (
3441+ (0, 0),
3442+ not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
3443+ InterInfo {
3444+ mode: InterMode::GlobalMv,
3445+ mv: (0, 0),
3446+ ref_mv_idx: 0,
3447+ },
3448+ ),
3449+ ];
3450+ let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
3451+ for idx in 1..=3usize {
3452+ if let Some(e) = stack.entries.get(idx) {
3453+ cands.push((
3454+ e.mv,
3455+ near_bits + drl_bits(1, idx),
3456+ InterInfo {
3457+ mode: InterMode::NearMv,
3458+ mv: e.mv,
3459+ ref_mv_idx: idx as u8,
3460+ },
3461+ ));
3462+ }
34943463 }
34953464
34963465 let source_block = luma.source_block(x, y, BLOCK);
@@ -3512,96 +3481,114 @@ fn search_inter_block(
35123481 #[cfg(test)]
35133482 stage_add(0, t.elapsed());
35143483 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
3515- if let Some(mv_bits) = mv_residual_bits(mv, stack.pred_mv) {
3516- let (luma_trial, u, v) = if mv == stack.nearest_mv {
3517- nearest_trials
3518- } else {
3519- (
3520- mc_trial(
3521- luma,
3522- x,
3523- y,
3524- BLOCK,
3525- mv,
3526- true,
3527- ref_luma.0,
3528- ref_luma.1,
3529- ref_luma.2,
3530- ref_luma.3,
3531- false,
3532- search.base_q_idx,
3533- search.deadzone,
3534- TxbSet::Luma32Inter, fctx,
3535- ),
3536- mc_trial(
3537- &chroma[0],
3538- x / 2,
3539- y / 2,
3540- BLOCK / 2,
3541- mv,
3542- false,
3543- ref_u.0,
3544- ref_u.1,
3545- ref_u.2,
3546- ref_u.3,
3547- false,
3548- search.base_q_idx,
3549- search.deadzone,
3550- chroma_set, fctx,
3551- ),
3552- mc_trial(
3553- &chroma[1],
3554- x / 2,
3555- y / 2,
3556- BLOCK / 2,
3557- mv,
3558- false,
3559- ref_v.0,
3560- ref_v.1,
3561- ref_v.2,
3562- ref_v.3,
3563- false,
3564- search.base_q_idx,
3565- search.deadzone,
3566- chroma_set, fctx,
3567- ),
3568- )
3569- };
3570- let drl_bits = if stack.entries.len() > 1 {
3571- symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
3572- } else {
3573- 0.0
3574- };
3575- let skip = luma_trial.levels.iter().all(|&l| l == 0)
3576- && u.levels.iter().all(|&l| l == 0)
3577- && v.levels.iter().all(|&l| l == 0);
3578- let cost = luma_trial.sse
3579- + u.sse
3580- + v.sse
3581- + search.lambda
3582- * (skip_bits(skip)
3583- + intra_inter_bits(true)
3584- + single_ref_bits
3585- + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
3586- + drl_bits
3587- + mv_bits
3588- + if skip {
3589- 0.0
3590- } else {
3591- luma_trial.bits + u.bits + v.bits
3592- });
3593- consider(Candidate {
3594- cost,
3595- luma: luma_trial,
3596- u,
3597- v,
3598- mode: DC_PRED,
3599- skip,
3600- inter: Some(InterInfo {
3484+ // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
3485+ // the same vector costs a different residual from each: take the index
3486+ // whose residual plus DRL bits is cheapest, not entry 0 by default.
3487+ let mut best_new: Option<(f64, u8)> = None;
3488+ for idx in 0..3usize {
3489+ if idx > 0 && stack.entries.len() <= idx {
3490+ break;
3491+ }
3492+ let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
3493+ if let Some(b) = mv_residual_bits(mv, base) {
3494+ let total = b + drl_bits(0, idx);
3495+ if best_new.is_none_or(|(t, _)| total < t) {
3496+ best_new = Some((total, idx as u8));
3497+ }
3498+ }
3499+ }
3500+ if let Some((bits, ref_mv_idx)) = best_new {
3501+ cands.push((
3502+ mv,
3503+ symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,
3504+ InterInfo {
36013505 mode: InterMode::NewMv,
36023506 mv,
3603- }),
3604- });
3507+ ref_mv_idx,
3508+ },
3509+ ));
3510+ }
3511+
3512+ // One trial set per distinct vector: sort by vector, cheapest syntax
3513+ // first, and drop the rest of each vector's run.
3514+ cands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
3515+ cands.dedup_by_key(|c| c.0);
3516+ {
3517+ for (mv, mode_bits_inter, info) in cands {
3518+ let luma_trial = mc_trial(
3519+ luma,
3520+ x,
3521+ y,
3522+ BLOCK,
3523+ mv,
3524+ true,
3525+ ref_luma.0,
3526+ ref_luma.1,
3527+ ref_luma.2,
3528+ ref_luma.3,
3529+ false,
3530+ search.base_q_idx,
3531+ search.deadzone,
3532+ TxbSet::Luma32Inter, fctx,
3533+ );
3534+ let u = mc_trial(
3535+ &chroma[0],
3536+ x / 2,
3537+ y / 2,
3538+ BLOCK / 2,
3539+ mv,
3540+ false,
3541+ ref_u.0,
3542+ ref_u.1,
3543+ ref_u.2,
3544+ ref_u.3,
3545+ false,
3546+ search.base_q_idx,
3547+ search.deadzone,
3548+ chroma_set, fctx,
3549+ );
3550+ let v = mc_trial(
3551+ &chroma[1],
3552+ x / 2,
3553+ y / 2,
3554+ BLOCK / 2,
3555+ mv,
3556+ false,
3557+ ref_v.0,
3558+ ref_v.1,
3559+ ref_v.2,
3560+ ref_v.3,
3561+ false,
3562+ search.base_q_idx,
3563+ search.deadzone,
3564+ chroma_set, fctx,
3565+ );
3566+ let skip = luma_trial.levels.iter().all(|&l| l == 0)
3567+ && u.levels.iter().all(|&l| l == 0)
3568+ && v.levels.iter().all(|&l| l == 0);
3569+ let cost = luma_trial.sse
3570+ + u.sse
3571+ + v.sse
3572+ + search.lambda
3573+ * (skip_bits(skip)
3574+ + intra_inter_bits(true)
3575+ + single_ref_bits
3576+ + mode_bits_inter
3577+ + if skip {
3578+ 0.0
3579+ } else {
3580+ luma_trial.bits + u.bits + v.bits
3581+ });
3582+ consider(Candidate {
3583+ cost,
3584+ luma: luma_trial,
3585+ u,
3586+ v,
3587+ mode: DC_PRED,
3588+ skip,
3589+ inter: Some(info),
3590+ });
3591+ }
36053592 }
36063593
36073594 let best = best.expect("the search offers at least the intra modes");
@@ -4574,6 +4561,7 @@ mod tests {
45744561 inter: Some(InterInfo {
45754562 mode: InterMode::NearestMv,
45764563 mv: (0, 0),
4564+ ref_mv_idx: 0,
45774565 }),
45784566 };
45794567 let skipped_block = BlockCoeffs {
@@ -4581,6 +4569,7 @@ mod tests {
45814569 inter: Some(InterInfo {
45824570 mode: InterMode::NearestMv,
45834571 mv: (0, 0),
4572+ ref_mv_idx: 0,
45844573 }),
45854574 ..BlockCoeffs::default()
45864575 };
@@ -6979,11 +6968,28 @@ mod tests {
69796968 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
69806969 let _ = take_partition_hits();
69816970 let _ = take_uv_mode_hits();
6971+ let _ = crate::tile::take_inter_mode_hits();
6972+ let _ = crate::tile::take_drl_hits();
69826973 let (ours, ours_wall) = our_ladder(&source, width, height, fctx);
69836974 // How often the inter split actually fired over this clip's four
69846975 // encodes, against the whole 32x32 that was the only outcome
69856976 // before (gate-blind-to-feature).
69866977 let [whole32, split32, whole16, split16] = take_partition_hits();
6978+ // Which inter modes actually fired over this clip's four encodes,
6979+ // and at which DRL index -- a mode nobody picks is a mode the BD
6980+ // number cannot be crediting (gate-blind-to-feature).
6981+ let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
6982+ let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
6983+ let modes_total = (nearest + near + global + new).max(1);
6984+ eprintln!(
6985+ "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
6986+ GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
6987+ {drl0}/{drl1}/{drl2}/{drl3}",
6988+ 100.0 * nearest as f64 / modes_total as f64,
6989+ 100.0 * near as f64 / modes_total as f64,
6990+ 100.0 * global as f64 / modes_total as f64,
6991+ 100.0 * new as f64 / modes_total as f64,
6992+ );
69876993 eprintln!(
69886994 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
69896995 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
crates/ec-av1/src/tile.rsmodified+139 -78
@@ -487,16 +487,21 @@ pub struct BlockCoeffs {
487487 pub tx_depth: u8,
488488 }
489489
490-/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take (spec
491-/// 5.11.24 `read_inter_mode`), reduced to the two branches its symbol chain
492-/// needs to prove out: the stack's own top candidate outright, or a coded
493-/// residual against it. `NEARMV`/`GLOBALMV` are never written.
490+/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
491+/// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
492+/// [`write_inter_mode`] with the decoder's own contexts.
494493 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
495494 pub enum InterMode {
496495 /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL.
497496 NearestMv,
498- /// `NEWMV`: codes `mv` as a residual against `MvStack::pred_mv`, through
499- /// a DRL index this writer always leaves at zero.
497+ /// `NEARMV`: takes the stack entry [`InterInfo::ref_mv_idx`] names
498+ /// (clamped to at least 1, the spec's own `RefMvIdx` base for this mode).
499+ NearMv,
500+ /// `GLOBALMV`: the identity global model's zero vector, two symbols and
501+ /// no MV at all.
502+ GlobalMv,
503+ /// `NEWMV`: codes `mv` as a residual against the stack entry
504+ /// [`InterInfo::ref_mv_idx`] names.
500505 NewMv,
501506 }
502507
@@ -510,6 +515,11 @@ pub struct InterInfo {
510515 pub mode: InterMode,
511516 /// The motion vector a [`InterMode::NewMv`] block's residual targets.
512517 pub mv: (i32, i32),
518+ /// The block's `RefMvIdx` (spec 5.11.24 `read_drl_idx`): which
519+ /// `MvStack::entries` slot `NEWMV` codes its residual against, or
520+ /// `NEARMV` takes outright. Ignored by the two modes that code no DRL
521+ /// index (`NEARESTMV`, `GLOBALMV`).
522+ pub ref_mv_idx: u8,
513523 }
514524
515525 impl From<Vec<Coeff>> for BlockCoeffs {
@@ -2632,6 +2642,123 @@ fn write_mv(
26322642 Ok(())
26332643 }
26342644
2645+/// Per-mode fire counts of [`write_inter_mode`], indexed
2646+/// `NEARESTMV`/`NEARMV`/`GLOBALMV`/`NEWMV`, and the DRL index each block
2647+/// coded (bucket 3 collects any index past 2). Read by the BD gate, which
2648+/// is the only thing that proves a newly added mode ever fires
2649+/// (gate-blind-to-feature).
2650+static INTER_MODE_HITS: [std::sync::atomic::AtomicUsize; 4] = [
2651+ std::sync::atomic::AtomicUsize::new(0),
2652+ std::sync::atomic::AtomicUsize::new(0),
2653+ std::sync::atomic::AtomicUsize::new(0),
2654+ std::sync::atomic::AtomicUsize::new(0),
2655+];
2656+static DRL_HITS: [std::sync::atomic::AtomicUsize; 4] = [
2657+ std::sync::atomic::AtomicUsize::new(0),
2658+ std::sync::atomic::AtomicUsize::new(0),
2659+ std::sync::atomic::AtomicUsize::new(0),
2660+ std::sync::atomic::AtomicUsize::new(0),
2661+];
2662+
2663+/// Bumps the two histograms for one coded inter block.
2664+fn note_inter_mode(mode: usize, drl: usize) {
2665+ INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2666+ DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2667+}
2668+
2669+/// Takes and clears the inter-mode histogram (NEAREST/NEAR/GLOBAL/NEW).
2670+#[cfg(test)]
2671+pub(crate) fn take_inter_mode_hits() -> [usize; 4] {
2672+ [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2673+}
2674+
2675+/// Takes and clears the DRL-index histogram (0, 1, 2, 3+).
2676+#[cfg(test)]
2677+pub(crate) fn take_drl_hits() -> [usize; 4] {
2678+ [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2679+}
2680+
2681+/// Writes the DRL index of one block: the loop the decoder runs (spec
2682+/// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one
2683+/// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to
2684+/// stop, at most two bits. `drl_ctx[idx]` is the context between
2685+/// `entries[idx]` and `entries[idx + 1]`, exactly the pair the bit chooses
2686+/// between.
2687+fn write_drl_idx(
2688+ enc: &mut SymbolEncoder,
2689+ cdfs: &mut Cdfs,
2690+ stack: &crate::mvstack::MvStack,
2691+ start: usize,
2692+ target: usize,
2693+) {
2694+ let mut idx = start;
2695+ while idx < start + 2 && stack.entries.len() > idx + 1 {
2696+ let advance = idx < target;
2697+ enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[idx]]);
2698+ if !advance {
2699+ return;
2700+ }
2701+ idx += 1;
2702+ }
2703+}
2704+
2705+/// Writer-side counterpart of the decoder's single-reference
2706+/// `read_inter_mode`/`assign_mv` chain (decode.rs ~26645): writes `info`'s
2707+/// mode symbols against `stack`'s own contexts and, for `NEWMV`, the MV
2708+/// residual against the DRL-selected predictor. Returns the motion vector
2709+/// the decoder will derive for the block (what the MI grid must record) and
2710+/// whether it is `NEWMV`.
2711+///
2712+/// `GLOBALMV` resolves to `(0, 0)` because this encoder writes no global
2713+/// motion parameters at all, so every `gm_get_motion_vector` the decoder
2714+/// runs is the identity model's zero vector; a lane that starts writing
2715+/// real `gm_params` has to feed the same vector in here.
2716+///
2717+/// # Errors
2718+/// As [`write_mv`]: a `NEWMV` residual needing eighth-pel precision.
2719+fn write_inter_mode(
2720+ enc: &mut SymbolEncoder,
2721+ cdfs: &mut Cdfs,
2722+ info: InterInfo,
2723+ stack: &crate::mvstack::MvStack,
2724+) -> Result<((i32, i32), bool)> {
2725+ let idx = usize::from(info.ref_mv_idx);
2726+ match info.mode {
2727+ InterMode::NewMv => {
2728+ enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]);
2729+ write_drl_idx(enc, cdfs, stack, 0, idx);
2730+ let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
2731+ write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?;
2732+ note_inter_mode(3, idx);
2733+ Ok((info.mv, true))
2734+ }
2735+ InterMode::GlobalMv => {
2736+ enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
2737+ enc.symbol(0, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // GLOBALMV
2738+ note_inter_mode(2, 0);
2739+ Ok(((0, 0), false))
2740+ }
2741+ InterMode::NearestMv => {
2742+ enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
2743+ enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
2744+ enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
2745+ note_inter_mode(0, 0);
2746+ Ok((stack.nearest_mv, false))
2747+ }
2748+ InterMode::NearMv => {
2749+ enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV
2750+ enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV
2751+ enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARMV
2752+ // `RefMvIdx` starts at 1 for NEARMV (spec 5.11.24).
2753+ let idx = idx.max(1);
2754+ write_drl_idx(enc, cdfs, stack, 1, idx);
2755+ let mv = stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv);
2756+ note_inter_mode(1, idx);
2757+ Ok((mv, false))
2758+ }
2759+ }
2760+}
2761+
26352762 /// Writes the payload of a one-tile inter frame built from `blocks`, one
26362763 /// 32x32 block per entry in raster order across the frame — every superblock
26372764 /// is split into its four quadrants the way [`split_coeff_key_frame_tile`]
@@ -3028,32 +3155,7 @@ pub fn sb_coeff_inter_frame_tile_tx(
30283155 mi_rows as usize,
30293156 );
30303157
3031- let is_new_mv = matches!(info.mode, InterMode::NewMv);
3032- if is_new_mv {
3033- enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV
3034- } else {
3035- enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new
3036- enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero
3037- enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
3038- }
3039- // This writer always keeps the first DRL candidate, so the
3040- // loop (spec 5.11.24 `read_drl_idx`) only ever runs its
3041- // first, breaking iteration.
3042- if is_new_mv && stack.entries.len() > 1 {
3043- enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]);
3044- }
3045- let mv = if is_new_mv {
3046- write_mv(
3047- &mut enc,
3048- &mut cdfs.mv_comp,
3049- &mut cdfs.mv_joint,
3050- info.mv,
3051- stack.pred_mv,
3052- )?;
3053- info.mv
3054- } else {
3055- stack.nearest_mv
3056- };
3158+ let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?;
30573159 grid.set(
30583160 mi_row,
30593161 mi_col,
@@ -3263,29 +3365,7 @@ fn write_inter_frame_leaf(
32633365 mi_rows as usize,
32643366 );
32653367
3266- let is_new_mv = matches!(info.mode, InterMode::NewMv);
3267- if is_new_mv {
3268- enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV
3269- } else {
3270- enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new
3271- enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero
3272- enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
3273- }
3274- if is_new_mv && stack.entries.len() > 1 {
3275- enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]);
3276- }
3277- let mv = if is_new_mv {
3278- write_mv(
3279- enc,
3280- &mut cdfs.mv_comp,
3281- &mut cdfs.mv_joint,
3282- info.mv,
3283- stack.pred_mv,
3284- )?;
3285- info.mv
3286- } else {
3287- stack.nearest_mv
3288- };
3368+ let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
32893369 for dr in 0..SUB_MI as usize {
32903370 for dc in 0..SUB_MI as usize {
32913371 grid.set(
@@ -3483,29 +3563,7 @@ fn write_inter_frame_leaf8(
34833563 mi_rows as usize,
34843564 );
34853565
3486- let is_new_mv = matches!(info.mode, InterMode::NewMv);
3487- if is_new_mv {
3488- enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV
3489- } else {
3490- enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new
3491- enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero
3492- enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV
3493- }
3494- if is_new_mv && stack.entries.len() > 1 {
3495- enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]);
3496- }
3497- let mv = if is_new_mv {
3498- write_mv(
3499- enc,
3500- &mut cdfs.mv_comp,
3501- &mut cdfs.mv_joint,
3502- info.mv,
3503- stack.pred_mv,
3504- )?;
3505- info.mv
3506- } else {
3507- stack.nearest_mv
3508- };
3566+ let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
35093567 for dr in 0..2 {
35103568 for dc in 0..2 {
35113569 grid.set(
@@ -5898,6 +5956,7 @@ mod tests {
58985956 inter: Some(InterInfo {
58995957 mode: InterMode::NearestMv,
59005958 mv: (0, 0),
5959+ ref_mv_idx: 0,
59015960 }),
59025961 skip: true,
59035962 ..BlockCoeffs::default()
@@ -5939,6 +5998,7 @@ mod tests {
59395998 inter: Some(InterInfo {
59405999 mode: InterMode::NearestMv,
59416000 mv: (0, 0),
6001+ ref_mv_idx: 0,
59426002 }),
59436003 skip: true,
59446004 ..BlockCoeffs::default()
@@ -5947,6 +6007,7 @@ mod tests {
59476007 inter: Some(InterInfo {
59486008 mode: InterMode::NewMv,
59496009 mv: (0, 2),
6010+ ref_mv_idx: 0,
59506011 }),
59516012 skip: true,
59526013 ..BlockCoeffs::default()