forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1refs'

Browse files at this commit

2bcbc811592503ba913915ffe78d62da73bd0206Ahmet Kaan GümüşParent: eb24ce51719c8e
crates/ec-av1/src/decode.rsmodified+126 -103
@@ -32,8 +32,9 @@ use crate::mc;
3232 use crate::msac::SymbolDecoder;
3333 use crate::mvstack::{
3434 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
35- MiGrid, MiInfo, find_mv_stack, single_ref_ctx, single_ref_p1_ctx, single_ref_p2_ctx,
36- single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
35+ MiGrid, MiInfo, NO_SIGN_BIAS, SignBiasTable, find_mv_stack, find_mv_stack_with_sign_bias,
36+ single_ref_ctx, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
37+ single_ref_p5_ctx, single_ref_p6_ctx,
3738 };
3839 use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
3940 use crate::transform::{TxType, dequant_and_inverse_typed};
@@ -117,6 +118,34 @@ pub(crate) fn non_last_ref_hits() -> usize {
117118 NON_LAST_REF_HITS.load(std::sync::atomic::Ordering::Relaxed)
118119 }
119120
121+/// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
122+/// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
123+/// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
124+/// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
125+/// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
126+/// `GOLDEN_FRAME` draw it did not ask for.
127+static LAST2_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
128+static LAST3_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
129+static GOLDEN_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
130+static BWDREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
131+static ALTREF2_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
132+static ALTREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
133+
134+/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
135+/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
136+pub(crate) fn ref_hits(ref_frame: i8) -> usize {
137+ let c = match ref_frame {
138+ LAST2_FRAME => &LAST2_HITS,
139+ LAST3_FRAME => &LAST3_HITS,
140+ GOLDEN_FRAME => &GOLDEN_HITS,
141+ BWDREF_FRAME => &BWDREF_HITS,
142+ ALTREF2_FRAME => &ALTREF2_HITS,
143+ ALTREF_FRAME => &ALTREF_HITS,
144+ other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
145+ };
146+ c.load(std::sync::atomic::Ordering::Relaxed)
147+}
148+
120149 thread_local! {
121150 /// The sequence header's `enable_intra_edge_filter`, set once per
122151 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
@@ -1248,6 +1277,14 @@ struct PlaneBuf {
12481277 true_height: usize,
12491278 }
12501279
1280+/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
1281+/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
1282+/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
1283+/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
1284+/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
1285+/// `ALTREF2`/`ALTREF`).
1286+type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
1287+
12511288 impl PlaneBuf {
12521289 fn edges(
12531290 &self,
@@ -3656,6 +3693,16 @@ fn read_single_ref(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above_ref: i8, left
36563693 };
36573694 if ref_frame != LAST_FRAME {
36583695 NON_LAST_REF_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3696+ let c = match ref_frame {
3697+ LAST2_FRAME => &LAST2_HITS,
3698+ LAST3_FRAME => &LAST3_HITS,
3699+ GOLDEN_FRAME => &GOLDEN_HITS,
3700+ BWDREF_FRAME => &BWDREF_HITS,
3701+ ALTREF2_FRAME => &ALTREF2_HITS,
3702+ ALTREF_FRAME => &ALTREF_HITS,
3703+ _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
3704+ };
3705+ c.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
36593706 }
36603707 ref_frame
36613708 }
@@ -3691,18 +3738,14 @@ fn decode_inter_block(
36913738 ref_y: &PlaneBuf,
36923739 ref_u: &PlaneBuf,
36933740 ref_v: &PlaneBuf,
3694- // corner-cut (lane-av1refs r1): only `LAST_FRAME` (`ref_y`/`u`/`v`) and
3695- // `GOLDEN_FRAME` (`golden_*`, when the frame header's own
3696- // `ref_frame_idx` names a slot with a picture) are threaded down to MC.
3697- // Ceiling: `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` still refuse by
3698- // name -- real short low-lag streams overwhelmingly pick `LAST` or
3699- // `GOLDEN` (the ledger's cdffwd trace). Upgrade path: widen `golden_*`
3700- // into a `[Option<&PlaneBuf>; REFS_PER_FRAME]` addressed by the decoded
3701- // reference, same as the CDF/picture DPB slots `decode_stream` already
3702- // keeps.
3703- golden_y: Option<&PlaneBuf>,
3704- golden_u: Option<&PlaneBuf>,
3705- golden_v: Option<&PlaneBuf>,
3741+ // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
3742+ // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
3743+ // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
3744+ // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
3745+ // slot's still empty (an error-resilient stream, or too early in the
3746+ // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
3747+ other_refs: &RefSlots,
3748+ sign_bias_table: &SignBiasTable,
37063749 base_q_idx: u8,
37073750 luma_set_intra: TxbSet,
37083751 luma_set_inter: TxbSet,
@@ -3737,57 +3780,31 @@ fn decode_inter_block(
37373780 if is_inter {
37383781 let ref_frame = read_single_ref(dec, cdfs, neighbours.above_ref[c], neighbours.left_ref[r]);
37393782 ref_frame_for_lf = ref_frame;
3740- // round 4-8 (lane-av1golden through lane-av1golden6): repeatedly
3741- // un-masked and re-masked chasing what looked like a GOLDEN_FRAME MC
3742- // bug -- lf_level `mode_deltas`/`ref_deltas` forwarding fixes
3743- // (rounds 5/6, both real and kept), and a switchable_interp ctx
3744- // ref-frame gate (round 8, real and kept). Every remaining
3745- // "GOLDEN_FRAME mismatch" chased past round 8 (including a frame-0
3746- // *intra keyframe* luma mismatch that could not possibly depend on
3747- // this arm at all) turned out to be a single unrelated cause: round
3748- // 9 (lane-av1golden7) traced `fixtures/golden6-mismatch.obu`'s
3749- // frame-0 mismatch down to `header.film_grain.apply_grain == true`
3750- // (aomenc's `--tune-content=film` denoises the coded picture and
3751- // has the decoder re-synthesize grain per spec 7.18.3) -- this
3752- // decoder never implements grain synthesis at all, so it silently
3753- // returned the clean base picture while ffmpeg (dav1d) returned the
3754- // grain-synthesized one. That bug fires on *any* frame, key or
3755- // inter, and is orthogonal to which reference a block selects --
3756- // the earlier "correlates with GOLDEN firing" pattern was survivor
3757- // bias: the golden gate only ever compared streams where
3758- // `non_last_ref_hits` fired, and `--tune-content=film` is part of
3759- // that same gate's own aomenc recipe. `decode_stream` now refuses
3760- // `apply_grain` streams by name instead of silently mismatching --
3761- // but unmasking `GOLDEN_FRAME` with that fix in still shows a real,
3762- // separate residual MC bug: round 9 (lane-av1golden7)'s forwarding
3763- // gate hit 1/20 real aomenc streams mismatching (frame 3 luma,
3764- // apply_grain=false, non_last_ref_hits delta=2), pinned in
3765- // `fixtures/golden7-forwarding-mismatch.obu` for round 10. `GOLDEN_FRAME`
3766- // stays refused by name until that's found.
3767- let (py_ref, pu_ref, pv_ref) = match ref_frame {
3768- LAST_FRAME => (ref_y, ref_u, ref_v),
3769- GOLDEN_FRAME => match (golden_y, golden_u, golden_v) {
3770- (Some(gy), Some(gu), Some(gv)) => (gy, gu, gv),
3771- _ => {
3783+ // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
3784+ // stacked defects (lf_level ref/mode-delta forwarding, the
3785+ // switchable_interp ref-frame ctx gate, and a film-grain synthesis
3786+ // gap that looked like a GOLDEN MC bug by survivor bias -- see the
3787+ // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
3788+ // below same as every other non-`LAST_FRAME` reference. lane-av1refs
3789+ // widens this from GOLDEN alone to every reference `read_single_ref`
3790+ // can name.
3791+ let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
3792+ (ref_y, ref_u, ref_v)
3793+ } else {
3794+ match other_refs[ref_frame as usize] {
3795+ Some((ry, ru, rv)) => (ry, ru, rv),
3796+ None => {
37723797 return Err(unsupported(
3773- "GOLDEN_FRAME selected with no golden picture at this frame's \
3774- ref_frame_idx[3] slot",
3798+ "a reference frame selected with no picture at this frame's own \
3799+ ref_frame_idx slot for it",
37753800 ));
37763801 }
3777- },
3778- _ => {
3779- return Err(unsupported(
3780- "a reference frame other than LAST_FRAME (LAST2/LAST3/GOLDEN/BWDREF/\
3781- ALTREF2/ALTREF still have no MC path -- GOLDEN's residual MC bug is \
3782- pinned in fixtures/golden7-forwarding-mismatch.obu, round 9 \
3783- lane-av1golden7)",
3784- ));
37853802 }
37863803 };
37873804
37883805 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
37893806 let bw4 = side / 4;
3790- let stack = find_mv_stack(
3807+ let stack = find_mv_stack_with_sign_bias(
37913808 grid,
37923809 mi_row,
37933810 mi_col,
@@ -3796,6 +3813,7 @@ fn decode_inter_block(
37963813 ref_frame,
37973814 mi_cols as usize,
37983815 mi_rows as usize,
3816+ sign_bias_table,
37993817 );
38003818 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
38013819 let mut is_globalmv = false;
@@ -4615,7 +4633,7 @@ pub fn decode_inter_frame_tile(
46154633 frame_width: u32,
46164634 frame_height: u32,
46174635 reference: &Picture,
4618- golden: Option<&Picture>,
4636+ other_refs: [Option<&Picture>; 8],
46194637 cdef: &CdefParams,
46204638 loop_filter: &LoopFilterParams,
46214639 allow_high_precision_mv: bool,
@@ -4630,11 +4648,12 @@ pub fn decode_inter_frame_tile(
46304648 frame_width,
46314649 frame_height,
46324650 reference,
4633- golden,
4651+ other_refs,
46344652 cdef,
46354653 loop_filter,
46364654 None,
46374655 allow_high_precision_mv,
4656+ NO_SIGN_BIAS,
46384657 interp_fixed,
46394658 enable_dual_filter,
46404659 )
@@ -4654,11 +4673,12 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
46544673 frame_width: u32,
46554674 frame_height: u32,
46564675 reference: &Picture,
4657- golden: Option<&Picture>,
4676+ other_refs: [Option<&Picture>; 8],
46584677 cdef: &CdefParams,
46594678 loop_filter: &LoopFilterParams,
46604679 initial_cdfs: Option<Cdfs>,
46614680 allow_high_precision_mv: bool,
4681+ sign_bias_table: SignBiasTable,
46624682 interp_fixed: Option<mc::InterpFilterKind>,
46634683 enable_dual_filter: bool,
46644684 ) -> Result<(Picture, Cdfs)> {
@@ -4696,38 +4716,44 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
46964716 true_width: reference.width / 2,
46974717 true_height: reference.height / 2,
46984718 };
4699- // `GOLDEN_FRAME`'s own picture, when the frame header's `ref_frame_idx`
4700- // names a DPB slot holding one and it is this frame's own true size --
4701- // `decode_inter_block`'s GOLDEN_FRAME arm refuses when it is `None` or a
4702- // mismatched size (spec 7.9 requires every active reference be a
4703- // compatible size; this decoder's single-slot-per-frame update makes
4704- // that always true for a stream this crate's own encoder writes).
4705- let (golden_y, golden_u, golden_v) = match golden {
4706- Some(g) if g.width == reference.width && g.height == reference.height => (
4707- Some(PlaneBuf {
4708- data: g.y.clone(),
4709- width: g.width,
4710- height: g.height,
4711- true_width: g.width,
4712- true_height: g.height,
4713- }),
4714- Some(PlaneBuf {
4715- data: g.u.clone(),
4716- width: g.width / 2,
4717- height: g.height / 2,
4718- true_width: g.width / 2,
4719- true_height: g.height / 2,
4720- }),
4721- Some(PlaneBuf {
4722- data: g.v.clone(),
4723- width: g.width / 2,
4724- height: g.height / 2,
4725- true_width: g.width / 2,
4726- true_height: g.height / 2,
4727- }),
4728- ),
4729- _ => (None, None, None),
4730- };
4719+ // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
4720+ // names a live DPB slot for (lane-av1refs: generalised from the old
4721+ // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
4722+ // now per-reference). `decode_inter_block` refuses by name when the
4723+ // block it is decoding selects an index that is still `None` here
4724+ // (spec 7.9 requires every *active* reference be a compatible size;
4725+ // an inactive one this frame never selects is simply left `None`).
4726+ let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
4727+ other_refs[i]
4728+ .filter(|g| g.width == reference.width && g.height == reference.height)
4729+ .map(|g| {
4730+ (
4731+ PlaneBuf {
4732+ data: g.y.clone(),
4733+ width: g.width,
4734+ height: g.height,
4735+ true_width: g.width,
4736+ true_height: g.height,
4737+ },
4738+ PlaneBuf {
4739+ data: g.u.clone(),
4740+ width: g.width / 2,
4741+ height: g.height / 2,
4742+ true_width: g.width / 2,
4743+ true_height: g.height / 2,
4744+ },
4745+ PlaneBuf {
4746+ data: g.v.clone(),
4747+ width: g.width / 2,
4748+ height: g.height / 2,
4749+ true_width: g.width / 2,
4750+ true_height: g.height / 2,
4751+ },
4752+ )
4753+ })
4754+ });
4755+ let ref_slots: RefSlots =
4756+ std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
47314757
47324758 let mut y = PlaneBuf {
47334759 data: vec![0u8; width * height],
@@ -4830,9 +4856,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
48304856 &ref_y,
48314857 &ref_u,
48324858 &ref_v,
4833- golden_y.as_ref(),
4834- golden_u.as_ref(),
4835- golden_v.as_ref(),
4859+ &ref_slots,
4860+ &sign_bias_table,
48364861 base_q_idx,
48374862 TxbSet::Luma32,
48384863 TxbSet::Luma32Inter,
@@ -4888,9 +4913,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
48884913 &ref_y,
48894914 &ref_u,
48904915 &ref_v,
4891- golden_y.as_ref(),
4892- golden_u.as_ref(),
4893- golden_v.as_ref(),
4916+ &ref_slots,
4917+ &sign_bias_table,
48944918 base_q_idx,
48954919 TxbSet::Luma16,
48964920 TxbSet::Luma16Inter,
@@ -5457,7 +5481,7 @@ mod tests {
54575481 width as u32,
54585482 height as u32,
54595483 &reference,
5460- None,
5484+ [None; 8],
54615485 &CdefParams::default(),
54625486 &LoopFilterParams::default(),
54635487 false,
@@ -5627,9 +5651,8 @@ mod tests {
56275651 &ref_y,
56285652 &ref_u,
56295653 &ref_v,
5630- None,
5631- None,
5632- None,
5654+ &[None; 8],
5655+ &NO_SIGN_BIAS,
56335656 100,
56345657 TxbSet::Luma16,
56355658 TxbSet::Luma16Inter,
@@ -5729,7 +5752,7 @@ mod tests {
57295752 coded_w,
57305753 coded_h,
57315754 &reference,
5732- None,
5755+ [None; 8],
57335756 &CdefParams::default(),
57345757 &LoopFilterParams::default(),
57355758 false,
crates/ec-av1/src/mvstack.rsmodified+56 -13
@@ -227,18 +227,30 @@ fn add_candidate(candidates: &mut Vec<StackEntry>, mv: (i32, i32), weight: u32)
227227 }
228228 }
229229
230-/// Whether `ref_frame`'s prediction runs backward in display order
231-/// (`cm->ref_frame_sign_bias`, libaom): flips a borrowed neighbour's MV
232-/// sign in [`process_single_ref_mv_candidate`] when the neighbour's own
233-/// reference disagrees. This decoder only ever threads forward references
234-/// (`LAST_FRAME`/`GOLDEN_FRAME`) to MC — never `BWDREF`/`ALTREF` — so every
235-/// call site compares `false != false` and the flip is always inert. Ported
236-/// anyway (never proved away, per this round's own bounds): a real
237-/// backward reference would need this to be correct on day one.
238-fn sign_bias(_ref_frame: i8) -> bool {
239- false
230+/// `cm->ref_frame_sign_bias[ref_frame]`, looked up from the frame header's
231+/// own `ref_frame_sign_bias` (spec 5.9.2's `get_relative_dist(ref_order_hint,
232+/// OrderHint) > 0` per active reference, already computed by
233+/// `ec_av1_syntax::frame::read_uncompressed_header` and indexed exactly like
234+/// `ref_frame_idx`: `table[ref_frame - LAST_FRAME]`). `find_mv_stack`'s
235+/// no-sign-bias callers (this crate's own encoder, which only ever writes
236+/// `LAST_FRAME`) pass an all-`false` table, matching this stub's old
237+/// always-`false` behaviour exactly.
238+fn sign_bias(table: &SignBiasTable, ref_frame: i8) -> bool {
239+ table[(ref_frame - LAST_FRAME) as usize]
240240 }
241241
242+/// One `bool` per `MV_REFERENCE_FRAME` past `INTRA_FRAME`/`NONE`
243+/// (`LAST_FRAME`..=`ALTREF_FRAME`), indexed `[ref_frame - LAST_FRAME]` --
244+/// spec `ec_av1_syntax::frame::FrameHeader::ref_frame_sign_bias`'s own
245+/// shape, threaded straight through.
246+pub type SignBiasTable = [bool; 7];
247+
248+/// The all-`false` table every no-sign-bias caller (this crate's own
249+/// encoder, and every test below) passes: correct as long as no candidate
250+/// or query ever names a backward reference, exactly this module's old
251+/// hardcoded `sign_bias` stub.
252+pub const NO_SIGN_BIAS: SignBiasTable = [false; 7];
253+
242254 /// libaom's `process_single_ref_mv_candidate` (mvref_common.c): folds one
243255 /// already-coded neighbour into the stack as a low-weight (`2`, unboosted)
244256 /// filler entry, used only by the single-reference extension pass below.
@@ -257,13 +269,14 @@ fn sign_bias(_ref_frame: i8) -> bool {
257269 fn process_single_ref_mv_candidate(
258270 candidate: &MiInfo,
259271 ref_frame: i8,
272+ sign_bias_table: &SignBiasTable,
260273 candidates: &mut Vec<StackEntry>,
261274 ) {
262275 if !candidate.is_inter {
263276 return;
264277 }
265278 let mut this_mv = candidate.mv;
266- if sign_bias(candidate.ref_frame) != sign_bias(ref_frame) {
279+ if sign_bias(sign_bias_table, candidate.ref_frame) != sign_bias(sign_bias_table, ref_frame) {
267280 this_mv = (-this_mv.0, -this_mv.1);
268281 }
269282 if !candidates.iter().any(|e| e.mv == this_mv) {
@@ -510,6 +523,36 @@ pub fn find_mv_stack(
510523 ref_frame: i8,
511524 mi_cols: usize,
512525 mi_rows: usize,
526+) -> MvStack {
527+ find_mv_stack_with_sign_bias(
528+ grid,
529+ mi_row,
530+ mi_col,
531+ bw4,
532+ bh4,
533+ ref_frame,
534+ mi_cols,
535+ mi_rows,
536+ &NO_SIGN_BIAS,
537+ )
538+}
539+
540+/// [`find_mv_stack`], with the frame header's real `ref_frame_sign_bias`
541+/// (lane-av1refs: `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` are forward
542+/// in display order, so the single-reference extension pass's borrowed-MV
543+/// flip is no longer always inert once one of them is live next to a
544+/// backward-biased neighbour).
545+#[allow(clippy::too_many_arguments)]
546+pub fn find_mv_stack_with_sign_bias(
547+ grid: &MiGrid,
548+ mi_row: usize,
549+ mi_col: usize,
550+ bw4: usize,
551+ bh4: usize,
552+ ref_frame: i8,
553+ mi_cols: usize,
554+ mi_rows: usize,
555+ sign_bias_table: &SignBiasTable,
513556 ) -> MvStack {
514557 let mut candidates = Vec::new();
515558 let mut newmv_count = 0u32;
@@ -703,7 +746,7 @@ pub fn find_mv_stack(
703746 let cand = grid.get(mi_row - 1, mi_col + idx);
704747 let step = cand.map_or(1, |c| c.size).max(1);
705748 if let Some(c) = cand {
706- process_single_ref_mv_candidate(c, ref_frame, &mut candidates);
749+ process_single_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut candidates);
707750 }
708751 idx += step;
709752 }
@@ -714,7 +757,7 @@ pub fn find_mv_stack(
714757 let cand = grid.get(mi_row + idx, mi_col - 1);
715758 let step = cand.map_or(1, |c| c.size).max(1);
716759 if let Some(c) = cand {
717- process_single_ref_mv_candidate(c, ref_frame, &mut candidates);
760+ process_single_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut candidates);
718761 }
719762 idx += step;
720763 }
crates/ec-av1/src/stream.rsmodified+303 -15
@@ -157,16 +157,17 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
157157 // model needs the full affine/translation MV derivation this
158158 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
159159 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
160- // lane-av1refs widens this from `[0]` (LAST_FRAME) alone to every
161- // reference `decode_inter_block` can now select -- LAST_FRAME (index
162- // 0) and GOLDEN_FRAME (index 3).
160+ // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
161+ // to every one of the 7 single-reference slots `decode_inter_block`
162+ // can now select.
163163 if header.frame_type != FrameType::Key
164- && (header.global_motion[0].model != WarpModel::Identity
165- || header.global_motion[3].model != WarpModel::Identity)
164+ && header.global_motion[..7]
165+ .iter()
166+ .any(|gm| gm.model != WarpModel::Identity)
166167 {
167168 return Err(Error::unsupported(
168169 "AV1 decode_stream",
169- "an inter frame whose LAST_FRAME/GOLDEN_FRAME global motion is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)",
170+ "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)",
170171 ));
171172 }
172173 // `decode_inter_block`'s `single_ref_p*` chain codes only
@@ -255,14 +256,22 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
255256 "an inter frame with no key frame before it",
256257 )
257258 })?;
258- // `ref_frame_idx[3]` names GOLDEN_FRAME's own DPB slot (spec
259- // 7.8/7.20 -- `ref_frame_idx` is indexed `ref_frame - LAST_FRAME`).
260- // Unlike LAST_FRAME, GOLDEN_FRAME having no picture yet is not a
261- // stream error on its own: `decode_inter_block` only needs it
262- // when a block actually selects GOLDEN_FRAME, and refuses by
263- // name there if the slot is still empty.
264- let golden_slot = header.ref_frame_idx[3] as usize;
265- let golden = ref_slots.get(golden_slot).and_then(Option::as_ref);
259+ // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
260+ // (spec 7.8/7.20). Any of them having no picture yet is not a
261+ // stream error on its own: `decode_inter_block` only needs a
262+ // given slot when a block actually selects that reference, and
263+ // refuses by name there if the slot is still empty -- widened
264+ // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
265+ // one of the 7 single-reference slots.
266+ let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| {
267+ if ref_frame == 0 {
268+ None
269+ } else {
270+ ref_slots
271+ .get(header.ref_frame_idx[ref_frame - 1] as usize)
272+ .and_then(Option::as_ref)
273+ }
274+ });
266275 decode_inter_frame_tile_with_cdfs(
267276 tile_bytes,
268277 header.mi_cols,
@@ -271,11 +280,12 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
271280 header.frame_width,
272281 header.frame_height,
273282 reference,
274- golden,
283+ other_refs,
275284 &header.cdef,
276285 &header.loop_filter,
277286 initial_cdfs,
278287 header.allow_high_precision_mv,
288+ header.ref_frame_sign_bias,
279289 interp_fixed,
280290 enable_dual_filter,
281291 )?
@@ -2156,6 +2166,284 @@ mod tests {
21562166 );
21572167 }
21582168
2169+ /// lane-av1refs's decisive gate for the 5 references widened past
2170+ /// `LAST_FRAME`/`GOLDEN_FRAME`: same envelope and pin-on-mismatch
2171+ /// pattern as
2172+ /// [`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`],
2173+ /// generalised over `(target_ref, extra_args, frame_count)` so each of
2174+ /// `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` gets its own attempt pool
2175+ /// and its own proof that `decode::ref_hits(target_ref)` -- not just
2176+ /// `non_last_ref_hits`, which cannot distinguish one reference from
2177+ /// another -- actually advanced. `--max-reference-frames=3
2178+ /// --reduced-reference-set=1` (the golden gate's own narrowing) is
2179+ /// DROPPED here: both suppress exactly the references this gate needs
2180+ /// aomenc's RD to reach.
2181+ fn a_real_aomenc_single_ref_gate(
2182+ gate_name: &str,
2183+ target_ref: i8,
2184+ target_ref_name: &str,
2185+ extra_args: &[&str],
2186+ width: usize,
2187+ height: usize,
2188+ frame_count: usize,
2189+ attempts: u32,
2190+ ) {
2191+ if !have_ffmpeg() {
2192+ eprintln!("SKIP {gate_name}: no ffmpeg");
2193+ return;
2194+ }
2195+ if !have_aomenc() {
2196+ eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
2197+ return;
2198+ }
2199+ let mut refusals = Vec::new();
2200+ let mut never_fired = 0u32;
2201+ for attempt in 0..attempts {
2202+ let seed = 42 + attempt % 40;
2203+ let duration = frame_count as f64 / 25.0;
2204+ let source =
2205+ format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25");
2206+ let y4m = Command::new("ffmpeg")
2207+ .args([
2208+ "-v",
2209+ "error",
2210+ "-f",
2211+ "lavfi",
2212+ "-i",
2213+ &source,
2214+ "-pix_fmt",
2215+ "yuv420p",
2216+ "-f",
2217+ "yuv4mpegpipe",
2218+ "-",
2219+ ])
2220+ .stdin(Stdio::null())
2221+ .stdout(Stdio::piped())
2222+ .stderr(Stdio::piped())
2223+ .output()
2224+ .expect("ffmpeg failed to run");
2225+ assert!(
2226+ y4m.status.success(),
2227+ "ffmpeg fixture: {}",
2228+ String::from_utf8_lossy(&y4m.stderr)
2229+ );
2230+ let mut args: Vec<&str> = vec![
2231+ "--codec=av1",
2232+ "--passes=1",
2233+ "--end-usage=q",
2234+ "--cq-level=55",
2235+ "--cpu-used=0",
2236+ "--kf-max-dist=1000",
2237+ "--threads=1",
2238+ "--row-mt=0",
2239+ "--enable-warped-motion=0",
2240+ "--enable-obmc=0",
2241+ "--enable-masked-comp=0",
2242+ "--enable-interintra-comp=0",
2243+ "--enable-dist-wtd-comp=0",
2244+ "--enable-diff-wtd-comp=0",
2245+ "--enable-onesided-comp=0",
2246+ "--enable-interintra-wedge=0",
2247+ "--enable-smooth-interintra=0",
2248+ "--enable-rect-partitions=0",
2249+ "--enable-ab-partitions=0",
2250+ "--enable-1to4-partitions=0",
2251+ "--enable-filter-intra=0",
2252+ "--enable-smooth-intra=0",
2253+ "--enable-paeth-intra=0",
2254+ "--enable-directional-intra=0",
2255+ "--enable-angle-delta=0",
2256+ "--enable-tx-size-search=0",
2257+ "--enable-cdef=0",
2258+ "--enable-restoration=0",
2259+ "--max-partition-size=32",
2260+ "--min-partition-size=32",
2261+ "--enable-palette=0",
2262+ "--enable-intrabc=0",
2263+ "--enable-cfl-intra=0",
2264+ // use_ref_frame_mvs (temporal MV projection) is unimplemented in
2265+ // mvstack; leaving it on silently desyncs symbols on inter frames.
2266+ "--enable-ref-frame-mvs=0",
2267+ "--obu",
2268+ "-o",
2269+ "-",
2270+ "-",
2271+ ];
2272+ // extra_args goes right before the trailing "-o", "-", "-" triple.
2273+ let tail = args.split_off(args.len() - 3);
2274+ args.extend_from_slice(extra_args);
2275+ args.extend_from_slice(&tail);
2276+ let mut child = Command::new(aomenc_path())
2277+ .args(&args)
2278+ .stdin(Stdio::piped())
2279+ .stdout(Stdio::piped())
2280+ .stderr(Stdio::piped())
2281+ .spawn()
2282+ .expect("aomenc failed to start");
2283+ child
2284+ .stdin
2285+ .take()
2286+ .expect("aomenc stdin")
2287+ .write_all(&y4m.stdout)
2288+ .expect("writing y4m to aomenc");
2289+ let out = child.wait_with_output().expect("aomenc failed to run");
2290+ assert!(
2291+ out.status.success(),
2292+ "aomenc refused the fixture: {}",
2293+ String::from_utf8_lossy(&out.stderr)
2294+ );
2295+ let stream = out.stdout;
2296+ let before = decode::ref_hits(target_ref);
2297+ let frames = match decode_stream(&stream) {
2298+ Err(e) => {
2299+ let msg = e.to_string();
2300+ assert!(
2301+ msg.contains("unsupported"),
2302+ "{gate_name} failed outright (seed {seed}): {msg}"
2303+ );
2304+ refusals.push(format!("seed {seed}: {msg}"));
2305+ continue;
2306+ }
2307+ Ok(frames) => frames,
2308+ };
2309+ if decode::ref_hits(target_ref) == before {
2310+ never_fired += 1;
2311+ continue;
2312+ }
2313+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2314+ assert_eq!(frames.len(), frame_count);
2315+ let mismatched = frames
2316+ .iter()
2317+ .zip(&ffmpeg_frames)
2318+ .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2319+ if mismatched {
2320+ if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
2321+ std::fs::write(&path, &stream).expect("writing pinned stream");
2322+ eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
2323+ }
2324+ }
2325+ for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2326+ assert_eq!(
2327+ got.y, want.y,
2328+ "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
2329+ );
2330+ assert_eq!(
2331+ got.u, want.u,
2332+ "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
2333+ );
2334+ assert_eq!(
2335+ got.v, want.v,
2336+ "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
2337+ );
2338+ }
2339+ eprintln!(
2340+ "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}",
2341+ decode::ref_hits(target_ref) - before
2342+ );
2343+ return;
2344+ }
2345+ eprintln!(
2346+ "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \
2347+ and every other attempt hit a named refusal:\n{}",
2348+ refusals.join("\n")
2349+ );
2350+ }
2351+
2352+ /// `LAST2_FRAME`/`LAST3_FRAME` are just older slots in the same forward
2353+ /// reference-buffer ring `LAST_FRAME`/`GOLDEN_FRAME` already prove --
2354+ /// dropping the golden gate's `--max-reference-frames=3
2355+ /// --reduced-reference-set=1` narrowing (which suppresses exactly these)
2356+ /// and running long enough for aomenc's own buffer rotation to reach
2357+ /// past the first 2 frames is the whole difference.
2358+ #[test]
2359+ fn a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact() {
2360+ a_real_aomenc_single_ref_gate(
2361+ "a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact",
2362+ crate::mvstack::LAST2_FRAME,
2363+ "LAST2_FRAME",
2364+ &["--auto-alt-ref=0", "--lag-in-frames=0"],
2365+ 64,
2366+ 64,
2367+ 8,
2368+ 120,
2369+ );
2370+ }
2371+
2372+ #[test]
2373+ fn a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact() {
2374+ a_real_aomenc_single_ref_gate(
2375+ "a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact",
2376+ crate::mvstack::LAST3_FRAME,
2377+ "LAST3_FRAME",
2378+ &["--auto-alt-ref=0", "--lag-in-frames=0"],
2379+ 64,
2380+ 64,
2381+ 8,
2382+ 120,
2383+ );
2384+ }
2385+
2386+ /// `BWDREF`/`ALTREF2`/`ALTREF` are all backward (display-order-forward)
2387+ /// references that only exist once aomenc builds a hierarchical GOP --
2388+ /// `--auto-alt-ref=1 --lag-in-frames` (need at least one full mini-GOP
2389+ /// of lookahead) is what makes aomenc code them at all; without it
2390+ /// every attempt would hit this decoder's own real, still-open
2391+ /// per-block sign-bias gap by never drawing the reference in the first
2392+ /// place, not by proving it correct.
2393+ #[test]
2394+ fn a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact() {
2395+ a_real_aomenc_single_ref_gate(
2396+ "a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact",
2397+ crate::mvstack::BWDREF_FRAME,
2398+ "BWDREF_FRAME",
2399+ &[
2400+ "--auto-alt-ref=1",
2401+ "--lag-in-frames=16",
2402+ "--enable-fwd-kf=0",
2403+ ],
2404+ 64,
2405+ 64,
2406+ 16,
2407+ 120,
2408+ );
2409+ }
2410+
2411+ #[test]
2412+ fn a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact() {
2413+ a_real_aomenc_single_ref_gate(
2414+ "a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact",
2415+ crate::mvstack::ALTREF2_FRAME,
2416+ "ALTREF2_FRAME",
2417+ &[
2418+ "--auto-alt-ref=1",
2419+ "--lag-in-frames=16",
2420+ "--enable-fwd-kf=0",
2421+ ],
2422+ 64,
2423+ 64,
2424+ 16,
2425+ 120,
2426+ );
2427+ }
2428+
2429+ #[test]
2430+ fn a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact() {
2431+ a_real_aomenc_single_ref_gate(
2432+ "a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact",
2433+ crate::mvstack::ALTREF_FRAME,
2434+ "ALTREF_FRAME",
2435+ &[
2436+ "--auto-alt-ref=1",
2437+ "--lag-in-frames=16",
2438+ "--enable-fwd-kf=0",
2439+ ],
2440+ 64,
2441+ 64,
2442+ 16,
2443+ 120,
2444+ );
2445+ }
2446+
21592447 /// scratch: decode a pinned stream end to end and report where/why it
21602448 /// refuses, plus `non_last_ref_hits` progression.
21612449 #[test]