forge
Explore
Log in

Don't you dare go Hollow

Code allow_high_precision_mv frames -- header bit, mv_hp symbols, pricer, eighth-pel search stage

Browse files at this commit

c5d38323191cfb1c00f4d042affb6d7f6822c983Ahmet Kaan GümüşParent: 1e4e107
  • feat
    • code allow_high_precision_mv frames -- header bit, mv_hp symbols, pricer, eighth-pel search stage
Show full message
feat(av1): code allow_high_precision_mv frames -- header bit, mv_hp symbols, pricer, eighth-pel search stage

The writer refused any odd eighth-pel mv residual, so the finest vector
this encoder could commit to was a quarter pel. It can now code a frame
with allow_high_precision_mv: the header bit follows libaom's own rule
(qindex below a threshold), tile::write_mv_component codes the
mv_hp/mv_class0_hp symbol, encode::mv_component_bits prices it,
round_to_valid_mv stops rounding, and motion::search runs a fourth
refinement stage at 1/8 pel in such a frame. Default stays off
(HP_MV_QTHRESH = 0) until the BD sweep decides the policy.

Witness: a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read
-- 0 hp symbols off, 6 on (5 of them eighth-pel vectors the off arm
cannot name), both arms sample-exact through ffmpeg and decode_stream.
crates/ec-av1/src/encode.rsmodified+137 -5
@@ -2074,7 +2074,11 @@ pub fn inter_frame_headers_slots(
20742074 idx[6] = altref_slot;
20752075 idx
20762076 },
2077- allow_high_precision_mv: false,
2077+ // lane-hpmv: libaom's own rule (`av1_pick_and_set_high_precision_mv`:
2078+ // `use_hp = qindex < HIGH_PRECISION_MV_QTHRESH`), with this crate's
2079+ // threshold in [`HP_MV_QTHRESH`]. `force_integer_mv` is false in
2080+ // every frame this constructor builds, so no further guard is needed.
2081+ allow_high_precision_mv: high_precision_mv_at(base_q_idx),
20782082 // A FIXED frame-level filter, so no block codes an `interp_filter`
20792083 // symbol. lane-obmc3 instrumented whether that costs anything: a
20802084 // libaom `cpu-used 6` crf 41 stream of the long-GOP film B window
@@ -8771,24 +8775,31 @@ fn mv_class_of(z: i32) -> usize {
87718775 /// through, not the tile writer's own adapting state, which this encoder has
87728776 /// no way to read without duplicating it block for block.
87738777 ///
8774-/// Returns `None` when `diff` needs the eighth-pel precision this crate's
8775-/// frames never carry (`allow_high_precision_mv` is always off), which is
8776-/// what [`round_to_valid_mv`] exists to avoid ever happening.
8778+/// Returns `None` when `diff` needs eighth-pel precision in a frame coded
8779+/// without `allow_high_precision_mv`, which is what [`round_to_valid_mv`]
8780+/// exists to avoid ever happening.
87778781 fn mv_component_bits(diff: i32) -> Option<f64> {
8782+ let hp_frame = crate::tile::high_precision_mv();
87788783 let mag = diff.unsigned_abs() as i32;
87798784 let z = mag - 1;
8780- if z & 1 == 0 {
8785+ if !hp_frame && z & 1 == 0 {
87818786 return None;
87828787 }
87838788 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
87848789 let class = mv_class_of(z);
87858790 bits += symbol_bits(&cdf::MV_CLASS, class);
87868791 let local = z - mv_class_base(class);
8792+ let hp = (local & 1) as usize;
87878793 if class == 0 {
87888794 let bit = (local >> 3) & 1;
87898795 let fr = (local >> 1) & 3;
87908796 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
87918797 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
8798+ // lane-hpmv: the writer codes the eighth-pel bit in a high-precision
8799+ // frame, so the pricer charges for it there and only there.
8800+ if hp_frame {
8801+ bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
8802+ }
87928803 } else {
87938804 let d = local >> 3;
87948805 let fr = (local >> 1) & 3;
@@ -8796,6 +8807,9 @@ fn mv_component_bits(diff: i32) -> Option<f64> {
87968807 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
87978808 }
87988809 bits += symbol_bits(&cdf::MV_FR, fr as usize);
8810+ if hp_frame {
8811+ bits += symbol_bits(&cdf::MV_HP, hp);
8812+ }
87998813 }
88008814 Some(bits)
88018815 }
@@ -8951,7 +8965,51 @@ fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
89518965 /// down keeps every coded MV — and so every `nearest_mv` a later block's
89528966 /// stack votes with — built from an even displacement from `(0, 0)`, so the
89538967 /// invariant holds without this function seeing the whole stack.
8968+/// A PROCESS-GLOBAL [`high_precision_mv_at`] override that wins over both
8969+/// the threshold and the environment (`u8::MAX` = unset, `0` = never, `1` =
8970+/// always), the shape [`set_frame_interp`] has: the witness that has to see
8971+/// `mv_hp` symbols coded turns it on through this while holding
8972+/// [`crate::speed::knob_write`].
8973+static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
8974+
8975+/// Sets [`HP_MV_OVERRIDE`]; `None` clears it.
8976+#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
8977+pub(crate) fn set_high_precision_mv(on: Option<bool>) {
8978+ HP_MV_OVERRIDE.store(on.map_or(u8::MAX, u8::from), std::sync::atomic::Ordering::Relaxed);
8979+}
8980+
8981+/// The qindex below which an inter frame codes `allow_high_precision_mv`
8982+/// (lane-hpmv). libaom's `HIGH_PRECISION_MV_QTHRESH` is 128; `0` is this
8983+/// crate's shipped value, i.e. high-precision motion vectors off in every
8984+/// frame -- see `lanes/hpmv.report.md` for the sweep that chose it.
8985+pub(crate) const HP_MV_QTHRESH: u8 = 0;
8986+
8987+/// Whether an inter frame at `base_q_idx` carries `allow_high_precision_mv`:
8988+/// [`HP_MV_QTHRESH`], overridable by `EC_AV1_HP_MV` (`0`/`off` never, `all`
8989+/// always, any number as the threshold) so the BD gate can sweep the policy
8990+/// without a rebuild.
8991+pub(crate) fn high_precision_mv_at(base_q_idx: u8) -> bool {
8992+ match HP_MV_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
8993+ 0 => return false,
8994+ 1 => return true,
8995+ _ => {}
8996+ }
8997+ static T: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
8998+ let threshold = *T.get_or_init(|| match std::env::var("EC_AV1_HP_MV").ok().as_deref() {
8999+ Some("all" | "always") => 256,
9000+ Some("0" | "off") => 0,
9001+ Some(v) => v.parse().unwrap_or(u16::from(HP_MV_QTHRESH)),
9002+ None => u16::from(HP_MV_QTHRESH),
9003+ });
9004+ u16::from(base_q_idx) < threshold
9005+}
9006+
89549007 fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
9008+ // lane-hpmv: with `allow_high_precision_mv` on, every eighth-pel
9009+ // residual is codable and there is nothing to round away.
9010+ if crate::tile::high_precision_mv() {
9011+ return mv;
9012+ }
89559013 let round = |m: i32, p: i32| {
89569014 let diff = m - p;
89579015 let mag = diff.unsigned_abs() as i32;
@@ -11324,6 +11382,10 @@ pub(crate) fn encode_inter_frame(
1132411382 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
1132511383 // never reached the tool).
1132611384 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
11385+ // lane-hpmv: armed here for the same reason the order hints are -- the
11386+ // block SEARCH reads it (its eighth-pel stage) long before the writer.
11387+ let hp_mv = header.allow_high_precision_mv;
11388+ crate::tile::arm_high_precision_mv(hp_mv);
1132711389 if let Some(p) = pyramid {
1132811390 header.show_frame = p.show_frame;
1132911391 header.showable_frame = !p.show_frame;
@@ -11580,6 +11642,7 @@ pub(crate) fn encode_inter_frame(
1158011642 // search step) is read by the SEARCH, so every worker arms it or the
1158111643 // tile's bits depend on the thread count.
1158211644 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
11645+ crate::tile::arm_high_precision_mv(hp_mv);
1158311646 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
1158411647 let rect = layout.rect(index);
1158511648 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
@@ -12265,6 +12328,7 @@ pub(crate) fn encode_inter_frame(
1226512328 crate::tile::arm_motion_mode(switchable_motion_mode);
1226612329 crate::tile::arm_warped_motion(warped_motion);
1226712330 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
12331+ crate::tile::arm_high_precision_mv(hp_mv);
1226812332 crate::tile::arm_screen(screen);
1226912333 crate::tile::arm_filter_intra(filter_intra_on());
1227012334 let mut cdfs = start_cdfs.0.clone();
@@ -18531,4 +18595,72 @@ mod tests {
1853118595 }
1853218596 }
1853318597
18598+
18599+ /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
18600+ /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
18601+ /// residual outright (`round_to_valid_mv` rounds it away first), so the
18602+ /// finest vector the encoder could commit to was a quarter pel. With the
18603+ /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
18604+ /// non-zero component and the search's fourth stage refines to the
18605+ /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
18606+ /// on arm, and -- the part that makes it a signal rather than a symbol
18607+ /// count (class `fixture proves the symbol, not the signal`) -- that some
18608+ /// of them come out ZERO, i.e. name a vector the off arm cannot code at
18609+ /// all. Both streams are decoded by ffmpeg AND by this crate's own
18610+ /// decoder and asserted sample-exact against the encoder's own
18611+ /// reconstruction, which is what proves the header bit and the symbols
18612+ /// agree.
18613+ #[test]
18614+ fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
18615+ let _knobs = crate::speed::knob_write();
18616+ if !have_ffmpeg() {
18617+ eprintln!("SKIP a_high_precision_frame_codes_eighth_pel_motion_vectors: no ffmpeg");
18618+ return;
18619+ }
18620+ let (width, height) = (256usize, 128usize);
18621+ let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect();
18622+ let mut arms = Vec::new();
18623+ for hp in [false, true] {
18624+ set_high_precision_mv(Some(hp));
18625+ let _ = crate::tile::take_hp_symbols();
18626+ let fctx = &crate::decode::FrameCtx::for_encoder();
18627+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
18628+ .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
18629+ let (symbols, eighth) = crate::tile::take_hp_symbols();
18630+ let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
18631+ let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18632+ assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
18633+ assert_eq!(ours.len(), pictures.len(), "hp={hp}: our decoder frame count");
18634+ for (i, e) in encoded.frames.iter().enumerate() {
18635+ for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
18636+ if let Some((plane, s, got, want)) = first_plane_mismatch(got, &e.reconstruction)
18637+ {
18638+ panic!(
18639+ "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
18640+ the encoder reconstructed {want}"
18641+ );
18642+ }
18643+ }
18644+ }
18645+ arms.push((symbols, eighth, encoded.stream));
18646+ }
18647+ set_high_precision_mv(None);
18648+ let (off, on) = (&arms[0], &arms[1]);
18649+ assert_eq!(off.0, 0, "a frame without the header bit codes no hp symbol");
18650+ assert!(on.0 > 0, "a high-precision frame codes hp symbols (got {})", on.0);
18651+ assert!(
18652+ on.1 > 0,
18653+ "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)",
18654+ on.0
18655+ );
18656+ assert_ne!(off.2, on.2, "the two arms coded the same bytes");
18657+ println!(
18658+ "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B",
18659+ off.0,
18660+ off.2.len(),
18661+ on.0,
18662+ on.1,
18663+ on.2.len()
18664+ );
18665+ }
1853418666 }
crates/ec-av1/src/motion.rsmodified+16 -3
@@ -36,6 +36,13 @@ const HALF_PEL_Q3: i32 = 4;
3636 /// refines by. Fixed by the unit, not swept.
3737 const QUARTER_PEL_Q3: i32 = 2;
3838
39+/// One eighth sample — the step of the fourth refinement stage, which runs
40+/// only in a frame coded with `allow_high_precision_mv` (lane-hpmv): without
41+/// that flag the writer cannot code an odd eighth-pel residual at all
42+/// (`encode::round_to_valid_mv` rounds it away), so refining to it would only
43+/// spend evaluations on vectors the stream cannot name.
44+const EIGHTH_PEL_Q3: i32 = 1;
45+
3946 /// The widest step the integer-pel search starts its log search at, in whole
4047 /// samples.
4148 ///
@@ -565,11 +572,17 @@ fn search_traced_from_step(
565572 step_pel /= 2;
566573 }
567574
568- // Stages 2 and 3: one ±1-step refinement each at half-pel then
569- // quarter-pel, through the same cost function (so the refinement is
575+ // Stages 2..4: one ±1-step refinement each at half-pel, quarter-pel and
576+ // (high-precision frames only) eighth-pel, through the same cost function (so the refinement is
570577 // costed at the precision it commits to, not the integer-pel SAD alone).
571578 let integer_evals = evals.get();
572- for step in [HALF_PEL_Q3, QUARTER_PEL_Q3] {
579+ // lane-hpmv: the eighth-pel stage runs only in a high-precision frame.
580+ let stages: &[i32] = if crate::tile::high_precision_mv() {
581+ &[HALF_PEL_Q3, QUARTER_PEL_Q3, EIGHTH_PEL_Q3]
582+ } else {
583+ &[HALF_PEL_Q3, QUARTER_PEL_Q3]
584+ };
585+ for &step in stages {
573586 // lane-newmv, class `search bounded by its heuristic`: ONE round per
574587 // step means a subpel winner two half-pels away from the integer
575588 // centre is unreachable. `EC_AV1_MV_SUBPEL_ITERS` runs the round
crates/ec-av1/src/tile.rsmodified+59 -10
@@ -819,6 +819,39 @@ pub(crate) fn order_hints() -> (u32, u32, [u32; 7]) {
819819 ORDER_HINTS.with(std::cell::Cell::get)
820820 }
821821
822+thread_local! {
823+ /// lane-hpmv: this frame's `allow_high_precision_mv`, armed per worker
824+ /// beside [`arm_order_hints`] -- the writer's eighth-pel symbol, the
825+ /// pricer's mv bits and the motion search's finest step all read it.
826+ static HIGH_PRECISION_MV: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
827+}
828+
829+/// Arms this frame's `allow_high_precision_mv` for the next tile written --
830+/// or searched -- on this thread.
831+pub(crate) fn arm_high_precision_mv(on: bool) {
832+ HIGH_PRECISION_MV.with(|c| c.set(on));
833+}
834+
835+/// What [`arm_high_precision_mv`] last armed on this thread.
836+pub(crate) fn high_precision_mv() -> bool {
837+ HIGH_PRECISION_MV.with(std::cell::Cell::get)
838+}
839+
840+/// lane-hpmv's witness counters: `[0]` counts every `mv_hp`/`mv_class0_hp`
841+/// symbol this process's writers coded (zero without
842+/// `allow_high_precision_mv`, one per non-zero mv component with it), `[1]`
843+/// counts the ones that came out ZERO -- an eighth-pel vector, i.e. one a
844+/// frame without the flag cannot name at all.
845+static HP_SYMBOLS: [std::sync::atomic::AtomicU64; 2] =
846+ [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
847+
848+/// Reads and clears [`HP_SYMBOLS`]: `(hp symbols coded, eighth-pel ones)`.
849+#[allow(dead_code)] // read only from the `#[cfg(test)]` witness
850+pub(crate) fn take_hp_symbols() -> (u64, u64) {
851+ let all = HP_SYMBOLS[0].swap(0, std::sync::atomic::Ordering::Relaxed);
852+ (all, HP_SYMBOLS[1].swap(0, std::sync::atomic::Ordering::Relaxed))
853+}
854+
822855 /// Writer-side counterpart of decode.rs `read_compound_ref_frames` (spec
823856 /// 5.11.25's `comp_reference_type`/`uni_comp_ref`/`comp_ref`/`comp_bwdref`
824857 /// trees), symbol for symbol at the same contexts -- which are, as that
@@ -5765,22 +5798,24 @@ fn mv_class_of(z: i32) -> usize {
57655798
57665799 /// Writes one motion vector component's non-zero diff (spec 5.11.32
57675800 /// `read_mv_component`, run backwards): sign, class, then the class's own
5768-/// bits. `allow_high_precision_mv` is off in every frame this writer codes,
5769-/// so the eighth-pel bit is always inferred as one rather than coded — which
5770-/// means only diffs whose eighth-pel bit really is one are representable;
5771-/// anything else is refused rather than rounded, since rounding would silently
5772-/// code a different vector than the caller asked for.
5801+/// bits, and (lane-hpmv) the eighth-pel bit when the frame armed through
5802+/// [`arm_high_precision_mv`] carries `allow_high_precision_mv`. Without that
5803+/// flag the eighth-pel bit is inferred as one rather than coded, so only
5804+/// diffs whose eighth-pel bit really is one are representable; anything else
5805+/// is refused rather than rounded, since rounding would silently code a
5806+/// different vector than the caller asked for.
57735807 ///
57745808 /// # Errors
5775-/// Returns an error when `diff` needs the eighth-pel precision this writer's
5776-/// frames do not carry.
5809+/// Returns an error when `diff` needs eighth-pel precision in a frame coded
5810+/// without `allow_high_precision_mv`.
57775811 fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
57785812 debug_assert_ne!(diff, 0);
5813+ let hp_frame = high_precision_mv();
57795814 let sign = diff < 0;
57805815 enc.symbol(usize::from(sign), &mut c.sign);
57815816 let mag = diff.unsigned_abs() as i32;
57825817 let z = mag - 1;
5783- if z & 1 == 0 {
5818+ if !hp_frame && z & 1 == 0 {
57845819 return Err(Error::unsupported(
57855820 "AV1 tile",
57865821 "a motion vector component needs eighth-pel precision, which \
@@ -5790,11 +5825,18 @@ fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i3
57905825 let class = mv_class_of(z);
57915826 enc.symbol(class, &mut c.class);
57925827 let local = z - mv_class_base(class);
5828+ let hp = (local & 1) as usize;
57935829 if class == 0 {
57945830 let bit = (local >> 3) & 1;
57955831 let fr = (local >> 1) & 3;
57965832 enc.symbol(bit as usize, &mut c.class0_bit);
57975833 enc.symbol(fr as usize, &mut c.class0_fr[bit as usize]);
5834+ // spec 5.11.32: the eighth-pel bit is CODED when the frame allows
5835+ // high-precision motion vectors, and inferred as one otherwise ("if
5836+ // (allow_high_precision_mv) mv_class0_hp ... else mv_class0_hp = 1").
5837+ if hp_frame {
5838+ enc.symbol(hp, &mut c.class0_hp);
5839+ }
57985840 } else {
57995841 let d = local >> 3;
58005842 let fr = (local >> 1) & 3;
@@ -5802,9 +5844,16 @@ fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i3
58025844 enc.symbol(((d >> i) & 1) as usize, &mut c.bit[i]);
58035845 }
58045846 enc.symbol(fr as usize, &mut c.fr);
5847+ if hp_frame {
5848+ enc.symbol(hp, &mut c.hp);
5849+ }
5850+ }
5851+ if hp_frame {
5852+ HP_SYMBOLS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5853+ if hp == 0 {
5854+ HP_SYMBOLS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5855+ }
58055856 }
5806- // The eighth-pel bit itself is inferred, not coded (spec 5.11.32: "if
5807- // (allow_high_precision_mv) mv_class0_hp ... else mv_class0_hp = 1").
58085857 Ok(())
58095858 }
58105859