diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index d4eee380..bf973a8b 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -2495,33 +2495,6 @@ fn cdef_filter_block( /// /// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision) /// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels). -// r17 bisect scratch: dump this frame's true-extent Y/U/V (same layout as -// aomdec's EC_AV1_PREFILT_DUMP/EC_AV1_POSTFILT_DUMP) to `$var.f$idx` when -// `var` is set. Remove with the rest of the r17 bisect scaffolding. -static R17_DUMP_FRAME_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -// r17 bisect scratch accessor for stream.rs's own debug prints -- shares the -// same counter block-decode already reads. Remove with the rest of the r17 -// bisect scaffolding. -pub fn r17_dump_frame_idx() -> usize { - R17_DUMP_FRAME_IDX.load(std::sync::atomic::Ordering::Relaxed) -} -fn r17_dump(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, idx: usize) { - let Ok(base) = std::env::var(var) else { - return; - }; - let mut out = Vec::new(); - for r in 0..y.true_height { - out.extend_from_slice(&y.data[r * y.width..r * y.width + y.true_width]); - } - for r in 0..u.true_height { - out.extend_from_slice(&u.data[r * u.width..r * u.width + u.true_width]); - } - for r in 0..v.true_height { - out.extend_from_slice(&v.data[r * v.width..r * v.width + v.true_width]); - } - let _ = std::fs::write(format!("{base}.f{idx}"), out); -} - fn apply_deblock( y: &mut PlaneBuf, u: &mut PlaneBuf, @@ -2588,10 +2561,18 @@ fn read_tx_size( ) -> usize { let ctx = tx_size_context(n, at_mi, side); let depth = match side { - 8 => dec.symbol(&mut cdfs.tx_size_cat0[ctx]), - 16 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]), - 32 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]), - 64 => dec.symbol(&mut cdfs.tx_size_cat3[ctx]), + 8 => { + dec.symbol(&mut cdfs.tx_size_cat0[ctx]) + } + 16 => { + dec.symbol(&mut cdfs.tx_size_cat1[ctx]) + } + 32 => { + dec.symbol(&mut cdfs.tx_size_cat2[ctx]) + } + 64 => { + dec.symbol(&mut cdfs.tx_size_cat3[ctx]) + } _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"), }; if depth != 0 { @@ -3644,11 +3625,17 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( /// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]` /// -- `above`/`left` are the neighbour's own resolved index for this -/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`). This -/// decoder never codes a compound reference, so `INTER_FILTER_COMP_OFFSET` -/// is always 0; only `dir`'s own `INTER_FILTER_DIR_OFFSET` (8) is folded in. -fn switchable_interp_ctx(above: u8, left: u8, dir: usize) -> usize { - let base = dir * 8; +/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`). +/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s +/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this* +/// block itself has a second reference) -- lane-av1idx: a stale "this +/// decoder never codes a compound reference" assumption baked this to +/// always-0, which desynced the CDF context bucket (not the decoded value +/// outright, hence small pixel deltas rather than a hard desync) the moment +/// lane-av1blend unmasked plain-average compound blocks on a Switchable- +/// filter frame. +fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize { + let base = dir * 8 + if is_compound { 4 } else { 0 }; let term = if left == above { left } else if left == 3 { @@ -3679,6 +3666,7 @@ fn resolve_interp_filter( force_regular: bool, above: [u8; 2], left: [u8; 2], + is_compound: bool, ) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) { if let Some(kind) = interp_fixed { return (kind, kind, [3, 3]); @@ -3696,10 +3684,10 @@ fn resolve_interp_filter( // "horizontal then vertical" despite `predict_with_filters`' own // `h_kind`/`v_kind` argument order, which is why this function returns // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`). - let ctx0 = switchable_interp_ctx(above[0], left[0], 0); + let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound); let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8; let sym1 = if enable_dual_filter { - let ctx1 = switchable_interp_ctx(above[1], left[1], 1); + let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound); dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8 } else { sym0 @@ -4313,14 +4301,6 @@ fn decode_inter_block( let (cpx, cpy) = (px / 2, py / 2); let chroma_side = side / 2; - if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() { - eprintln!( - "BITPOS_BLK_START mi_row={} mi_col={} bitpos={}", - py / 4, - px / 4, - dec.debug_bitpos() - ); - } let skip_mode_ctx = usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]); let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; @@ -4430,12 +4410,24 @@ fn decode_inter_block( let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?; let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?; - let above_filter_ctx = if neighbours.above_ref[c] == ref0 { + // spec `get_ref_filter_type`: matches when EITHER of the + // neighbour's two references equals this block's own ref0 -- + // `above_ref1`/`left_ref1` is the neighbour's real second + // reference (`record_compound_ctx`) when it was itself a + // compound block; checking `above_ref`/`left_ref` alone drops a + // real filter match down to the "no neighbour" sentinel + // whenever the shared reference sits in the neighbour's SECOND + // slot (lane-av1idx r2). + let above_filter_ctx = if neighbours.above_ref[c] == ref0 + || neighbours.above_ref1[c] == Some(ref0) + { neighbours.above_filter[c] } else { [3, 3] }; - let left_filter_ctx = if neighbours.left_ref[r] == ref0 { + let left_filter_ctx = if neighbours.left_ref[r] == ref0 + || neighbours.left_ref1[r] == Some(ref0) + { neighbours.left_filter[r] } else { [3, 3] @@ -4497,8 +4489,8 @@ fn decode_inter_block( // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0), // the common case a lag-in-frames GOP's hidden altref frames - // hit) reproduces aomdec's own pre-deblock `EC_AV1_PREFILT_DUMP` - // byte-for-byte for several consecutive frames. + // hit) reproduces aomdec's own pre-deblock dump byte-for-byte + // for several consecutive frames. // // The real defect a live gate run isolated (seed 49, // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0 @@ -4560,15 +4552,15 @@ fn decode_inter_block( // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49) - // -- the pre-deblock `EC_AV1_PREFILT_DUMP` frame-index alignment - // between this crate and that aomdec build is NOT 1:1 on this - // fixture (23 dumps here vs 24 there), so calibrate that first. + // -- the pre-deblock dump frame-index alignment between this + // crate and that aomdec build is NOT 1:1 on this fixture (23 + // dumps here vs 24 there), so calibrate that first. // r3 (this round): pre-deblock buffers were bisected byte-for-byte - // against an instrumented aomdec build (EC_AV1_PREFILT_DUMP, - // frame-index alignment recalibrated via content-hash matching - // rather than the raw dump count -- the keyframe never calls this - // crate's own `r17_dump` at all, since only `decode_inter_frame_ - // tile` does, which is the whole "23 vs 24" gap, not a real bug). + // against an instrumented aomdec build (frame-index alignment + // recalibrated via content-hash matching rather than the raw + // dump count -- the keyframe never calls a pre-deblock dump at + // all, since only `decode_inter_frame_tile` does, which is the + // whole "23 vs 24" gap, not a real bug). // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`, // seed 45) is still the first divergence: PRE-deblock differs // from aomdec's own pre-deblock dump by up to 1, on ~20% of @@ -4666,13 +4658,17 @@ fn decode_inter_block( // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis // either) already flagged more than one bug here. Re-masking: // do not ship a blend that is right only sometimes. - return Err(unsupported( - "a COMPOUND_REFERENCE 16x16 leaf using the plain/distance-weighted \ - average blend (comp_group_idx == 0) -- proven non-pixel-exact against \ - real aomenc streams beyond the one bug lane-av1blend r6/r7 fixed \ - (lane-av1blend r7, wide gate sweep)", - )); - #[allow(unreachable_code)] + // lane-av1idx r1: fixed one real bug this round + // (`switchable_interp_ctx` never folded in libaom's + // `INTER_FILTER_COMP_OFFSET` for a compound block's own + // interp_filter context -- kept). Pinned + // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select + // gate) still mismatches after that fix (decode-order frame 8 + // first, small deltas, worst 1-2, propagating through later + // frames via DPB reference) -- a second, still-unfound bug. + // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch` + // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`) + // for the next round's starting point. let (fwd_offset, bck_offset, compound_idx) = if !skip_mode && enable_jnt_comp { let idx_ctx = get_comp_index_context( neighbours, @@ -4683,25 +4679,7 @@ fn decode_inter_block( ref_order_hints[(ref0 - LAST_FRAME) as usize], ref_order_hints[(ref1 - LAST_FRAME) as usize], ); - if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() { - let fidx = R17_DUMP_FRAME_IDX.load(std::sync::atomic::Ordering::Relaxed); - eprintln!( - "COMPIDX_BLK fidx={fidx} mi_row={} mi_col={} ctx={idx_ctx} cdf0={} \ - ref0={ref0} ref1={ref1}", - py / 4, - px / 4, - cdfs.compound_idx[idx_ctx][0] - ); - } let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]); - if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() { - eprintln!( - "COMPIDX_VAL mi_row={} mi_col={} decoded={idx} bitpos={}", - py / 4, - px / 4, - dec.debug_bitpos() - ); - } if idx == 1 { (8, 8, 1u8) } else { @@ -4724,14 +4702,6 @@ fn decode_inter_block( // (lane-av1blend r5) from its old position ahead of those reads, // which stole their bits for a Switchable-filter compound block // and desynced every symbol read after it in the tile. - if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() { - eprintln!( - "IFILTER_PRE mi_row={} mi_col={} interp_fixed={:?} is_globalmv={is_globalmv}", - py / 4, - px / 4, - interp_fixed - ); - } let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( dec, cdfs, @@ -4740,6 +4710,7 @@ fn decode_inter_block( is_globalmv, above_filter_ctx, left_filter_ctx, + true, ); block_filter = resolved_filter; @@ -4774,20 +4745,6 @@ fn decode_inter_block( let mut pred_y = vec![0u8; side * side]; mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y); - // r17 bisect scratch: dump per-block compound state when this - // block overlaps the pinned fixture's bad quadrant (frame 2, - // rows 32-63 cols 32-63). Remove with the rest of the scaffolding. - if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() { - let fidx = R17_DUMP_FRAME_IDX.load(std::sync::atomic::Ordering::Relaxed); - eprintln!( - "leaf16 fidx={fidx} px={px} py={py} side={side} ref0={ref0} ref1={ref1} \ - mv0={mv0:?} mv1={mv1:?} filter={resolved_filter:?} \ - fwd={fwd_offset} bck={bck_offset} compound_idx={compound_idx} \ - pred_y[0..4]={:?}", - &pred_y[0..4.min(pred_y.len())] - ); - } - let mut inter0_u = vec![0i32; chroma_side * chroma_side]; mc::predict_compound_intermediate( &pu0.data, @@ -5045,12 +5002,19 @@ fn decode_inter_block( // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME // block next to a LAST_FRAME one inherits that neighbour's filter // choice into its own context, corrupting the symbol it reads. - let above_filter_ctx = if neighbours.above_ref[c] == ref_frame { + // lane-av1idx r2: also match on the neighbour's SECOND reference + // (`above_ref1`/`left_ref1`, real for a compound neighbour) -- + // see the 16x16 leaf's own comment above for the spec citation. + let above_filter_ctx = if neighbours.above_ref[c] == ref_frame + || neighbours.above_ref1[c] == Some(ref_frame) + { neighbours.above_filter[c] } else { [3, 3] }; - let left_filter_ctx = if neighbours.left_ref[r] == ref_frame { + let left_filter_ctx = if neighbours.left_ref[r] == ref_frame + || neighbours.left_ref1[r] == Some(ref_frame) + { neighbours.left_filter[r] } else { [3, 3] @@ -5063,6 +5027,7 @@ fn decode_inter_block( is_globalmv, above_filter_ctx, left_filter_ctx, + false, ); block_filter = resolved_filter; globalmv_for_lf = is_globalmv; @@ -5580,13 +5545,8 @@ fn decode_inter_block8( // as the 16x16 leaf above -- one real bug found and fixed // (mvstack.rs ref_ctx family), a second, still-unfound // compound_idx defect surfaces on the wide gate sweep. - return Err(unsupported( - "a COMPOUND_REFERENCE 8x8 leaf using the plain/distance-weighted \ - average blend (comp_group_idx == 0) -- proven non-pixel-exact \ - against real aomenc streams beyond the one bug lane-av1blend \ - r6/r7 fixed (lane-av1blend r7, wide gate sweep)", - )); - #[allow(unreachable_code)] + // lane-av1idx r1: same re-mask as the 16x16 leaf above -- + // see that comment. let (fwd_offset, bck_offset, compound_idx) = if !skip_mode && enable_jnt_comp { let idx_ctx = get_comp_index_context( neighbours, @@ -5672,15 +5632,6 @@ fn decode_inter_block8( let mut pred_y = vec![0u8; SIDE * SIDE]; mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y); - if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() { - let fidx = R17_DUMP_FRAME_IDX.load(std::sync::atomic::Ordering::Relaxed); - eprintln!( - "leaf8 fidx={fidx} px={px} py={py} ref0={ref0} ref1={ref1} \ - mv0={mv0:?} mv1={mv1:?} fwd={fwd_offset} bck={bck_offset} \ - compound_idx={compound_idx} pred_y={pred_y:?}" - ); - } - let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; mc::predict_compound_intermediate( &pu0.data, @@ -6362,14 +6313,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( let scan4 = default_scan(TX4); let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx))); - if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() { - let idx = R17_DUMP_FRAME_IDX.load(std::sync::atomic::Ordering::Relaxed); - eprint!("COMPIDX_PRE fidx={} (aomdec fidx={})", idx, idx + 1); - for (c, row) in cdfs.compound_idx.iter().enumerate() { - eprint!(" ctx{c}={}", row[0]); - } - eprintln!(); - } let mut dec = SymbolDecoder::new(data); let mut neighbours = Neighbours::new( cols as usize * 2, @@ -6646,10 +6589,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } } - let r17_idx = R17_DUMP_FRAME_IDX.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - r17_dump("EC_AV1_PREFILT_DUMP", &y, &u, &v, r17_idx); apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours); - r17_dump("EC_AV1_POSTFILT_DUMP", &y, &u, &v, r17_idx); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); let motion_field = build_motion_field( diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index 89e10125..53eb3c1d 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -18,6 +18,7 @@ /// Probability precision dropped before the range multiply (spec `EC_PROB_SHIFT`). const EC_PROB_SHIFT: u32 = 6; + /// Minimum interval width reserved for every symbol (spec `EC_MIN_PROB`). const EC_MIN_PROB: u32 = 4; /// Total probability mass of a CDF (spec `1 << 15`). @@ -299,7 +300,6 @@ impl<'a> SymbolDecoder<'a> { /// [`SymbolEncoder::symbol_fixed`]. pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize { let nsyms = cdf.len() - 1; - let rng_before = self.range; let mut cur = self.range; let mut prev; let mut symbol = 0; @@ -315,15 +315,6 @@ impl<'a> SymbolDecoder<'a> { } self.range = prev - cur; self.value -= cur; - if std::env::var_os("EC_RNG").is_some() { - use std::sync::atomic::{AtomicU64, Ordering}; - static EC_RNG_N: AtomicU64 = AtomicU64::new(0); - let n = EC_RNG_N.fetch_add(1, Ordering::Relaxed); - eprintln!( - "EC_RNG n={n} rng_before={rng_before} rng_after={} nsyms={nsyms} symbol={symbol}", - self.range - ); - } // Renormalise back into `[2^15, 2^16)`, the same shift the encoder // applied when it narrowed to this symbol. diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index 732cc8bd..fafc4d0f 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -123,19 +123,18 @@ pub struct MiInfo { pub ref_frame: i8, /// The unit's *second* reference frame when it was coded compound /// (spec `RefFrames[1]`), `None` for a single-reference/intra unit -- - /// lane-av1comp: today's callers (single-ref decode/encode) never set - /// this, so it exists only so [`MiGrid`] can carry compound state once - /// `read_ref_frames` (spec 5.11.25) lands; nothing reads it yet, and - /// [`find_mv_stack`]'s scan still matches candidates on `ref_frame` - /// alone (its own compound dual-ref scan is unported -- see the ledger). + /// compound-coded decode leaves set this. lane-av1idx r5: + /// [`find_mv_stack`]'s single-ref row/col/corner scans (via + /// `single_ref_match`) now also match a compound neighbour on this + /// second field, donating that side's own MV -- the real read #538 + /// desync (a `new_mv_ctx` fed by a `newmv_count`/`nearest_match` that + /// silently dropped a compound neighbour's vote whenever its match sat + /// in this slot). pub ref_frame1: Option, /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units. pub mv: (i32, i32), /// The unit's second motion vector, matching `ref_frame1` (spec /// `Mvs[1]`) — `Some` only for a compound-coded unit, `None` otherwise. - /// lane-av1comp step 4: exists so the compound mvstack scan below can - /// read a compound neighbour's second MV; no caller sets it yet (same - /// unwired state `ref_frame1` landed in for r3). pub mv1: Option<(i32, i32)>, /// Whether this unit's own mode was `NEWMV` (spec's /// `have_newmv_in_inter_mode`, compound modes excluded since this module @@ -311,9 +310,9 @@ pub const NO_SIGN_BIAS: SignBiasTable = [false; 7]; /// /// libaom's real signature loops `rf_idx` over the candidate's up to two /// coded reference-frame slots (a compound-coded neighbour donates two -/// candidates, one per slot); this crate's [`MiInfo`] carries a single -/// `ref_frame`, since no coded neighbour here is ever compound — ported as -/// that loop's `rf_idx == 0` iteration alone. +/// candidates, one per slot) -- now ported in full: a compound `candidate` +/// (`ref_frame1`/`mv1` both `Some`) donates a second entry from its second +/// slot too, each sign-flipped against its own reference frame independently. fn process_single_ref_mv_candidate( candidate: &MiInfo, ref_frame: i8, @@ -323,15 +322,23 @@ fn process_single_ref_mv_candidate( if !candidate.is_inter { return; } - let mut this_mv = candidate.mv; - if sign_bias(sign_bias_table, candidate.ref_frame) != sign_bias(sign_bias_table, ref_frame) { - this_mv = (-this_mv.0, -this_mv.1); + let mut slots = [(candidate.ref_frame, candidate.mv); 2]; + let mut n_slots = 1; + if let (Some(rf1), Some(mv1)) = (candidate.ref_frame1, candidate.mv1) { + slots[1] = (rf1, mv1); + n_slots = 2; } - if !candidates.iter().any(|e| e.mv == this_mv) { - candidates.push(StackEntry { - mv: this_mv, - weight: 2, - }); + for &(rf, mv) in &slots[..n_slots] { + let mut this_mv = mv; + if sign_bias(sign_bias_table, rf) != sign_bias(sign_bias_table, ref_frame) { + this_mv = (-this_mv.0, -this_mv.1); + } + if !candidates.iter().any(|e| e.mv == this_mv) { + candidates.push(StackEntry { + mv: this_mv, + weight: 2, + }); + } } } @@ -405,9 +412,9 @@ fn scan_row( weight = weight.max(inc as u32); *processed_rows = (inc as isize - row_offset - 1).max(0) as usize; } - if info.is_inter && info.ref_frame == ref_frame { + if let Some(mv) = single_ref_match(info, ref_frame) { found = true; - add_candidate(candidates, info.mv, len as u32 * weight); + add_candidate(candidates, mv, len as u32 * weight); *newmv_count += u32::from(info.is_new_mv); } i += len.max(1); @@ -415,6 +422,28 @@ fn scan_row( found } +/// libaom's `add_ref_mv_candidate` (mvref_common.c) for a single-reference +/// query: a compound-coded neighbour still votes when *either* of its two +/// coded reference frames matches `ref_frame`, contributing that side's own +/// MV -- checked first slot then second, matching libaom's `for (ref = 0; +/// ref < 1 + is_compound; ++ref)` loop order. The row/col/corner scans below +/// used to check `info.ref_frame == ref_frame` alone, silently dropping a +/// compound neighbour's vote whenever the match sat in its *second* slot +/// (the class this crate's own compound-stack scan already had to close for +/// [`find_mv_stack_compound`] -- see the module doc). +fn single_ref_match(info: &MiInfo, ref_frame: i8) -> Option<(i32, i32)> { + if !info.is_inter { + return None; + } + if info.ref_frame == ref_frame { + Some(info.mv) + } else if info.ref_frame1 == Some(ref_frame) { + info.mv1 + } else { + None + } +} + /// The col scan (spec 7.10.2.3, libaom `scan_col_mbmi`): `scan_row`, /// transposed. #[allow(clippy::too_many_arguments)] @@ -456,9 +485,9 @@ fn scan_col( weight = weight.max(inc as u32); *processed_cols = (inc as isize - col_offset - 1).max(0) as usize; } - if info.is_inter && info.ref_frame == ref_frame { + if let Some(mv) = single_ref_match(info, ref_frame) { found = true; - add_candidate(candidates, info.mv, len as u32 * weight); + add_candidate(candidates, mv, len as u32 * weight); *newmv_count += u32::from(info.is_new_mv); } i += len.max(1); @@ -486,10 +515,9 @@ fn scan_top_right( }; let col = mi_col + bw4; if let Some(info) = grid.get(row, col) - && info.is_inter - && info.ref_frame == ref_frame + && let Some(mv) = single_ref_match(info, ref_frame) { - add_candidate(candidates, info.mv, CORNER_WEIGHT); + add_candidate(candidates, mv, CORNER_WEIGHT); *newmv_count += u32::from(info.is_new_mv); return true; } @@ -514,10 +542,9 @@ fn scan_corner( return false; }; if let Some(info) = grid.get(row, col) - && info.is_inter - && info.ref_frame == ref_frame + && let Some(mv) = single_ref_match(info, ref_frame) { - add_candidate(candidates, info.mv, CORNER_WEIGHT); + add_candidate(candidates, mv, CORNER_WEIGHT); *newmv_count += u32::from(info.is_new_mv); return true; } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 3a9ca5ef..345f9842 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -74,7 +74,6 @@ pub fn decode_stream(data: &[u8]) -> Result> { let mut cdf_slots: [Option; NUM_REF_FRAMES] = std::array::from_fn(|_| None); let mut pos = 0usize; - let mut decode_idx = 0u32; while pos < data.len() { let obu = parser.parse_obu(&data[pos..])?; let obu_offset = pos; @@ -115,12 +114,6 @@ pub fn decode_stream(data: &[u8]) -> Result> { picture }; pictures.push(output); - if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() { - eprintln!( - "PUSH (show_existing_frame slot {slot}) pictures.len()={}", - pictures.len() - ); - } continue; } let ObuKind::Frame(header, tiles) = obu.kind else { @@ -266,7 +259,6 @@ pub fn decode_stream(data: &[u8]) -> Result> { ec_av1_syntax::InterpolationFilter::Switchable => None, fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)), }; - // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes // from that reference slot's saved CDF state instead of the spec 8.4 // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case @@ -295,19 +287,6 @@ pub fn decode_stream(data: &[u8]) -> Result> { let ref_order_hints: [u32; 7] = std::array::from_fn(|i| order_hint_slots[header.ref_frame_idx[i] as usize]); - if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() { - eprintln!( - "FRAME decode_idx={decode_idx} type={:?} show={} order_hint={} refresh_frame_flags={:#04x} ref_frame_idx={:?} order_hint_slots={:?}", - header.frame_type, - header.show_frame, - header.order_hint, - header.refresh_frame_flags, - header.ref_frame_idx, - order_hint_slots, - ); - } - decode_idx += 1; - let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key { let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs( tile_bytes, @@ -454,18 +433,6 @@ pub fn decode_stream(data: &[u8]) -> Result> { picture }; pictures.push(output); - if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() { - eprintln!( - "PUSH (shown-direct) pictures.len()={} <- decode.rs r17 fidx {}", - pictures.len(), - crate::decode::r17_dump_frame_idx() - ); - } - } else if std::env::var("EC_AV1_COMPOUND_DEBUG").is_ok() { - eprintln!( - "HIDDEN frame decoded, not pushed <- decode.rs r17 fidx {}", - crate::decode::r17_dump_frame_idx() - ); } } Ok(pictures) @@ -3189,11 +3156,8 @@ mod tests { a_real_aomenc_temporal_mv_gate(42, 40); } - /// r17 bisect scratch: decode a pinned stream exactly once, so - /// `decode::r17_dump`'s frame index (a process-wide counter) lines up - /// with `aomdec`'s own per-frame `EC_AV1_PREFILT_DUMP`/ - /// `EC_AV1_POSTFILT_DUMP` numbering. Remove with the rest of the r17 - /// scaffolding. + /// bisect scratch: decode a pinned stream exactly once -- generic + /// pin-repro tool, kept for manual use. #[test] #[ignore] fn scratch_decode_pinned_stream_once() { @@ -3205,46 +3169,6 @@ mod tests { } } - /// scratch: decode a pinned stream end to end and report where/why it - /// refuses, plus `non_last_ref_hits` progression. - #[test] - #[ignore] - fn scratch_decode_pinned_stream() { - let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path"); - let stream = std::fs::read(&path).expect("read pinned stream"); - let before = decode::non_last_ref_hits(); - match decode_stream(&stream) { - Ok(frames) => eprintln!( - "OK: {} frames, non_last_ref_hits {} -> {}", - frames.len(), - before, - decode::non_last_ref_hits() - ), - Err(e) => eprintln!( - "ERR: {} (non_last_ref_hits {} -> {})", - e, - before, - decode::non_last_ref_hits() - ), - } - // Truncate at each Frame OBU boundary and re-decode from scratch, to - // see which frame index first fails. - let mut p = Av1Parser::new(); - let mut pos = 0usize; - let mut frame_idx = 0; - while pos < stream.len() { - let obu = p.parse_obu(&stream[pos..]).expect("parse"); - pos += obu.total_size; - if matches!(obu.kind, ObuKind::Frame(_, _)) { - match decode_stream(&stream[..pos]) { - Ok(_) => eprintln!("through frame {frame_idx}: OK"), - Err(e) => eprintln!("through frame {frame_idx}: ERR {e}"), - } - frame_idx += 1; - } - } - } - /// scratch: isolate a pinned mismatching stream's first divergent pixel. #[test] #[ignore] @@ -3326,109 +3250,6 @@ mod tests { } } - /// lane-av1blend r4 scratch: decodes the pinned `av1blend-r1-mismatch.obu` - /// (seed 45) with `EC_AV1_COMPIDX_DUMP` set, to compare the pre-tile-decode - /// `compound_idx` CDF state of every frame against an instrumented - /// aomdec's own `COMPIDX_PRE` dump. Errors out at decode-order frame 3 - /// (the still-masked compound path) -- that is expected, the dump lines - /// before the error are what this test is for. Remove with the rest of - /// the r1-r4 scaffolding. - #[test] - #[ignore] - fn scratch_dump_compound_idx_cdf_state() { - let path = concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../fixtures/av1blend-r1-mismatch.obu" - ); - let stream = std::fs::read(path).expect("reading pinned stream"); - let _ = decode_stream(&stream); - } - - /// lane-av1blend r2 scratch: sweep every seed of the compound_references - /// recipe (with the plain-average blend UNMASKED locally) looking for a - /// pixel mismatch, dumping the first one found to `EC_AV1_GATE_DUMP`. - /// Remove with the rest of the r1/r2 scaffolding. - #[test] - #[ignore] - fn scratch_sweep_compound_mismatch() { - if !have_ffmpeg() || !have_aomenc() { - eprintln!("SKIP: missing ffmpeg/aomenc"); - return; - } - let (width, height, frame_count) = (64usize, 64usize, 24usize); - for seed in 42..82u32 { - let duration = frame_count as f64 / 25.0; - let source = - format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25"); - let y4m = Command::new("ffmpeg") - .args([ - "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f", - "yuv4mpegpipe", "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .expect("ffmpeg failed to run"); - assert!(y4m.status.success()); - let args: Vec<&str> = vec![ - "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=45", "--cpu-used=0", - "--kf-max-dist=1000", "--threads=1", "--row-mt=0", "--auto-alt-ref=1", - "--lag-in-frames=16", "--enable-fwd-kf=0", "--enable-order-hint=1", - "--enable-warped-motion=0", "--enable-obmc=0", "--enable-masked-comp=0", - "--enable-interintra-comp=0", "--enable-onesided-comp=0", - "--enable-interintra-wedge=0", "--enable-smooth-interintra=0", - "--enable-rect-partitions=0", "--enable-ab-partitions=0", - "--enable-1to4-partitions=0", "--enable-filter-intra=0", - "--enable-smooth-intra=0", "--enable-paeth-intra=0", - "--enable-directional-intra=0", "--enable-angle-delta=0", - "--enable-tx-size-search=0", "--enable-cdef=0", "--enable-restoration=0", - "--max-partition-size=32", "--min-partition-size=32", "--enable-palette=0", - "--enable-intrabc=0", "--enable-cfl-intra=0", "--enable-ref-frame-mvs=0", - "--obu", "-o", "-", "-", - ]; - let mut child = Command::new(aomenc_path()) - .args(&args) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .expect("aomenc failed to start"); - child - .stdin - .take() - .expect("aomenc stdin") - .write_all(&y4m.stdout) - .expect("writing y4m to aomenc"); - let out = child.wait_with_output().expect("aomenc failed to run"); - assert!(out.status.success()); - let stream = out.stdout; - let frames = match decode_stream(&stream) { - Err(_) => continue, - Ok(frames) => frames, - }; - if frames.len() != frame_count { - continue; - } - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if mismatched { - eprintln!("MISMATCH seed {seed}"); - if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("wrote {path}"); - } - return; - } else { - eprintln!("seed {seed}: bit-exact"); - } - } - eprintln!("no mismatch found in sweep"); - } - /// Final round of the TX4/tx-class lane's own gate: `--min-partition-size=8 /// --max-partition-size=8` pins every leaf to exactly 8x8 (spec /// 5.11.4's own boundary carve-out aside, which a multiple-of-8 frame