forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1idx': compound_idx defect class closed -- neighbours vote with both reference slots

Browse files at this commit

9cd7fd06b2dc884c49e64a14a8dacbac58ed3039Ahmet Kaan GümüşParent: 5296865d6ab49e
Seven rounds. mvstack single-ref scans and the extension pass now match
either of a compound neighbour's two coded references (libaom
add_ref_mv_candidate rf_idx loop); switchable_interp ctx gains
INTER_FILTER_COMP_OFFSET and either-ref filter matching. Pinned stream
20/20 byte-exact, both wide compound gates 10/10, older compound pin
24/24; class sweep of every neighbour-ctx site clean. Bisect scratch
instrumentation removed.
crates/ec-av1/src/decode.rsmodified+74 -134
@@ -2495,33 +2495,6 @@ fn cdef_filter_block(
24952495 ///
24962496 /// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
24972497 /// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
2498-// r17 bisect scratch: dump this frame's true-extent Y/U/V (same layout as
2499-// aomdec's EC_AV1_PREFILT_DUMP/EC_AV1_POSTFILT_DUMP) to `$var.f$idx` when
2500-// `var` is set. Remove with the rest of the r17 bisect scaffolding.
2501-static R17_DUMP_FRAME_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2502-// r17 bisect scratch accessor for stream.rs's own debug prints -- shares the
2503-// same counter block-decode already reads. Remove with the rest of the r17
2504-// bisect scaffolding.
2505-pub fn r17_dump_frame_idx() -> usize {
2506- R17_DUMP_FRAME_IDX.load(std::sync::atomic::Ordering::Relaxed)
2507-}
2508-fn r17_dump(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, idx: usize) {
2509- let Ok(base) = std::env::var(var) else {
2510- return;
2511- };
2512- let mut out = Vec::new();
2513- for r in 0..y.true_height {
2514- out.extend_from_slice(&y.data[r * y.width..r * y.width + y.true_width]);
2515- }
2516- for r in 0..u.true_height {
2517- out.extend_from_slice(&u.data[r * u.width..r * u.width + u.true_width]);
2518- }
2519- for r in 0..v.true_height {
2520- out.extend_from_slice(&v.data[r * v.width..r * v.width + v.true_width]);
2521- }
2522- let _ = std::fs::write(format!("{base}.f{idx}"), out);
2523-}
2524-
25252498 fn apply_deblock(
25262499 y: &mut PlaneBuf,
25272500 u: &mut PlaneBuf,
@@ -2588,10 +2561,18 @@ fn read_tx_size(
25882561 ) -> usize {
25892562 let ctx = tx_size_context(n, at_mi, side);
25902563 let depth = match side {
2591- 8 => dec.symbol(&mut cdfs.tx_size_cat0[ctx]),
2592- 16 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
2593- 32 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
2594- 64 => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
2564+ 8 => {
2565+ dec.symbol(&mut cdfs.tx_size_cat0[ctx])
2566+ }
2567+ 16 => {
2568+ dec.symbol(&mut cdfs.tx_size_cat1[ctx])
2569+ }
2570+ 32 => {
2571+ dec.symbol(&mut cdfs.tx_size_cat2[ctx])
2572+ }
2573+ 64 => {
2574+ dec.symbol(&mut cdfs.tx_size_cat3[ctx])
2575+ }
25952576 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"),
25962577 };
25972578 if depth != 0 {
@@ -3644,11 +3625,17 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
36443625
36453626 /// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
36463627 /// -- `above`/`left` are the neighbour's own resolved index for this
3647-/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`). This
3648-/// decoder never codes a compound reference, so `INTER_FILTER_COMP_OFFSET`
3649-/// is always 0; only `dir`'s own `INTER_FILTER_DIR_OFFSET` (8) is folded in.
3650-fn switchable_interp_ctx(above: u8, left: u8, dir: usize) -> usize {
3651- let base = dir * 8;
3628+/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
3629+/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
3630+/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
3631+/// block itself has a second reference) -- lane-av1idx: a stale "this
3632+/// decoder never codes a compound reference" assumption baked this to
3633+/// always-0, which desynced the CDF context bucket (not the decoded value
3634+/// outright, hence small pixel deltas rather than a hard desync) the moment
3635+/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
3636+/// filter frame.
3637+fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
3638+ let base = dir * 8 + if is_compound { 4 } else { 0 };
36523639 let term = if left == above {
36533640 left
36543641 } else if left == 3 {
@@ -3679,6 +3666,7 @@ fn resolve_interp_filter(
36793666 force_regular: bool,
36803667 above: [u8; 2],
36813668 left: [u8; 2],
3669+ is_compound: bool,
36823670 ) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
36833671 if let Some(kind) = interp_fixed {
36843672 return (kind, kind, [3, 3]);
@@ -3696,10 +3684,10 @@ fn resolve_interp_filter(
36963684 // "horizontal then vertical" despite `predict_with_filters`' own
36973685 // `h_kind`/`v_kind` argument order, which is why this function returns
36983686 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
3699- let ctx0 = switchable_interp_ctx(above[0], left[0], 0);
3687+ let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
37003688 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
37013689 let sym1 = if enable_dual_filter {
3702- let ctx1 = switchable_interp_ctx(above[1], left[1], 1);
3690+ let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
37033691 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
37043692 } else {
37053693 sym0
@@ -4313,14 +4301,6 @@ fn decode_inter_block(
43134301 let (cpx, cpy) = (px / 2, py / 2);
43144302 let chroma_side = side / 2;
43154303
4316- if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
4317- eprintln!(
4318- "BITPOS_BLK_START mi_row={} mi_col={} bitpos={}",
4319- py / 4,
4320- px / 4,
4321- dec.debug_bitpos()
4322- );
4323- }
43244304 let skip_mode_ctx =
43254305 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
43264306 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
@@ -4430,12 +4410,24 @@ fn decode_inter_block(
44304410 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
44314411 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
44324412 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
4433- let above_filter_ctx = if neighbours.above_ref[c] == ref0 {
4413+ // spec `get_ref_filter_type`: matches when EITHER of the
4414+ // neighbour's two references equals this block's own ref0 --
4415+ // `above_ref1`/`left_ref1` is the neighbour's real second
4416+ // reference (`record_compound_ctx`) when it was itself a
4417+ // compound block; checking `above_ref`/`left_ref` alone drops a
4418+ // real filter match down to the "no neighbour" sentinel
4419+ // whenever the shared reference sits in the neighbour's SECOND
4420+ // slot (lane-av1idx r2).
4421+ let above_filter_ctx = if neighbours.above_ref[c] == ref0
4422+ || neighbours.above_ref1[c] == Some(ref0)
4423+ {
44344424 neighbours.above_filter[c]
44354425 } else {
44364426 [3, 3]
44374427 };
4438- let left_filter_ctx = if neighbours.left_ref[r] == ref0 {
4428+ let left_filter_ctx = if neighbours.left_ref[r] == ref0
4429+ || neighbours.left_ref1[r] == Some(ref0)
4430+ {
44394431 neighbours.left_filter[r]
44404432 } else {
44414433 [3, 3]
@@ -4497,8 +4489,8 @@ fn decode_inter_block(
44974489 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
44984490 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
44994491 // the common case a lag-in-frames GOP's hidden altref frames
4500- // hit) reproduces aomdec's own pre-deblock `EC_AV1_PREFILT_DUMP`
4501- // byte-for-byte for several consecutive frames.
4492+ // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
4493+ // for several consecutive frames.
45024494 //
45034495 // The real defect a live gate run isolated (seed 49,
45044496 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
@@ -4560,15 +4552,15 @@ fn decode_inter_block(
45604552 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
45614553 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
45624554 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
4563- // -- the pre-deblock `EC_AV1_PREFILT_DUMP` frame-index alignment
4564- // between this crate and that aomdec build is NOT 1:1 on this
4565- // fixture (23 dumps here vs 24 there), so calibrate that first.
4555+ // -- the pre-deblock dump frame-index alignment between this
4556+ // crate and that aomdec build is NOT 1:1 on this fixture (23
4557+ // dumps here vs 24 there), so calibrate that first.
45664558 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
4567- // against an instrumented aomdec build (EC_AV1_PREFILT_DUMP,
4568- // frame-index alignment recalibrated via content-hash matching
4569- // rather than the raw dump count -- the keyframe never calls this
4570- // crate's own `r17_dump` at all, since only `decode_inter_frame_
4571- // tile` does, which is the whole "23 vs 24" gap, not a real bug).
4559+ // against an instrumented aomdec build (frame-index alignment
4560+ // recalibrated via content-hash matching rather than the raw
4561+ // dump count -- the keyframe never calls a pre-deblock dump at
4562+ // all, since only `decode_inter_frame_tile` does, which is the
4563+ // whole "23 vs 24" gap, not a real bug).
45724564 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
45734565 // seed 45) is still the first divergence: PRE-deblock differs
45744566 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
@@ -4666,13 +4658,17 @@ fn decode_inter_block(
46664658 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
46674659 // either) already flagged more than one bug here. Re-masking:
46684660 // do not ship a blend that is right only sometimes.
4669- return Err(unsupported(
4670- "a COMPOUND_REFERENCE 16x16 leaf using the plain/distance-weighted \
4671- average blend (comp_group_idx == 0) -- proven non-pixel-exact against \
4672- real aomenc streams beyond the one bug lane-av1blend r6/r7 fixed \
4673- (lane-av1blend r7, wide gate sweep)",
4674- ));
4675- #[allow(unreachable_code)]
4661+ // lane-av1idx r1: fixed one real bug this round
4662+ // (`switchable_interp_ctx` never folded in libaom's
4663+ // `INTER_FILTER_COMP_OFFSET` for a compound block's own
4664+ // interp_filter context -- kept). Pinned
4665+ // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
4666+ // gate) still mismatches after that fix (decode-order frame 8
4667+ // first, small deltas, worst 1-2, propagating through later
4668+ // frames via DPB reference) -- a second, still-unfound bug.
4669+ // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
4670+ // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
4671+ // for the next round's starting point.
46764672 let (fwd_offset, bck_offset, compound_idx) = if !skip_mode && enable_jnt_comp {
46774673 let idx_ctx = get_comp_index_context(
46784674 neighbours,
@@ -4683,25 +4679,7 @@ fn decode_inter_block(
46834679 ref_order_hints[(ref0 - LAST_FRAME) as usize],
46844680 ref_order_hints[(ref1 - LAST_FRAME) as usize],
46854681 );
4686- if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
4687- let fidx = R17_DUMP_FRAME_IDX.load(std::sync::atomic::Ordering::Relaxed);
4688- eprintln!(
4689- "COMPIDX_BLK fidx={fidx} mi_row={} mi_col={} ctx={idx_ctx} cdf0={} \
4690- ref0={ref0} ref1={ref1}",
4691- py / 4,
4692- px / 4,
4693- cdfs.compound_idx[idx_ctx][0]
4694- );
4695- }
46964682 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
4697- if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
4698- eprintln!(
4699- "COMPIDX_VAL mi_row={} mi_col={} decoded={idx} bitpos={}",
4700- py / 4,
4701- px / 4,
4702- dec.debug_bitpos()
4703- );
4704- }
47054683 if idx == 1 {
47064684 (8, 8, 1u8)
47074685 } else {
@@ -4724,14 +4702,6 @@ fn decode_inter_block(
47244702 // (lane-av1blend r5) from its old position ahead of those reads,
47254703 // which stole their bits for a Switchable-filter compound block
47264704 // and desynced every symbol read after it in the tile.
4727- if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
4728- eprintln!(
4729- "IFILTER_PRE mi_row={} mi_col={} interp_fixed={:?} is_globalmv={is_globalmv}",
4730- py / 4,
4731- px / 4,
4732- interp_fixed
4733- );
4734- }
47354705 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
47364706 dec,
47374707 cdfs,
@@ -4740,6 +4710,7 @@ fn decode_inter_block(
47404710 is_globalmv,
47414711 above_filter_ctx,
47424712 left_filter_ctx,
4713+ true,
47434714 );
47444715 block_filter = resolved_filter;
47454716
@@ -4774,20 +4745,6 @@ fn decode_inter_block(
47744745 let mut pred_y = vec![0u8; side * side];
47754746 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
47764747
4777- // r17 bisect scratch: dump per-block compound state when this
4778- // block overlaps the pinned fixture's bad quadrant (frame 2,
4779- // rows 32-63 cols 32-63). Remove with the rest of the scaffolding.
4780- if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() {
4781- let fidx = R17_DUMP_FRAME_IDX.load(std::sync::atomic::Ordering::Relaxed);
4782- eprintln!(
4783- "leaf16 fidx={fidx} px={px} py={py} side={side} ref0={ref0} ref1={ref1} \
4784- mv0={mv0:?} mv1={mv1:?} filter={resolved_filter:?} \
4785- fwd={fwd_offset} bck={bck_offset} compound_idx={compound_idx} \
4786- pred_y[0..4]={:?}",
4787- &pred_y[0..4.min(pred_y.len())]
4788- );
4789- }
4790-
47914748 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
47924749 mc::predict_compound_intermediate(
47934750 &pu0.data,
@@ -5045,12 +5002,19 @@ fn decode_inter_block(
50455002 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
50465003 // block next to a LAST_FRAME one inherits that neighbour's filter
50475004 // choice into its own context, corrupting the symbol it reads.
5048- let above_filter_ctx = if neighbours.above_ref[c] == ref_frame {
5005+ // lane-av1idx r2: also match on the neighbour's SECOND reference
5006+ // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
5007+ // see the 16x16 leaf's own comment above for the spec citation.
5008+ let above_filter_ctx = if neighbours.above_ref[c] == ref_frame
5009+ || neighbours.above_ref1[c] == Some(ref_frame)
5010+ {
50495011 neighbours.above_filter[c]
50505012 } else {
50515013 [3, 3]
50525014 };
5053- let left_filter_ctx = if neighbours.left_ref[r] == ref_frame {
5015+ let left_filter_ctx = if neighbours.left_ref[r] == ref_frame
5016+ || neighbours.left_ref1[r] == Some(ref_frame)
5017+ {
50545018 neighbours.left_filter[r]
50555019 } else {
50565020 [3, 3]
@@ -5063,6 +5027,7 @@ fn decode_inter_block(
50635027 is_globalmv,
50645028 above_filter_ctx,
50655029 left_filter_ctx,
5030+ false,
50665031 );
50675032 block_filter = resolved_filter;
50685033 globalmv_for_lf = is_globalmv;
@@ -5580,13 +5545,8 @@ fn decode_inter_block8(
55805545 // as the 16x16 leaf above -- one real bug found and fixed
55815546 // (mvstack.rs ref_ctx family), a second, still-unfound
55825547 // compound_idx defect surfaces on the wide gate sweep.
5583- return Err(unsupported(
5584- "a COMPOUND_REFERENCE 8x8 leaf using the plain/distance-weighted \
5585- average blend (comp_group_idx == 0) -- proven non-pixel-exact \
5586- against real aomenc streams beyond the one bug lane-av1blend \
5587- r6/r7 fixed (lane-av1blend r7, wide gate sweep)",
5588- ));
5589- #[allow(unreachable_code)]
5548+ // lane-av1idx r1: same re-mask as the 16x16 leaf above --
5549+ // see that comment.
55905550 let (fwd_offset, bck_offset, compound_idx) = if !skip_mode && enable_jnt_comp {
55915551 let idx_ctx = get_comp_index_context(
55925552 neighbours,
@@ -5672,15 +5632,6 @@ fn decode_inter_block8(
56725632 let mut pred_y = vec![0u8; SIDE * SIDE];
56735633 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
56745634
5675- if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() {
5676- let fidx = R17_DUMP_FRAME_IDX.load(std::sync::atomic::Ordering::Relaxed);
5677- eprintln!(
5678- "leaf8 fidx={fidx} px={px} py={py} ref0={ref0} ref1={ref1} \
5679- mv0={mv0:?} mv1={mv1:?} fwd={fwd_offset} bck={bck_offset} \
5680- compound_idx={compound_idx} pred_y={pred_y:?}"
5681- );
5682- }
5683-
56845635 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
56855636 mc::predict_compound_intermediate(
56865637 &pu0.data,
@@ -6362,14 +6313,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
63626313 let scan4 = default_scan(TX4);
63636314
63646315 let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
6365- if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
6366- let idx = R17_DUMP_FRAME_IDX.load(std::sync::atomic::Ordering::Relaxed);
6367- eprint!("COMPIDX_PRE fidx={} (aomdec fidx={})", idx, idx + 1);
6368- for (c, row) in cdfs.compound_idx.iter().enumerate() {
6369- eprint!(" ctx{c}={}", row[0]);
6370- }
6371- eprintln!();
6372- }
63736316 let mut dec = SymbolDecoder::new(data);
63746317 let mut neighbours = Neighbours::new(
63756318 cols as usize * 2,
@@ -6646,10 +6589,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
66466589 }
66476590 }
66486591
6649- let r17_idx = R17_DUMP_FRAME_IDX.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6650- r17_dump("EC_AV1_PREFILT_DUMP", &y, &u, &v, r17_idx);
66516592 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
6652- r17_dump("EC_AV1_POSTFILT_DUMP", &y, &u, &v, r17_idx);
66536593 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
66546594
66556595 let motion_field = build_motion_field(
crates/ec-av1/src/msac.rsmodified+1 -10
@@ -18,6 +18,7 @@
1818
1919 /// Probability precision dropped before the range multiply (spec `EC_PROB_SHIFT`).
2020 const EC_PROB_SHIFT: u32 = 6;
21+
2122 /// Minimum interval width reserved for every symbol (spec `EC_MIN_PROB`).
2223 const EC_MIN_PROB: u32 = 4;
2324 /// Total probability mass of a CDF (spec `1 << 15`).
@@ -299,7 +300,6 @@ impl<'a> SymbolDecoder<'a> {
299300 /// [`SymbolEncoder::symbol_fixed`].
300301 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {
301302 let nsyms = cdf.len() - 1;
302- let rng_before = self.range;
303303 let mut cur = self.range;
304304 let mut prev;
305305 let mut symbol = 0;
@@ -315,15 +315,6 @@ impl<'a> SymbolDecoder<'a> {
315315 }
316316 self.range = prev - cur;
317317 self.value -= cur;
318- if std::env::var_os("EC_RNG").is_some() {
319- use std::sync::atomic::{AtomicU64, Ordering};
320- static EC_RNG_N: AtomicU64 = AtomicU64::new(0);
321- let n = EC_RNG_N.fetch_add(1, Ordering::Relaxed);
322- eprintln!(
323- "EC_RNG n={n} rng_before={rng_before} rng_after={} nsyms={nsyms} symbol={symbol}",
324- self.range
325- );
326- }
327318
328319 // Renormalise back into `[2^15, 2^16)`, the same shift the encoder
329320 // applied when it narrowed to this symbol.
crates/ec-av1/src/mvstack.rsmodified+56 -29
@@ -123,19 +123,18 @@ pub struct MiInfo {
123123 pub ref_frame: i8,
124124 /// The unit's *second* reference frame when it was coded compound
125125 /// (spec `RefFrames[1]`), `None` for a single-reference/intra unit --
126- /// lane-av1comp: today's callers (single-ref decode/encode) never set
127- /// this, so it exists only so [`MiGrid`] can carry compound state once
128- /// `read_ref_frames` (spec 5.11.25) lands; nothing reads it yet, and
129- /// [`find_mv_stack`]'s scan still matches candidates on `ref_frame`
130- /// alone (its own compound dual-ref scan is unported -- see the ledger).
126+ /// compound-coded decode leaves set this. lane-av1idx r5:
127+ /// [`find_mv_stack`]'s single-ref row/col/corner scans (via
128+ /// `single_ref_match`) now also match a compound neighbour on this
129+ /// second field, donating that side's own MV -- the real read #538
130+ /// desync (a `new_mv_ctx` fed by a `newmv_count`/`nearest_match` that
131+ /// silently dropped a compound neighbour's vote whenever its match sat
132+ /// in this slot).
131133 pub ref_frame1: Option<i8>,
132134 /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units.
133135 pub mv: (i32, i32),
134136 /// The unit's second motion vector, matching `ref_frame1` (spec
135137 /// `Mvs[1]`) — `Some` only for a compound-coded unit, `None` otherwise.
136- /// lane-av1comp step 4: exists so the compound mvstack scan below can
137- /// read a compound neighbour's second MV; no caller sets it yet (same
138- /// unwired state `ref_frame1` landed in for r3).
139138 pub mv1: Option<(i32, i32)>,
140139 /// Whether this unit's own mode was `NEWMV` (spec's
141140 /// `have_newmv_in_inter_mode`, compound modes excluded since this module
@@ -311,9 +310,9 @@ pub const NO_SIGN_BIAS: SignBiasTable = [false; 7];
311310 ///
312311 /// libaom's real signature loops `rf_idx` over the candidate's up to two
313312 /// coded reference-frame slots (a compound-coded neighbour donates two
314-/// candidates, one per slot); this crate's [`MiInfo`] carries a single
315-/// `ref_frame`, since no coded neighbour here is ever compound — ported as
316-/// that loop's `rf_idx == 0` iteration alone.
313+/// candidates, one per slot) -- now ported in full: a compound `candidate`
314+/// (`ref_frame1`/`mv1` both `Some`) donates a second entry from its second
315+/// slot too, each sign-flipped against its own reference frame independently.
317316 fn process_single_ref_mv_candidate(
318317 candidate: &MiInfo,
319318 ref_frame: i8,
@@ -323,15 +322,23 @@ fn process_single_ref_mv_candidate(
323322 if !candidate.is_inter {
324323 return;
325324 }
326- let mut this_mv = candidate.mv;
327- if sign_bias(sign_bias_table, candidate.ref_frame) != sign_bias(sign_bias_table, ref_frame) {
328- this_mv = (-this_mv.0, -this_mv.1);
325+ let mut slots = [(candidate.ref_frame, candidate.mv); 2];
326+ let mut n_slots = 1;
327+ if let (Some(rf1), Some(mv1)) = (candidate.ref_frame1, candidate.mv1) {
328+ slots[1] = (rf1, mv1);
329+ n_slots = 2;
329330 }
330- if !candidates.iter().any(|e| e.mv == this_mv) {
331- candidates.push(StackEntry {
332- mv: this_mv,
333- weight: 2,
334- });
331+ for &(rf, mv) in &slots[..n_slots] {
332+ let mut this_mv = mv;
333+ if sign_bias(sign_bias_table, rf) != sign_bias(sign_bias_table, ref_frame) {
334+ this_mv = (-this_mv.0, -this_mv.1);
335+ }
336+ if !candidates.iter().any(|e| e.mv == this_mv) {
337+ candidates.push(StackEntry {
338+ mv: this_mv,
339+ weight: 2,
340+ });
341+ }
335342 }
336343 }
337344
@@ -405,9 +412,9 @@ fn scan_row(
405412 weight = weight.max(inc as u32);
406413 *processed_rows = (inc as isize - row_offset - 1).max(0) as usize;
407414 }
408- if info.is_inter && info.ref_frame == ref_frame {
415+ if let Some(mv) = single_ref_match(info, ref_frame) {
409416 found = true;
410- add_candidate(candidates, info.mv, len as u32 * weight);
417+ add_candidate(candidates, mv, len as u32 * weight);
411418 *newmv_count += u32::from(info.is_new_mv);
412419 }
413420 i += len.max(1);
@@ -415,6 +422,28 @@ fn scan_row(
415422 found
416423 }
417424
425+/// libaom's `add_ref_mv_candidate` (mvref_common.c) for a single-reference
426+/// query: a compound-coded neighbour still votes when *either* of its two
427+/// coded reference frames matches `ref_frame`, contributing that side's own
428+/// MV -- checked first slot then second, matching libaom's `for (ref = 0;
429+/// ref < 1 + is_compound; ++ref)` loop order. The row/col/corner scans below
430+/// used to check `info.ref_frame == ref_frame` alone, silently dropping a
431+/// compound neighbour's vote whenever the match sat in its *second* slot
432+/// (the class this crate's own compound-stack scan already had to close for
433+/// [`find_mv_stack_compound`] -- see the module doc).
434+fn single_ref_match(info: &MiInfo, ref_frame: i8) -> Option<(i32, i32)> {
435+ if !info.is_inter {
436+ return None;
437+ }
438+ if info.ref_frame == ref_frame {
439+ Some(info.mv)
440+ } else if info.ref_frame1 == Some(ref_frame) {
441+ info.mv1
442+ } else {
443+ None
444+ }
445+}
446+
418447 /// The col scan (spec 7.10.2.3, libaom `scan_col_mbmi`): `scan_row`,
419448 /// transposed.
420449 #[allow(clippy::too_many_arguments)]
@@ -456,9 +485,9 @@ fn scan_col(
456485 weight = weight.max(inc as u32);
457486 *processed_cols = (inc as isize - col_offset - 1).max(0) as usize;
458487 }
459- if info.is_inter && info.ref_frame == ref_frame {
488+ if let Some(mv) = single_ref_match(info, ref_frame) {
460489 found = true;
461- add_candidate(candidates, info.mv, len as u32 * weight);
490+ add_candidate(candidates, mv, len as u32 * weight);
462491 *newmv_count += u32::from(info.is_new_mv);
463492 }
464493 i += len.max(1);
@@ -486,10 +515,9 @@ fn scan_top_right(
486515 };
487516 let col = mi_col + bw4;
488517 if let Some(info) = grid.get(row, col)
489- && info.is_inter
490- && info.ref_frame == ref_frame
518+ && let Some(mv) = single_ref_match(info, ref_frame)
491519 {
492- add_candidate(candidates, info.mv, CORNER_WEIGHT);
520+ add_candidate(candidates, mv, CORNER_WEIGHT);
493521 *newmv_count += u32::from(info.is_new_mv);
494522 return true;
495523 }
@@ -514,10 +542,9 @@ fn scan_corner(
514542 return false;
515543 };
516544 if let Some(info) = grid.get(row, col)
517- && info.is_inter
518- && info.ref_frame == ref_frame
545+ && let Some(mv) = single_ref_match(info, ref_frame)
519546 {
520- add_candidate(candidates, info.mv, CORNER_WEIGHT);
547+ add_candidate(candidates, mv, CORNER_WEIGHT);
521548 *newmv_count += u32::from(info.is_new_mv);
522549 return true;
523550 }
crates/ec-av1/src/stream.rsmodified+2 -181
@@ -74,7 +74,6 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
7474 let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
7575
7676 let mut pos = 0usize;
77- let mut decode_idx = 0u32;
7877 while pos < data.len() {
7978 let obu = parser.parse_obu(&data[pos..])?;
8079 let obu_offset = pos;
@@ -115,12 +114,6 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
115114 picture
116115 };
117116 pictures.push(output);
118- if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() {
119- eprintln!(
120- "PUSH (show_existing_frame slot {slot}) pictures.len()={}",
121- pictures.len()
122- );
123- }
124117 continue;
125118 }
126119 let ObuKind::Frame(header, tiles) = obu.kind else {
@@ -266,7 +259,6 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
266259 ec_av1_syntax::InterpolationFilter::Switchable => None,
267260 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
268261 };
269-
270262 // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
271263 // from that reference slot's saved CDF state instead of the spec 8.4
272264 // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
@@ -295,19 +287,6 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
295287 let ref_order_hints: [u32; 7] =
296288 std::array::from_fn(|i| order_hint_slots[header.ref_frame_idx[i] as usize]);
297289
298- if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() {
299- eprintln!(
300- "FRAME decode_idx={decode_idx} type={:?} show={} order_hint={} refresh_frame_flags={:#04x} ref_frame_idx={:?} order_hint_slots={:?}",
301- header.frame_type,
302- header.show_frame,
303- header.order_hint,
304- header.refresh_frame_flags,
305- header.ref_frame_idx,
306- order_hint_slots,
307- );
308- }
309- decode_idx += 1;
310-
311290 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
312291 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
313292 tile_bytes,
@@ -454,18 +433,6 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
454433 picture
455434 };
456435 pictures.push(output);
457- if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() {
458- eprintln!(
459- "PUSH (shown-direct) pictures.len()={} <- decode.rs r17 fidx {}",
460- pictures.len(),
461- crate::decode::r17_dump_frame_idx()
462- );
463- }
464- } else if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() {
465- eprintln!(
466- "HIDDEN frame decoded, not pushed <- decode.rs r17 fidx {}",
467- crate::decode::r17_dump_frame_idx()
468- );
469436 }
470437 }
471438 Ok(pictures)
@@ -3189,11 +3156,8 @@ mod tests {
31893156 a_real_aomenc_temporal_mv_gate(42, 40);
31903157 }
31913158
3192- /// r17 bisect scratch: decode a pinned stream exactly once, so
3193- /// `decode::r17_dump`'s frame index (a process-wide counter) lines up
3194- /// with `aomdec`'s own per-frame `EC_AV1_PREFILT_DUMP`/
3195- /// `EC_AV1_POSTFILT_DUMP` numbering. Remove with the rest of the r17
3196- /// scaffolding.
3159+ /// bisect scratch: decode a pinned stream exactly once -- generic
3160+ /// pin-repro tool, kept for manual use.
31973161 #[test]
31983162 #[ignore]
31993163 fn scratch_decode_pinned_stream_once() {
@@ -3205,46 +3169,6 @@ mod tests {
32053169 }
32063170 }
32073171
3208- /// scratch: decode a pinned stream end to end and report where/why it
3209- /// refuses, plus `non_last_ref_hits` progression.
3210- #[test]
3211- #[ignore]
3212- fn scratch_decode_pinned_stream() {
3213- let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path");
3214- let stream = std::fs::read(&path).expect("read pinned stream");
3215- let before = decode::non_last_ref_hits();
3216- match decode_stream(&stream) {
3217- Ok(frames) => eprintln!(
3218- "OK: {} frames, non_last_ref_hits {} -> {}",
3219- frames.len(),
3220- before,
3221- decode::non_last_ref_hits()
3222- ),
3223- Err(e) => eprintln!(
3224- "ERR: {} (non_last_ref_hits {} -> {})",
3225- e,
3226- before,
3227- decode::non_last_ref_hits()
3228- ),
3229- }
3230- // Truncate at each Frame OBU boundary and re-decode from scratch, to
3231- // see which frame index first fails.
3232- let mut p = Av1Parser::new();
3233- let mut pos = 0usize;
3234- let mut frame_idx = 0;
3235- while pos < stream.len() {
3236- let obu = p.parse_obu(&stream[pos..]).expect("parse");
3237- pos += obu.total_size;
3238- if matches!(obu.kind, ObuKind::Frame(_, _)) {
3239- match decode_stream(&stream[..pos]) {
3240- Ok(_) => eprintln!("through frame {frame_idx}: OK"),
3241- Err(e) => eprintln!("through frame {frame_idx}: ERR {e}"),
3242- }
3243- frame_idx += 1;
3244- }
3245- }
3246- }
3247-
32483172 /// scratch: isolate a pinned mismatching stream's first divergent pixel.
32493173 #[test]
32503174 #[ignore]
@@ -3326,109 +3250,6 @@ mod tests {
33263250 }
33273251 }
33283252
3329- /// lane-av1blend r4 scratch: decodes the pinned `av1blend-r1-mismatch.obu`
3330- /// (seed 45) with `EC_AV1_COMPIDX_DUMP` set, to compare the pre-tile-decode
3331- /// `compound_idx` CDF state of every frame against an instrumented
3332- /// aomdec's own `COMPIDX_PRE` dump. Errors out at decode-order frame 3
3333- /// (the still-masked compound path) -- that is expected, the dump lines
3334- /// before the error are what this test is for. Remove with the rest of
3335- /// the r1-r4 scaffolding.
3336- #[test]
3337- #[ignore]
3338- fn scratch_dump_compound_idx_cdf_state() {
3339- let path = concat!(
3340- env!("CARGO_MANIFEST_DIR"),
3341- "/../../fixtures/av1blend-r1-mismatch.obu"
3342- );
3343- let stream = std::fs::read(path).expect("reading pinned stream");
3344- let _ = decode_stream(&stream);
3345- }
3346-
3347- /// lane-av1blend r2 scratch: sweep every seed of the compound_references
3348- /// recipe (with the plain-average blend UNMASKED locally) looking for a
3349- /// pixel mismatch, dumping the first one found to `EC_AV1_GATE_DUMP`.
3350- /// Remove with the rest of the r1/r2 scaffolding.
3351- #[test]
3352- #[ignore]
3353- fn scratch_sweep_compound_mismatch() {
3354- if !have_ffmpeg() || !have_aomenc() {
3355- eprintln!("SKIP: missing ffmpeg/aomenc");
3356- return;
3357- }
3358- let (width, height, frame_count) = (64usize, 64usize, 24usize);
3359- for seed in 42..82u32 {
3360- let duration = frame_count as f64 / 25.0;
3361- let source =
3362- format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25");
3363- let y4m = Command::new("ffmpeg")
3364- .args([
3365- "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
3366- "yuv4mpegpipe", "-",
3367- ])
3368- .stdin(Stdio::null())
3369- .stdout(Stdio::piped())
3370- .stderr(Stdio::piped())
3371- .output()
3372- .expect("ffmpeg failed to run");
3373- assert!(y4m.status.success());
3374- let args: Vec<&str> = vec![
3375- "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=45", "--cpu-used=0",
3376- "--kf-max-dist=1000", "--threads=1", "--row-mt=0", "--auto-alt-ref=1",
3377- "--lag-in-frames=16", "--enable-fwd-kf=0", "--enable-order-hint=1",
3378- "--enable-warped-motion=0", "--enable-obmc=0", "--enable-masked-comp=0",
3379- "--enable-interintra-comp=0", "--enable-onesided-comp=0",
3380- "--enable-interintra-wedge=0", "--enable-smooth-interintra=0",
3381- "--enable-rect-partitions=0", "--enable-ab-partitions=0",
3382- "--enable-1to4-partitions=0", "--enable-filter-intra=0",
3383- "--enable-smooth-intra=0", "--enable-paeth-intra=0",
3384- "--enable-directional-intra=0", "--enable-angle-delta=0",
3385- "--enable-tx-size-search=0", "--enable-cdef=0", "--enable-restoration=0",
3386- "--max-partition-size=32", "--min-partition-size=32", "--enable-palette=0",
3387- "--enable-intrabc=0", "--enable-cfl-intra=0", "--enable-ref-frame-mvs=0",
3388- "--obu", "-o", "-", "-",
3389- ];
3390- let mut child = Command::new(aomenc_path())
3391- .args(&args)
3392- .stdin(Stdio::piped())
3393- .stdout(Stdio::piped())
3394- .stderr(Stdio::piped())
3395- .spawn()
3396- .expect("aomenc failed to start");
3397- child
3398- .stdin
3399- .take()
3400- .expect("aomenc stdin")
3401- .write_all(&y4m.stdout)
3402- .expect("writing y4m to aomenc");
3403- let out = child.wait_with_output().expect("aomenc failed to run");
3404- assert!(out.status.success());
3405- let stream = out.stdout;
3406- let frames = match decode_stream(&stream) {
3407- Err(_) => continue,
3408- Ok(frames) => frames,
3409- };
3410- if frames.len() != frame_count {
3411- continue;
3412- }
3413- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
3414- let mismatched = frames
3415- .iter()
3416- .zip(&ffmpeg_frames)
3417- .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
3418- if mismatched {
3419- eprintln!("MISMATCH seed {seed}");
3420- if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
3421- std::fs::write(&path, &stream).expect("writing pinned stream");
3422- eprintln!("wrote {path}");
3423- }
3424- return;
3425- } else {
3426- eprintln!("seed {seed}: bit-exact");
3427- }
3428- }
3429- eprintln!("no mismatch found in sweep");
3430- }
3431-
34323253 /// Final round of the TX4/tx-class lane's own gate: `--min-partition-size=8
34333254 /// --max-partition-size=8` pins every leaf to exactly 8x8 (spec
34343255 /// 5.11.4's own boundary carve-out aside, which a multiple-of-8 frame