diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 575c891d..73dffedb 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -24179,6 +24179,25 @@ fn overlappable_left( out } +/// libaom `motion_mode_allowed`'s neighbour term: does ANY bordering inter +/// block sit on this block's above row or left column ("check_num_overlappable +/// _neighbors", `obmc.h`). The single source of truth for the DECODER's own +/// `motion_mode_eligible` and for the tile WRITER's (`tile::write_motion_mode`) +/// -- the two disagreeing by one block writes a `motion_mode` symbol the +/// decoder never reads (class `symbol-consumption-gap`). +pub(crate) fn has_overlappable_neighbour( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bw4: usize, + bh4: usize, + mi_cols: usize, + mi_rows: usize, +) -> bool { + !overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, 1).is_empty() + || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, 1).is_empty() +} + /// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples` /// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2: /// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128` @@ -27249,9 +27268,9 @@ fn decode_inter_block( // min(bw, bh) >= 8, false for a 16x4 / 4x16 strip. && write_w.min(write_h) >= 8 && interintra_mode.is_none() - && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty() - || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1) - .is_empty()) + && has_overlappable_neighbour( + grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, + ) // libaom `motion_mode_allowed`: a GLOBALMV block whose model // is non-IDENTITY-non-TRANSLATION under free (non-integer) // mv reads no motion_mode/obmc symbol at all -- implicit @@ -31988,8 +32007,9 @@ fn decode_inter_block8( && !skip_mode && interintra_mode.is_none() && !(is_global_mv_block && !force_integer_mv) - && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty() - || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty()); + && has_overlappable_neighbour( + grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, + ); let mut warp_params: Option = None; let mut warped_selected = false; let mut obmc_selected = false; @@ -33043,13 +33063,19 @@ pub(crate) fn decode_inter_frame_tile( // starts from what the previous frame stored, not from the defaults. Same // class as `tx_select` above, third instance. initial_cdfs: Option, + // lane-av1obmc: this frame header's own `is_motion_mode_switchable` + // (spec 5.9.2). Hard-coding `false` here desynced every stream this + // crate's own encoder writes once inter blocks started carrying a + // `motion_mode` symbol (class: test asserts against a stale header). + switchable_motion_mode: bool, fctx: &crate::decode::FrameCtx, ) -> Result { decode_inter_frame_tile_lr( data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef, loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, reference_select, tx_select, - &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false, fctx, + &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false, + switchable_motion_mode, fctx, ) } @@ -33090,6 +33116,11 @@ pub(crate) fn decode_inter_frame_tile_lr( // `sign_bias` rather than beside the other bools on purpose (the // `adjacent-same-typed-args` class). allow_screen_content_tools: bool, + // lane-av1obmc: this frame header's own `is_motion_mode_switchable` + // (spec 5.9.2). Hard-coding `false` here desynced every stream this + // crate's own encoder writes once inter blocks started carrying a + // `motion_mode` symbol (class: test asserts against a stale header). + switchable_motion_mode: bool, fctx: &crate::decode::FrameCtx, ) -> Result { let single_tile = TileInfo { @@ -33118,6 +33149,7 @@ pub(crate) fn decode_inter_frame_tile_lr( initial_cdfs, sign_bias, allow_screen_content_tools, + switchable_motion_mode, fctx, ) } @@ -33148,6 +33180,11 @@ pub(crate) fn decode_inter_frame_tiles_lr( // This frame header's own `allow_screen_content_tools` (see the // single-tile wrapper): the palette syntax its intra blocks carry. allow_screen_content_tools: bool, + // lane-av1obmc: this frame header's own `is_motion_mode_switchable` + // (spec 5.9.2). Hard-coding `false` here desynced every stream this + // crate's own encoder writes once inter blocks started carrying a + // `motion_mode` symbol (class: test asserts against a stale header). + switchable_motion_mode: bool, fctx: &crate::decode::FrameCtx, ) -> Result { decode_inter_frame_tile_with_cdfs( @@ -33182,7 +33219,7 @@ pub(crate) fn decode_inter_frame_tiles_lr( [0; 2], true, tx_select, - false, + switchable_motion_mode, false, allow_screen_content_tools, DeltaParams::default(), @@ -37314,6 +37351,7 @@ mod tests { false, false, None, + false, fctx, ) .unwrap_err(); @@ -37732,6 +37770,9 @@ mod tests { // This frame's own `allow_screen_content_tools`, off the // `Encoded` the encoder handed back (stale-header class). frame.screen, + // Same stale-header class: the bit that makes this frame's + // inter blocks carry a `motion_mode` symbol. + frame.switchable_motion_mode, fctx, ) .unwrap(); @@ -38063,6 +38104,9 @@ mod tests { // This frame's own `allow_screen_content_tools`, off the // `Encoded` the encoder handed back (stale-header class). frame.screen, + // Same stale-header class: the bit that makes this frame's + // inter blocks carry a `motion_mode` symbol. + frame.switchable_motion_mode, fctx, ) .unwrap(); diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index ced2d7d6..a176fb47 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -693,6 +693,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En mi_rows: encoded.mi_rows, base_q_idx: encoded.base_q_idx, tx_select: encoded.tx_select, + switchable_motion_mode: encoded.switchable_motion_mode, screen: encoded.screen, start_cdfs: encoded.start_cdfs.clone(), next_cdfs: encoded.next_cdfs.clone(), @@ -747,6 +748,12 @@ pub struct Encoded { /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first /// block. pub(crate) tx_select: bool, + /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the + /// bit that makes every eligible single-reference inter block carry a + /// `motion_mode` symbol. Same contract as `tx_select` above: a test + /// decoding `tile` directly must pass it along or it desyncs at the + /// first eligible block. + pub(crate) switchable_motion_mode: bool, /// The CDF state this frame's tile writer started from -- the defaults /// for a key frame and for the first inter frame, and the previous /// frame's stored tables after that. A test that decodes `tile` directly @@ -1152,7 +1159,11 @@ pub fn inter_frame_headers_slots( }, allow_high_precision_mv: false, interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap, - is_motion_mode_switchable: false, + // lane-av1obmc: every single-reference inter block libaom's + // `motion_mode_allowed` accepts carries a `motion_mode` symbol + // (`crate::tile::write_motion_mode`). `allow_warped_motion` stays + // false, so the alphabet is the 2-symbol `obmc_cdf`. + is_motion_mode_switchable: true, use_ref_frame_mvs: false, // Forces `get_tx_set` (spec 5.11.48) to the two-symbol // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only @@ -3855,6 +3866,7 @@ fn code_square_inter( palette_uv: None, tx_depth, inter: Some(info), + obmc: false, }, cost + dcost, ); @@ -3886,6 +3898,7 @@ fn code_square_inter( palette: None, palette_uv: None, tx_depth, + obmc: false, inter: Some(InterInfo { ref1: None, mv1: (0, 0), @@ -5047,6 +5060,8 @@ pub(crate) fn encode_key_frame_inner( mi_rows: header.mi_rows, base_q_idx, tx_select, + // A key frame codes no inter block, so no motion_mode symbol. + switchable_motion_mode: false, screen, next_cdfs: start_cdfs.clone(), start_cdfs, @@ -6261,6 +6276,7 @@ fn search_inter_block( uv_mode: DC_PRED, skip: best.skip, inter: best.inter, + obmc: false, eight: None, dv: None, palette: None, @@ -6975,6 +6991,7 @@ pub(crate) fn encode_inter_frame( .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); let start_cdfs = CdfSnapshot(cdfs); let reference_select_bit = header.reference_select; + let switchable_motion_mode = header.is_motion_mode_switchable; let order_hint_bits = seq.order_hint_bits; let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; @@ -6996,6 +7013,7 @@ pub(crate) fn encode_inter_frame( crate::tile::arm_sign_bias(sign_bias); // Thread-locals: every tile job arms its own worker. crate::tile::arm_reference_select(reference_select_bit); + crate::tile::arm_motion_mode(switchable_motion_mode); crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); crate::tile::arm_screen(screen); let mut cdfs = start_cdfs.0.clone(); @@ -7122,6 +7140,7 @@ pub(crate) fn encode_inter_frame( Some(start_cdfs.0.clone()), sign_bias, h.allow_screen_content_tools, + switchable_motion_mode, fctx, ) }, @@ -7154,6 +7173,7 @@ pub(crate) fn encode_inter_frame( mi_rows: header.mi_rows, base_q_idx, tx_select, + switchable_motion_mode, screen, start_cdfs, next_cdfs, @@ -7924,6 +7944,7 @@ mod tests { mv: (0, 0), ref_mv_idx: 0, }), + obmc: false, }; let skipped_block = BlockCoeffs { skip: true, @@ -7943,6 +7964,10 @@ mod tests { Quadrant::Whole(skipped_block.clone()), Quadrant::Whole(skipped_block), ]; + // lane-av1obmc: the header this tile is decoded under carries + // `is_motion_mode_switchable`, so the writer must be armed with it + // too or the decoder reads a `motion_mode` symbol nobody wrote. + crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable); let tile = crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks) .unwrap(); @@ -10548,7 +10573,7 @@ mod tests { }) }; let pins: [(u8, usize, u64); 2] = - [(150, 7106, 0x1da4_9acd_a892_68e3), (60, 25963, 0x94df_8f46_174e_1a5e)]; + [(150, 7111, 0xd375_2e36_13c4_9fc4), (60, 25969, 0x83b2_8522_cec6_38d4)]; for (q, bytes, hash) in pins { let encoded = encode_sequence(&source, q, 0.5).unwrap(); assert_eq!( diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 4716428e..079e0946 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -381,6 +381,99 @@ pub(crate) fn arm_reference_select(on: bool) { REFERENCE_SELECT.with(|c| c.set(on)); } +thread_local! { + /// This frame header's own `is_motion_mode_switchable` bit (spec 5.9.2), + /// armed exactly like [`REFERENCE_SELECT`]. `true` makes every + /// single-reference inter block that libaom's `motion_mode_allowed` + /// accepts carry a `motion_mode`/`obmc` symbol right after its MV syntax, + /// exactly where decode.rs' `read_motion_mode` reads one. + static MOTION_MODE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Arms the frame's `is_motion_mode_switchable` bit for the next tile written +/// on this thread; cleared by [`CdefIdxGuard`] when that writer returns. +pub(crate) fn arm_motion_mode(on: bool) { + MOTION_MODE.with(|c| c.set(on)); +} + +/// How many single-reference inter blocks this writer coded a `motion_mode` +/// symbol for, split by the value it coded and by the block's own footprint +/// -- the histogram a gate prints so that "OBMC is on" is a measurement, not +/// a claim (class `gate-blind-to-feature`). Index: `0 + 2 * bucket` for +/// SIMPLE, `1 + 2 * bucket` for OBMC, bucket 0/1/2 = 32x32/16x16/8x8. +static MOTION_MODE_HITS: [std::sync::atomic::AtomicUsize; 6] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 6]; + +/// Reads [`MOTION_MODE_HITS`] and zeroes it, so a gate can attribute the +/// counts to its own encode. +#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +pub(crate) fn take_motion_mode_hits() -> [usize; 6] { + std::array::from_fn(|i| MOTION_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// `read_motion_mode`'s write side (spec 5.11.24), called on a +/// single-reference inter block right after its MV syntax and before the +/// (never switchable here) interpolation filter -- libaom's own sequential +/// order in `read_inter_block_mode_info`. +/// +/// Eligibility is decode.rs' own `motion_mode_eligible`, term for term, with +/// the terms this writer settles statically dropped: no block it codes is +/// `skip_mode`, interintra or a non-IDENTITY-global `GLOBALMV` one, so what +/// is left is the footprint floor and the overlappable-neighbour walk +/// ([`crate::decode::has_overlappable_neighbour`], shared with the decoder so +/// the two cannot drift). The frame header keeps `allow_warped_motion == 0`, +/// so the alphabet is always the 2-symbol `obmc_cdf`, never the 3-symbol +/// `motion_mode_cdf`. +fn write_motion_mode( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + grid: &MiGrid, + (mi_row, mi_col): (usize, usize), + (bw4, bh4): (usize, usize), + (write_w, write_h): (usize, usize), + (mi_cols, mi_rows): (usize, usize), + obmc: bool, +) -> Result<()> { + let eligible = MOTION_MODE.with(std::cell::Cell::get) + && write_w.min(write_h) >= 8 + && crate::decode::has_overlappable_neighbour( + grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, + ); + if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { + eprintln!( + "EC_MMW mi_row={mi_row} mi_col={mi_col} w={write_w} h={write_h} elig={}", + eligible as u8 + ); + } + if !eligible { + // The encoder trialled an OBMC prediction for a block this writer + // codes as SIMPLE_TRANSLATION: its reconstruction is not the + // decoder's (class encoder-grid-drift), which is exactly what the + // `EC_COMP_MISMATCH` rung exists to catch. + if obmc && crate::envflags::env_flag!("EC_COMP_MISMATCH") { + eprintln!( + "EC_COMP_MISMATCH motion_mode enc=OBMC wrote=SIMPLE mi=({mi_row},{mi_col}) wh=({write_w}x{write_h})" + ); + } + return Ok(()); + } + let row = crate::decode::motion_mode_cdf_row(write_w, write_h).ok_or_else(|| { + Error::unsupported( + "AV1 tile", + format!("a {write_w}x{write_h} block has no motion_mode CDF row"), + ) + })?; + enc.symbol(usize::from(obmc), &mut cdfs.obmc[row]); + let bucket = match write_w.min(write_h) { + 32.. => 0, + 16 => 1, + _ => 2, + }; + MOTION_MODE_HITS[usize::from(obmc) + 2 * bucket] + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Ok(()) +} + /// The compound half of a block's end-of-block neighbour record: nothing for /// a single-reference or intra block, and `record_compound_mi`'s overwrite of /// the ALTREF default for a compound one (this writer only codes @@ -759,6 +852,7 @@ impl Drop for CdefIdxGuard { SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS)); SCREEN.with(|c| c.set(false)); REFERENCE_SELECT.with(|c| c.set(false)); + MOTION_MODE.with(|c| c.set(false)); INTRABC.with(|c| c.set(false)); INTRABC_GRID.with(|c| *c.borrow_mut() = None); ORDER_HINTS.with(|c| c.set((7, 0, [0; 7]))); @@ -1240,6 +1334,12 @@ pub struct BlockCoeffs { /// block. Only [`sb_coeff_inter_frame_tile`] codes `is_inter`; the key /// frame writers never read this field. pub inter: Option, + /// Whether this (single-reference inter) block's prediction was built + /// with OBMC -- spec `motion_mode == OBMC_CAUSAL`, written by + /// [`write_motion_mode`]. `false` (the [`Default`]) is + /// `SIMPLE_TRANSLATION`, the only motion mode this writer coded before + /// lane-av1obmc. + pub obmc: bool, /// The 8x8 leaves a straddling 16x16 block is split into (lane-av1-rect), /// each with its own 8x8 luma transform and 4x4 chroma transforms, in /// raster order among the leaves that are inside the true frame. `Some` @@ -5439,6 +5539,16 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( ); } } + write_motion_mode( + &mut enc, + &mut cdfs, + &grid, + (mi_row, mi_col), + (8, 8), + (BLOCK, BLOCK), + (mi_cols as usize, mi_rows as usize), + block.obmc, + )?; mode_for_tx = 0; } } else { @@ -5663,6 +5773,16 @@ fn write_inter_frame_leaf( ); } } + write_motion_mode( + enc, + cdfs, + grid, + (mi_row, mi_col), + (SUB_MI as usize, SUB_MI as usize), + (SUB, SUB), + (mi_cols as usize, mi_rows as usize), + block.obmc, + )?; mode_for_tx = 0; } } else { @@ -5893,6 +6013,16 @@ fn write_inter_frame_leaf8( ); } } + write_motion_mode( + enc, + cdfs, + grid, + (mi_row, mi_col), + (2, 2), + (8, 8), + (mi_cols as usize, mi_rows as usize), + block.obmc, + )?; mode_for_tx = 0; } } else {