diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 90d096da..3b5a2d74 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -32,8 +32,9 @@ use crate::mc; use crate::msac::SymbolDecoder; 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, + MiGrid, MiInfo, NO_SIGN_BIAS, SignBiasTable, find_mv_stack, find_mv_stack_with_sign_bias, + 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}; @@ -117,6 +118,34 @@ pub(crate) fn non_last_ref_hits() -> usize { NON_LAST_REF_HITS.load(std::sync::atomic::Ordering::Relaxed) } +/// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter +/// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one +/// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`) +/// can prove THAT reference fired rather than any non-`LAST_FRAME` one -- +/// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a +/// `GOLDEN_FRAME` draw it did not ask for. +static LAST2_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static LAST3_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static GOLDEN_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static BWDREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static ALTREF2_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static ALTREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`; +/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here). +pub(crate) fn ref_hits(ref_frame: i8) -> usize { + let c = match ref_frame { + LAST2_FRAME => &LAST2_HITS, + LAST3_FRAME => &LAST3_HITS, + GOLDEN_FRAME => &GOLDEN_HITS, + BWDREF_FRAME => &BWDREF_HITS, + ALTREF2_FRAME => &ALTREF2_HITS, + ALTREF_FRAME => &ALTREF_HITS, + other => panic!("ref_hits: no per-reference counter for ref_frame {other}"), + }; + c.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 @@ -1248,6 +1277,14 @@ struct PlaneBuf { true_height: usize, } +/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/ +/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this +/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it +/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already +/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/ +/// `ALTREF2`/`ALTREF`). +type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8]; + impl PlaneBuf { fn edges( &self, @@ -3656,6 +3693,16 @@ fn read_single_ref(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above_ref: i8, left }; if ref_frame != LAST_FRAME { NON_LAST_REF_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let c = match ref_frame { + LAST2_FRAME => &LAST2_HITS, + LAST3_FRAME => &LAST3_HITS, + GOLDEN_FRAME => &GOLDEN_HITS, + BWDREF_FRAME => &BWDREF_HITS, + ALTREF2_FRAME => &ALTREF2_HITS, + ALTREF_FRAME => &ALTREF_HITS, + _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"), + }; + c.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } ref_frame } @@ -3691,18 +3738,14 @@ 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>, + // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own + // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]` + // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME` + // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the + // slot's still empty (an error-resilient stream, or too early in the + // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below. + other_refs: &RefSlots, + sign_bias_table: &SignBiasTable, base_q_idx: u8, luma_set_intra: TxbSet, luma_set_inter: TxbSet, @@ -3737,57 +3780,31 @@ fn decode_inter_block( if is_inter { let ref_frame = read_single_ref(dec, cdfs, neighbours.above_ref[c], neighbours.left_ref[r]); ref_frame_for_lf = ref_frame; - // round 4-8 (lane-av1golden through lane-av1golden6): repeatedly - // un-masked and re-masked chasing what looked like a GOLDEN_FRAME MC - // bug -- lf_level `mode_deltas`/`ref_deltas` forwarding fixes - // (rounds 5/6, both real and kept), and a switchable_interp ctx - // ref-frame gate (round 8, real and kept). Every remaining - // "GOLDEN_FRAME mismatch" chased past round 8 (including a frame-0 - // *intra keyframe* luma mismatch that could not possibly depend on - // this arm at all) turned out to be a single unrelated cause: round - // 9 (lane-av1golden7) traced `fixtures/golden6-mismatch.obu`'s - // frame-0 mismatch down to `header.film_grain.apply_grain == true` - // (aomenc's `--tune-content=film` denoises the coded picture and - // has the decoder re-synthesize grain per spec 7.18.3) -- this - // decoder never implements grain synthesis at all, so it silently - // returned the clean base picture while ffmpeg (dav1d) returned the - // grain-synthesized one. That bug fires on *any* frame, key or - // inter, and is orthogonal to which reference a block selects -- - // the earlier "correlates with GOLDEN firing" pattern was survivor - // bias: the golden gate only ever compared streams where - // `non_last_ref_hits` fired, and `--tune-content=film` is part of - // that same gate's own aomenc recipe. `decode_stream` now refuses - // `apply_grain` streams by name instead of silently mismatching -- - // but unmasking `GOLDEN_FRAME` with that fix in still shows a real, - // separate residual MC bug: round 9 (lane-av1golden7)'s forwarding - // gate hit 1/20 real aomenc streams mismatching (frame 3 luma, - // apply_grain=false, non_last_ref_hits delta=2), pinned in - // `fixtures/golden7-forwarding-mismatch.obu` for round 10. `GOLDEN_FRAME` - // stays refused by name until that's found. - let (py_ref, pu_ref, pv_ref) = match ref_frame { - LAST_FRAME => (ref_y, ref_u, ref_v), - GOLDEN_FRAME => match (golden_y, golden_u, golden_v) { - (Some(gy), Some(gu), Some(gv)) => (gy, gu, gv), - _ => { + // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own + // stacked defects (lf_level ref/mode-delta forwarding, the + // switchable_interp ref-frame ctx gate, and a film-grain synthesis + // gap that looked like a GOLDEN MC bug by survivor bias -- see the + // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs` + // below same as every other non-`LAST_FRAME` reference. lane-av1refs + // widens this from GOLDEN alone to every reference `read_single_ref` + // can name. + let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME { + (ref_y, ref_u, ref_v) + } else { + match other_refs[ref_frame as usize] { + Some((ry, ru, rv)) => (ry, ru, rv), + None => { return Err(unsupported( - "GOLDEN_FRAME selected with no golden picture at this frame's \ - ref_frame_idx[3] slot", + "a reference frame selected with no picture at this frame's own \ + ref_frame_idx slot for it", )); } - }, - _ => { - return Err(unsupported( - "a reference frame other than LAST_FRAME (LAST2/LAST3/GOLDEN/BWDREF/\ - ALTREF2/ALTREF still have no MC path -- GOLDEN's residual MC bug is \ - pinned in fixtures/golden7-forwarding-mismatch.obu, round 9 \ - lane-av1golden7)", - )); } }; let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); let bw4 = side / 4; - let stack = find_mv_stack( + let stack = find_mv_stack_with_sign_bias( grid, mi_row, mi_col, @@ -3796,6 +3813,7 @@ fn decode_inter_block( ref_frame, mi_cols as usize, mi_rows as usize, + sign_bias_table, ); let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; let mut is_globalmv = false; @@ -4615,7 +4633,7 @@ pub fn decode_inter_frame_tile( frame_width: u32, frame_height: u32, reference: &Picture, - golden: Option<&Picture>, + other_refs: [Option<&Picture>; 8], cdef: &CdefParams, loop_filter: &LoopFilterParams, allow_high_precision_mv: bool, @@ -4630,11 +4648,12 @@ pub fn decode_inter_frame_tile( frame_width, frame_height, reference, - golden, + other_refs, cdef, loop_filter, None, allow_high_precision_mv, + NO_SIGN_BIAS, interp_fixed, enable_dual_filter, ) @@ -4654,11 +4673,12 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( frame_width: u32, frame_height: u32, reference: &Picture, - golden: Option<&Picture>, + other_refs: [Option<&Picture>; 8], cdef: &CdefParams, loop_filter: &LoopFilterParams, initial_cdfs: Option, allow_high_precision_mv: bool, + sign_bias_table: SignBiasTable, interp_fixed: Option, enable_dual_filter: bool, ) -> Result<(Picture, Cdfs)> { @@ -4696,38 +4716,44 @@ 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), - }; + // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx` + // names a live DPB slot for (lane-av1refs: generalised from the old + // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal, + // now per-reference). `decode_inter_block` refuses by name when the + // block it is decoding selects an index that is still `None` here + // (spec 7.9 requires every *active* reference be a compatible size; + // an inactive one this frame never selects is simply left `None`). + let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| { + other_refs[i] + .filter(|g| g.width == reference.width && g.height == reference.height) + .map(|g| { + ( + PlaneBuf { + data: g.y.clone(), + width: g.width, + height: g.height, + true_width: g.width, + true_height: g.height, + }, + PlaneBuf { + data: g.u.clone(), + width: g.width / 2, + height: g.height / 2, + true_width: g.width / 2, + true_height: g.height / 2, + }, + PlaneBuf { + data: g.v.clone(), + width: g.width / 2, + height: g.height / 2, + true_width: g.width / 2, + true_height: g.height / 2, + }, + ) + }) + }); + let ref_slots: RefSlots = + std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c))); let mut y = PlaneBuf { data: vec![0u8; width * height], @@ -4830,9 +4856,8 @@ 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(), + &ref_slots, + &sign_bias_table, base_q_idx, TxbSet::Luma32, TxbSet::Luma32Inter, @@ -4888,9 +4913,8 @@ 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(), + &ref_slots, + &sign_bias_table, base_q_idx, TxbSet::Luma16, TxbSet::Luma16Inter, @@ -5457,7 +5481,7 @@ mod tests { width as u32, height as u32, &reference, - None, + [None; 8], &CdefParams::default(), &LoopFilterParams::default(), false, @@ -5627,9 +5651,8 @@ mod tests { &ref_y, &ref_u, &ref_v, - None, - None, - None, + &[None; 8], + &NO_SIGN_BIAS, 100, TxbSet::Luma16, TxbSet::Luma16Inter, @@ -5729,7 +5752,7 @@ mod tests { coded_w, coded_h, &reference, - None, + [None; 8], &CdefParams::default(), &LoopFilterParams::default(), false, diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index eb1113eb..2534f077 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -227,18 +227,30 @@ fn add_candidate(candidates: &mut Vec, mv: (i32, i32), weight: u32) } } -/// Whether `ref_frame`'s prediction runs backward in display order -/// (`cm->ref_frame_sign_bias`, libaom): flips a borrowed neighbour's MV -/// sign in [`process_single_ref_mv_candidate`] when the neighbour's own -/// reference disagrees. This decoder only ever threads forward references -/// (`LAST_FRAME`/`GOLDEN_FRAME`) to MC — never `BWDREF`/`ALTREF` — so every -/// call site compares `false != false` and the flip is always inert. Ported -/// anyway (never proved away, per this round's own bounds): a real -/// backward reference would need this to be correct on day one. -fn sign_bias(_ref_frame: i8) -> bool { - false +/// `cm->ref_frame_sign_bias[ref_frame]`, looked up from the frame header's +/// own `ref_frame_sign_bias` (spec 5.9.2's `get_relative_dist(ref_order_hint, +/// OrderHint) > 0` per active reference, already computed by +/// `ec_av1_syntax::frame::read_uncompressed_header` and indexed exactly like +/// `ref_frame_idx`: `table[ref_frame - LAST_FRAME]`). `find_mv_stack`'s +/// no-sign-bias callers (this crate's own encoder, which only ever writes +/// `LAST_FRAME`) pass an all-`false` table, matching this stub's old +/// always-`false` behaviour exactly. +fn sign_bias(table: &SignBiasTable, ref_frame: i8) -> bool { + table[(ref_frame - LAST_FRAME) as usize] } +/// One `bool` per `MV_REFERENCE_FRAME` past `INTRA_FRAME`/`NONE` +/// (`LAST_FRAME`..=`ALTREF_FRAME`), indexed `[ref_frame - LAST_FRAME]` -- +/// spec `ec_av1_syntax::frame::FrameHeader::ref_frame_sign_bias`'s own +/// shape, threaded straight through. +pub type SignBiasTable = [bool; 7]; + +/// The all-`false` table every no-sign-bias caller (this crate's own +/// encoder, and every test below) passes: correct as long as no candidate +/// or query ever names a backward reference, exactly this module's old +/// hardcoded `sign_bias` stub. +pub const NO_SIGN_BIAS: SignBiasTable = [false; 7]; + /// libaom's `process_single_ref_mv_candidate` (mvref_common.c): folds one /// already-coded neighbour into the stack as a low-weight (`2`, unboosted) /// filler entry, used only by the single-reference extension pass below. @@ -257,13 +269,14 @@ fn sign_bias(_ref_frame: i8) -> bool { fn process_single_ref_mv_candidate( candidate: &MiInfo, ref_frame: i8, + sign_bias_table: &SignBiasTable, candidates: &mut Vec, ) { if !candidate.is_inter { return; } let mut this_mv = candidate.mv; - if sign_bias(candidate.ref_frame) != sign_bias(ref_frame) { + if sign_bias(sign_bias_table, candidate.ref_frame) != sign_bias(sign_bias_table, ref_frame) { this_mv = (-this_mv.0, -this_mv.1); } if !candidates.iter().any(|e| e.mv == this_mv) { @@ -510,6 +523,36 @@ pub fn find_mv_stack( ref_frame: i8, mi_cols: usize, mi_rows: usize, +) -> MvStack { + find_mv_stack_with_sign_bias( + grid, + mi_row, + mi_col, + bw4, + bh4, + ref_frame, + mi_cols, + mi_rows, + &NO_SIGN_BIAS, + ) +} + +/// [`find_mv_stack`], with the frame header's real `ref_frame_sign_bias` +/// (lane-av1refs: `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` are forward +/// in display order, so the single-reference extension pass's borrowed-MV +/// flip is no longer always inert once one of them is live next to a +/// backward-biased neighbour). +#[allow(clippy::too_many_arguments)] +pub fn find_mv_stack_with_sign_bias( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bw4: usize, + bh4: usize, + ref_frame: i8, + mi_cols: usize, + mi_rows: usize, + sign_bias_table: &SignBiasTable, ) -> MvStack { let mut candidates = Vec::new(); let mut newmv_count = 0u32; @@ -703,7 +746,7 @@ pub fn find_mv_stack( let cand = grid.get(mi_row - 1, mi_col + idx); let step = cand.map_or(1, |c| c.size).max(1); if let Some(c) = cand { - process_single_ref_mv_candidate(c, ref_frame, &mut candidates); + process_single_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut candidates); } idx += step; } @@ -714,7 +757,7 @@ pub fn find_mv_stack( let cand = grid.get(mi_row + idx, mi_col - 1); let step = cand.map_or(1, |c| c.size).max(1); if let Some(c) = cand { - process_single_ref_mv_candidate(c, ref_frame, &mut candidates); + process_single_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut candidates); } idx += step; } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index b7a71b66..44ff6a72 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -157,16 +157,17 @@ pub fn decode_stream(data: &[u8]) -> Result> { // model needs the full affine/translation MV derivation this // 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). + // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME) + // to every one of the 7 single-reference slots `decode_inter_block` + // can now select. if header.frame_type != FrameType::Key - && (header.global_motion[0].model != WarpModel::Identity - || header.global_motion[3].model != WarpModel::Identity) + && header.global_motion[..7] + .iter() + .any(|gm| gm.model != WarpModel::Identity) { return Err(Error::unsupported( "AV1 decode_stream", - "an inter frame whose LAST_FRAME/GOLDEN_FRAME global motion is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)", + "an inter frame whose global motion for a single-reference frame is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)", )); } // `decode_inter_block`'s `single_ref_p*` chain codes only @@ -255,14 +256,22 @@ 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); + // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i` + // (spec 7.8/7.20). Any of them having no picture yet is not a + // stream error on its own: `decode_inter_block` only needs a + // given slot when a block actually selects that reference, and + // refuses by name there if the slot is still empty -- widened + // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every + // one of the 7 single-reference slots. + let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| { + if ref_frame == 0 { + None + } else { + ref_slots + .get(header.ref_frame_idx[ref_frame - 1] as usize) + .and_then(Option::as_ref) + } + }); decode_inter_frame_tile_with_cdfs( tile_bytes, header.mi_cols, @@ -271,11 +280,12 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.frame_width, header.frame_height, reference, - golden, + other_refs, &header.cdef, &header.loop_filter, initial_cdfs, header.allow_high_precision_mv, + header.ref_frame_sign_bias, interp_fixed, enable_dual_filter, )? @@ -2156,6 +2166,284 @@ mod tests { ); } + /// lane-av1refs's decisive gate for the 5 references widened past + /// `LAST_FRAME`/`GOLDEN_FRAME`: same envelope and pin-on-mismatch + /// pattern as + /// [`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`], + /// generalised over `(target_ref, extra_args, frame_count)` so each of + /// `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` gets its own attempt pool + /// and its own proof that `decode::ref_hits(target_ref)` -- not just + /// `non_last_ref_hits`, which cannot distinguish one reference from + /// another -- actually advanced. `--max-reference-frames=3 + /// --reduced-reference-set=1` (the golden gate's own narrowing) is + /// DROPPED here: both suppress exactly the references this gate needs + /// aomenc's RD to reach. + fn a_real_aomenc_single_ref_gate( + gate_name: &str, + target_ref: i8, + target_ref_name: &str, + extra_args: &[&str], + width: usize, + height: usize, + frame_count: usize, + attempts: u32, + ) { + if !have_ffmpeg() { + eprintln!("SKIP {gate_name}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display()); + return; + } + let mut refusals = Vec::new(); + let mut never_fired = 0u32; + for attempt in 0..attempts { + 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 mut args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=55", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--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", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + // use_ref_frame_mvs (temporal MV projection) is unimplemented in + // mvstack; leaving it on silently desyncs symbols on inter frames. + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]; + // extra_args goes right before the trailing "-o", "-", "-" triple. + let tail = args.split_off(args.len() - 3); + args.extend_from_slice(extra_args); + args.extend_from_slice(&tail); + 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::ref_hits(target_ref); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{gate_name} failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + Ok(frames) => frames, + }; + if decode::ref_hits(target_ref) == 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, + "{gate_name} frame {i} luma vs ffmpeg (seed {seed})" + ); + assert_eq!( + got.u, want.u, + "{gate_name} frame {i} U vs ffmpeg (seed {seed})" + ); + assert_eq!( + got.v, want.v, + "{gate_name} frame {i} V vs ffmpeg (seed {seed})" + ); + } + eprintln!( + "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}", + decode::ref_hits(target_ref) - before + ); + return; + } + eprintln!( + "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \ + and every other attempt hit a named refusal:\n{}", + refusals.join("\n") + ); + } + + /// `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 + /// --reduced-reference-set=1` narrowing (which suppresses exactly these) + /// and running long enough for aomenc's own buffer rotation to reach + /// past the first 2 frames is the whole difference. + #[test] + fn a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact() { + a_real_aomenc_single_ref_gate( + "a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact", + crate::mvstack::LAST2_FRAME, + "LAST2_FRAME", + &["--auto-alt-ref=0", "--lag-in-frames=0"], + 64, + 64, + 8, + 120, + ); + } + + #[test] + fn a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact() { + a_real_aomenc_single_ref_gate( + "a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact", + crate::mvstack::LAST3_FRAME, + "LAST3_FRAME", + &["--auto-alt-ref=0", "--lag-in-frames=0"], + 64, + 64, + 8, + 120, + ); + } + + /// `BWDREF`/`ALTREF2`/`ALTREF` are all backward (display-order-forward) + /// references that only exist once aomenc builds a hierarchical GOP -- + /// `--auto-alt-ref=1 --lag-in-frames` (need at least one full mini-GOP + /// of lookahead) is what makes aomenc code them at all; without it + /// every attempt would hit this decoder's own real, still-open + /// per-block sign-bias gap by never drawing the reference in the first + /// place, not by proving it correct. + #[test] + fn a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact() { + a_real_aomenc_single_ref_gate( + "a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact", + crate::mvstack::BWDREF_FRAME, + "BWDREF_FRAME", + &[ + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + ], + 64, + 64, + 16, + 120, + ); + } + + #[test] + fn a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact() { + a_real_aomenc_single_ref_gate( + "a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact", + crate::mvstack::ALTREF2_FRAME, + "ALTREF2_FRAME", + &[ + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + ], + 64, + 64, + 16, + 120, + ); + } + + #[test] + fn a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact() { + a_real_aomenc_single_ref_gate( + "a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact", + crate::mvstack::ALTREF_FRAME, + "ALTREF_FRAME", + &[ + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + ], + 64, + 64, + 16, + 120, + ); + } + /// scratch: decode a pinned stream end to end and report where/why it /// refuses, plus `non_last_ref_hits` progression. #[test]