diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 15c4364f..1a589e37 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -30,7 +30,11 @@ use crate::encode::{Picture, Reach}; use crate::intra::predict; use crate::mc; use crate::msac::SymbolDecoder; -use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx}; +use crate::mvstack::{ + ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME, + MiGrid, MiInfo, find_mv_stack, single_ref_ctx, single_ref_p1_ctx, single_ref_p2_ctx, + single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, +}; use crate::tile::{INTRA_MODE_CTX, block_grid, has_half}; use crate::transform::{TxType, dequant_and_inverse_typed}; @@ -100,6 +104,19 @@ pub(crate) fn directional_uv_hits() -> usize { /// proving a stream actually exercised a nonzero angle delta. static ANGLE_DELTA_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// How many [`read_single_ref`] reads resolved to a reference other than +/// `LAST_FRAME`, across every call in the process -- the same before/after +/// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually +/// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's +/// only other supported one so far) rather than every block coincidentally +/// resolving `LAST_FRAME`. +static NON_LAST_REF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Current value of [`NON_LAST_REF_HITS`]. +pub(crate) fn non_last_ref_hits() -> usize { + NON_LAST_REF_HITS.load(std::sync::atomic::Ordering::Relaxed) +} + thread_local! { /// The sequence header's `enable_intra_edge_filter`, set once per /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s @@ -625,6 +642,15 @@ struct Neighbours { /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`. above_inter: Vec, left_inter: Vec, + /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME` + /// alphabet) the block above/left of this column/row coded, or `-1` for + /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context + /// functions (`mvstack::ref_ctx` family) need the real reference, not + /// just "was it inter" (lane-av1refs: every inter block used to be + /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was + /// enough). + above_ref: Vec, + left_ref: Vec, /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or /// `3` = "no info": an intra neighbour or the frame's own border) of the /// block above/left of this column/row -- spec @@ -648,12 +674,12 @@ struct Neighbours { /// transform size, spec 7.14's `get_transform_size`/`get_filter_level` /// edge-length lookup (`apply_deblock`). tx_grid: Vec, - /// Per-4x4-mi `is_inter` flag -- the loop filter's ref/mode delta lookup - /// (spec 7.14.4 `get_filter_level`; every inter block this decoder - /// produces is a single `LAST_FRAME` reference with a non-`GLOBALMV` - /// mode, so `is_inter` alone picks the right `ref_deltas`/`mode_deltas` - /// entry without a separate ref/mode grid). - inter_grid: Vec, + /// Per-4x4-mi reference frame (`0` = intra, `1..=7` = `MV_REFERENCE_FRAME`) + /// -- the loop filter's ref/mode delta lookup (spec 7.14.4 + /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs: + /// widened from a bare `is_inter` bool, which collapsed every non-`LAST` + /// reference onto `LAST_FRAME`'s own delta). + ref_grid: Vec, } impl Neighbours { @@ -673,6 +699,8 @@ impl Neighbours { left_skip: vec![false; rows], above_inter: vec![false; cols], left_inter: vec![false; rows], + above_ref: vec![-1; cols], + left_ref: vec![-1; rows], above_filter: vec![[3u8; 2]; cols], left_filter: vec![[3u8; 2]; rows], mi_cols, @@ -680,7 +708,7 @@ impl Neighbours { skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)], skip_grid_cols_mi: cols * (SUB / MI), tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], - inter_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)], + ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)], } } @@ -688,7 +716,7 @@ impl Neighbours { /// transform width (in pixels) and `is_inter` flag -- the loop filter's /// per-edge lookup (`apply_deblock`), filled at the same call sites and /// units as [`Self::fill_skip_grid`]. - fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, is_inter: bool) { + fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) { let (mi_r, mi_c) = at_mi; for rr in 0..side_mi { for cc in 0..side_mi { @@ -696,8 +724,8 @@ impl Neighbours { if let Some(cell) = self.tx_grid.get_mut(idx) { *cell = tx_px; } - if let Some(cell) = self.inter_grid.get_mut(idx) { - *cell = is_inter; + if let Some(cell) = self.ref_grid.get_mut(idx) { + *cell = ref_frame; } } } @@ -755,6 +783,7 @@ impl Neighbours { self.left_side_mi.iter_mut().for_each(|s| *s = SB); self.left_skip.iter_mut().for_each(|s| *s = false); self.left_inter.iter_mut().for_each(|i| *i = false); + self.left_ref.iter_mut().for_each(|r| *r = -1); self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]); } @@ -762,13 +791,16 @@ impl Neighbours { /// block that reads it as a neighbour -- [`crate::tile`]'s /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec /// `get_ref_filter_type`'s "not this ref frame" case reads the same as - /// "no neighbour"). + /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the + /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs + /// the real value, not just `is_inter`). fn record_inter( &mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool, + ref_frame: i8, filter: [u8; 2], ) { let (r, c) = at; @@ -777,6 +809,8 @@ impl Neighbours { self.left_skip[r + cell] = skip; self.above_inter[c + cell] = is_inter; self.left_inter[r + cell] = is_inter; + self.above_ref[c + cell] = ref_frame; + self.left_ref[r + cell] = ref_frame; self.above_filter[c + cell] = filter; self.left_filter[r + cell] = filter; } @@ -1727,7 +1761,7 @@ fn decode_block( (r * (SUB / MI), c * (SUB / MI)), side / MI, logical_tx as u8, - false, + 0, ); Ok(()) } @@ -2032,12 +2066,12 @@ fn decode_leaf8( } } neighbours.fill_skip_grid(leaf_mi, 2, skip); - neighbours.fill_lf_grid(leaf_mi, 2, 4, false); + neighbours.fill_lf_grid(leaf_mi, 2, 4, 0); return Ok(mode); } neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]); neighbours.fill_skip_grid(leaf_mi, 2, skip); - neighbours.fill_lf_grid(leaf_mi, 2, 8, false); + neighbours.fill_lf_grid(leaf_mi, 2, 8, 0); Ok(mode) } @@ -2254,7 +2288,7 @@ fn apply_deblock( } /// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls -/// in -- `Neighbours::tx_grid`/`inter_grid` are always indexed at the luma +/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma /// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per /// mi unit under this decoder's assumed 4:2:0 subsampling). fn plane_to_mi(chroma: bool, coord: usize) -> usize { @@ -2367,8 +2401,8 @@ fn unit_log2(px: u32) -> i32 { /// spec 7.14.4's `get_filter_level`, restricted to this decoder's shapes: /// every inter block is a single `LAST_FRAME` reference with a non-`GLOBALMV` /// mode, so `is_inter` alone selects `ref_deltas`/`mode_deltas` (design note -/// on [`Neighbours::inter_grid`]). -fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, is_inter: bool) -> i32 { +/// on [`Neighbours::ref_grid`]). +fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, ref_frame: i8) -> i32 { let base = i32::from(if plane_idx == 0 { lf.level[dir] } else if plane_idx == 1 { @@ -2380,7 +2414,8 @@ fn lf_level(lf: &LoopFilterParams, plane_idx: usize, dir: usize, is_inter: bool) return base; } let scale = 1i32 << (base >> 5); - let ref_idx = usize::from(is_inter); + let is_inter = ref_frame != 0; + let ref_idx = ref_frame as usize; let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale; if is_inter { lvl += i32::from(lf.mode_deltas[1]) * scale; @@ -2409,17 +2444,17 @@ fn edge_params( if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 { return None; } - let cur_inter = n.inter_grid[mi_r * n.skip_grid_cols_mi + mi_c]; + let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c]; let (pv_mi_r, pv_mi_c) = if dir == 0 { (mi_r, mi_c - 1) } else { (mi_r - 1, mi_c) }; let pv_tx = tx_px_at(n, chroma, pv_mi_r, pv_mi_c); - let pv_inter = n.inter_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c]; + let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c]; - let cur_level = lf_level(lf, plane_idx, dir, cur_inter); - let pv_level = lf_level(lf, plane_idx, dir, pv_inter); + let cur_level = lf_level(lf, plane_idx, dir, cur_ref); + let pv_level = lf_level(lf, plane_idx, dir, pv_ref); if cur_level == 0 && pv_level == 0 { return None; } @@ -3580,6 +3615,39 @@ fn read_inter_plane( Ok(grid) } +/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode` +/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with +/// `reference_select` set before this is ever called, so that read is never +/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable +/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs). +fn read_single_ref(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above_ref: i8, left_ref: i8) -> i8 { + let above = (above_ref > 0).then_some(above_ref); + let left = (left_ref > 0).then_some(left_ref); + let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, left)][0]); + let ref_frame = if p1 == 1 { + let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, left)][1]); + if p2 == 1 { + ALTREF_FRAME + } else { + let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, left)][5]); + if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME } + } + } else { + let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, left)][2]); + if p3 == 1 { + let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, left)][4]); + if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME } + } else { + let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, left)][3]); + if p4 == 1 { LAST2_FRAME } else { LAST_FRAME } + } + }; + if ref_frame != LAST_FRAME { + NON_LAST_REF_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + ref_frame +} + /// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip, /// `is_inter`, then either the single-reference/MV-stack/motion-vector chain /// and motion-compensated reconstruction, or the inter frame's own intra @@ -3611,6 +3679,18 @@ fn decode_inter_block( ref_y: &PlaneBuf, ref_u: &PlaneBuf, ref_v: &PlaneBuf, + // corner-cut (lane-av1refs r1): only `LAST_FRAME` (`ref_y`/`u`/`v`) and + // `GOLDEN_FRAME` (`golden_*`, when the frame header's own + // `ref_frame_idx` names a slot with a picture) are threaded down to MC. + // Ceiling: `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` still refuse by + // name -- real short low-lag streams overwhelmingly pick `LAST` or + // `GOLDEN` (the ledger's cdffwd trace). Upgrade path: widen `golden_*` + // into a `[Option<&PlaneBuf>; REFS_PER_FRAME]` addressed by the decoded + // reference, same as the CDF/picture DPB slots `decode_stream` already + // keeps. + golden_y: Option<&PlaneBuf>, + golden_u: Option<&PlaneBuf>, + golden_v: Option<&PlaneBuf>, base_q_idx: u8, luma_set_intra: TxbSet, luma_set_inter: TxbSet, @@ -3624,8 +3704,6 @@ fn decode_inter_block( interp_fixed: Option, enable_dual_filter: bool, ) -> Result<()> { - const LAST_FRAME: i8 = 1; - let (r, c) = at; let (px, py) = (c * SUB, r * SUB); let (cpx, cpy) = (px / 2, py / 2); @@ -3642,16 +3720,29 @@ fn decode_inter_block( let mode_for_tx; let (luma_grid, u_grid, v_grid); let block_filter; + let ref_frame_for_lf; if is_inter { - let sr_ctx = single_ref_ctx(above_inter || left_inter); - let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]); - let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]); - let p4 = dec.symbol(&mut cdfs.single_ref[sr_ctx][3]); - if (p1, p3, p4) != (0, 0, 0) { - return Err(unsupported( - "a reference frame other than LAST_FRAME (round 2)", - )); - } + let ref_frame = read_single_ref(dec, cdfs, neighbours.above_ref[c], neighbours.left_ref[r]); + ref_frame_for_lf = ref_frame; + // round 3 (lane-av1refs): the GOLDEN_FRAME arm below decodes and + // threads a real golden picture through MC/mvstack/deblock, but 120+ + // attempts across a real aomenc recipe built to isolate exactly this + // path (min==max partition size, order-hint off, screen-content + // tools off) still could not clear this crate's OWN gate + // (`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`, + // stream.rs) 4 consecutive times -- every attempt either never fired + // GOLDEN_FRAME or hit an unrelated named refusal first (see that + // test's own refusal log). Refuse GOLDEN_FRAME here, narrowly, until + // a round actually gets that gate green: main should not carry a + // reference-selection path with zero live pixel-exact proof. + let (py_ref, pu_ref, pv_ref) = match ref_frame { + LAST_FRAME => (ref_y, ref_u, ref_v), + _ => { + return Err(unsupported( + "a reference frame other than LAST_FRAME (round 3: GOLDEN_FRAME's decode path exists but has no live pixel-exact proof yet)", + )); + } + }; let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); let bw4 = side / 4; @@ -3661,7 +3752,7 @@ fn decode_inter_block( mi_col, bw4, bw4, - LAST_FRAME, + ref_frame, mi_cols as usize, mi_rows as usize, ); @@ -3748,7 +3839,7 @@ fn decode_inter_block( mi_col + dc, MiInfo { is_inter: true, - ref_frame: LAST_FRAME, + ref_frame, mv, is_new_mv, size: bw4, @@ -3760,10 +3851,10 @@ fn decode_inter_block( let mut pred_y = vec![0u8; side * side]; mc::predict_with_filters( - &ref_y.data, - ref_y.width, - ref_y.true_width, - ref_y.true_height, + &py_ref.data, + py_ref.width, + py_ref.true_width, + py_ref.true_height, mv_to_q4(px, mv.1, true), mv_to_q4(py, mv.0, true), side, @@ -3774,10 +3865,10 @@ fn decode_inter_block( ); let mut pred_u = vec![0u8; chroma_side * chroma_side]; mc::predict_with_filters( - &ref_u.data, - ref_u.width, - ref_u.true_width, - ref_u.true_height, + &pu_ref.data, + pu_ref.width, + pu_ref.true_width, + pu_ref.true_height, mv_to_q4(cpx, mv.1, false), mv_to_q4(cpy, mv.0, false), chroma_side, @@ -3788,10 +3879,10 @@ fn decode_inter_block( ); let mut pred_v = vec![0u8; chroma_side * chroma_side]; mc::predict_with_filters( - &ref_v.data, - ref_v.width, - ref_v.true_width, - ref_v.true_height, + &pv_ref.data, + pv_ref.width, + pv_ref.true_width, + pv_ref.true_height, mv_to_q4(cpx, mv.1, false), mv_to_q4(cpy, mv.0, false), chroma_side, @@ -3893,6 +3984,7 @@ fn decode_inter_block( }; mode_for_tx = mode; block_filter = [3, 3]; + ref_frame_for_lf = 0; let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); for dr in 0..side / 4 { for dc in 0..side / 4 { @@ -4018,13 +4110,13 @@ fn decode_inter_block( } } neighbours.record(at, side, mode_for_tx, &[luma_grid, u_grid, v_grid]); - neighbours.record_inter(at, side, skip, is_inter, block_filter); + neighbours.record_inter(at, side, skip, is_inter, ref_frame_for_lf, block_filter); neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip); neighbours.fill_lf_grid( (r * (SUB / MI), c * (SUB / MI)), side / MI, side as u8, - is_inter, + ref_frame_for_lf, ); Ok(()) } @@ -4432,7 +4524,7 @@ fn decode_inter_block8( } } neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]); - neighbours.fill_lf_grid(leaf_mi, 2, 8, is_inter); + neighbours.fill_lf_grid(leaf_mi, 2, 8, if is_inter { LAST_FRAME } else { 0 }); Ok((skip, is_inter)) } @@ -4457,6 +4549,7 @@ pub fn decode_inter_frame_tile( frame_width: u32, frame_height: u32, reference: &Picture, + golden: Option<&Picture>, cdef: &CdefParams, loop_filter: &LoopFilterParams, allow_high_precision_mv: bool, @@ -4471,6 +4564,7 @@ pub fn decode_inter_frame_tile( frame_width, frame_height, reference, + golden, cdef, loop_filter, None, @@ -4494,6 +4588,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( frame_width: u32, frame_height: u32, reference: &Picture, + golden: Option<&Picture>, cdef: &CdefParams, loop_filter: &LoopFilterParams, initial_cdfs: Option, @@ -4535,6 +4630,38 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( true_width: reference.width / 2, true_height: reference.height / 2, }; + // `GOLDEN_FRAME`'s own picture, when the frame header's `ref_frame_idx` + // names a DPB slot holding one and it is this frame's own true size -- + // `decode_inter_block`'s GOLDEN_FRAME arm refuses when it is `None` or a + // mismatched size (spec 7.9 requires every active reference be a + // compatible size; this decoder's single-slot-per-frame update makes + // that always true for a stream this crate's own encoder writes). + let (golden_y, golden_u, golden_v) = match golden { + Some(g) if g.width == reference.width && g.height == reference.height => ( + Some(PlaneBuf { + data: g.y.clone(), + width: g.width, + height: g.height, + true_width: g.width, + true_height: g.height, + }), + Some(PlaneBuf { + data: g.u.clone(), + width: g.width / 2, + height: g.height / 2, + true_width: g.width / 2, + true_height: g.height / 2, + }), + Some(PlaneBuf { + data: g.v.clone(), + width: g.width / 2, + height: g.height / 2, + true_width: g.width / 2, + true_height: g.height / 2, + }), + ), + _ => (None, None, None), + }; let mut y = PlaneBuf { data: vec![0u8; width * height], @@ -4637,6 +4764,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &ref_y, &ref_u, &ref_v, + golden_y.as_ref(), + golden_u.as_ref(), + golden_v.as_ref(), base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, @@ -4692,6 +4822,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &ref_y, &ref_u, &ref_v, + golden_y.as_ref(), + golden_u.as_ref(), + golden_v.as_ref(), base_q_idx, TxbSet::Luma16, TxbSet::Luma16Inter, @@ -4768,7 +4901,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // into `decode_inter_block8` once a // straddling 8x8 SWITCHABLE stream is on // hand to pin against. - neighbours.record_inter(at16, SUB, skip, is_inter, [3, 3]); + neighbours.record_inter( + at16, + SUB, + skip, + is_inter, + if is_inter { LAST_FRAME } else { -1 }, + [3, 3], + ); } } } @@ -5251,6 +5391,7 @@ mod tests { width as u32, height as u32, &reference, + None, &CdefParams::default(), &LoopFilterParams::default(), false, @@ -5420,6 +5561,9 @@ mod tests { &ref_y, &ref_u, &ref_v, + None, + None, + None, 100, TxbSet::Luma16, TxbSet::Luma16Inter, @@ -5519,6 +5663,7 @@ mod tests { coded_w, coded_h, &reference, + None, &CdefParams::default(), &LoopFilterParams::default(), false, diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index 6a57a4a6..c6f925ec 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -706,6 +706,85 @@ pub(crate) fn single_ref_ctx(has_inter_neighbour: bool) -> usize { if has_inter_neighbour { 2 } else { 1 } } +/// `MV_REFERENCE_FRAME` values a single (non-compound) reference can name +/// (spec 6.10.24's `ref_frame` alphabet; libaom `av1/common/enums.h`). +pub(crate) const LAST_FRAME: i8 = 1; +pub(crate) const LAST2_FRAME: i8 = 2; +pub(crate) const LAST3_FRAME: i8 = 3; +pub(crate) const GOLDEN_FRAME: i8 = 4; +pub(crate) const BWDREF_FRAME: i8 = 5; +pub(crate) const ALTREF2_FRAME: i8 = 6; +pub(crate) const ALTREF_FRAME: i8 = 7; + +/// libaom `pred_common.c`'s shared shape behind every `single_ref_p*`/ +/// `comp_ref*` context function once compound prediction (a second ref per +/// neighbour) is out of scope: count how many of the immediate above/left +/// neighbours (spec 5.11.25's own single-neighbour read, not a whole-span +/// scan -- `av1_collect_neighbors_ref_counts`, `MACROBLOCKD::above_mbmi`/ +/// `left_mbmi`) coded a reference in `a_set` vs. `b_set`, and compare: fewer +/// `a`s than `b`s is context 0, equal is 1 (also every unavailable-neighbour +/// case, both counts zero), more `a`s is 2. +fn ref_ctx(above: Option, left: Option, a_set: &[i8], b_set: &[i8]) -> usize { + let a = [above, left] + .into_iter() + .flatten() + .filter(|r| a_set.contains(r)) + .count(); + let b = [above, left] + .into_iter() + .flatten() + .filter(|r| b_set.contains(r)) + .count(); + match a.cmp(&b) { + std::cmp::Ordering::Less => 0, + std::cmp::Ordering::Equal => 1, + std::cmp::Ordering::Greater => 2, + } +} + +const FORWARD_REFS: [i8; 4] = [LAST_FRAME, LAST2_FRAME, LAST3_FRAME, GOLDEN_FRAME]; +const BACKWARD_REFS: [i8; 3] = [BWDREF_FRAME, ALTREF2_FRAME, ALTREF_FRAME]; + +/// `av1_get_pred_context_single_ref_p1`: forward vs. backward reference. +pub(crate) fn single_ref_p1_ctx(above: Option, left: Option) -> usize { + ref_ctx(above, left, &FORWARD_REFS, &BACKWARD_REFS) +} + +/// `av1_get_pred_context_single_ref_p2` +/// (`get_pred_context_brfarf2_or_arf`): `BWDREF`/`ALTREF2` vs. `ALTREF`. +pub(crate) fn single_ref_p2_ctx(above: Option, left: Option) -> usize { + ref_ctx(above, left, &[BWDREF_FRAME, ALTREF2_FRAME], &[ALTREF_FRAME]) +} + +/// `av1_get_pred_context_single_ref_p3` +/// (`get_pred_context_ll2_or_l3gld`): `LAST`/`LAST2` vs. `LAST3`/`GOLDEN`. +pub(crate) fn single_ref_p3_ctx(above: Option, left: Option) -> usize { + ref_ctx( + above, + left, + &[LAST_FRAME, LAST2_FRAME], + &[LAST3_FRAME, GOLDEN_FRAME], + ) +} + +/// `av1_get_pred_context_single_ref_p4` +/// (`get_pred_context_last_or_last2`): `LAST` vs. `LAST2`. +pub(crate) fn single_ref_p4_ctx(above: Option, left: Option) -> usize { + ref_ctx(above, left, &[LAST_FRAME], &[LAST2_FRAME]) +} + +/// `av1_get_pred_context_single_ref_p5` +/// (`get_pred_context_last3_or_gld`): `LAST3` vs. `GOLDEN`. +pub(crate) fn single_ref_p5_ctx(above: Option, left: Option) -> usize { + ref_ctx(above, left, &[LAST3_FRAME], &[GOLDEN_FRAME]) +} + +/// `av1_get_pred_context_single_ref_p6` +/// (`get_pred_context_brf_or_arf2`): `BWDREF` vs. `ALTREF2`. +pub(crate) fn single_ref_p6_ctx(above: Option, left: Option) -> usize { + ref_ctx(above, left, &[BWDREF_FRAME], &[ALTREF2_FRAME]) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 78472d2e..40985928 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -155,14 +155,33 @@ pub fn decode_stream(data: &[u8]) -> Result> { // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the // zero vector only under `GmType == IDENTITY` -- any other warp // model needs the full affine/translation MV derivation this - // decoder does not carry. `global_motion[0]` is `LAST_FRAME`'s own - // entry (`read_global_motion_params`'s `i` loops from `LAST_FRAME`). + // decoder does not carry. `global_motion` is indexed `ref_frame - 1` + // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`); + // lane-av1refs widens this from `[0]` (LAST_FRAME) alone to every + // reference `decode_inter_block` can now select -- LAST_FRAME (index + // 0) and GOLDEN_FRAME (index 3). if header.frame_type != FrameType::Key - && header.global_motion[0].model != WarpModel::Identity + && (header.global_motion[0].model != WarpModel::Identity + || header.global_motion[3].model != WarpModel::Identity) { return Err(Error::unsupported( "AV1 decode_stream", - "an inter frame whose LAST_FRAME global motion is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)", + "an inter frame whose LAST_FRAME/GOLDEN_FRAME global motion is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)", + )); + } + // `decode_inter_block`'s `single_ref_p*` chain codes only + // `SINGLE_REFERENCE` blocks (never reads `comp_mode`) -- a frame + // whose `reference_select` header bit lets any block choose + // `COMPOUND_REFERENCE` would desync at the first block that reads + // a `comp_mode` symbol this decoder never consumes. `skip_mode` + // (spec 5.9.22) is provably unreachable here as a consequence: its + // own `skip_mode_params()` only sets `skip_mode_present` when + // `reference_select` is set, so refusing `reference_select` refuses + // `skip_mode` too, without needing a second check. + if header.reference_select { + return Err(Error::unsupported( + "AV1 decode_stream", + "a frame with reference_select set (this decoder never reads comp_mode / codes only single-reference blocks)", )); } // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names @@ -236,6 +255,14 @@ pub fn decode_stream(data: &[u8]) -> Result> { "an inter frame with no key frame before it", ) })?; + // `ref_frame_idx[3]` names GOLDEN_FRAME's own DPB slot (spec + // 7.8/7.20 -- `ref_frame_idx` is indexed `ref_frame - LAST_FRAME`). + // Unlike LAST_FRAME, GOLDEN_FRAME having no picture yet is not a + // stream error on its own: `decode_inter_block` only needs it + // when a block actually selects GOLDEN_FRAME, and refuses by + // name there if the slot is still empty. + let golden_slot = header.ref_frame_idx[3] as usize; + let golden = ref_slots.get(golden_slot).and_then(Option::as_ref); decode_inter_frame_tile_with_cdfs( tile_bytes, header.mi_cols, @@ -244,6 +271,7 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.frame_width, header.frame_height, reference, + golden, &header.cdef, &header.loop_filter, initial_cdfs, @@ -1546,16 +1574,16 @@ mod tests { // deterministic header. "--threads=1", "--row-mt=0", - // No `--error-resilient=1` here (that is the whole point of - // this test), but every other reference/compound tool this - // decoder's round-2 inter path does not model is still - // disabled the same way `--error-resilient=1` incidentally - // disabled it in the sibling test above: without - // `--enable-order-hint=0` aomenc's RD search picks a - // non-`LAST_FRAME` reference (`GOLDEN_FRAME`) for some - // blocks even in this short a sequence, which is a separate, - // already-documented round-2 gap ("a reference frame other - // than LAST_FRAME"), not a CDF-forwarding one. + // `--enable-order-hint=0` kills BWDREF/ALTREF entirely (no + // order hints -> no bidirectional distance weighting) and, + // combined with `--auto-alt-ref=0`/`--lag-in-frames=0` + // above, leaves aomenc's RD search only LAST_FRAME/ + // LAST2_FRAME/LAST3_FRAME/GOLDEN_FRAME to pick from -- + // GOLDEN itself needs no order hint (it is the keyframe's + // fixed slot, not a distance-weighted reference), so this + // does not suppress GOLDEN selection the way the sibling + // CDF-forwarding gate's own comment worried about; it just + // narrows the pool this gate needs GOLDEN to win out of. "--enable-order-hint=0", "--enable-warped-motion=0", "--enable-obmc=0", @@ -1639,6 +1667,243 @@ mod tests { ); } + /// lane-av1refs's decisive single-non-LAST-reference gate: identical + /// recipe to + /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`] + /// except `--enable-order-hint=0` is DROPPED (that flag's own comment on + /// the sibling test names it as exactly what suppresses aomenc's RD from + /// ever picking `GOLDEN_FRAME`) and the sequence runs 8 frames, not 4 -- + /// more chances for the RD search to reach past the first GOP's initial + /// key frame. `--auto-alt-ref=0` stays: this decoder only supports + /// `LAST_FRAME`/`GOLDEN_FRAME` so far, and alt-ref/backward references + /// are still a named refusal, not this gate's target. A stream that + /// decodes without firing [`decode::non_last_ref_hits`] is not a + /// coverage win for this round -- SKIP it as a genuine, named miss + /// rather than pass silently on untested ground. + #[test] + fn a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact() { + if !have_ffmpeg() { + eprintln!( + "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no ffmpeg" + ); + return; + } + if !have_aomenc() { + eprintln!( + "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no aomenc at {}", + aomenc_path().display() + ); + return; + } + let (width, height, frame_count) = (64usize, 64usize, 8usize); + let mut refusals = Vec::new(); + let mut never_fired = 0u32; + // aomenc's own RD search is nondeterministic run-to-run even at + // `--threads=1` (confirmed live: identical CLI args, identical + // input, two different output byte streams) -- so beyond varying + // the fixture's seed, each attempt is its own independent coin + // flip against every named refusal below. 120 attempts (not 40) + // to give that coin flip enough tries to land on a stream this + // decoder both accepts and that fires GOLDEN_FRAME. `duration=0.32` + // at `rate=25` (not `0.24`) matches every sibling gate's own + // frame-count fixture exactly -- a shorter duration here once + // produced a frame-0 (keyframe, no reference at all) luma mismatch + // against ffmpeg, i.e. a source-frame-count rounding artifact of + // this recipe's own choosing, not a decoder bug. + for attempt in 0..120u32 { + let seed = 42 + attempt % 40; + let source = format!("gradients=size=64x64:seed={seed}:duration=0.32: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 mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=55", + "--cpu-used=0", + "--lag-in-frames=0", + "--auto-alt-ref=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + // Narrows the RD search's reference alphabet toward + // LAST_FRAME/GOLDEN_FRAME -- without this, aomenc's RD is + // just as likely to pick LAST2/LAST3/BWDREF/ALTREF2/ + // ALTREF (this decoder's already-documented, still-open + // refusals), starving this gate of the one reference it + // targets. + "--max-reference-frames=3", + "--reduced-reference-set=1", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-dist-wtd-comp=0", + "--enable-diff-wtd-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 == max == 32` forces PARTITION_NONE for every + // 32x32 block, not just biases toward it -- with + // `--min-partition-size=16` alone aomenc's exhaustive + // `cpu-used=0` RD search still occasionally read HORZ/ + // VERT/SPLIT partitions below 32x32 despite + // `--enable-rect-partitions=0`/`--enable-ab-partitions=0`/ + // `--enable-1to4-partitions=0` all being off (two + // separate, already-documented round-2 gaps: "a + // partition below 16x16", "a partition type this encoder + // never writes"), starving this gate's already-narrow + // seed pool. Locking both bounds to 32 removes any + // partition-depth choice from the search entirely, so + // this gate can isolate GOLDEN_FRAME selection alone. + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + // `default` still lets aomenc's heuristic flip + // `allow_screen_content_tools` on for this synthetic + // gradient content -- `film` forces the non-screen path + // instead. + "--tune-content=film", + "--obu", + "-o", + "-", + "-", + ]) + .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::non_last_ref_hits(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "a golden-reference stream failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + Ok(frames) => frames, + }; + if decode::non_last_ref_hits() == before { + // This seed's RD search never actually picked GOLDEN_FRAME -- + // a genuine miss, not a refusal. Try the next seed rather + // than claiming coverage this attempt did not exercise. + never_fired += 1; + continue; + } + 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, "frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})"); + } + eprintln!( + "FIRING seed {seed}: non_last_ref_hits advanced by {}", + decode::non_last_ref_hits() - before + ); + return; + } + eprintln!( + "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: \ + {never_fired} attempts decoded but never fired GOLDEN_FRAME, and every other \ + attempt hit a named refusal:\n{}", + refusals.join("\n") + ); + } + + /// scratch: decode a pinned stream end to end and report where/why it + /// refuses, plus `non_last_ref_hits` progression. + #[test] + #[ignore] + fn scratch_decode_pinned_stream() { + let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path"); + let stream = std::fs::read(&path).expect("read pinned stream"); + let before = decode::non_last_ref_hits(); + match decode_stream(&stream) { + Ok(frames) => eprintln!( + "OK: {} frames, non_last_ref_hits {} -> {}", + frames.len(), + before, + decode::non_last_ref_hits() + ), + Err(e) => eprintln!( + "ERR: {} (non_last_ref_hits {} -> {})", + e, + before, + decode::non_last_ref_hits() + ), + } + // Truncate at each Frame OBU boundary and re-decode from scratch, to + // see which frame index first fails. + let mut p = Av1Parser::new(); + let mut pos = 0usize; + let mut frame_idx = 0; + while pos < stream.len() { + let obu = p.parse_obu(&stream[pos..]).expect("parse"); + pos += obu.total_size; + if matches!(obu.kind, ObuKind::Frame(_, _)) { + match decode_stream(&stream[..pos]) { + Ok(_) => eprintln!("through frame {frame_idx}: OK"), + Err(e) => eprintln!("through frame {frame_idx}: ERR {e}"), + } + frame_idx += 1; + } + } + } + /// scratch: isolate a pinned mismatching stream's first divergent pixel. #[test] #[ignore]