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;
32 use crate::msac::SymbolDecoder;32 use crate::msac::SymbolDecoder;
33 use crate::mvstack::{33 use crate::mvstack::{
34 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,34 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,35+ MiGrid, MiInfo, NO_SIGN_BIAS, SignBiasTable, find_mv_stack, find_mv_stack_with_sign_bias,
36- single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,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,
37 };38 };
38 use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};39 use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
39 use crate::transform::{TxType, dequant_and_inverse_typed};40 use crate::transform::{TxType, dequant_and_inverse_typed};
@@ -117,6 +118,34 @@ pub(crate) fn non_last_ref_hits() -> usize {
117 NON_LAST_REF_HITS.load(std::sync::atomic::Ordering::Relaxed)118 NON_LAST_REF_HITS.load(std::sync::atomic::Ordering::Relaxed)
118 }119 }
119 120
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+
120 thread_local! {149 thread_local! {
121 /// The sequence header's `enable_intra_edge_filter`, set once per150 /// The sequence header's `enable_intra_edge_filter`, set once per
122 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s151 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
@@ -1248,6 +1277,14 @@ struct PlaneBuf {
1248 true_height: usize,1277 true_height: usize,
1249 }1278 }
1250 1279
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+
1251 impl PlaneBuf {1288 impl PlaneBuf {
1252 fn edges(1289 fn edges(
1253 &self,1290 &self,
@@ -3656,6 +3693,16 @@ fn read_single_ref(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above_ref: i8, left
3656 };3693 };
3657 if ref_frame != LAST_FRAME {3694 if ref_frame != LAST_FRAME {
3658 NON_LAST_REF_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);3695 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);
3659 }3706 }
3660 ref_frame3707 ref_frame
3661 }3708 }
@@ -3691,18 +3738,14 @@ fn decode_inter_block(
3691 ref_y: &PlaneBuf,3738 ref_y: &PlaneBuf,
3692 ref_u: &PlaneBuf,3739 ref_u: &PlaneBuf,
3693 ref_v: &PlaneBuf,3740 ref_v: &PlaneBuf,
3694- // corner-cut (lane-av1refs r1): only `LAST_FRAME` (`ref_y`/`u`/`v`) and3741+ // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
3695- // `GOLDEN_FRAME` (`golden_*`, when the frame header's own3742+ // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
3696- // `ref_frame_idx` names a slot with a picture) are threaded down to MC.3743+ // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
3697- // Ceiling: `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` still refuse by3744+ // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
3698- // name -- real short low-lag streams overwhelmingly pick `LAST` or3745+ // slot's still empty (an error-resilient stream, or too early in the
3699- // `GOLDEN` (the ledger's cdffwd trace). Upgrade path: widen `golden_*`3746+ // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
3700- // into a `[Option<&PlaneBuf>; REFS_PER_FRAME]` addressed by the decoded3747+ other_refs: &RefSlots,
3701- // reference, same as the CDF/picture DPB slots `decode_stream` already3748+ sign_bias_table: &SignBiasTable,
3702- // keeps.
3703- golden_y: Option<&PlaneBuf>,
3704- golden_u: Option<&PlaneBuf>,
3705- golden_v: Option<&PlaneBuf>,
3706 base_q_idx: u8,3749 base_q_idx: u8,
3707 luma_set_intra: TxbSet,3750 luma_set_intra: TxbSet,
3708 luma_set_inter: TxbSet,3751 luma_set_inter: TxbSet,
@@ -3737,57 +3780,31 @@ fn decode_inter_block(
3737 if is_inter {3780 if is_inter {
3738 let ref_frame = read_single_ref(dec, cdfs, neighbours.above_ref[c], neighbours.left_ref[r]);3781 let ref_frame = read_single_ref(dec, cdfs, neighbours.above_ref[c], neighbours.left_ref[r]);
3739 ref_frame_for_lf = ref_frame;3782 ref_frame_for_lf = ref_frame;
3740- // round 4-8 (lane-av1golden through lane-av1golden6): repeatedly3783+ // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
3741- // un-masked and re-masked chasing what looked like a GOLDEN_FRAME MC3784+ // stacked defects (lf_level ref/mode-delta forwarding, the
3742- // bug -- lf_level `mode_deltas`/`ref_deltas` forwarding fixes3785+ // switchable_interp ref-frame ctx gate, and a film-grain synthesis
3743- // (rounds 5/6, both real and kept), and a switchable_interp ctx3786+ // gap that looked like a GOLDEN MC bug by survivor bias -- see the
3744- // ref-frame gate (round 8, real and kept). Every remaining3787+ // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
3745- // "GOLDEN_FRAME mismatch" chased past round 8 (including a frame-03788+ // below same as every other non-`LAST_FRAME` reference. lane-av1refs
3746- // *intra keyframe* luma mismatch that could not possibly depend on3789+ // widens this from GOLDEN alone to every reference `read_single_ref`
3747- // this arm at all) turned out to be a single unrelated cause: round3790+ // can name.
3748- // 9 (lane-av1golden7) traced `fixtures/golden6-mismatch.obu`'s3791+ let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
3749- // frame-0 mismatch down to `header.film_grain.apply_grain == true`3792+ (ref_y, ref_u, ref_v)
3750- // (aomenc's `--tune-content=film` denoises the coded picture and3793+ } else {
3751- // has the decoder re-synthesize grain per spec 7.18.3) -- this3794+ match other_refs[ref_frame as usize] {
3752- // decoder never implements grain synthesis at all, so it silently3795+ Some((ry, ru, rv)) => (ry, ru, rv),
3753- // returned the clean base picture while ffmpeg (dav1d) returned the3796+ None => {
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- _ => {
3772 return Err(unsupported(3797 return Err(unsupported(
3773- "GOLDEN_FRAME selected with no golden picture at this frame's \3798+ "a reference frame selected with no picture at this frame's own \
3774- ref_frame_idx[3] slot",3799+ ref_frame_idx slot for it",
3775 ));3800 ));
3776 }3801 }
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- ));
3785 }3802 }
3786 };3803 };
3787 3804
3788 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);3805 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
3789 let bw4 = side / 4;3806 let bw4 = side / 4;
3790- let stack = find_mv_stack(3807+ let stack = find_mv_stack_with_sign_bias(
3791 grid,3808 grid,
3792 mi_row,3809 mi_row,
3793 mi_col,3810 mi_col,
@@ -3796,6 +3813,7 @@ fn decode_inter_block(
3796 ref_frame,3813 ref_frame,
3797 mi_cols as usize,3814 mi_cols as usize,
3798 mi_rows as usize,3815 mi_rows as usize,
3816+ sign_bias_table,
3799 );3817 );
3800 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;3818 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
3801 let mut is_globalmv = false;3819 let mut is_globalmv = false;
@@ -4615,7 +4633,7 @@ pub fn decode_inter_frame_tile(
4615 frame_width: u32,4633 frame_width: u32,
4616 frame_height: u32,4634 frame_height: u32,
4617 reference: &Picture,4635 reference: &Picture,
4618- golden: Option<&Picture>,4636+ other_refs: [Option<&Picture>; 8],
4619 cdef: &CdefParams,4637 cdef: &CdefParams,
4620 loop_filter: &LoopFilterParams,4638 loop_filter: &LoopFilterParams,
4621 allow_high_precision_mv: bool,4639 allow_high_precision_mv: bool,
@@ -4630,11 +4648,12 @@ pub fn decode_inter_frame_tile(
4630 frame_width,4648 frame_width,
4631 frame_height,4649 frame_height,
4632 reference,4650 reference,
4633- golden,4651+ other_refs,
4634 cdef,4652 cdef,
4635 loop_filter,4653 loop_filter,
4636 None,4654 None,
4637 allow_high_precision_mv,4655 allow_high_precision_mv,
4656+ NO_SIGN_BIAS,
4638 interp_fixed,4657 interp_fixed,
4639 enable_dual_filter,4658 enable_dual_filter,
4640 )4659 )
@@ -4654,11 +4673,12 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
4654 frame_width: u32,4673 frame_width: u32,
4655 frame_height: u32,4674 frame_height: u32,
4656 reference: &Picture,4675 reference: &Picture,
4657- golden: Option<&Picture>,4676+ other_refs: [Option<&Picture>; 8],
4658 cdef: &CdefParams,4677 cdef: &CdefParams,
4659 loop_filter: &LoopFilterParams,4678 loop_filter: &LoopFilterParams,
4660 initial_cdfs: Option<Cdfs>,4679 initial_cdfs: Option<Cdfs>,
4661 allow_high_precision_mv: bool,4680 allow_high_precision_mv: bool,
4681+ sign_bias_table: SignBiasTable,
4662 interp_fixed: Option<mc::InterpFilterKind>,4682 interp_fixed: Option<mc::InterpFilterKind>,
4663 enable_dual_filter: bool,4683 enable_dual_filter: bool,
4664 ) -> Result<(Picture, Cdfs)> {4684 ) -> Result<(Picture, Cdfs)> {
@@ -4696,38 +4716,44 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
4696 true_width: reference.width / 2,4716 true_width: reference.width / 2,
4697 true_height: reference.height / 2,4717 true_height: reference.height / 2,
4698 };4718 };
4699- // `GOLDEN_FRAME`'s own picture, when the frame header's `ref_frame_idx`4719+ // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
4700- // names a DPB slot holding one and it is this frame's own true size --4720+ // names a live DPB slot for (lane-av1refs: generalised from the old
4701- // `decode_inter_block`'s GOLDEN_FRAME arm refuses when it is `None` or a4721+ // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
4702- // mismatched size (spec 7.9 requires every active reference be a4722+ // now per-reference). `decode_inter_block` refuses by name when the
4703- // compatible size; this decoder's single-slot-per-frame update makes4723+ // block it is decoding selects an index that is still `None` here
4704- // that always true for a stream this crate's own encoder writes).4724+ // (spec 7.9 requires every *active* reference be a compatible size;
4705- let (golden_y, golden_u, golden_v) = match golden {4725+ // an inactive one this frame never selects is simply left `None`).
4706- Some(g) if g.width == reference.width && g.height == reference.height => (4726+ let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
4707- Some(PlaneBuf {4727+ other_refs[i]
4708- data: g.y.clone(),4728+ .filter(|g| g.width == reference.width && g.height == reference.height)
4709- width: g.width,4729+ .map(|g| {
4710- height: g.height,4730+ (
4711- true_width: g.width,4731+ PlaneBuf {
4712- true_height: g.height,4732+ data: g.y.clone(),
4713- }),4733+ width: g.width,
4714- Some(PlaneBuf {4734+ height: g.height,
4715- data: g.u.clone(),4735+ true_width: g.width,
4716- width: g.width / 2,4736+ true_height: g.height,
4717- height: g.height / 2,4737+ },
4718- true_width: g.width / 2,4738+ PlaneBuf {
4719- true_height: g.height / 2,4739+ data: g.u.clone(),
4720- }),4740+ width: g.width / 2,
4721- Some(PlaneBuf {4741+ height: g.height / 2,
4722- data: g.v.clone(),4742+ true_width: g.width / 2,
4723- width: g.width / 2,4743+ true_height: g.height / 2,
4724- height: g.height / 2,4744+ },
4725- true_width: g.width / 2,4745+ PlaneBuf {
4726- true_height: g.height / 2,4746+ data: g.v.clone(),
4727- }),4747+ width: g.width / 2,
4728- ),4748+ height: g.height / 2,
4729- _ => (None, None, None),4749+ true_width: g.width / 2,
4730- };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)));
4731 4757
4732 let mut y = PlaneBuf {4758 let mut y = PlaneBuf {
4733 data: vec![0u8; width * height],4759 data: vec![0u8; width * height],
@@ -4830,9 +4856,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
4830 &ref_y,4856 &ref_y,
4831 &ref_u,4857 &ref_u,
4832 &ref_v,4858 &ref_v,
4833- golden_y.as_ref(),4859+ &ref_slots,
4834- golden_u.as_ref(),4860+ &sign_bias_table,
4835- golden_v.as_ref(),
4836 base_q_idx,4861 base_q_idx,
4837 TxbSet::Luma32,4862 TxbSet::Luma32,
4838 TxbSet::Luma32Inter,4863 TxbSet::Luma32Inter,
@@ -4888,9 +4913,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
4888 &ref_y,4913 &ref_y,
4889 &ref_u,4914 &ref_u,
4890 &ref_v,4915 &ref_v,
4891- golden_y.as_ref(),4916+ &ref_slots,
4892- golden_u.as_ref(),4917+ &sign_bias_table,
4893- golden_v.as_ref(),
4894 base_q_idx,4918 base_q_idx,
4895 TxbSet::Luma16,4919 TxbSet::Luma16,
4896 TxbSet::Luma16Inter,4920 TxbSet::Luma16Inter,
@@ -5457,7 +5481,7 @@ mod tests {
5457 width as u32,5481 width as u32,
5458 height as u32,5482 height as u32,
5459 &reference,5483 &reference,
5460- None,5484+ [None; 8],
5461 &CdefParams::default(),5485 &CdefParams::default(),
5462 &LoopFilterParams::default(),5486 &LoopFilterParams::default(),
5463 false,5487 false,
@@ -5627,9 +5651,8 @@ mod tests {
5627 &ref_y,5651 &ref_y,
5628 &ref_u,5652 &ref_u,
5629 &ref_v,5653 &ref_v,
5630- None,5654+ &[None; 8],
5631- None,5655+ &NO_SIGN_BIAS,
5632- None,
5633 100,5656 100,
5634 TxbSet::Luma16,5657 TxbSet::Luma16,
5635 TxbSet::Luma16Inter,5658 TxbSet::Luma16Inter,
@@ -5729,7 +5752,7 @@ mod tests {
5729 coded_w,5752 coded_w,
5730 coded_h,5753 coded_h,
5731 &reference,5754 &reference,
5732- None,5755+ [None; 8],
5733 &CdefParams::default(),5756 &CdefParams::default(),
5734 &LoopFilterParams::default(),5757 &LoopFilterParams::default(),
5735 false,5758 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)
227 }227 }
228 }228 }
229 229
230-/// Whether `ref_frame`'s prediction runs backward in display order230+/// `cm->ref_frame_sign_bias[ref_frame]`, looked up from the frame header's
231-/// (`cm->ref_frame_sign_bias`, libaom): flips a borrowed neighbour's MV231+/// own `ref_frame_sign_bias` (spec 5.9.2's `get_relative_dist(ref_order_hint,
232-/// sign in [`process_single_ref_mv_candidate`] when the neighbour's own232+/// OrderHint) > 0` per active reference, already computed by
233-/// reference disagrees. This decoder only ever threads forward references233+/// `ec_av1_syntax::frame::read_uncompressed_header` and indexed exactly like
234-/// (`LAST_FRAME`/`GOLDEN_FRAME`) to MC — never `BWDREF`/`ALTREF` — so every234+/// `ref_frame_idx`: `table[ref_frame - LAST_FRAME]`). `find_mv_stack`'s
235-/// call site compares `false != false` and the flip is always inert. Ported235+/// no-sign-bias callers (this crate's own encoder, which only ever writes
236-/// anyway (never proved away, per this round's own bounds): a real236+/// `LAST_FRAME`) pass an all-`false` table, matching this stub's old
237-/// backward reference would need this to be correct on day one.237+/// always-`false` behaviour exactly.
238-fn sign_bias(_ref_frame: i8) -> bool {238+fn sign_bias(table: &SignBiasTable, ref_frame: i8) -> bool {
239- false239+ table[(ref_frame - LAST_FRAME) as usize]
240 }240 }
241 241
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+
242 /// libaom's `process_single_ref_mv_candidate` (mvref_common.c): folds one254 /// libaom's `process_single_ref_mv_candidate` (mvref_common.c): folds one
243 /// already-coded neighbour into the stack as a low-weight (`2`, unboosted)255 /// already-coded neighbour into the stack as a low-weight (`2`, unboosted)
244 /// filler entry, used only by the single-reference extension pass below.256 /// filler entry, used only by the single-reference extension pass below.
@@ -257,13 +269,14 @@ fn sign_bias(_ref_frame: i8) -> bool {
257 fn process_single_ref_mv_candidate(269 fn process_single_ref_mv_candidate(
258 candidate: &MiInfo,270 candidate: &MiInfo,
259 ref_frame: i8,271 ref_frame: i8,
272+ sign_bias_table: &SignBiasTable,
260 candidates: &mut Vec<StackEntry>,273 candidates: &mut Vec<StackEntry>,
261 ) {274 ) {
262 if !candidate.is_inter {275 if !candidate.is_inter {
263 return;276 return;
264 }277 }
265 let mut this_mv = candidate.mv;278 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) {
267 this_mv = (-this_mv.0, -this_mv.1);280 this_mv = (-this_mv.0, -this_mv.1);
268 }281 }
269 if !candidates.iter().any(|e| e.mv == this_mv) {282 if !candidates.iter().any(|e| e.mv == this_mv) {
@@ -510,6 +523,36 @@ pub fn find_mv_stack(
510 ref_frame: i8,523 ref_frame: i8,
511 mi_cols: usize,524 mi_cols: usize,
512 mi_rows: usize,525 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,
513 ) -> MvStack {556 ) -> MvStack {
514 let mut candidates = Vec::new();557 let mut candidates = Vec::new();
515 let mut newmv_count = 0u32;558 let mut newmv_count = 0u32;
@@ -703,7 +746,7 @@ pub fn find_mv_stack(
703 let cand = grid.get(mi_row - 1, mi_col + idx);746 let cand = grid.get(mi_row - 1, mi_col + idx);
704 let step = cand.map_or(1, |c| c.size).max(1);747 let step = cand.map_or(1, |c| c.size).max(1);
705 if let Some(c) = cand {748 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);
707 }750 }
708 idx += step;751 idx += step;
709 }752 }
@@ -714,7 +757,7 @@ pub fn find_mv_stack(
714 let cand = grid.get(mi_row + idx, mi_col - 1);757 let cand = grid.get(mi_row + idx, mi_col - 1);
715 let step = cand.map_or(1, |c| c.size).max(1);758 let step = cand.map_or(1, |c| c.size).max(1);
716 if let Some(c) = cand {759 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);
718 }761 }
719 idx += step;762 idx += step;
720 }763 }
crates/ec-av1/src/stream.rsmodified+303 -15
@@ -157,16 +157,17 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
157 // model needs the full affine/translation MV derivation this157 // model needs the full affine/translation MV derivation this
158 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`158 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
159 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);159 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
160- // lane-av1refs widens this from `[0]` (LAST_FRAME) alone to every160+ // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
161- // reference `decode_inter_block` can now select -- LAST_FRAME (index161+ // to every one of the 7 single-reference slots `decode_inter_block`
162- // 0) and GOLDEN_FRAME (index 3).162+ // can now select.
163 if header.frame_type != FrameType::Key163 if header.frame_type != FrameType::Key
164- && (header.global_motion[0].model != WarpModel::Identity164+ && header.global_motion[..7]
165- || header.global_motion[3].model != WarpModel::Identity)165+ .iter()
166+ .any(|gm| gm.model != WarpModel::Identity)
166 {167 {
167 return Err(Error::unsupported(168 return Err(Error::unsupported(
168 "AV1 decode_stream",169 "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)",
170 ));171 ));
171 }172 }
172 // `decode_inter_block`'s `single_ref_p*` chain codes only173 // `decode_inter_block`'s `single_ref_p*` chain codes only
@@ -255,14 +256,22 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
255 "an inter frame with no key frame before it",256 "an inter frame with no key frame before it",
256 )257 )
257 })?;258 })?;
258- // `ref_frame_idx[3]` names GOLDEN_FRAME's own DPB slot (spec259+ // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
259- // 7.8/7.20 -- `ref_frame_idx` is indexed `ref_frame - LAST_FRAME`).260+ // (spec 7.8/7.20). Any of them having no picture yet is not a
260- // Unlike LAST_FRAME, GOLDEN_FRAME having no picture yet is not a261+ // stream error on its own: `decode_inter_block` only needs a
261- // stream error on its own: `decode_inter_block` only needs it262+ // given slot when a block actually selects that reference, and
262- // when a block actually selects GOLDEN_FRAME, and refuses by263+ // refuses by name there if the slot is still empty -- widened
263- // name there if the slot is still empty.264+ // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
264- let golden_slot = header.ref_frame_idx[3] as usize;265+ // one of the 7 single-reference slots.
265- let golden = ref_slots.get(golden_slot).and_then(Option::as_ref);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+ });
266 decode_inter_frame_tile_with_cdfs(275 decode_inter_frame_tile_with_cdfs(
267 tile_bytes,276 tile_bytes,
268 header.mi_cols,277 header.mi_cols,
@@ -271,11 +280,12 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
271 header.frame_width,280 header.frame_width,
272 header.frame_height,281 header.frame_height,
273 reference,282 reference,
274- golden,283+ other_refs,
275 &header.cdef,284 &header.cdef,
276 &header.loop_filter,285 &header.loop_filter,
277 initial_cdfs,286 initial_cdfs,
278 header.allow_high_precision_mv,287 header.allow_high_precision_mv,
288+ header.ref_frame_sign_bias,
279 interp_fixed,289 interp_fixed,
280 enable_dual_filter,290 enable_dual_filter,
281 )?291 )?
@@ -2156,6 +2166,284 @@ mod tests {
2156 );2166 );
2157 }2167 }
2158 2168
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+
2159 /// scratch: decode a pinned stream end to end and report where/why it2447 /// scratch: decode a pinned stream end to end and report where/why it
2160 /// refuses, plus `non_last_ref_hits` progression.2448 /// refuses, plus `non_last_ref_hits` progression.
2161 #[test]2449 #[test]