diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index ab413f4a..90d096da 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -3766,6 +3766,15 @@ fn decode_inter_block( // stays refused by name until that's found. let (py_ref, pu_ref, pv_ref) = match ref_frame { LAST_FRAME => (ref_y, ref_u, ref_v), + GOLDEN_FRAME => match (golden_y, golden_u, golden_v) { + (Some(gy), Some(gu), Some(gv)) => (gy, gu, gv), + _ => { + return Err(unsupported( + "GOLDEN_FRAME selected with no golden picture at this frame's \ + ref_frame_idx[3] slot", + )); + } + }, _ => { return Err(unsupported( "a reference frame other than LAST_FRAME (LAST2/LAST3/GOLDEN/BWDREF/\ @@ -3788,7 +3797,6 @@ fn decode_inter_block( mi_cols as usize, mi_rows as usize, ); - let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; let mut is_globalmv = false; let (mv, is_new_mv) = if !not_new { @@ -3879,8 +3887,8 @@ fn decode_inter_block( globalmv_for_lf = is_globalmv; if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( - "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side}", - skip as u8, mv.0, mv.1 + "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side} ref={ref_frame} filter={:?}", + skip as u8, mv.0, mv.1, block_filter ); } for dr in 0..bw4 { diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index c6f925ec..eb1113eb 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -192,6 +192,15 @@ const REF_CAT_LEVEL: u32 = 640; /// The most candidates a stack keeps (spec `MAX_REF_MV_STACK_SIZE`). const MAX_STACK_SIZE: usize = 8; +/// The single-reference extension's own, *smaller* cap (spec's +/// `MAX_MV_REF_CANDIDATES`, `av1/common/enums.h`): that pass only ever tops +/// the stack up to two entries — enough to guarantee `NEARESTMV`/`NEARMV` +/// predictors — never all the way to [`MAX_STACK_SIZE`]. libaom gates its +/// two extension loops on `*refmv_count < MAX_MV_REF_CANDIDATES`, not the +/// 8-entry stack cap; this module's prior hand-written pass used +/// `MAX_STACK_SIZE` here, which is the wrong bound. +const MAX_MV_REF_CANDIDATES: usize = 2; + /// The floor libaom's `scan_row_mbmi`/`scan_col_mbmi` weight starts at /// before a same-or-wider candidate block can raise it (`uint16_t weight = /// 2;`, mvref_common.c). @@ -218,6 +227,53 @@ fn add_candidate(candidates: &mut Vec, mv: (i32, i32), weight: u32) } } +/// Whether `ref_frame`'s prediction runs backward in display order +/// (`cm->ref_frame_sign_bias`, libaom): flips a borrowed neighbour's MV +/// sign in [`process_single_ref_mv_candidate`] when the neighbour's own +/// reference disagrees. This decoder only ever threads forward references +/// (`LAST_FRAME`/`GOLDEN_FRAME`) to MC — never `BWDREF`/`ALTREF` — so every +/// call site compares `false != false` and the flip is always inert. Ported +/// anyway (never proved away, per this round's own bounds): a real +/// backward reference would need this to be correct on day one. +fn sign_bias(_ref_frame: i8) -> bool { + false +} + +/// libaom's `process_single_ref_mv_candidate` (mvref_common.c): folds one +/// already-coded neighbour into the stack as a low-weight (`2`, unboosted) +/// filler entry, used only by the single-reference extension pass below. +/// Unlike every scan above, this runs over *any* inter neighbour regardless +/// of which reference frame it coded — that is the whole point of the +/// pass (topping the stack up when the real scans found too few same-ref +/// candidates) — and dedupes by MV value against the *whole* stack so far, +/// silently dropping the candidate (no weight bump, unlike +/// [`add_candidate`]) when a match is already there. +/// +/// 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. +fn process_single_ref_mv_candidate( + candidate: &MiInfo, + ref_frame: i8, + candidates: &mut Vec, +) { + if !candidate.is_inter { + return; + } + let mut this_mv = candidate.mv; + if sign_bias(candidate.ref_frame) != sign_bias(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, + }); + } +} + /// The row scan (spec 7.10.2.2, libaom `scan_row_mbmi`): walks candidate /// *blocks* — not individual 4x4 cells — along the row `row_offset` mi units /// above the block's own row, in run-length steps sized by each candidate's @@ -605,6 +661,65 @@ pub fn find_mv_stack( candidates.sort_by_key(|e| std::cmp::Reverse(e.weight)); candidates.truncate(MAX_STACK_SIZE); + // libaom's "single reference frame extension" (`setup_ref_mv_list`, + // mvref_common.c, the `else` branch under "Handle single reference + // frame extension", calling `process_single_ref_mv_candidate`): when + // fewer than [`MAX_MV_REF_CANDIDATES`] (2, *not* `MAX_STACK_SIZE`) survive + // the scans above, top the stack up to that guarantee by re-walking the + // row directly above and the column directly left, gated on + // `refmv_count < MAX_MV_REF_CANDIDATES` per step (so it can stop after + // just one addition) -- over *any* inter neighbour regardless of which + // reference frame it coded, not just `ref_frame`. This module's doc + // used to call this pass a no-op ("whatever it would add was already + // added by the row/col scan"), true only while a stream ever has one + // live reference frame: once a second reference (`GOLDEN_FRAME`) is + // live next to `LAST_FRAME` blocks, this pass pulls in the other + // reference's MV as a low-weight (`2`, unboosted -- below + // `REF_CAT_LEVEL`) filler entry purely to make `entries.len()` (and + // hence how many `drl_mode` bits a `NEWMV` block reads) match the real + // bitstream -- round 10 (lane-av1golden8) traced a `GOLDEN_FRAME` + // `NEWMV` block desyncing its own `read_mv` by exactly this gap (real + // stack `len=2`, this module's `len=1`, one missing `drl_mode` bit). + // Round 11 replaced that round's hand-proved reduction (a bespoke + // re-scan gated on `MAX_STACK_SIZE`, weighing every hit `2` unconditionally) + // with this exact port: real gate is `MAX_MV_REF_CANDIDATES` (2), real + // reach is the block's own `bw4`/`bh4` (see `mi_size` below, not a flat + // 16), and dedup/weight/sign-bias now live in + // [`process_single_ref_mv_candidate`] itself, ported from libaom's + // function of the same name rather than re-derived by hand. + // libaom's `mi_size` for this pass (`setup_ref_mv_list`): the block's + // own span (`xd->width`/`xd->height`, i.e. `bw4`/`bh4` here), capped at + // a 64x64 superblock's 16 mi units, further clipped to the frame edge — + // never just "16, clipped to the frame edge" the way the prior + // hand-written pass had it, which over-walked past a small query + // block's own row/col run into cells that real neighbour scan (a wider + // block covering more than `bw4`/`bh4`) had already folded in above. + let mi_width = (16usize).min(bw4).min(mi_cols.saturating_sub(mi_col)); + let mi_height = (16usize).min(bh4).min(mi_rows.saturating_sub(mi_row)); + let mi_size = mi_width.min(mi_height); + if max_row_offset.unsigned_abs() >= 1 { + let mut idx = 0usize; + while idx < mi_size && candidates.len() < MAX_MV_REF_CANDIDATES { + let cand = grid.get(mi_row - 1, mi_col + idx); + let step = cand.map_or(1, |c| c.size).max(1); + if let Some(c) = cand { + process_single_ref_mv_candidate(c, ref_frame, &mut candidates); + } + idx += step; + } + } + if max_col_offset.unsigned_abs() >= 1 { + let mut idx = 0usize; + while idx < mi_size && candidates.len() < MAX_MV_REF_CANDIDATES { + let cand = grid.get(mi_row + idx, mi_col - 1); + let step = cand.map_or(1, |c| c.size).max(1); + if let Some(c) = cand { + process_single_ref_mv_candidate(c, ref_frame, &mut candidates); + } + idx += step; + } + } + let clamp = |mv| clamp_mv_ref(mv, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows); let nearest_mv = candidates.first().map_or((0, 0), |e| clamp(e.mv)); let near_mv = candidates.get(1).map_or((0, 0), |e| clamp(e.mv)); diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 079ec920..47518bc7 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -558,23 +558,26 @@ mod tests { /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME` /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy - /// of GOLDEN's picture. Round 4 asserted a pixel-exact decode against - /// ffmpeg here; round 5 (lane-av1golden2) found that only proved the - /// symbol path plus a whole-pel copy -- the first real aomenc GOLDEN - /// streams mismatch past a stacked defect, so the arm is masked again - /// and this fixture now asserts the mask: the stream must still reach - /// the `GOLDEN_FRAME` `single_ref` read (hit counter) and must then - /// refuse by name, not decode-and-be-wrong or misparse. Round 6 - /// (lane-av1golden4) un-masked, found the residue is now a narrow - /// deblock-edge rounding defect at GOLDEN/LAST boundaries (`decode.rs`'s - /// round-6 note, pinned by - /// `stream::tests::pinned_golden4_stream_decodes_pixel_exact`), and - /// re-masked -- this fixture proves the symbol path and a whole-pel - /// copy only, not real subpel MC + deblock off the golden plane. The - /// fixture itself is kept verbatim -- the next round flips this test - /// back to the pixel-exact form the moment the live path holds. + /// of GOLDEN's picture, so its output must equal frame 0's own + /// reconstruction exactly, and must differ from frame 1's -- proof the + /// decoder actually read the golden plane, not silently substituted + /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a + /// deblock/MC residue that turned out to be film-grain synthesis + /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN); + /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing + /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so + /// this fixture flips back to its round-4 pixel-exact form. ffmpeg + /// decodes the identical wire bytes as the foreign oracle + /// (shared-oracle-blindness class): this crate's own decoder agreeing + /// with itself would prove nothing. #[test] - fn a_hand_built_golden_reference_refuses_by_name() { + fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() { + if !have_ffmpeg() { + eprintln!( + "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg" + ); + return; + } use crate::cdf_state::Cdfs; use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of}; use crate::encode::{inter_frame_headers, key_frame_headers}; @@ -648,20 +651,31 @@ mod tests { stream.extend(frame_obu(&seq, &header2, &tile2).unwrap()); let before = non_last_ref_hits(); - let err = decode_stream(&stream).expect_err( - "the masked GOLDEN_FRAME arm decoded a hand-built GOLDEN stream -- \ - if the mask was lifted on purpose, flip this test back to its round-4 \ - pixel-exact form", - ); + let decoded = decode_stream(&stream).unwrap(); + assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures"); assert!( non_last_ref_hits() > before, - "run {run}: GOLDEN_FRAME's single_ref read never fired -- the stream \ - misparsed before reaching the refusal it is supposed to prove" + "run {run}: GOLDEN_FRAME never fired" ); - let msg = err.to_string(); - assert!( - msg.contains("other than LAST_FRAME"), - "run {run}: refused, but not by the GOLDEN mask's own name: {msg}" + + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3); + for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg"); + assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg"); + assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg"); + } + assert_eq!( + decoded[0].y, key.reconstruction.y, + "run {run}: frame 0 vs the encoder's own reconstruction" + ); + assert_eq!( + decoded[2].y, key.reconstruction.y, + "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names" + ); + assert_ne!( + decoded[2].y, decoded[1].y, + "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \ + distinguishable -- the gate proves nothing" ); } } @@ -2045,11 +2059,19 @@ mod tests { "--enable-palette=0", "--enable-intrabc=0", "--enable-cfl-intra=0", - // `default` still lets aomenc's heuristic flip + // `--tune-content=film` was dropped: on this box it + // makes aomenc emit `apply_grain` almost every attempt + // (lane-av1golden8 round 10 measurement, live: 120/120 + // real attempts hit a named refusal, 0 ever fired + // GOLDEN_FRAME -- mostly `apply_grain`, dominated by its + // own recipe flag) -- film grain synthesis has its own + // dedicated refusal test and must not starve this gate + // of the GOLDEN_FRAME draws it exists to prove. Default + // content tuning still occasionally flips // `allow_screen_content_tools` on for this synthetic - // gradient content -- `film` forces the non-screen path - // instead. - "--tune-content=film", + // gradient content (a separate, already-documented open + // refusal), which the 120-attempt coin flip below + // tolerates the same way. "--obu", "-o", "-",