forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1comp2' (238c65d8): NEAREST_NEW/NEW_NEAREST compound modes, distance-scaled motion search, and the encoder's mi grid votes both references

Browse files at this commit

fa932fb4cfc55d2de4ff1aeab68ceccfe86d74aeAhmet Kaan GümüşParent: fe25c8daeaf6ba
BD vs libaom +94.4/+104.3/+66.8, vs rav1e +47.5/+63.6/+10.7 (from
+120.1/+128.5/+66.4 and +67.8/+86.0/+10.3). Root cause: record_mi published
compound blocks as single-reference, so 95 blocks per gate run were
predicted from vectors never trialled -- invisible to the ffmpeg gate;
EC_COMP_MISMATCH=1 is the detector (0 is the invariant). Pyramid still
loses on all three clips and stays off.
crates/ec-av1/src/encode.rsmodified+123 -15
@@ -2884,6 +2884,7 @@ fn code_square_inter(
28842884 stack.pred_mv,
28852885 &seeds[..seed_n],
28862886 search.lambda, fctx,
2887+ 1,
28872888 );
28882889 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
28892890 if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) {
@@ -3015,10 +3016,24 @@ fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: O
30153016 Some(info) => MiInfo {
30163017 is_inter: true,
30173018 ref_frame: info.ref_frame,
3018- ref_frame1: NO_REF1,
3019- mv1: (0, 0),
3019+ // A COMPOUND block votes with BOTH of its references and both of
3020+ // its vectors, exactly as the tile writer publishes it: recording
3021+ // a compound block as a single-reference one here left the
3022+ // encoder's own grid disagreeing with the writer's from the first
3023+ // compound block on, so every later stack it searched against was
3024+ // not the stack the decoder derives.
3025+ ref_frame1: info.ref1.unwrap_or(NO_REF1),
3026+ mv1: mv16(info.mv1),
30203027 mv: mv16(info.mv),
3021- is_new_mv: matches!(info.mode, InterMode::NewMv),
3028+ // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
3029+ // side, compound modes 2/3/7 on the other.
3030+ is_new_mv: matches!(
3031+ info.mode,
3032+ InterMode::NewMv
3033+ | InterMode::NewNewMv
3034+ | InterMode::NearestNewMv
3035+ | InterMode::NewNearestMv
3036+ ),
30223037 size,
30233038 size_h: size,
30243039 is_global_mv0: false,
@@ -4423,6 +4438,22 @@ fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
44234438 /// coding `mv` as a residual against `pred`: the joint symbol naming which
44244439 /// components differ, then each differing component. `None` under the same
44254440 /// condition [`mv_component_bits`] returns `None`.
4441+/// How many frames back `ref_frame` sits from the frame being coded, off the
4442+/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
4443+/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
4444+/// what [`crate::motion::search`] scales its starting step by.
4445+fn ref_distance(ref_frame: i8) -> u32 {
4446+ let (bits, order_hint, hints) = crate::tile::order_hints();
4447+ let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
4448+ let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
4449+ .unsigned_abs()
4450+ .max(1);
4451+ if crate::envflags::env_flag!("EC_TRACE_DIST") {
4452+ eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]);
4453+ }
4454+ d
4455+}
4456+
44264457 fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
44274458 let diff = (mv.0 - pred.0, mv.1 - pred.1);
44284459 let joint = match (diff.0 != 0, diff.1 != 0) {
@@ -4835,6 +4866,7 @@ fn search_inter_block(
48354866 stack.pred_mv,
48364867 &seeds[..seed_n],
48374868 search.lambda, fctx,
4869+ 1,
48384870 );
48394871 #[cfg(test)]
48404872 stage_add(0, t.elapsed());
@@ -4934,6 +4966,7 @@ fn search_inter_block(
49344966 gstack.pred_mv,
49354967 &gseeds[..gn],
49364968 search.lambda, fctx,
4969+ ref_distance(ref_frame),
49374970 );
49384971 #[cfg(test)]
49394972 stage_add(0, t.elapsed());
@@ -4962,6 +4995,12 @@ fn search_inter_block(
49624995 // reference alone is right. Priced with the same static-CDF approximation
49634996 // the single-reference candidates use, plus the compound-only symbols
49644997 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
4998+ // The two compound-mode arms, each measured alone on the BD gate before
4999+ // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
5000+ // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
5001+ // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
5002+ let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
5003+ let half_new = true;
49655004 for (ref1, g, cstack) in compound {
49665005 let (ref1, g) = (*ref1, *g);
49675006 let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME)
@@ -5011,13 +5050,66 @@ fn search_inter_block(
50115050 },
50125051 ),
50135052 ];
5014- // `NEW_NEWMV` seeded from the two single-reference searches this
5015- // block already ran -- no joint search of its own.
5053+ // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
5054+ // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
5055+ // the stack is deep enough for that walk to read one.
5056+ if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
5057+ let drl = if cstack.entries.len() > 2 {
5058+ symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
5059+ } else {
5060+ 0.0
5061+ };
5062+ ccands.push((
5063+ (e.mv0, e.mv1),
5064+ mode_bits_of(1) + drl,
5065+ InterInfo {
5066+ ref_frame: crate::mvstack::LAST_FRAME,
5067+ mode: InterMode::NearNearMv,
5068+ mv: e.mv0,
5069+ mv1: e.mv1,
5070+ ref1: Some(ref1),
5071+ ref_mv_idx: 0,
5072+ },
5073+ ));
5074+ }
5075+ // The half-new modes and `NEW_NEWMV`, all seeded from the two
5076+ // single-reference searches this block already ran -- no joint search
5077+ // of its own. Every residual is priced against stack entry 0, which
5078+ // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
5079+ let cbase = cstack
5080+ .entries
5081+ .first()
5082+ .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
5083+ if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
5084+ ccands.push((
5085+ (mv, cstack.nearest_mv.1),
5086+ mode_bits_of(3) + b0,
5087+ InterInfo {
5088+ ref_frame: crate::mvstack::LAST_FRAME,
5089+ mode: InterMode::NewNearestMv,
5090+ mv,
5091+ mv1: cstack.nearest_mv.1,
5092+ ref1: Some(ref1),
5093+ ref_mv_idx: 0,
5094+ },
5095+ ));
5096+ }
50165097 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
5017- let base = cstack
5018- .entries
5019- .first()
5020- .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
5098+ if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
5099+ ccands.push((
5100+ (cstack.nearest_mv.0, mv1),
5101+ mode_bits_of(2) + b1,
5102+ InterInfo {
5103+ ref_frame: crate::mvstack::LAST_FRAME,
5104+ mode: InterMode::NearestNewMv,
5105+ mv: cstack.nearest_mv.0,
5106+ mv1,
5107+ ref1: Some(ref1),
5108+ ref_mv_idx: 0,
5109+ },
5110+ ));
5111+ }
5112+ let base = cbase;
50215113 if let (Some(b0), Some(b1)) = (
50225114 mv_residual_bits(mv, base.0),
50235115 mv_residual_bits(mv1, base.1),
@@ -5324,6 +5416,12 @@ pub(crate) fn encode_inter_frame(
53245416 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
53255417 header.order_hints = order_hints;
53265418 header.reference_select = reference_select();
5419+ // Armed HERE, not only beside the tile write below: `ref_distance`'s own
5420+ // per-reference order-hint distance is read by the block SEARCH, which
5421+ // runs long before the writer arms these (the distance-scaled search step
5422+ // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
5423+ // never reached the tool).
5424+ crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
53275425 if let Some(p) = pyramid {
53285426 header.show_frame = p.show_frame;
53295427 header.showable_frame = !p.show_frame;
@@ -5439,6 +5537,11 @@ pub(crate) fn encode_inter_frame(
54395537 let search_tile = |index: usize,
54405538 fctx: &crate::decode::FrameCtx|
54415539 -> Result<Vec<(usize, Quadrant)>> {
5540+ // Thread-local, and this job may be running on a `search_tiles`
5541+ // worker: `ref_distance`'s order-hint distance (the scaled motion
5542+ // search step) is read by the SEARCH, so every worker arms it or the
5543+ // tile's bits depend on the thread count.
5544+ crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
54425545 let rect = layout.rect(index);
54435546 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
54445547 let mut chroma = [
@@ -8270,9 +8373,13 @@ mod tests {
82708373 );
82718374 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
82728375 // the worst inter frame, where nearly every block now codes an MV
8273- // residual and a reference the coefficient sum never counts.
8376+ // residual and a reference the coefficient sum never counts. Re-measured
8377+ // at +29.6% once the encoder's grid published compound blocks properly
8378+ // (compound share 8.8% -> 11.5%): a compound block carries a second
8379+ // reference tree, a compound mode symbol and -- for the half-new modes
8380+ // -- an MV residual, none of which the coefficient sum counts.
82748381 assert!(
8275- worst_under <= 0.22,
8382+ worst_under <= 0.32,
82768383 "the writer spent {:.2}% more than the search priced -- more than \
82778384 the mode/mv syntax outside the coefficient sum explains",
82788385 worst_under * 100.0
@@ -9150,7 +9257,7 @@ mod tests {
91509257 })
91519258 };
91529259 let pins: [(u8, usize, u64); 2] =
9153- [(150, 7209, 0xacdd_6952_78c1_49f2), (60, 27353, 0x9be8_7898_f08d_3b77)];
9260+ [(150, 7103, 0xb9b7_763b_6f18_a887), (60, 26778, 0x4071_f16e_1e5d_87c3)];
91549261 for (q, bytes, hash) in pins {
91559262 let encoded = encode_sequence(&source, q, 0.5).unwrap();
91569263 assert_eq!(
@@ -9429,11 +9536,12 @@ mod tests {
94299536 let comp_total: usize = comp_modes.iter().sum();
94309537 eprintln!(
94319538 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
9432- NEAREST_NEAREST {} NEAR_NEAR {} GLOBAL_GLOBAL {} NEW_NEW {}; pairs \
9433- LAST+GOLDEN {} LAST+ALTREF {}",
9539+ NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
9540+ GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
94349541 modes_total + comp_total,
94359542 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
9436- comp_modes[0], comp_modes[1], comp_modes[6], comp_modes[7],
9543+ comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3],
9544+ comp_modes[6], comp_modes[7],
94379545 comp_pairs[3], comp_pairs[6],
94389546 );
94399547 // Where the wall-owning stage actually goes: how many candidate
crates/ec-av1/src/motion.rsmodified+39 -2
@@ -318,19 +318,54 @@ pub(crate) fn search(
318318 pred_mv: (i32, i32),
319319 seeds: &[(i32, i32)],
320320 lambda: f64, fctx: &crate::decode::FrameCtx,
321+ // How many frames back (order-hint distance) this reference sits: a
322+ // reference twice as far away holds content that has moved about twice
323+ // as far, so the log stage starts from a proportionally wider step. See
324+ // [`dist_initial_step`].
325+ dist: u32,
321326 ) -> MotionSearch {
322- let (result, _trace) = search_traced(
327+ let (result, _trace) = search_traced_from_step(
323328 reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h,
324329 pred_mv,
325330 if seeded() { seeds } else { &[] },
326- lambda, fctx,
331+ lambda,
332+ dist_initial_step(dist), fctx,
327333 );
328334 result
329335 }
330336
337+/// The integer-pel log stage's starting step for a reference at order-hint
338+/// distance `dist`: `step * (1 + k * (dist - 1))`, `k` = `EC_AV1_MV_DIST_SCALE`
339+/// in a test build. `k = 0` is the flat step every reference used before.
340+fn dist_initial_step(dist: u32) -> i32 {
341+ let base = if seeded() { seeded_step() } else { SEARCH_INITIAL_STEP_PEL };
342+ static K: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
343+ let k = *K.get_or_init(|| match std::env::var("EC_AV1_MV_DIST_SCALE").ok() {
344+ Some(v) if cfg!(test) => v.parse().unwrap_or(MV_DIST_SCALE),
345+ _ => MV_DIST_SCALE,
346+ });
347+ if dist <= 1 || k <= 0.0 {
348+ return base;
349+ }
350+ let scaled = f64::from(base) * k.mul_add(f64::from(dist - 1), 1.0);
351+ // Past 4x the base the log stage spends its rounds on vectors no
352+ // reference in this encoder's GOP reaches.
353+ scaled.round().clamp(f64::from(base), f64::from(base * 4)) as i32
354+}
355+
356+/// The distance scale [`dist_initial_step`] ships with. Swept on the BD gate
357+/// (vs libaom, 1080p/2160p/screen): 0 = +100.7/+115.8/+73.3, 0.25
358+/// +98.5/+112.2, 0.375 +98.2/+115.6, 0.5 +94.4/+104.3, 0.625 +95.9/+106.5,
359+/// 0.75 +92.8/+112.7, 1.0 +98.8/+113.0 -- screen is byte-identical at every
360+/// point (its motion is small enough that a wider start converges to the same
361+/// vector). 0.5 wins both film clips together; the ranking either side of it
362+/// is near-tie churn, not a gradient.
363+const MV_DIST_SCALE: f64 = 0.5;
364+
331365 /// [`search`], plus the running best cost after every round any of its three
332366 /// stages ran — what `cost_is_monotone_non_increasing_over_the_search` below
333367 /// checks.
368+#[cfg(test)]
334369 #[allow(clippy::too_many_arguments)] // one reference plane, one block, one predictor
335370 fn search_traced(
336371 reference: &[u16],
@@ -594,6 +629,7 @@ mod tests {
594629 (0, 0),
595630 &[],
596631 0.1, fctx,
632+ 1,
597633 );
598634 assert_eq!(
599635 result.mv,
@@ -644,6 +680,7 @@ mod tests {
644680 (0, 0),
645681 &[],
646682 0.1, fctx,
683+ 1,
647684 );
648685 assert_eq!(
649686 result.mv,
crates/ec-av1/src/tile.rsmodified+70 -2
@@ -361,6 +361,12 @@ pub(crate) fn arm_order_hints(bits: u32, order_hint: u32, hints: [u32; 7]) {
361361 ORDER_HINTS.with(|c| c.set((bits, order_hint, hints)));
362362 }
363363
364+/// What [`arm_order_hints`] last armed: `(order_hint_bits, order_hint,
365+/// ref_order_hints)`, for the encoder's own per-reference distance.
366+pub(crate) fn order_hints() -> (u32, u32, [u32; 7]) {
367+ ORDER_HINTS.with(std::cell::Cell::get)
368+}
369+
364370 /// Writer-side counterpart of decode.rs `read_compound_ref_frames` (spec
365371 /// 5.11.25's `comp_reference_type`/`uni_comp_ref`/`comp_ref`/`comp_bwdref`
366372 /// trees), symbol for symbol at the same contexts -- which are, as that
@@ -478,7 +484,7 @@ pub(crate) fn take_compound_pair_hits() -> [usize; 7] {
478484 /// order. Returns the two motion vectors the decoder derives (what the MI
479485 /// grid must record) and whether the mode was a `NEW*` one.
480486 ///
481-/// Only the three modes [`InterMode::compound_index`] names are written, and
487+/// Only the modes [`InterMode::compound_index`] names are written, and
482488 /// only the `comp_group_idx == 0`, `compound_idx == 1` blend (spec
483489 /// `COMPOUND_AVERAGE`) -- masked compound and the distance-weighted blend are
484490 /// not searched.
@@ -540,6 +546,41 @@ fn write_compound_block(
540546 let mvs = match info.mode {
541547 InterMode::NearestNearestMv => stack.nearest_mv,
542548 InterMode::GlobalGlobalMv => ((0, 0), (0, 0)),
549+ InterMode::NearNearMv => {
550+ // decode.rs `assign_compound_mv`'s second DRL loop: the index
551+ // starts at 1 and the mode's own `ref_mv_idx` is `idx - 1`, so
552+ // this walk starts at 1 too and reads entry `ref_mv_idx + 1`.
553+ let idx = usize::from(info.ref_mv_idx) + 1;
554+ let mut walk = 1usize;
555+ while walk < 3 && stack.entries.len() > walk + 1 {
556+ let advance = walk < idx;
557+ enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[walk]]);
558+ if !advance {
559+ break;
560+ }
561+ walk += 1;
562+ }
563+ stack
564+ .entries
565+ .get(idx)
566+ .map_or(stack.near_mv, |e| (e.mv0, e.mv1))
567+ }
568+ InterMode::NearestNewMv | InterMode::NewNearestMv => {
569+ // Neither mode codes a DRL index (the decoder leaves `ref_mv_idx`
570+ // at 0): the NEAREST half is derived, the NEW half codes a
571+ // residual against stack entry 0.
572+ let base = stack
573+ .entries
574+ .first()
575+ .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1));
576+ if matches!(info.mode, InterMode::NearestNewMv) {
577+ write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?;
578+ (stack.nearest_mv.0, info.mv1)
579+ } else {
580+ write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?;
581+ (info.mv, stack.nearest_mv.1)
582+ }
583+ }
543584 _ => {
544585 let idx = usize::from(info.ref_mv_idx);
545586 let mut walk = 0usize;
@@ -574,7 +615,21 @@ fn write_compound_block(
574615 COMPOUND_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
575616 COMPOUND_PAIR_HITS[(ref1.max(1) - 1) as usize % 7]
576617 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
577- Ok((mvs.0, mvs.1, matches!(info.mode, InterMode::NewNewMv)))
618+ if crate::envflags::env_flag!("EC_COMP_MISMATCH") && (mvs.0 != info.mv || mvs.1 != info.mv1) {
619+ eprintln!(
620+ "EC_COMP_MISMATCH mode={mode} enc=({:?},{:?}) wrote=({:?},{:?})",
621+ info.mv, info.mv1, mvs.0, mvs.1
622+ );
623+ }
624+ // decode.rs' own `is_new_mv` for a compound block: modes 2, 3, 4, 5, 7.
625+ Ok((
626+ mvs.0,
627+ mvs.1,
628+ matches!(
629+ info.mode,
630+ InterMode::NewNewMv | InterMode::NearestNewMv | InterMode::NewNearestMv
631+ ),
632+ ))
578633 }
579634
580635 /// Writer-side counterpart of decode.rs `read_comp_mode` (spec 5.11.25's
@@ -1153,6 +1208,16 @@ pub enum InterMode {
11531208 /// `NEAREST_NEARESTMV`: both sides take the compound stack's own nearest
11541209 /// pair, no residual, no DRL.
11551210 NearestNearestMv,
1211+ /// `NEAR_NEARMV`: both sides take compound stack entry
1212+ /// [`InterInfo::ref_mv_idx`]` + 1` (decode.rs `assign_compound_mv`'s own
1213+ /// `ref_mv_idx + 1`), reached by a DRL walk that starts at index 1.
1214+ NearNearMv,
1215+ /// `NEAREST_NEWMV`: the first side takes the stack's nearest vector, the
1216+ /// second codes a residual against stack entry 0.
1217+ NearestNewMv,
1218+ /// `NEW_NEARESTMV`: the first side codes a residual against stack entry 0,
1219+ /// the second takes the stack's nearest vector.
1220+ NewNearestMv,
11561221 /// `GLOBAL_GLOBALMV`: both sides take the identity global model's zero
11571222 /// vector.
11581223 GlobalGlobalMv,
@@ -1168,6 +1233,9 @@ impl InterMode {
11681233 fn compound_index(self) -> Option<usize> {
11691234 match self {
11701235 InterMode::NearestNearestMv => Some(0),
1236+ InterMode::NearNearMv => Some(1),
1237+ InterMode::NearestNewMv => Some(2),
1238+ InterMode::NewNearestMv => Some(3),
11711239 InterMode::GlobalGlobalMv => Some(6),
11721240 InterMode::NewNewMv => Some(7),
11731241 _ => None,