forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1obmc2' (ab190a23): OBMC at the 16x16/8x8 leaves and a local warp candidate, both behind knobs; the trial decode honours allow_warped_motion

Browse files at this commit

0ebeaad0cbc849c2be0eac349ca5bcca35eb4bccAhmet Kaan GümüşParent: 16ecf06fd3f898
Both tools are byte-exact and measured losses on the native table (OBMC
wins 85% of eligible 8x8 leaves and still costs bytes; warp fires on 2-7%
of blocks). Default streams byte-identical. decode_inter_frame_tiles_lr
hard-coded allow_warped_motion=false and the encoder's own trial decode
went through it (stale-header class).
crates/ec-av1/src/decode.rsmodified+32 -5
@@ -552,7 +552,7 @@ pub(crate) fn warp_plane_suppress_hits() -> usize {
552 /// block dimensions decide it -- never the square `side`/`chroma_side`, which552 /// block dimensions decide it -- never the square `side`/`chroma_side`, which
553 /// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is553 /// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
554 /// bigger than the real block in one axis.554 /// bigger than the real block in one axis.
555-fn warp_plane_allowed(w: usize, h: usize) -> bool {555+pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool {
556 if w >= 8 && h >= 8 {556 if w >= 8 && h >= 8 {
557 return true;557 return true;
558 }558 }
@@ -24220,7 +24220,7 @@ fn has_top_right(mi_row: usize, mi_col: usize, bs: usize, fctx: &crate::decode::
24220 /// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)24220 /// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
24221 /// come from the *neighbour* cell's own coded size, not this block's.24221 /// come from the *neighbour* cell's own coded size, not this block's.
24222 #[allow(clippy::too_many_arguments)]24222 #[allow(clippy::too_many_arguments)]
24223-fn find_samples(24223+pub(crate) fn find_samples(
24224 grid: &MiGrid,24224 grid: &MiGrid,
24225 mi_row: usize,24225 mi_row: usize,
24226 mi_col: usize,24226 mi_col: usize,
@@ -24378,7 +24378,7 @@ fn find_samples(
24378 /// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over24378 /// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
24379 /// the 2-symbol `obmc_cdf` (spec 5.11.24).24379 /// the 2-symbol `obmc_cdf` (spec 5.11.24).
24380 #[allow(clippy::too_many_arguments)]24380 #[allow(clippy::too_many_arguments)]
24381-fn num_proj_ref(24381+pub(crate) fn num_proj_ref(
24382 grid: &MiGrid,24382 grid: &MiGrid,
24383 mi_row: usize,24383 mi_row: usize,
24384 mi_col: usize,24384 mi_col: usize,
@@ -32053,6 +32053,12 @@ fn decode_inter_block8(
32053 mc::scale_factor(ref_width, frame_width) != mc::REF_NO_SCALE;32053 mc::scale_factor(ref_width, frame_width) != mc::REF_NO_SCALE;
32054 let warp_eligible =32054 let warp_eligible =
32055 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;32055 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
32056+ if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
32057+ eprintln!(
32058+ "EC_MM8 mi_row={mi_row} mi_col={mi_col} proj={} warp_elig={} awm={}",
32059+ proj_ok as u8, warp_eligible as u8, allow_warped_motion as u8
32060+ );
32061+ }
32056 if allow_warped_motion && proj_ok && ref_is_scaled {32062 if allow_warped_motion && proj_ok && ref_is_scaled {
32057 hit!(SCALED_WARP_SUPPRESSED_HITS);32063 hit!(SCALED_WARP_SUPPRESSED_HITS);
32058 }32064 }
@@ -33086,7 +33092,7 @@ pub(crate) fn decode_inter_frame_tile(
33086 loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed,33092 loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed,
33087 enable_dual_filter, reference_select, tx_select,33093 enable_dual_filter, reference_select, tx_select,
33088 &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false,33094 &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false,
33089- switchable_motion_mode, fctx,33095+ switchable_motion_mode, false, fctx,
33090 )33096 )
33091 }33097 }
33092 33098
@@ -33132,6 +33138,12 @@ pub(crate) fn decode_inter_frame_tile_lr(
33132 // crate's own encoder writes once inter blocks started carrying a33138 // crate's own encoder writes once inter blocks started carrying a
33133 // `motion_mode` symbol (class: test asserts against a stale header).33139 // `motion_mode` symbol (class: test asserts against a stale header).
33134 switchable_motion_mode: bool,33140 switchable_motion_mode: bool,
33141+ // lane-av1obmc2: this frame header's own `allow_warped_motion` (spec
33142+ // 5.9.2) -- what picks the 3-symbol `motion_mode_cdf` alphabet over the
33143+ // 2-symbol `obmc_cdf` one at a block with a warp sample. Hard-coding
33144+ // `false` here desynced every stream this crate's encoder writes with the
33145+ // warp knob on: the same stale-header class as the parameter above.
33146+ allow_warped_motion: bool,
33135 fctx: &crate::decode::FrameCtx,33147 fctx: &crate::decode::FrameCtx,
33136 ) -> Result<Picture> {33148 ) -> Result<Picture> {
33137 let single_tile = TileInfo {33149 let single_tile = TileInfo {
@@ -33161,6 +33173,7 @@ pub(crate) fn decode_inter_frame_tile_lr(
33161 sign_bias,33173 sign_bias,
33162 allow_screen_content_tools,33174 allow_screen_content_tools,
33163 switchable_motion_mode,33175 switchable_motion_mode,
33176+ allow_warped_motion,
33164 fctx,33177 fctx,
33165 )33178 )
33166 }33179 }
@@ -33196,6 +33209,12 @@ pub(crate) fn decode_inter_frame_tiles_lr(
33196 // crate's own encoder writes once inter blocks started carrying a33209 // crate's own encoder writes once inter blocks started carrying a
33197 // `motion_mode` symbol (class: test asserts against a stale header).33210 // `motion_mode` symbol (class: test asserts against a stale header).
33198 switchable_motion_mode: bool,33211 switchable_motion_mode: bool,
33212+ // lane-av1obmc2: this frame header's own `allow_warped_motion` (spec
33213+ // 5.9.2) -- what picks the 3-symbol `motion_mode_cdf` alphabet over the
33214+ // 2-symbol `obmc_cdf` one at a block with a warp sample. Hard-coding
33215+ // `false` here desynced every stream this crate's encoder writes with the
33216+ // warp knob on: the same stale-header class as the parameter above.
33217+ allow_warped_motion: bool,
33199 fctx: &crate::decode::FrameCtx,33218 fctx: &crate::decode::FrameCtx,
33200 ) -> Result<Picture> {33219 ) -> Result<Picture> {
33201 decode_inter_frame_tile_with_cdfs(33220 decode_inter_frame_tile_with_cdfs(
@@ -33231,7 +33250,7 @@ pub(crate) fn decode_inter_frame_tiles_lr(
33231 true,33250 true,
33232 tx_select,33251 tx_select,
33233 switchable_motion_mode,33252 switchable_motion_mode,
33234- false,33253+ allow_warped_motion,
33235 allow_screen_content_tools,33254 allow_screen_content_tools,
33236 DeltaParams::default(),33255 DeltaParams::default(),
33237 // `enable_filter_intra`: this crate's own encoder never writes the33256 // `enable_filter_intra`: this crate's own encoder never writes the
@@ -37784,6 +37803,10 @@ mod tests {
37784 // Same stale-header class: the bit that makes this frame's37803 // Same stale-header class: the bit that makes this frame's
37785 // inter blocks carry a `motion_mode` symbol.37804 // inter blocks carry a `motion_mode` symbol.
37786 frame.switchable_motion_mode,37805 frame.switchable_motion_mode,
37806+ // These GOP round trips decode a tile the encoder wrote, so
37807+ // the warp bit must be the one it wrote too (lane-av1obmc2);
37808+ // the encoder only sets it under `EC_AV1_WARP`.
37809+ crate::envflags::env_flag!("EC_AV1_WARP"),
37787 fctx,37810 fctx,
37788 )37811 )
37789 .unwrap();37812 .unwrap();
@@ -38118,6 +38141,10 @@ mod tests {
38118 // Same stale-header class: the bit that makes this frame's38141 // Same stale-header class: the bit that makes this frame's
38119 // inter blocks carry a `motion_mode` symbol.38142 // inter blocks carry a `motion_mode` symbol.
38120 frame.switchable_motion_mode,38143 frame.switchable_motion_mode,
38144+ // These GOP round trips decode a tile the encoder wrote, so
38145+ // the warp bit must be the one it wrote too (lane-av1obmc2);
38146+ // the encoder only sets it under `EC_AV1_WARP`.
38147+ crate::envflags::env_flag!("EC_AV1_WARP"),
38121 fctx,38148 fctx,
38122 )38149 )
38123 .unwrap();38150 .unwrap();
crates/ec-av1/src/encode.rsmodified+561 -123
@@ -1028,7 +1028,10 @@ pub(crate) fn key_frame_headers_colour(
1028 additional_frame_id_length: 0,1028 additional_frame_id_length: 0,
1029 enable_interintra_compound: false,1029 enable_interintra_compound: false,
1030 enable_masked_compound: false,1030 enable_masked_compound: false,
1031- enable_warped_motion: false,1031+ // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
1032+ // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
1033+ // header is byte-identical to the streams before this lane.
1034+ enable_warped_motion: crate::envflags::env_flag!("EC_AV1_WARP"),
1032 enable_dual_filter: false,1035 enable_dual_filter: false,
1033 enable_jnt_comp: false,1036 enable_jnt_comp: false,
1034 enable_ref_frame_mvs: false,1037 enable_ref_frame_mvs: false,
@@ -1166,9 +1169,14 @@ pub fn inter_frame_headers_slots(
1166 // to the OBMC knob rather than always on: with every block choosing1169 // to the OBMC knob rather than always on: with every block choosing
1167 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the1170 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
1168 // gate clip), so the DEFAULT path writes no motion_mode syntax at all1171 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
1169- // and stays byte-identical to the streams before this lane. A future1172+ // and stays byte-identical to the streams before this lane.
1170- // warp knob joins this disjunction.1173+ // lane-av1obmc2: the warp knob joins that disjunction, and turns on
1171- is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC"),1174+ // `allow_warped_motion` besides -- which is what makes an eligible
1175+ // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
1176+ // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
1177+ is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC")
1178+ || crate::envflags::env_flag!("EC_AV1_WARP"),
1179+ allow_warped_motion: crate::envflags::env_flag!("EC_AV1_WARP"),
1172 use_ref_frame_mvs: false,1180 use_ref_frame_mvs: false,
1173 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol1181 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
1174 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only1182 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
@@ -2439,14 +2447,173 @@ impl Reach {
2439 }2447 }
2440 2448
2441 /// What one symbol costs against a CDF, in bits.2449 /// What one symbol costs against a CDF, in bits.
2442-/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the default2450+/// The smallest LEAF an OBMC candidate is offered for, so the census can
2443-/// table rather than the tile's adapted one -- the same static-CDF estimate2451+/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
2444-/// every other symbol in this search is priced with.2452+/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
2445-fn obmc_bits(write_w: usize, write_h: usize, obmc: bool) -> f64 {2453+/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
2454+///
2455+/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
2456+/// (12 frames, four quantizers, the standing keep table):
2457+///
2458+/// | min side | film 1080p | film 2160p | screen |
2459+/// |---|---|---|---|
2460+/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
2461+/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
2462+/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
2463+/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
2464+///
2465+/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
2466+/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
2467+/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
2468+/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
2469+/// that wins the local RD on five blocks in six and loses ladder bytes is
2470+/// the `local-RD-on-references` class again, not a missing footprint. The
2471+/// tool stays OFF by default; the upgrade path is the price, not the size
2472+/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
2473+/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
2474+/// 1080p film up, i.e. the same disagreement between the two gates).
2475+fn obmc_min_side() -> usize {
2476+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2477+ *N.get_or_init(|| {
2478+ std::env::var("EC_AV1_OBMC_MIN")
2479+ .ok()
2480+ .and_then(|v| v.parse().ok())
2481+ .unwrap_or(8)
2482+ })
2483+}
2484+
2485+/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
2486+/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
2487+/// same frame-CDF price the coefficients of a non-screen frame are estimated
2488+/// with, not the static default table.
2489+/// The same price for whichever alphabet the writer will really use for this
2490+/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
2491+/// (`allow_warped_motion` and at least one warp sample), otherwise the
2492+/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
2493+/// search pay it, so the alphabet cancels out of a comparison and only its
2494+/// per-value spread decides.
2495+fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
2446 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {2496 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
2447 return 0.0;2497 return 0.0;
2448 };2498 };
2449- symbol_bits(&cdf::OBMC[row], usize::from(obmc))2499+ match warp_alphabet {
2500+ true => crate::tile::motion_mode_symbol_bits(row, motion),
2501+ false => crate::tile::obmc_symbol_bits(row, motion == 1),
2502+ }
2503+}
2504+
2505+/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
2506+/// candidate, the header's `allow_warped_motion` and the sequence's
2507+/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
2508+/// native keep table, against the same build with the knob off:
2509+///
2510+/// | clip | warp on | off |
2511+/// |---|---|---|
2512+/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
2513+/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
2514+/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
2515+///
2516+/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
2517+/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
2518+/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
2519+/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
2520+/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
2521+/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
2522+/// this is a measured loss, not an inert knob. Same shape as the OBMC
2523+/// candidate above it (`obmc_min_side`): a local RD win that does not convert
2524+/// into ladder bytes.
2525+///
2526+/// The WARPED_CAUSAL prediction of one square single-reference block: the
2527+/// decoder's own warp-sample walk (`decode::find_samples` +
2528+/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
2529+/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
2530+/// grid -- never a second implementation of any of the three. `None` when the
2531+/// block would code no motion_mode symbol at all, when it has no warp sample
2532+/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
2533+/// or when the projection is not filter-representable (the decoder would then
2534+/// predict translationally, so the mode is pure cost).
2535+#[allow(clippy::too_many_arguments)]
2536+fn warp_prediction(
2537+ grid: &MiGrid,
2538+ (mi_row, mi_col): (usize, usize),
2539+ (mi_rows, mi_cols): (usize, usize),
2540+ (x, y): (usize, usize),
2541+ side: usize,
2542+ mv: (i32, i32),
2543+ ref_frame: i8,
2544+ ref_planes: [(&[u16], usize, usize, usize); 3],
2545+ fctx: &crate::decode::FrameCtx,
2546+) -> Option<[Vec<u8>; 3]> {
2547+ let n4 = side / 4;
2548+ if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
2549+ return None;
2550+ }
2551+ let mut samples = crate::decode::find_samples(
2552+ grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
2553+ );
2554+ if samples.is_empty() {
2555+ return None;
2556+ }
2557+ if samples.len() > 1 {
2558+ crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
2559+ }
2560+ let params = crate::warp::find_projection(
2561+ &samples,
2562+ side as i32,
2563+ side as i32,
2564+ mv.1,
2565+ mv.0,
2566+ mi_row as i32,
2567+ mi_col as i32,
2568+ )?;
2569+ let mut pred = [
2570+ vec![0u16; side * side],
2571+ vec![0u16; side * side / 4],
2572+ vec![0u16; side * side / 4],
2573+ ];
2574+ // The translational prediction first, exactly as the decoder builds it,
2575+ // then the affine one over the planes whose OWN block is at least 8x8
2576+ // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
2577+ // 4x4 chroma stays translational).
2578+ for (i, r) in ref_planes.into_iter().enumerate() {
2579+ let luma_plane = i == 0;
2580+ let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
2581+ let s = if luma_plane { side } else { side / 2 };
2582+ mc::predict(
2583+ r.0,
2584+ r.1,
2585+ r.2,
2586+ r.3,
2587+ mv_to_q4(px, mv.1, luma_plane),
2588+ mv_to_q4(py, mv.0, luma_plane),
2589+ s,
2590+ s,
2591+ &mut pred[i],
2592+ fctx,
2593+ );
2594+ if crate::decode::warp_plane_allowed(s, s) {
2595+ let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
2596+ crate::warp::warp_affine(
2597+ &params,
2598+ r.0,
2599+ r.2 as i32,
2600+ r.3 as i32,
2601+ r.1 as i32,
2602+ &mut pred[i],
2603+ px as i32,
2604+ py as i32,
2605+ cside,
2606+ cside,
2607+ cside,
2608+ sub,
2609+ sub,
2610+ fctx,
2611+ );
2612+ }
2613+ }
2614+ let [py_buf, pu_buf, pv_buf] = pred;
2615+ let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
2616+ Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
2450 }2617 }
2451 2618
2452 pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {2619 pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
@@ -3595,6 +3762,86 @@ fn leaf_compound_stacks<'a>(
3595 .collect()3762 .collect()
3596 }3763 }
3597 3764
3765+/// The OBMC prediction of one square single-reference block: this block's own
3766+/// translation prediction (`mc::predict`) with every bordering above/left
3767+/// neighbour blended into the overlap strips by the DECODER's own plan and
3768+/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
3769+/// the search prices is what a decoder reconstructs -- never a second
3770+/// implementation of the blend. `None` when the block has no overlappable
3771+/// neighbour at all (the writer would then code no `motion_mode` symbol) or
3772+/// when the plan cannot be built (a neighbour naming a reference this encode
3773+/// does not hold).
3774+#[allow(clippy::too_many_arguments)]
3775+fn obmc_prediction(
3776+ grid: &MiGrid,
3777+ (mi_row, mi_col): (usize, usize),
3778+ (mi_rows, mi_cols): (usize, usize),
3779+ (x, y): (usize, usize),
3780+ side: usize,
3781+ mv: (i32, i32),
3782+ refs: &[Option<&Picture>; 8],
3783+ // This block's OWN reference planes, luma then both chroma, each as
3784+ // (samples, stride, true width, true height).
3785+ ref_planes: [(&[u16], usize, usize, usize); 3],
3786+ frame_width: usize,
3787+ fctx: &crate::decode::FrameCtx,
3788+) -> Option<[Vec<u8>; 3]> {
3789+ let n4 = side / 4;
3790+ if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
3791+ return None;
3792+ }
3793+ let refpix = crate::decode::RefPix::ready(*refs);
3794+ let plan = crate::decode::obmc_plan(
3795+ grid,
3796+ &[],
3797+ &[],
3798+ mi_row,
3799+ mi_col,
3800+ n4,
3801+ n4,
3802+ mi_rows,
3803+ mi_cols,
3804+ side,
3805+ side,
3806+ side,
3807+ side / 2,
3808+ x,
3809+ y,
3810+ x / 2,
3811+ y / 2,
3812+ &refpix,
3813+ Some(mc::InterpFilterKind::Regular),
3814+ frame_width,
3815+ )
3816+ .ok()?;
3817+ let mut pred = [
3818+ vec![0u16; side * side],
3819+ vec![0u16; side * side / 4],
3820+ vec![0u16; side * side / 4],
3821+ ];
3822+ for (i, r) in ref_planes.into_iter().enumerate() {
3823+ let luma_plane = i == 0;
3824+ let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
3825+ let s = if luma_plane { side } else { side / 2 };
3826+ mc::predict(
3827+ r.0,
3828+ r.1,
3829+ r.2,
3830+ r.3,
3831+ mv_to_q4(px, mv.1, luma_plane),
3832+ mv_to_q4(py, mv.0, luma_plane),
3833+ s,
3834+ s,
3835+ &mut pred[i],
3836+ fctx,
3837+ );
3838+ }
3839+ let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
3840+ crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
3841+ let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
3842+ Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
3843+}
3844+
3598 fn code_square_inter(3845 fn code_square_inter(
3599 luma: &mut Plane,3846 luma: &mut Plane,
3600 chroma: &mut [Plane; 2],3847 chroma: &mut [Plane; 2],
@@ -3608,6 +3855,17 @@ fn code_square_inter(
3608 // leaf's own `bw4`/`bh4` (empty on a frame that does not code3855 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
3609 // `reference_select`, and at the straddling call sites).3856 // `reference_select`, and at the straddling call sites).
3610 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],3857 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
3858+ // lane-av1obmc2: the mi grid this leaf's neighbours were published into
3859+ // (`record_mi`, in the writer's own coding order) and this leaf's place in
3860+ // it -- what the OBMC candidate's eligibility walk and neighbour plan
3861+ // read, the same state the tile writer reads when it codes the leaf's
3862+ // `motion_mode` symbol.
3863+ grid: &MiGrid,
3864+ (mi_row, mi_col): (usize, usize),
3865+ (mi_rows, mi_cols): (usize, usize),
3866+ // Every picture an OBMC neighbour can name: a leaf only searches LAST,
3867+ // but the neighbours it blends may be GOLDEN/ALTREF blocks.
3868+ refs: &[Option<&Picture>; 8],
3611 fctx: &crate::decode::FrameCtx,3869 fctx: &crate::decode::FrameCtx,
3612 ) -> (BlockCoeffs, f64) {3870 ) -> (BlockCoeffs, f64) {
3613 let (intra_block, intra_cost) =3871 let (intra_block, intra_cost) =
@@ -3747,6 +4005,21 @@ fn code_square_inter(
3747 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to4005 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
3748 // a vector the residual syntax can name -- at this leaf's own side.4006 // a vector the residual syntax can name -- at this leaf's own side.
3749 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);4007 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
4008+ // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
4009+ // re-price below can hand it back as the winner's own mode info.
4010+ let nearest_info = InterInfo {
4011+ ref1: None,
4012+ mv1: (0, 0),
4013+ ref_frame: crate::mvstack::LAST_FRAME,
4014+ mode: InterMode::NearestMv,
4015+ mv,
4016+ ref_mv_idx: 0,
4017+ };
4018+ // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
4019+ // syntax, apart from its residual: the OBMC candidate re-prices the same
4020+ // syntax against a different prediction, so both sides of that comparison
4021+ // carry it.
4022+ let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
3750 // This leaf's own `NEWMV` vector, kept whether or not it won the4023 // This leaf's own `NEWMV` vector, kept whether or not it won the
3751 // single-reference comparison: it seeds the compound half-new candidate4024 // single-reference comparison: it seeds the compound half-new candidate
3752 // below, exactly as `search_inter_block` seeds its own from the searches4025 // below, exactly as `search_inter_block` seeds its own from the searches
@@ -3823,6 +4096,11 @@ fn code_square_inter(
3823 luma_new.bits + u_new.bits + v_new.bits4096 luma_new.bits + u_new.bits + v_new.bits
3824 });4097 });
3825 if cost_new < best.0 {4098 if cost_new < best.0 {
4099+ single_syntax = intra_inter_bits(true)
4100+ + single_ref_bits
4101+ + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
4102+ + drl_bits
4103+ + mv_bits;
3826 best = (4104 best = (
3827 cost_new,4105 cost_new,
3828 Some((4106 Some((
@@ -4037,6 +4315,112 @@ fn code_square_inter(
4037 }4315 }
4038 }4316 }
4039 4317
4318+ // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
4319+ // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
4320+ // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
4321+ // the writer codes no symbol for one. The prediction is the decoder's own
4322+ // plan and blend over the neighbours this leaf's `grid` already carries
4323+ // (published by `record_mi` in the writer's coding order), so the
4324+ // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
4325+ // offered this only at 32x32, which is not where libaom cashes its OBMC
4326+ // gain.
4327+ let mut motion_won = 0u8;
4328+ let single = match &best.1 {
4329+ None => Some(nearest_info),
4330+ Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
4331+ Some(_) => None,
4332+ };
4333+ if let Some(info) = single.filter(|i| {
4334+ (crate::envflags::env_flag!("EC_AV1_OBMC") || crate::envflags::env_flag!("EC_AV1_WARP"))
4335+ && i.ref_frame == crate::mvstack::LAST_FRAME
4336+ }) {
4337+ let planes = [
4338+ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
4339+ (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
4340+ (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
4341+ ];
4342+ // Which alphabet this block's writer will code the symbol against
4343+ // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
4344+ // 3-symbol one only under `allow_warped_motion` and at least one warp
4345+ // sample. Mirrored here so the candidates are priced against the
4346+ // table the tile really narrows.
4347+ let warp_alphabet = crate::envflags::env_flag!("EC_AV1_WARP")
4348+ && crate::decode::num_proj_ref(
4349+ grid,
4350+ mi_row,
4351+ mi_col,
4352+ side / 4,
4353+ side / 4,
4354+ mi_cols,
4355+ mi_rows,
4356+ info.ref_frame,
4357+ fctx,
4358+ ) >= 1;
4359+ let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
4360+ let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
4361+ if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
4362+ if let Some(pred) = obmc_prediction(
4363+ grid,
4364+ (mi_row, mi_col),
4365+ (mi_rows, mi_cols),
4366+ (x, y),
4367+ side,
4368+ info.mv,
4369+ refs,
4370+ planes,
4371+ reference.width,
4372+ fctx,
4373+ ) {
4374+ candidates.push((1, pred));
4375+ }
4376+ }
4377+ if warp_alphabet {
4378+ if let Some(pred) = warp_prediction(
4379+ grid,
4380+ (mi_row, mi_col),
4381+ (mi_rows, mi_cols),
4382+ (x, y),
4383+ side,
4384+ info.mv,
4385+ info.ref_frame,
4386+ planes,
4387+ fctx,
4388+ ) {
4389+ candidates.push((2, pred));
4390+ }
4391+ }
4392+ for (motion, pred) in candidates {
4393+ let luma_o = luma.code_from_prediction(
4394+ x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set,
4395+ );
4396+ let u_o = chroma[0].code_from_prediction(
4397+ x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone,
4398+ chroma_set,
4399+ );
4400+ let v_o = chroma[1].code_from_prediction(
4401+ x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone,
4402+ chroma_set,
4403+ );
4404+ let skip_o = luma_o.levels.iter().all(|&l| l == 0)
4405+ && u_o.levels.iter().all(|&l| l == 0)
4406+ && v_o.levels.iter().all(|&l| l == 0);
4407+ let cost_o = luma_o.sse
4408+ + u_o.sse
4409+ + v_o.sse
4410+ + search.lambda
4411+ * (skip_bits(skip_o)
4412+ + single_syntax
4413+ + mm(motion)
4414+ + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits });
4415+ // The incumbent pays the motion_mode symbol IT would code, so
4416+ // both sides of the comparison carry that syntax.
4417+ if cost_o < best.0 + search.lambda * mm(motion_won) {
4418+ motion_won = motion;
4419+ best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
4420+ }
4421+ }
4422+ }
4423+
4040 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {4424 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
4041 if cost < intra_cost {4425 if cost < intra_cost {
4042 // A compound winner commits the flat trial it was priced from:4426 // A compound winner commits the flat trial it was priced from:
@@ -4059,7 +4443,10 @@ fn code_square_inter(
4059 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the4443 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
4060 // same build without it. The static-CDF estimate was NOT what4444 // same build without it. The static-CDF estimate was NOT what
4061 // held the compound var-tx trial back. The flat trial stays.4445 // held the compound var-tx trial back. The flat trial stays.
4062- let (levels, tx_depth, dcost) = if info.ref1.is_some() {4446+ // An OBMC winner commits the flat trial too: `commit_inter_luma`
4447+ // re-predicts each var-tx unit by plain translation, which is not
4448+ // the prediction this candidate was priced from.
4449+ let (levels, tx_depth, dcost) = if info.ref1.is_some() || motion_won != 0 {
4063 luma.commit(x, y, side, &luma_new);4450 luma.commit(x, y, side, &luma_new);
4064 (luma_new.levels.clone(), 0, 0.0)4451 (luma_new.levels.clone(), 0, 0.0)
4065 } else {4452 } else {
@@ -4085,7 +4472,7 @@ fn code_square_inter(
4085 palette_uv: None,4472 palette_uv: None,
4086 tx_depth,4473 tx_depth,
4087 inter: Some(info),4474 inter: Some(info),
4088- obmc: false,4475+ motion_mode: motion_won,
4089 },4476 },
4090 cost + dcost,4477 cost + dcost,
4091 );4478 );
@@ -4117,7 +4504,7 @@ fn code_square_inter(
4117 palette: None,4504 palette: None,
4118 palette_uv: None,4505 palette_uv: None,
4119 tx_depth,4506 tx_depth,
4120- obmc: false,4507+ motion_mode: 0,
4121 inter: Some(InterInfo {4508 inter: Some(InterInfo {
4122 ref1: None,4509 ref1: None,
4123 mv1: (0, 0),4510 mv1: (0, 0),
@@ -6516,117 +6903,117 @@ fn search_inter_block(
6516 // that is where libaom cashes most of its OBMC gain), and the symbol/6903 // that is where libaom cashes most of its OBMC gain), and the symbol/
6517 // residual price here is the static-CDF estimate.6904 // residual price here is the static-CDF estimate.
6518 let mut best = best;6905 let mut best = best;
6519- let mut obmc_won = false;6906+ let mut motion_won = 0u8;
6520- if let Some(info) = best.inter.filter(|i| i.ref1.is_none()) {6907+ if let Some(info) = best.inter.filter(|i| {
6521- if crate::envflags::env_flag!("EC_AV1_OBMC")6908+ i.ref1.is_none()
6522- && crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, 8, 8, mi_cols, mi_rows)6909+ && (crate::envflags::env_flag!("EC_AV1_OBMC")
6523- {6910+ || crate::envflags::env_flag!("EC_AV1_WARP"))
6524- let mut refs: [Option<&Picture>; 8] = [None; 8];6911+ }) {
6525- refs[LAST_FRAME as usize] = Some(reference);6912+ let mut refs: [Option<&Picture>; 8] = [None; 8];
6526- for &(r, p, _) in extra {6913+ refs[LAST_FRAME as usize] = Some(reference);
6527- refs[r as usize] = Some(p);6914+ for &(r, p, _) in extra {
6528- }6915+ refs[r as usize] = Some(p);
6529- let refpix = crate::decode::RefPix::ready(refs);6916+ }
6530- let plan = crate::decode::obmc_plan(6917+ // This block's OWN reference planes: the single-reference winner may
6918+ // be one of the extra references, not LAST.
6919+ let planes: [(&[u16], usize, usize, usize); 3] =
6920+ match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
6921+ Some(&(_, g, _)) => [
6922+ (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
6923+ (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
6924+ (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
6925+ ],
6926+ None => [
6927+ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
6928+ (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
6929+ (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
6930+ ],
6931+ };
6932+ // The alphabet `tile::write_motion_mode` will code this block's
6933+ // symbol against, mirrored term for term (libaom
6934+ // `motion_mode_allowed`).
6935+ let warp_alphabet = crate::envflags::env_flag!("EC_AV1_WARP")
6936+ && crate::decode::num_proj_ref(
6531 grid,6937 grid,
6532- &[],
6533- &[],
6534 mi_row,6938 mi_row,
6535 mi_col,6939 mi_col,
6536 8,6940 8,
6537 8,6941 8,
6538- mi_rows,
6539 mi_cols,6942 mi_cols,
6943+ mi_rows,
6944+ info.ref_frame,
6945+ fctx,
6946+ ) >= 1;
6947+ let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
6948+ let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
6949+ if crate::envflags::env_flag!("EC_AV1_OBMC") {
6950+ if let Some(pred) = obmc_prediction(
6951+ grid,
6952+ (mi_row, mi_col),
6953+ (mi_rows, mi_cols),
6954+ (x, y),
6540 BLOCK,6955 BLOCK,
6541- BLOCK,6956+ info.mv,
6542- BLOCK,6957+ &refs,
6543- BLOCK / 2,6958+ planes,
6544- x,
6545- y,
6546- x / 2,
6547- y / 2,
6548- &refpix,
6549- Some(mc::InterpFilterKind::Regular),
6550 reference.width,6959 reference.width,
6960+ fctx,
6961+ ) {
6962+ candidates.push((1, pred));
6963+ }
6964+ }
6965+ if warp_alphabet {
6966+ if let Some(pred) = warp_prediction(
6967+ grid,
6968+ (mi_row, mi_col),
6969+ (mi_rows, mi_cols),
6970+ (x, y),
6971+ BLOCK,
6972+ info.mv,
6973+ info.ref_frame,
6974+ planes,
6975+ fctx,
6976+ ) {
6977+ candidates.push((2, pred));
6978+ }
6979+ }
6980+ for (motion, pred) in candidates {
6981+ let luma_trial = luma.code_from_prediction(
6982+ x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone,
6983+ TxbSet::Luma32Inter,
6551 );6984 );
6552- if let Ok(plan) = plan {6985+ let u = chroma[0].code_from_prediction(
6553- let (ref_luma, ref_u, ref_v) = match extra6986+ x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone,
6554- .iter()6987+ chroma_set,
6555- .find(|(r, _, _)| *r == info.ref_frame)6988+ );
6556- {6989+ let v = chroma[1].code_from_prediction(
6557- Some(&(_, g, _)) => (6990+ x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone,
6558- (&g.y, g.width, luma.true_width, luma.true_height),6991+ chroma_set,
6559- (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),6992+ );
6560- (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),6993+ let skip = luma_trial.levels.iter().all(|&l| l == 0)
6561- ),6994+ && u.levels.iter().all(|&l| l == 0)
6562- None => (ref_luma, ref_u, ref_v),6995+ && v.levels.iter().all(|&l| l == 0);
6996+ let cost = luma_trial.sse
6997+ + u.sse
6998+ + v.sse
6999+ + search.lambda
7000+ * (skip_bits(skip)
7001+ + intra_inter_bits(true)
7002+ + best.mode_bits
7003+ + mm(motion)
7004+ + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
7005+ if cost < best.cost + search.lambda * mm(motion_won) {
7006+ motion_won = motion;
7007+ best = Candidate {
7008+ cost,
7009+ luma: luma_trial,
7010+ u,
7011+ v,
7012+ mode: DC_PRED,
7013+ skip,
7014+ mode_bits: best.mode_bits,
7015+ inter: best.inter,
6563 };7016 };
6564- let mv = info.mv;
6565- let mut pred = [
6566- vec![0u16; BLOCK * BLOCK],
6567- vec![0u16; BLOCK * BLOCK / 4],
6568- vec![0u16; BLOCK * BLOCK / 4],
6569- ];
6570- for (i, (r, luma_plane)) in
6571- [(ref_luma, true), (ref_u, false), (ref_v, false)].into_iter().enumerate()
6572- {
6573- let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
6574- let side = if luma_plane { BLOCK } else { BLOCK / 2 };
6575- mc::predict(
6576- r.0,
6577- r.1,
6578- r.2,
6579- r.3,
6580- mv_to_q4(px, mv.1, luma_plane),
6581- mv_to_q4(py, mv.0, luma_plane),
6582- side,
6583- side,
6584- &mut pred[i],
6585- fctx,
6586- );
6587- }
6588- let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
6589- crate::decode::obmc_run(
6590- &plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx,
6591- );
6592- let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
6593- let luma_trial = luma.code_from_prediction(
6594- x, y, BLOCK, &u8s(&py_buf), false, search.base_q_idx, search.deadzone,
6595- TxbSet::Luma32Inter,
6596- );
6597- let u = chroma[0].code_from_prediction(
6598- x / 2, y / 2, BLOCK / 2, &u8s(&pu_buf), false, search.base_q_idx,
6599- search.deadzone, chroma_set,
6600- );
6601- let v = chroma[1].code_from_prediction(
6602- x / 2, y / 2, BLOCK / 2, &u8s(&pv_buf), false, search.base_q_idx,
6603- search.deadzone, chroma_set,
6604- );
6605- let skip = luma_trial.levels.iter().all(|&l| l == 0)
6606- && u.levels.iter().all(|&l| l == 0)
6607- && v.levels.iter().all(|&l| l == 0);
6608- let cost = luma_trial.sse
6609- + u.sse
6610- + v.sse
6611- + search.lambda
6612- * (skip_bits(skip)
6613- + intra_inter_bits(true)
6614- + best.mode_bits
6615- + obmc_bits(BLOCK, BLOCK, true)
6616- + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
6617- if cost < best.cost + search.lambda * obmc_bits(BLOCK, BLOCK, false) {
6618- obmc_won = true;
6619- best = Candidate {
6620- cost,
6621- luma: luma_trial,
6622- u,
6623- v,
6624- mode: DC_PRED,
6625- skip,
6626- mode_bits: best.mode_bits,
6627- inter: best.inter,
6628- };
6629- }
6630 }7017 }
6631 }7018 }
6632 }7019 }
@@ -6651,7 +7038,7 @@ fn search_inter_block(
6651 uv_mode: DC_PRED,7038 uv_mode: DC_PRED,
6652 skip: best.skip,7039 skip: best.skip,
6653 inter: best.inter,7040 inter: best.inter,
6654- obmc: obmc_won,7041+ motion_mode: motion_won,
6655 eight: None,7042 eight: None,
6656 dv: None,7043 dv: None,
6657 palette: None,7044 palette: None,
@@ -6932,6 +7319,12 @@ pub(crate) fn encode_inter_frame(
6932 clip_planes_to_tile(&mut luma, &mut chroma, rect);7319 clip_planes_to_tile(&mut luma, &mut chroma, rect);
6933 let mut grid = MiGrid::new(mi_cols, mi_rows);7320 let mut grid = MiGrid::new(mi_cols, mi_rows);
6934 grid.set_sign_bias(sign_bias);7321 grid.set_sign_bias(sign_bias);
7322+ // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
7323+ // built once per tile job (`obmc_prediction`).
7324+ let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
7325+ obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
7326+ obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
7327+ obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
6935 grid.set_tile_bounds(7328 grid.set_tile_bounds(
6936 rect.mi_row0 as usize,7329 rect.mi_row0 as usize,
6937 rect.mi_col0 as usize,7330 rect.mi_col0 as usize,
@@ -7100,7 +7493,13 @@ pub(crate) fn encode_inter_frame(
7100 &search,7493 &search,
7101 &mode_bits_table,7494 &mode_bits_table,
7102 reference,7495 reference,
7103- &stack, &cstacks, fctx,7496+ &stack,
7497+ &cstacks,
7498+ &grid,
7499+ (mi_row, mi_col),
7500+ (mi_rows, mi_cols),
7501+ &obmc_refs,
7502+ fctx,
7104 );7503 );
7105 let leaf_cost = leaf_cost7504 let leaf_cost = leaf_cost
7106 + search.lambda * partition_bits(SUB, false);7505 + search.lambda * partition_bits(SUB, false);
@@ -7161,7 +7560,13 @@ pub(crate) fn encode_inter_frame(
7161 &search,7560 &search,
7162 &mode_bits_table,7561 &mode_bits_table,
7163 reference,7562 reference,
7164- &stack8, &cstacks8, fctx,7563+ &stack8,
7564+ &cstacks8,
7565+ &grid,
7566+ (mr, mc),
7567+ (mi_rows, mi_cols),
7568+ &obmc_refs,
7569+ fctx,
7165 );7570 );
7166 cost8 += cost;7571 cost8 += cost;
7167 record_mi(&mut grid, mr, mc, 2, leaf8.inter);7572 record_mi(&mut grid, mr, mc, 2, leaf8.inter);
@@ -7266,7 +7671,13 @@ pub(crate) fn encode_inter_frame(
7266 &search,7671 &search,
7267 &mode_bits_table,7672 &mode_bits_table,
7268 reference,7673 reference,
7269- &stack, &cstacks, fctx,7674+ &stack,
7675+ &cstacks,
7676+ &grid,
7677+ (mi_row, mi_col),
7678+ (mi_rows, mi_cols),
7679+ &obmc_refs,
7680+ fctx,
7270 );7681 );
7271 // One publication point for every coded leaf7682 // One publication point for every coded leaf
7272 // (`record_mi`): this site used to spell the vote7683 // (`record_mi`): this site used to spell the vote
@@ -7303,7 +7714,13 @@ pub(crate) fn encode_inter_frame(
7303 &search,7714 &search,
7304 &mode_bits_table,7715 &mode_bits_table,
7305 reference,7716 reference,
7306- &stack, &cstacks, fctx,7717+ &stack,
7718+ &cstacks,
7719+ &grid,
7720+ (mi_row, mi_col),
7721+ (mi_rows, mi_cols),
7722+ &obmc_refs,
7723+ fctx,
7307 );7724 );
7308 // Same publication point as the 16x167725 // Same publication point as the 16x16
7309 // straddling leaf above (`record_mi`).7726 // straddling leaf above (`record_mi`).
@@ -7374,6 +7791,7 @@ pub(crate) fn encode_inter_frame(
7374 let start_cdfs = CdfSnapshot(cdfs);7791 let start_cdfs = CdfSnapshot(cdfs);
7375 let reference_select_bit = header.reference_select;7792 let reference_select_bit = header.reference_select;
7376 let switchable_motion_mode = header.is_motion_mode_switchable;7793 let switchable_motion_mode = header.is_motion_mode_switchable;
7794+ let warped_motion = header.allow_warped_motion;
7377 let order_hint_bits = seq.order_hint_bits;7795 let order_hint_bits = seq.order_hint_bits;
7378 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;7796 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
7379 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;7797 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
@@ -7396,6 +7814,7 @@ pub(crate) fn encode_inter_frame(
7396 // Thread-locals: every tile job arms its own worker.7814 // Thread-locals: every tile job arms its own worker.
7397 crate::tile::arm_reference_select(reference_select_bit);7815 crate::tile::arm_reference_select(reference_select_bit);
7398 crate::tile::arm_motion_mode(switchable_motion_mode);7816 crate::tile::arm_motion_mode(switchable_motion_mode);
7817+ crate::tile::arm_warped_motion(warped_motion);
7399 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);7818 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
7400 crate::tile::arm_screen(screen);7819 crate::tile::arm_screen(screen);
7401 let mut cdfs = start_cdfs.0.clone();7820 let mut cdfs = start_cdfs.0.clone();
@@ -7523,6 +7942,7 @@ pub(crate) fn encode_inter_frame(
7523 sign_bias,7942 sign_bias,
7524 h.allow_screen_content_tools,7943 h.allow_screen_content_tools,
7525 switchable_motion_mode,7944 switchable_motion_mode,
7945+ h.allow_warped_motion,
7526 fctx,7946 fctx,
7527 )7947 )
7528 },7948 },
@@ -8326,7 +8746,7 @@ mod tests {
8326 mv: (0, 0),8746 mv: (0, 0),
8327 ref_mv_idx: 0,8747 ref_mv_idx: 0,
8328 }),8748 }),
8329- obmc: false,8749+ motion_mode: 0,
8330 };8750 };
8331 let skipped_block = BlockCoeffs {8751 let skipped_block = BlockCoeffs {
8332 skip: true,8752 skip: true,
@@ -8350,6 +8770,7 @@ mod tests {
8350 // `is_motion_mode_switchable`, so the writer must be armed with it8770 // `is_motion_mode_switchable`, so the writer must be armed with it
8351 // too or the decoder reads a `motion_mode` symbol nobody wrote.8771 // too or the decoder reads a `motion_mode` symbol nobody wrote.
8352 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);8772 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
8773+ crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
8353 let tile =8774 let tile =
8354 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)8775 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
8355 .unwrap();8776 .unwrap();
@@ -11441,10 +11862,12 @@ mod tests {
11441 // `gate-blind-to-feature`).11862 // `gate-blind-to-feature`).
11442 let mm = crate::tile::take_motion_mode_hits();11863 let mm = crate::tile::take_motion_mode_hits();
11443 eprintln!(11864 eprintln!(
11444- "{name}: motion_mode 32x32 SIMPLE={} OBMC={} | 16x16 SIMPLE={} OBMC={} | \11865+ "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
11445- 8x8 SIMPLE={} OBMC={} ({:.1}% OBMC of {} eligible)",11866+ WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
11446- mm[0], mm[1], mm[2], mm[3], mm[4], mm[5],11867+ eligible)",
11447- 100.0 * (mm[1] + mm[3] + mm[5]) as f64 / mm.iter().sum::<usize>().max(1) as f64,11868+ mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
11869+ 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
11870+ 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
11448 mm.iter().sum::<usize>(),11871 mm.iter().sum::<usize>(),
11449 );11872 );
11450 let (aom, aom_wall) =11873 let (aom, aom_wall) =
@@ -11654,6 +12077,21 @@ mod tests {
11654 // the real side, a screen clip none of them.12077 // the real side, a screen clip none of them.
11655 let (price_default, price_real) = crate::tile::take_pricing_hits();12078 let (price_default, price_real) = crate::tile::take_pricing_hits();
11656 eprintln!("{name}: pricer armings default={price_default} real={price_real}");12079 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
12080+ // lane-av1obmc2: the same motion_mode census the 640x384 gate
12081+ // prints (class `gate-blind-to-feature`) -- how many blocks coded
12082+ // the symbol at each footprint and how many took OBMC. Without it
12083+ // the native table, which is the standing keep table, could not
12084+ // say whether the tool fired at all.
12085+ let mm = crate::tile::take_motion_mode_hits();
12086+ eprintln!(
12087+ "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
12088+ WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
12089+ eligible)",
12090+ mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
12091+ 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
12092+ 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
12093+ mm.iter().sum::<usize>(),
12094+ );
11657 let palette = crate::tile::take_palette_hits();12095 let palette = crate::tile::take_palette_hits();
11658 let palette_uv = crate::tile::take_palette_uv_hits();12096 let palette_uv = crate::tile::take_palette_uv_hits();
11659 let ibc = crate::tile::take_intrabc_hits();12097 let ibc = crate::tile::take_intrabc_hits();
crates/ec-av1/src/tile.rsmodified+101 -18
@@ -390,6 +390,28 @@ thread_local! {
390 static MOTION_MODE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };390 static MOTION_MODE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
391 }391 }
392 392
393+thread_local! {
394+ /// This frame header's own `allow_warped_motion` bit (spec 5.9.2): with
395+ /// it set, every block libaom's `motion_mode_allowed` accepts AND that
396+ /// has at least one warp sample (`num_proj_ref >= 1`) reads the 3-symbol
397+ /// `motion_mode_cdf` alphabet instead of the 2-symbol `obmc_cdf` one.
398+ /// lane-av1obmc2.
399+ static WARPED_MOTION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
400+ /// The frame geometry the warp-sample walk needs (`num_proj_ref` ->
401+ /// `has_top_right`), which is only ever this writer's own superblock
402+ /// size. Every stream this crate writes uses a 64 superblock, which is
403+ /// `FrameCtx::new`'s default.
404+ /// corner-cut: ceiling is a 128-superblock WRITER -- it must arm the real
405+ /// frame context here (or take one as a parameter) or the warp-sample
406+ /// walk reads the wrong `has_top_right` geometry.
407+ static WRITER_FCTX: crate::decode::FrameCtx = crate::decode::FrameCtx::new();
408+}
409+
410+/// Arms [`WARPED_MOTION`] for the next tile written on this thread.
411+pub(crate) fn arm_warped_motion(on: bool) {
412+ WARPED_MOTION.with(|c| c.set(on));
413+}
414+
393 /// Arms the frame's `is_motion_mode_switchable` bit for the next tile written415 /// Arms the frame's `is_motion_mode_switchable` bit for the next tile written
394 /// on this thread; cleared by [`CdefIdxGuard`] when that writer returns.416 /// on this thread; cleared by [`CdefIdxGuard`] when that writer returns.
395 pub(crate) fn arm_motion_mode(on: bool) {417 pub(crate) fn arm_motion_mode(on: bool) {
@@ -401,16 +423,40 @@ pub(crate) fn arm_motion_mode(on: bool) {
401 /// -- the histogram a gate prints so that "OBMC is on" is a measurement, not423 /// -- the histogram a gate prints so that "OBMC is on" is a measurement, not
402 /// a claim (class `gate-blind-to-feature`). Index: `0 + 2 * bucket` for424 /// a claim (class `gate-blind-to-feature`). Index: `0 + 2 * bucket` for
403 /// SIMPLE, `1 + 2 * bucket` for OBMC, bucket 0/1/2 = 32x32/16x16/8x8.425 /// SIMPLE, `1 + 2 * bucket` for OBMC, bucket 0/1/2 = 32x32/16x16/8x8.
404-static MOTION_MODE_HITS: [std::sync::atomic::AtomicUsize; 6] =426+static MOTION_MODE_HITS: [std::sync::atomic::AtomicUsize; 9] =
405- [const { std::sync::atomic::AtomicUsize::new(0) }; 6];427+ [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
406 428
407 /// Reads [`MOTION_MODE_HITS`] and zeroes it, so a gate can attribute the429 /// Reads [`MOTION_MODE_HITS`] and zeroes it, so a gate can attribute the
408 /// counts to its own encode.430 /// counts to its own encode.
409 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates431 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
410-pub(crate) fn take_motion_mode_hits() -> [usize; 6] {432+pub(crate) fn take_motion_mode_hits() -> [usize; 9] {
411 std::array::from_fn(|i| MOTION_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))433 std::array::from_fn(|i| MOTION_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
412 }434 }
413 435
436+/// What the 3-symbol `motion_mode` symbol costs, in bits, against the same
437+/// frame tables [`obmc_symbol_bits`] prices the 2-symbol alphabet off --
438+/// which alphabet a block reads is `motion_mode_allowed`'s own choice
439+/// ([`write_motion_mode`]).
440+pub(crate) fn motion_mode_symbol_bits(row: usize, motion: u8) -> f64 {
441+ PRICING_BASE.with_borrow(|slot| match slot.as_deref() {
442+ Some(s) => crate::encode::symbol_bits(&s.0.motion_mode[row], usize::from(motion)),
443+ None => crate::encode::symbol_bits(&crate::cdf::MOTION_MODE[row], usize::from(motion)),
444+ })
445+}
446+
447+/// What the `motion_mode`/`obmc` symbol costs, in bits, against the tables
448+/// this frame's writer really starts from ([`arm_pricing_cdfs`]) -- the same
449+/// tables the coefficients are priced off since lane-av1price2, rather than
450+/// the static defaults the symbol used to be estimated with. Falls back to
451+/// the default table whenever the search is armed with the defaults (a key
452+/// frame, or a screen frame the gate turned off).
453+pub(crate) fn obmc_symbol_bits(row: usize, obmc: bool) -> f64 {
454+ PRICING_BASE.with_borrow(|slot| match slot.as_deref() {
455+ Some(s) => crate::encode::symbol_bits(&s.0.obmc[row], usize::from(obmc)),
456+ None => crate::encode::symbol_bits(&crate::cdf::OBMC[row], usize::from(obmc)),
457+ })
458+}
459+
414 /// `read_motion_mode`'s write side (spec 5.11.24), called on a460 /// `read_motion_mode`'s write side (spec 5.11.24), called on a
415 /// single-reference inter block right after its MV syntax and before the461 /// single-reference inter block right after its MV syntax and before the
416 /// (never switchable here) interpolation filter -- libaom's own sequential462 /// (never switchable here) interpolation filter -- libaom's own sequential
@@ -432,7 +478,12 @@ fn write_motion_mode(
432 (bw4, bh4): (usize, usize),478 (bw4, bh4): (usize, usize),
433 (write_w, write_h): (usize, usize),479 (write_w, write_h): (usize, usize),
434 (mi_cols, mi_rows): (usize, usize),480 (mi_cols, mi_rows): (usize, usize),
435- obmc: bool,481+ // This block's own reference, for the warp-sample walk that picks the
482+ // alphabet (`num_proj_ref`).
483+ ref_frame: i8,
484+ // 0 SIMPLE_TRANSLATION, 1 OBMC_CAUSAL, 2 WARPED_CAUSAL -- what the
485+ // encoder's search committed for this block.
486+ motion: u8,
436 ) -> Result<()> {487 ) -> Result<()> {
437 let eligible = MOTION_MODE.with(std::cell::Cell::get)488 let eligible = MOTION_MODE.with(std::cell::Cell::get)
438 && write_w.min(write_h) >= 8489 && write_w.min(write_h) >= 8
@@ -440,9 +491,15 @@ fn write_motion_mode(
440 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows,491 grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows,
441 );492 );
442 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {493 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
494+ let proj = WRITER_FCTX.with(|fctx| {
495+ crate::decode::num_proj_ref(
496+ grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx,
497+ )
498+ });
443 eprintln!(499 eprintln!(
444- "EC_MMW mi_row={mi_row} mi_col={mi_col} w={write_w} h={write_h} elig={}",500+ "EC_MMW mi_row={mi_row} mi_col={mi_col} w={write_w} h={write_h} elig={} proj={proj} warp_armed={} motion={motion}",
445- eligible as u8501+ eligible as u8,
502+ WARPED_MOTION.with(std::cell::Cell::get) as u8,
446 );503 );
447 }504 }
448 if !eligible {505 if !eligible {
@@ -450,7 +507,7 @@ fn write_motion_mode(
450 // codes as SIMPLE_TRANSLATION: its reconstruction is not the507 // codes as SIMPLE_TRANSLATION: its reconstruction is not the
451 // decoder's (class encoder-grid-drift), which is exactly what the508 // decoder's (class encoder-grid-drift), which is exactly what the
452 // `EC_COMP_MISMATCH` rung exists to catch.509 // `EC_COMP_MISMATCH` rung exists to catch.
453- if obmc && crate::envflags::env_flag!("EC_COMP_MISMATCH") {510+ if motion != 0 && crate::envflags::env_flag!("EC_COMP_MISMATCH") {
454 eprintln!(511 eprintln!(
455 "EC_COMP_MISMATCH motion_mode enc=OBMC wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})"512 "EC_COMP_MISMATCH motion_mode enc=OBMC wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})"
456 );513 );
@@ -463,13 +520,37 @@ fn write_motion_mode(
463 format!("a {write_w}x{write_h} block has no motion_mode CDF row"),520 format!("a {write_w}x{write_h} block has no motion_mode CDF row"),
464 )521 )
465 })?;522 })?;
466- enc.symbol(usize::from(obmc), &mut cdfs.obmc[row]);523+ // libaom `motion_mode_allowed`: the 3-symbol `motion_mode_cdf` alphabet
524+ // exactly when `allow_warped_motion` is on and the block has at least one
525+ // warp sample. The other two vetoes libaom applies there cannot fire for
526+ // a stream this encoder writes -- it codes no scaled reference and no
527+ // inter frame with `force_integer_mv` -- and the decoder checks all three
528+ // (`decode.rs`'s `warp_eligible`), so the two sides agree term for term.
529+ let warp_alphabet = WARPED_MOTION.with(std::cell::Cell::get)
530+ && WRITER_FCTX.with(|fctx| {
531+ crate::decode::num_proj_ref(
532+ grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx,
533+ )
534+ }) >= 1;
535+ if warp_alphabet {
536+ enc.symbol(usize::from(motion), &mut cdfs.motion_mode[row]);
537+ } else {
538+ // A warp winner whose block the writer resolves to the 2-symbol
539+ // alphabet would reconstruct as SIMPLE at the decoder: the same
540+ // encoder-grid-drift rung the OBMC case above prints.
541+ if motion == 2 && crate::envflags::env_flag!("EC_COMP_MISMATCH") {
542+ eprintln!(
543+ "EC_COMP_MISMATCH motion_mode enc=WARP wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})"
544+ );
545+ }
546+ enc.symbol(usize::from(motion == 1), &mut cdfs.obmc[row]);
547+ }
467 let bucket = match write_w.min(write_h) {548 let bucket = match write_w.min(write_h) {
468 32.. => 0,549 32.. => 0,
469 16 => 1,550 16 => 1,
470 _ => 2,551 _ => 2,
471 };552 };
472- MOTION_MODE_HITS[usize::from(obmc) + 2 * bucket]553+ MOTION_MODE_HITS[usize::from(motion.min(2)) + 3 * bucket]
473 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);554 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
474 Ok(())555 Ok(())
475 }556 }
@@ -1334,12 +1415,11 @@ pub struct BlockCoeffs {
1334 /// block. Only [`sb_coeff_inter_frame_tile`] codes `is_inter`; the key1415 /// block. Only [`sb_coeff_inter_frame_tile`] codes `is_inter`; the key
1335 /// frame writers never read this field.1416 /// frame writers never read this field.
1336 pub inter: Option<InterInfo>,1417 pub inter: Option<InterInfo>,
1337- /// Whether this (single-reference inter) block's prediction was built1418+ /// This (single-reference inter) block's spec `motion_mode`, written by
1338- /// with OBMC -- spec `motion_mode == OBMC_CAUSAL`, written by1419+ /// [`write_motion_mode`]: 0 `SIMPLE_TRANSLATION` (the [`Default`], and
1339- /// [`write_motion_mode`]. `false` (the [`Default`]) is1420+ /// the only mode this writer coded before lane-av1obmc), 1 `OBMC_CAUSAL`,
1340- /// `SIMPLE_TRANSLATION`, the only motion mode this writer coded before1421+ /// 2 `WARPED_CAUSAL` (lane-av1obmc2).
1341- /// lane-av1obmc.1422+ pub motion_mode: u8,
1342- pub obmc: bool,
1343 /// The 8x8 leaves a straddling 16x16 block is split into (lane-av1-rect),1423 /// The 8x8 leaves a straddling 16x16 block is split into (lane-av1-rect),
1344 /// each with its own 8x8 luma transform and 4x4 chroma transforms, in1424 /// each with its own 8x8 luma transform and 4x4 chroma transforms, in
1345 /// raster order among the leaves that are inside the true frame. `Some`1425 /// raster order among the leaves that are inside the true frame. `Some`
@@ -5607,7 +5687,8 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
5607 (8, 8),5687 (8, 8),
5608 (BLOCK, BLOCK),5688 (BLOCK, BLOCK),
5609 (mi_cols as usize, mi_rows as usize),5689 (mi_cols as usize, mi_rows as usize),
5610- block.obmc,5690+ info.ref_frame,
5691+ block.motion_mode,
5611 )?;5692 )?;
5612 mode_for_tx = 0;5693 mode_for_tx = 0;
5613 }5694 }
@@ -5841,7 +5922,8 @@ fn write_inter_frame_leaf(
5841 (SUB_MI as usize, SUB_MI as usize),5922 (SUB_MI as usize, SUB_MI as usize),
5842 (SUB, SUB),5923 (SUB, SUB),
5843 (mi_cols as usize, mi_rows as usize),5924 (mi_cols as usize, mi_rows as usize),
5844- block.obmc,5925+ info.ref_frame,
5926+ block.motion_mode,
5845 )?;5927 )?;
5846 mode_for_tx = 0;5928 mode_for_tx = 0;
5847 }5929 }
@@ -6081,7 +6163,8 @@ fn write_inter_frame_leaf8(
6081 (2, 2),6163 (2, 2),
6082 (8, 8),6164 (8, 8),
6083 (mi_cols as usize, mi_rows as usize),6165 (mi_cols as usize, mi_rows as usize),
6084- block.obmc,6166+ info.ref_frame,
6167+ block.motion_mode,
6085 )?;6168 )?;
6086 mode_for_tx = 0;6169 mode_for_tx = 0;
6087 }6170 }