diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index f5e0a250..38d08158 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -1205,6 +1205,19 @@ pub const SINGLE_REF: [[[u16; 3]; 6]; 3] = [ /// least 8x8 both dims (`is_comp_ref_allowed`) -- lane-av1comp. pub const SKIP_MODE: [[u16; 3]; 3] = [[32621, 32768, 0], [20708, 32768, 0], [8127, 32768, 0]]; +/// `default_obmc_cdf` (spec 9.4): `use_obmc`, by square bsize (`BLOCK_8X8`, +/// `BLOCK_16X16`, `BLOCK_32X32`, `BLOCK_64X64` -- `BLOCK_SIZES_ALL` indices +/// 3/6/9/12, the only sizes this decoder ever codes). Read only once +/// `motion_mode_allowed` (spec 5.11.24's `read_motion_mode`) offers +/// `OBMC_CAUSAL` rather than `WARPED_CAUSAL` -- lane-motionmode round 1 +/// never reaches the three-way `motion_mode_cdf`, see `decode.rs`. +pub const OBMC: [[u16; 3]; 4] = [ + [10437, 32768, 0], + [17432, 32768, 0], + [25817, 32768, 0], + [30128, 32768, 0], +]; + /// `Default_Comp_Mode_Cdf` (spec 9.4, `default_comp_inter_cdf`): whether an /// inter block reads `SINGLE_REFERENCE` or `COMPOUND_REFERENCE` -- only /// reached once `read_ref_frames` knows the frame's `reference_select` diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index f04826cd..f243bd2d 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -318,6 +318,15 @@ pub(crate) struct Cdfs { /// Whether a block reads `skip_mode` (lane-av1comp, spec 5.11.29's /// `skip_mode`), indexed by `av1_get_skip_mode_context`. pub skip_mode: [[u16; 3]; 3], + /// `use_obmc` (spec 5.11.24's `read_motion_mode`, the `OBMC_CAUSAL`-vs- + /// `SIMPLE_TRANSLATION` two-symbol alphabet libaom's `obmc_cdf` reads + /// whenever `motion_mode_allowed` can't offer `WARPED_CAUSAL` -- + /// lane-motionmode round 1 only reaches this arm, never the three-way + /// `motion_mode_cdf`), indexed by this block's own square bsize: 0 = + /// `BLOCK_8X8`, 1 = `BLOCK_16X16`, 2 = `BLOCK_32X32`, 3 = `BLOCK_64X64` + /// (`default_obmc_cdf`'s own `BLOCK_SIZES_ALL` indices 3/6/9/12 -- + /// this decoder only ever codes those four square sizes). + pub obmc: [[u16; 3]; 4], /// Which of the eight `INTER_COMPOUND_MODES` a `COMPOUND_REFERENCE` /// block takes (lane-av1comp, spec 5.11.24's `compound_mode`). pub inter_compound_mode: [[u16; 9]; 8], @@ -548,6 +557,7 @@ impl Cdfs { reset3(&mut self.single_ref); reset2(&mut self.comp_mode); reset2(&mut self.skip_mode); + reset2(&mut self.obmc); reset2(&mut self.inter_compound_mode); reset2(&mut self.comp_ref_type); reset3(&mut self.uni_comp_ref); @@ -988,6 +998,7 @@ impl Cdfs { comp_ref: cdf::COMP_REF, comp_bwdref: cdf::COMP_BWDREF, skip_mode: cdf::SKIP_MODE, + obmc: cdf::OBMC, comp_group_idx: cdf::COMP_GROUP_IDX, compound_idx: cdf::COMPOUND_IDX, y_mode: cdf::Y_MODE, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 6b2a8c85..63fbb242 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -154,6 +154,28 @@ pub(crate) fn skip_mode_hits() -> usize { SKIP_MODE_HITS.load(std::sync::atomic::Ordering::Relaxed) } +/// lane-motionmode: how many blocks actually decoded `obmc_selected == true` +/// (as opposed to just reaching an eligible `read_motion_mode` symbol read) +/// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream +/// reached [`obmc_blend`], not just the header bit. +static OBMC_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Current value of [`OBMC_HITS`]. +pub(crate) fn obmc_hits() -> usize { + OBMC_HITS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to +/// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of +/// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an +/// 8x8-leaf OBMC block apart from a 16x16+ one. +static OBMC_HITS_8: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Current value of [`OBMC_HITS_8`]. +pub(crate) fn obmc_hits_8() -> usize { + OBMC_HITS_8.load(std::sync::atomic::Ordering::Relaxed) +} + /// How many [`read_inter_compound_mode`] reads actually happened /// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own /// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound @@ -3959,6 +3981,263 @@ fn ref_planes<'a>( } } +/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row +/// directly above this block's own column span, one bordering block at a +/// time (stepping by that neighbour's own `MiInfo::size`, which is always +/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting +/// every *inter* neighbour found (an intra or unset cell is skipped, one mi +/// unit at a time, and does not itself count as a step). `max_neighbors` +/// caller-bounds the scan: `1` for the eligibility check (any hit at all), +/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the +/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as +/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is +/// not ported -- no block this decoder codes is narrower than 8px, so it +/// never fires here regardless of what a neighbour's own decoder was. +fn overlappable_above( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bw4: usize, + mi_cols: usize, + max_neighbors: usize, +) -> Vec<(usize, usize, MiInfo)> { + let mut out = Vec::new(); + if mi_row == 0 { + return out; + } + let end_col = (mi_col + bw4).min(mi_cols); + let mut col = mi_col; + while col < end_col && out.len() < max_neighbors { + let cell = grid.get(mi_row - 1, col); + let step = cell.map_or(1, |c| c.size).max(1); + if let Some(info) = cell { + if info.is_inter { + out.push((col - mi_col, step.min(end_col - col), *info)); + } + } + col += step; + } + out +} + +/// `foreach_overlappable_nb_left`'s left-column mirror of +/// [`overlappable_above`] -- see its doc for the shared corner-cut. +fn overlappable_left( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bh4: usize, + mi_rows: usize, + max_neighbors: usize, +) -> Vec<(usize, usize, MiInfo)> { + let mut out = Vec::new(); + if mi_col == 0 { + return out; + } + let end_row = (mi_row + bh4).min(mi_rows); + let mut row = mi_row; + while row < end_row && out.len() < max_neighbors { + let cell = grid.get(row, mi_col - 1); + let step = cell.map_or(1, |c| c.size).max(1); + if let Some(info) = cell { + if info.is_inter { + out.push((row - mi_row, step.min(end_row - row), *info)); + } + } + row += step; + } + out +} + +/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight +/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own +/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr + +/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising +/// to 64 (no neighbour contribution) away from it. Only the lengths this +/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16) +/// are transcribed. +fn obmc_mask(len: usize) -> &'static [u8] { + const M4: [u8; 4] = [39, 50, 59, 64]; + const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64]; + const M16: [u8; 16] = [ + 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64, + ]; + const M32: [u8; 32] = [ + 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60, + 61, 62, 64, 64, 64, 64, 64, 64, 64, 64, + ]; + match len { + 4 => &M4, + 8 => &M8, + 16 => &M16, + 32 => &M32, + _ => unreachable!("obmc overlap length outside this decoder's own block-size range"), + } +} + +/// A bordering block's own resolved interp filter kernel, `(h, v)` -- +/// mirrors [`resolve_interp_filter`]'s own return order from its stored +/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` = +/// `[v_sym, h_sym]`). Never calls `from_switchable_symbol` on the `[3, 3]` +/// sentinel: that value is only ever stored for an intra neighbour (already +/// excluded by [`overlappable_above`]/[`overlappable_left`]'s `is_inter` +/// gate) or when `interp_fixed` is `Some` for the whole frame, handled here +/// first. +fn neighbour_filter( + interp_fixed: Option, + sym: [u8; 2], +) -> (mc::InterpFilterKind, mc::InterpFilterKind) { + if let Some(kind) = interp_fixed { + return (kind, kind); + } + ( + mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize), + mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize), + ) +} + +/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh +/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor` +/// under `av1_setup_build_prediction_by_{above,left}_pred`). +#[allow(clippy::too_many_arguments)] +fn obmc_neighbour_pred( + refplane: &PlaneBuf, + x: usize, + y: usize, + mv: (i32, i32), + w: usize, + h: usize, + luma: bool, + h_kind: mc::InterpFilterKind, + v_kind: mc::InterpFilterKind, +) -> Vec { + let mut out = vec![0u8; w * h]; + mc::predict_with_filters( + &refplane.data, + refplane.width, + refplane.true_width, + refplane.true_height, + mv_to_q4(x, mv.1, luma), + mv_to_q4(y, mv.0, luma), + w, + h, + h_kind, + v_kind, + &mut out, + ); + out +} + +/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by +/// row (the above-neighbour pass, `aom_blend_a64_vmask`). +fn obmc_blend_v(dst: &mut [u8], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u8]) { + let mask = obmc_mask(h); + for row in 0..h { + let m = u32::from(mask[row]); + for col in 0..w { + let d = &mut dst[(oy + row) * stride + ox + col]; + let t = u32::from(tmp[row * w + col]); + *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u8; + } + } +} + +/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the +/// left-neighbour pass, `aom_blend_a64_hmask`). +fn obmc_blend_h(dst: &mut [u8], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u8]) { + let mask = obmc_mask(w); + for row in 0..h { + for col in 0..w { + let m = u32::from(mask[col]); + let d = &mut dst[(oy + row) * stride + ox + col]; + let t = u32::from(tmp[row * w + col]); + *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u8; + } + } +} + +/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts +/// the overlap strip against each bordering above/left inter neighbour's own +/// mv/ref/filter and blends it into this block's just-built single-reference +/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then +/// left, each reading only the *original* prediction this function was +/// handed (never the other pass's own output), matching libaom's own +/// independence between the two. `max_neighbor_obmc`'s own cap table +/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this +/// decoder's own square blocks always index the same value both ways) bounds +/// how many bordering blocks actually get blended, separate from the +/// eligibility scan's own unbounded ("any at all") walk. +#[allow(clippy::too_many_arguments)] +fn obmc_blend( + grid: &MiGrid, + neighbours: &Neighbours, + mi_row: usize, + mi_col: usize, + bw4: usize, + mi_rows: usize, + mi_cols: usize, + side: usize, + chroma_side: usize, + px: usize, + py: usize, + cpx: usize, + cpy: usize, + ref_y: &PlaneBuf, + ref_u: &PlaneBuf, + ref_v: &PlaneBuf, + other_refs: &RefSlots, + interp_fixed: Option, + pred_y: &mut [u8], + pred_u: &mut [u8], + pred_v: &mut [u8], +) -> Result<()> { + let max_neighbors = match bw4 { + 1..=4 => 2, + 5..=8 => 3, + _ => 4, + }; + let overlap = side / 2; + let coverlap = overlap / 2; + + for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_neighbors) + { + // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns + // (this decoder's own outer block-loop granularity), one step + // coarser than the mi(4px) units `overlappable_above` walks in -- + // divide back down to that column. + let (h_kind, v_kind) = neighbour_filter( + interp_fixed, + neighbours.above_filter[(mi_col + off4) / SUB_MI as usize], + ); + let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?; + let (bw, bh, ox) = (span4 * 4, overlap, off4 * 4); + let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind); + obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y); + let (cbw, cbh, cox) = (bw / 2, coverlap, ox / 2); + let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind); + obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u); + let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind); + obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v); + } + + for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bw4, mi_rows, max_neighbors) { + let (h_kind, v_kind) = neighbour_filter( + interp_fixed, + neighbours.left_filter[(mi_row + off4) / SUB_MI as usize], + ); + let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?; + let (bw, bh, oy) = (overlap, span4 * 4, off4 * 4); + let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind); + obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y); + let (cbw, cbh, coy) = (coverlap, bh / 2, oy / 2); + let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind); + obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u); + let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind); + obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v); + } + Ok(()) +} + /// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to /// the square block sizes this decoder ever decodes (32/16/8, all /// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then @@ -4306,6 +4585,10 @@ fn decode_inter_block( // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509). skip_mode_present: bool, skip_mode_frame: [u8; 2], + // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/ + // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`). + switchable_motion_mode: bool, + allow_warped_motion: bool, ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); @@ -5011,6 +5294,48 @@ fn decode_inter_block( }; (mv, false) }; + // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24; + // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528), + // placed right after MV assignment and before the switchable + // interp filter read below (`read_mb_interp_filter`, decodemv.c + // ~1600) -- libaom's own sequential order. `motion_mode_allowed` + // (`reconinter.h`) reduces, for every block this single-ref path + // reaches, to "does an inter neighbour border the above row or + // left column": `is_motion_variation_allowed_bsize` always holds + // (`side` is never below 16px on this path), `ref_frame[1] != + // INTRA_FRAME` always holds (no interintra reader here), + // `is_motion_variation_allowed_compound` always holds (this is + // the single-ref branch), and `is_global_mv_block` never + // triggers (this decoder's global motion is always `IDENTITY`, + // so its warp `type` is never `> TRANSLATION`). A stream with + // `allow_warped_motion=1` is refused right at an eligible block + // rather than guessed at: `av1_findSamples`/`num_proj_ref` is + // not ported, so this decoder cannot tell a real + // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`) + // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever + // the header allows warp -- reading the wrong alphabet desyncs + // the tile. + let motion_mode_eligible = switchable_motion_mode + && !skip_mode + && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty() + || !overlappable_left(grid, mi_row, mi_col, bw4, mi_rows as usize, 1) + .is_empty()); + let mut obmc_selected = false; + if motion_mode_eligible { + if allow_warped_motion { + return Err(unsupported( + "a motion-variation-eligible block under allow_warped_motion=1 \ + (round 1 only reads the 2-symbol obmc_cdf; telling OBMC_CAUSAL \ + from WARPED_CAUSAL needs av1_findSamples, not ported)", + )); + } + // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3. + let bsize_idx = (side.trailing_zeros() - 3) as usize; + obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1; + if obmc_selected { + OBMC_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } // spec `get_ref_filter_type`: a neighbour's own filter only feeds // this block's switchable_interp context when that neighbour coded // the SAME reference frame this block is about to read -- a @@ -5116,6 +5441,32 @@ fn decode_inter_block( &mut pred_v, ); + if obmc_selected { + obmc_blend( + grid, + neighbours, + mi_row, + mi_col, + bw4, + mi_rows as usize, + mi_cols as usize, + side, + chroma_side, + px, + py, + cpx, + cpy, + ref_y, + ref_u, + ref_v, + other_refs, + interp_fixed, + &mut pred_y, + &mut pred_u, + &mut pred_v, + )?; + } + if skip { y.reconstruct_mc(px, py, side, &pred_y, &vec![0i32; side * side]); u.reconstruct_mc( @@ -5421,6 +5772,16 @@ fn decode_inter_block8( // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see // [`decode_inter_frame_tile_with_cdfs`]'s own doc. reduced_tx_set: bool, + // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/ + // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus + // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour + // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own + // prediction is always `Regular` (documented corner-cut, `mc::predict` + // has no filter param), but an OBMC neighbour can be a real 16x16+ + // block that DID resolve a switchable filter. + interp_fixed: Option, + switchable_motion_mode: bool, + allow_warped_motion: bool, // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own @@ -5868,6 +6229,33 @@ fn decode_inter_block8( }; (mv, false) }; + // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the + // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8 + // is the spec's own minimum eligible size, single-ref-only branch, + // no interintra reader, `IDENTITY`-only global motion). Mirrors the + // 16x16 leaf's own `decode_inter_block` read (see its doc above) -- + // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1` + // refusal (warp needs `av1_findSamples`, not ported at either leaf). + let motion_mode_eligible = switchable_motion_mode + && !skip_mode + && (!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()); + let mut obmc_selected = false; + if motion_mode_eligible { + if allow_warped_motion { + return Err(unsupported( + "a motion-variation-eligible 8x8 leaf under allow_warped_motion=1 \ + (round 3 only reads the 2-symbol obmc_cdf; telling OBMC_CAUSAL \ + from WARPED_CAUSAL needs av1_findSamples, not ported)", + )); + } + // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3. + obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1; + if obmc_selected { + OBMC_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + OBMC_HITS_8.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } for dr in 0..2 { for dc in 0..2 { grid.set( @@ -5924,6 +6312,32 @@ fn decode_inter_block8( &mut pred_v, ); + if obmc_selected { + obmc_blend( + grid, + neighbours, + mi_row, + mi_col, + 2, + mi_rows as usize, + mi_cols as usize, + SIDE, + CHROMA_SIDE, + px, + py, + cpx, + cpy, + ref_y, + ref_u, + ref_v, + other_refs, + interp_fixed, + &mut pred_y, + &mut pred_u, + &mut pred_v, + )?; + } + if skip { y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]); u.reconstruct_mc( @@ -6207,6 +6621,8 @@ pub fn decode_inter_frame_tile( false, [0; 2], true, + false, + false, ) .map(|(picture, _, _)| picture) } @@ -6257,6 +6673,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // `Set1` coefficient tables at 16x16/8x8 rather than the reduced // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]). reduced_tx_set: bool, + // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/ + // `allow_warped_motion` bits, threaded to every `decode_inter_block`/ + // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`). + switchable_motion_mode: bool, + allow_warped_motion: bool, ) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> { let tpl_frame = tpl_field.map(|field| TplFrameArgs { field, @@ -6461,6 +6882,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( ref_order_hints, skip_mode_present, skip_mode_frame, + switchable_motion_mode, + allow_warped_motion, )?; } PARTITION_SPLIT => { @@ -6531,6 +6954,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( ref_order_hints, skip_mode_present, skip_mode_frame, + switchable_motion_mode, + allow_warped_motion, )?; } else { let ctx16 = neighbours.partition_ctx(at16, SUB); @@ -6593,6 +7018,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( skip_mode_present, skip_mode_frame, reduced_tx_set, + interp_fixed, + switchable_motion_mode, + allow_warped_motion, )?; prev_leaf = Some((leaf_mi, skip, is_inter)); last_skip_mode = skip_mode_leaf; @@ -7373,6 +7801,8 @@ mod tests { [0; 7], false, [0; 2], + false, + false, ) .unwrap(); diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index fdcc5626..15cc5cbd 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -379,6 +379,8 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.skip_mode_present, header.skip_mode_frame, header.reduced_tx_set, + header.is_motion_mode_switchable, + header.allow_warped_motion, )? }; // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's @@ -2898,6 +2900,487 @@ mod tests { ); } + /// lane-motionmode round 1: `--enable-obmc=1 --enable-warped-motion=0` + /// on the base recipe (`--auto-alt-ref=1 --lag-in-frames=16 + /// --enable-fwd-kf=0 --enable-ref-frame-mvs=0`) -- pixel-exact against + /// ffmpeg, gated on [`decode::obmc_hits`] actually advancing (a real + /// block picked `OBMC_CAUSAL`, not just that the header bit was set). + /// Structure copied from + /// `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`: + /// a seed sweep with a named-refusal escape hatch and an + /// `EC_AV1_GATE_DUMP` pin on mismatch. + #[test] + fn a_real_aomenc_stream_with_obmc_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_obmc_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (64usize, 64usize, 24usize); + let mut refusals = Vec::new(); + let mut never_fired = 0u32; + for attempt in 0..80u32 { + let seed = 42 + attempt % 40; + let duration = frame_count as f64 / 25.0; + let source = + format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + "--enable-warped-motion=0", + "--enable-obmc=1", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::obmc_hits(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + Ok(frames) => frames, + }; + if decode::obmc_hits() == before { + never_fired += 1; + continue; + } + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if mismatched { + if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); + } + eprintln!( + "{NAME} FIRING seed {seed}: obmc hits advanced by {}", + decode::obmc_hits() - before + ); + return; + } + eprintln!( + "SKIP {NAME}: {never_fired} attempts decoded but never fired obmc, and every \ + other attempt hit a named refusal:\n{}", + refusals.join("\n") + ); + } + + /// lane-motionmode round 3: same shape as + /// `a_real_aomenc_stream_with_obmc_decodes_pixel_exact`, but relaxed the + /// `--min-partition-size=32 --max-partition-size=32` clamp (that other + /// gate's own doc: locked to remove partition-depth choice from the + /// search entirely) to `8`/`32`, to make an 8x8-leaf `OBMC_CAUSAL` pick + /// possible at all. Gated on [`decode::obmc_hits_8`] specifically, not + /// the aggregate [`decode::obmc_hits`]. Measured live (round 3, this + /// box): 80 attempts, 0 ever called `decode_inter_block8` at all -- + /// `cpu-used=0`'s RD search never once splits a 16x16 down to a clean + /// 4-way 8x8 leaf for this smooth `gradients` fixture (large blocks + /// always win the RD cost there); the handful of named refusals seen + /// are `PARTITION_SPLIT` chosen *at* 8x8 (down to 4x4, already refused + /// at `decode.rs`'s `part8 != PARTITION_NONE` check) or + /// `allow_screen_content_tools`, neither reaching a leaf. Kept anyway + /// (mirrors this file's own `never_fired`-skip convention) as the + /// honest record of the attempt; a real 8x8 OBMC fixture needs + /// higher-frequency content than this gate's fixtures use, out of + /// round-3 budget. + #[test] + fn a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (64usize, 64usize, 24usize); + let mut refusals = Vec::new(); + let mut never_fired = 0u32; + let mut total_obmc8 = 0usize; + for attempt in 0..80u32 { + let seed = 42 + attempt % 40; + let duration = frame_count as f64 / 25.0; + let source = + format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + "--enable-warped-motion=0", + "--enable-obmc=1", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--min-partition-size=8", + "--max-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before8 = decode::obmc_hits_8(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + Ok(frames) => frames, + }; + let fired8 = decode::obmc_hits_8() - before8; + total_obmc8 += fired8; + if fired8 == 0 { + never_fired += 1; + continue; + } + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if mismatched { + if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); + } + eprintln!( + "{NAME} FIRING seed {seed}: 8x8 obmc hits {fired8} (total across attempts so far {total_obmc8})" + ); + return; + } + eprintln!( + "SKIP {NAME}: {never_fired} attempts decoded but never fired an 8x8 obmc block \ + ({total_obmc8} total 8x8 obmc hits across all attempts), and every other attempt \ + hit a named refusal:\n{}", + refusals.join("\n") + ); + } + + /// lane-motionmode round 1: `--enable-warped-motion=1` must be a NAMED + /// refusal, never a silent mis-decode -- this decoder does not port + /// `av1_findSamples`/`num_proj_ref`, so it cannot tell `OBMC_CAUSAL` + /// from `WARPED_CAUSAL` at an eligible block once the header allows + /// warp (see `decode_inter_block`'s own `allow_warped_motion` refusal). + /// Every attempt across the seed sweep must either name the refusal or + /// decode pixel-exact (an eligible block simply never fired in that + /// attempt) -- a silent pixel mismatch here would mean the refusal + /// failed to fire on a stream that actually needed it. + #[test] + fn a_real_aomenc_stream_with_warped_motion_refuses_or_matches() { + const NAME: &str = "a_real_aomenc_stream_with_warped_motion_refuses_or_matches"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (64usize, 64usize, 24usize); + let mut named_refusals = 0u32; + let mut matched = 0u32; + for attempt in 0..40u32 { + let seed = 42 + attempt; + let duration = frame_count as f64 / 25.0; + let source = + format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + "--enable-warped-motion=1", + "--enable-obmc=1", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" + ); + named_refusals += 1; + continue; + } + Ok(frames) => frames, + }; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + assert_eq!(frames.len(), frame_count); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!( + got.y, want.y, + "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- decoded without a named \ + refusal but mismatched, meaning the refusal failed to fire" + ); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); + } + matched += 1; + } + eprintln!( + "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of 40" + ); + } + /// `LAST2_FRAME`/`LAST3_FRAME` are just older slots in the same forward /// reference-buffer ring `LAST_FRAME`/`GOLDEN_FRAME` already prove -- /// dropping the golden gate's `--max-reference-frames=3