diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index a6025eb8..1afe3977 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1730,24 +1730,61 @@ pub(crate) fn build_motion_field( mi_cols: usize, mi_rows: usize, order_hint: u32, + order_hint_bits: u32, ref_order_hints: [u32; 7], ) -> crate::motion_field::MotionField { let mut field = crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints); + // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference + // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other + // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block + // referencing one stores only its OTHER side's mv. With + // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and + // nothing is skipped. + let other_side = |rf: i8| -> bool { + if order_hint_bits == 0 { + return false; + } + let oh = ref_order_hints[(rf - LAST_FRAME) as usize]; + crate::motion_field::get_relative_dist(order_hint_bits, oh, order_hint) > 0 + || oh == order_hint + }; + // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is + // capped at 12 bits per component; a longer one is not stored at all. + const REFMVS_LIMIT: i32 = (1 << 12) - 1; for row in 0..mi_rows { for col in 0..mi_cols { - if let Some(info) = grid.get(row, col) - && info.is_inter - && info.ref_frame > 0 - { - field.set( - row, - col, - crate::motion_field::SavedMv { - mv: info.mv, - ref_frame: info.ref_frame, - }, - ); + let Some(info) = grid.get(row, col) else { + continue; + }; + if !info.is_inter { + continue; + } + // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST + // qualifying one wins -- a compound block stores its second + // reference's mv, never its first (unless the second is on the + // other side or over the limit). Storing slot 0 unconditionally + // put the wrong (mv, ref_frame_offset) pair in every compound + // block's cell, which a later frame's temporal candidate then + // projected with the wrong reference distance. + let mut saved: Option = None; + for (rf, mv) in [ + (info.ref_frame, Some(info.mv)), + (info.ref_frame1.unwrap_or(0), info.mv1), + ] { + let (Some(mv), true) = (mv, rf > 0) else { + continue; + }; + if other_side(rf) { + continue; + } + if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT { + continue; + } + saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf }); + } + if let Some(saved) = saved { + field.set(row, col, saved); } } } @@ -14412,6 +14449,10 @@ fn decode_inter_block( ); let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; let mut is_globalmv = false; + // lane-interbis r1: which single-ref mode this block resolved to, + // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for + // the `EC_MODE_VAL` value ladder below. + let mut dbg_mode = 16u32; let (mv, is_new_mv) = if !not_new { // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): // read at most two `drl_mode` bits, one per stack entry past the @@ -14444,9 +14485,11 @@ fn decode_inter_block( let mv = if !not_zero { // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already // computed at this block's own position in `gm_table`. + dbg_mode = 15; gm_table[(ref_frame - LAST_FRAME) as usize] } else { let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; + dbg_mode = if nearest { 13 } else { 14 }; if nearest { stack.nearest_mv } else { @@ -14468,6 +14511,21 @@ fn decode_inter_block( }; (mv, false) }; + if std::env::var_os("EC_TRACE_MODE").is_some() { + for (i, e) in stack.entries.iter().enumerate() { + eprintln!( + "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}", + e.mv.0, e.mv.1, e.weight + ); + } + eprintln!( + "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={dbg_mode} ref0={ref_frame} ref1=-1 mv0=({},{}) stack={} rng={}", + mv.0, + mv.1, + stack.entries.len(), + dec.debug_state().0 + ); + } // lane-gm r2: the two libaom predicates single-ref GLOBALMV // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating @@ -18985,6 +19043,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( mi_cols as usize, mi_rows as usize, order_hint, + order_hint_bits, ref_order_hints, ); diff --git a/crates/ec-av1/src/motion_field.rs b/crates/ec-av1/src/motion_field.rs index bac2f6eb..7768f7ac 100644 --- a/crates/ec-av1/src/motion_field.rs +++ b/crates/ec-av1/src/motion_field.rs @@ -420,7 +420,17 @@ pub fn add_tpl_ref_mv( if row8 < 0 || col8 < 0 { return None; } - let (fwd_mv, ref_frame_offset) = tpl.get(row8 as usize / 2, col8 as usize / 2)?; + let probe = tpl.get(row8 as usize / 2, col8 as usize / 2); + if std::env::var_os("EC_TRACE_TPL").is_some() { + match probe { + None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"), + Some((m, rfo)) => eprintln!( + "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) mfmv0=({},{}) rfo={rfo}", + m.0, m.1 + ), + } + } + let (fwd_mv, ref_frame_offset) = probe?; let projected = get_mv_projection(fwd_mv, cur_offset_0, ref_frame_offset); let mv = lower_mv_precision(projected, allow_high_precision_mv); Some(TplCandidate { mv }) diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 2ea18d78..aa60b0c7 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -4739,6 +4739,144 @@ mod tests { /// 8-bit AND 10-bit. Every decoded frame is compared to ffmpeg on Y, U and /// V; a refusal is counted, never SKIPped; an attempt that carried no rect /// inter residual is counted separately and still required pixel-exact. + /// Temporal (MFMV) motion-vector candidates, on a real aomenc stream + /// whose compound blocks feed the next frame's motion field + /// (`av1_copy_frame_mvs` -> `av1_setup_motion_field` -> `add_tpl_ref_mv`). + /// + /// lane-interbis r1 pinned this recipe because it is the one the rect + /// gate's attempt 1 decoded FULLY and still mismatched ffmpeg (a + /// 32x32 NEARESTMV block at mi (24, 40) of decode-order frame 5 took its + /// nearest candidate from a temporal cell holding the wrong reference: + /// `build_motion_field` stored a compound block's FIRST reference where + /// libaom stores its second). Every fully decoded attempt is compared + /// plane by plane; a refusal is counted, never SKIPped; the temporal + /// candidate counter must fire on a compared attempt, or the gate proves + /// nothing. + #[test] + fn a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 6usize); + for bit_depth in [8u32, 10u32] { + let (mut named_refusals, mut compared, mut tmv_proved) = (0u32, 0u32, 0usize); + for attempt in 0..2u32 { + let tx_search = if attempt == 0 { "0" } else { "1" }; + let duration = frame_count as f64 / 25.0; + // The pinned source: horizontal structure translating along X + // at 3 px/frame, which makes aomenc code compound LAST+GOLDEN + // blocks whose stored motion field the last frame reads back. + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)',format=yuv420p" + ); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let tx_arg = format!("--enable-tx-size-search={tx_search}"); + let args: Vec<&str> = vec![ + "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=34", "--cpu-used=0", + "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg, + "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", + "--lag-in-frames=0", + // Per-arm overrides go LAST (aomenc keeps the last + // occurrence of a repeated --enable-* flag). + &tx_arg, + "--enable-rect-partitions=1", "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", "--min-partition-size=16", + "--max-partition-size=32", + "--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(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::tmv_hits(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ + attempt {attempt}): {msg}" + ); + named_refusals += 1; + eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let tmv = decode::tmv_hits() - before; + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"); + } + compared += 1; + tmv_proved += tmv; + } + eprintln!( + "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \ + pixel-exact attempts, blocks with a temporal MV candidate={tmv_proved}" + ); + assert!( + compared > 0, + "{NAME} ({bit_depth}-bit): every attempt refused -- gate proved nothing" + ); + assert!( + tmv_proved > 0, + "{NAME} ({bit_depth}-bit): no compared attempt ever folded a temporal MV \ + candidate into a block's stack -- gate proved nothing" + ); + } + } + #[test] // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter // residual path IS implemented and reached, but no aomenc recipe swept diff --git a/lanes/interbis-r1.report.md b/lanes/interbis-r1.report.md new file mode 100644 index 00000000..a3fa2ca7 --- /dev/null +++ b/lanes/interbis-r1.report.md @@ -0,0 +1,118 @@ +# lane-interbis r1 — the "decodes fully, still mismatches" inter defect + +Branch `lane-interbis`, worktree `edith_codecs-interbis`, off lane-inter4 `d2d7327`. +No rebase (main unchanged since that base). + +## STEP 1 — reproduced and pinned + +The rect gate's 8-bit **attempt 1** is the one that decodes fully and mismatches: +192x128, 6 frames @25, `geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)'`, cq 34, +`--enable-tx-size-search=1`, `--min/max-partition-size=16/32`, cpu-used=0, lag 0. +Regenerated twice, byte-identical: +`fa70b7f68d311e577e3d14a86574909e6e58cac817b5a7fae04341c41ff50260` +(script `$HOME/.cache/interbis/gen.sh`; 10-bit twin +`67cad9bd5341db897de8a5308faecaedb1b0df761e4f315f1817156d124caef7`). + +Decode order == display order (no hidden frames; `--lag-in-frames=0`). +Frames 0..4 exact; **frame 5** luma only, 646 px, bbox x160-191 y93-127, max delta 39. +`EC_AV1_PREFILT_DUMP` (ours) vs the same rung from the instrumented aomdec: +frames 0-4 byte-identical, frame 5 differs in 640 luma px at x160-191 y96-127 — +i.e. **reconstruction**, not deblock/CDEF/LR, and exactly one 32x32 block: +mi (row 24, col 40), the frame's last block. + +EVIDENCE: $HOME/.cache/interbis/{o_pre.f5,a_pre.f5} | EC_AV1_PREFILT_DUMP ours vs aomdec, per-frame byte diff | frames 0-4 identical, frame 5 640 luma px wrong in the single 32x32 block at mi(24,40) + +## STEP 2 — first divergent element + +Entropy is **exact**: the msac range ladder agrees at that block's entry +(`EC_MODE ... rng=37852` both) and at the end of its mode read +(`rng=59818` both). Both decoders read mode 13 (NEARESTMV), ref0=2 (LAST2), +stack size 3. The **VALUE** differs: + + ours EC_MODE_VAL mi_row=24 mi_col=40 mode=13 ref0=2 mv0=(0,72) + aomdec EC_MODE_VAL mi_row=24 mi_col=40 mode=13 ref0=2 mv0=(0,-230) + +New `EC_STACK` rung (added to both decoders) shows entries 1 and 2 identical +(`(0,24) w=2`, `(0,-785) w=2`, the extra-search neighbours) and entry 0 — +the temporal (MFMV) candidate — wrong: ours `(0,72) w=32`, aomdec `(0,-230) w=16`. + +New `EC_TPL` rung (per `add_tpl_ref_mv` probe, both decoders) isolates it to the +projected motion field itself: over the 16 probes of that block, aomdec reads +`INVALID` at blk_col 0/2 and `mfmv0=(0,-230) rfo=3` at blk_col 4/6; ours reads +`mfmv0=(0,24) rfo=1` at all 16. `(0,24)*3/1 = (0,72)` — our wrong stored pair +projected exactly to the wrong candidate. + +EVIDENCE: $HOME/.cache/interbis/{o_tpl.txt,a_tpl.txt} | EC_TRACE_MODE + EC_TRACE_TPL on both decoders, block mi(24,40) of frame 5 | ours mfmv0=(0,24) rfo=1 x16 vs aomdec INVALID x8 + (0,-230) rfo=3 x8; stack entry 0 (0,72) vs (0,-230) + +## Root cause (decode.rs `build_motion_field`, spec 7.19 / libaom `av1_copy_frame_mvs`) + +Our per-frame saved motion field stored **`ref_frame[0]`/`mv[0]` of every inter +block**. libaom walks **both** reference slots and the **last qualifying one +wins**, skipping a slot when + +* `cm->ref_frame_side[ref]` is non-zero — the reference's OrderHint is ahead of + (or equal to) this frame's (`av1_calculate_ref_frame_side`), or +* `|mv| > REFMVS_LIMIT` (`(1<<12)-1`). + +Every compound block in this stream is `LAST + GOLDEN` (both past), so libaom +stores GOLDEN's mv with `ref_frame_offset = 3` where we stored LAST's with +offset 1 — a wrong (mv, distance) pair in every compound block's 8x8 cell, which +the next frame's temporal candidate then projects with the wrong reference +distance. Class name: **saved-field-keeps-slot-0** — a per-frame/DPB *summary* +of a multi-slot field must replay the reference's own slot walk (order + skips), +not keep slot 0. (Sibling of `neighbour-votes-all-its-fields`: there the +consumer voted only one slot, here the producer stores only one.) + +Fix: `crates/ec-av1/src/decode.rs:1728-1800` (`build_motion_field` now takes +`order_hint_bits`, walks both slots last-wins, applies the side and +`REFMVS_LIMIT` skips); call site `decode.rs:19040`. + +## Sweep + +`build_motion_field` is the only writer of `MotionField`/`SavedMv` +(`grep -rn "SavedMv\|MotionField" crates/ec-av1/src`); the mv-stack neighbour +maps already carry both slots (`MiInfo::ref_frame1`/`mv1`), and +`motion_field_projection`/`setup_motion_field` were re-read line-for-line +against `mvref_common.c` this round and match (one known, unreached gap noted +below). + +## Gate — GREEN, and it binds + +`a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact` +(`crates/ec-av1/src/stream.rs`, next to the rect gate): the pinned recipe above, +2 tx-size-search arms x {8-bit, 10-bit}, every fully decoded attempt compared +Y/U/V against ffmpeg, refusals counted (never SKIPped), and `decode::tmv_hits()` +asserted > 0 per depth. + + cargo test -p ec-av1 --lib temporal_mv_candidates -- --nocapture + 8-bit: 1 named refusal, 1 pixel-exact attempt, temporal-MV blocks = 66 + 10-bit: 1 named refusal, 1 pixel-exact attempt, temporal-MV blocks = 67 + test result: ok. 1 passed; 0 failed + +EVIDENCE: $HOME/.cache/interbis-tmvgate.log | cargo test -p ec-av1 --lib temporal_mv_candidates | 8-bit + 10-bit pixel-exact, tmv counter 66/67 + +Negative control (gate binds): with the store put back to first-slot-wins the +same gate fails at `frame 5 luma vs ffmpeg (attempt 1, 8-bit)`. + +EVIDENCE: $HOME/.cache/interbis-tmvgate-neg.log | one-line revert to `if saved.is_none()` then re-run the gate | FAILED, frame 5 luma, restored immediately after + +## Instruments added (env-gated, both decoders) + +- ours: `EC_MODE_VAL` + `EC_STACK` on the single-ref path of `decode_inter_block` + (byte-format-identical to the oracle's rung), `EC_TPL` per `add_tpl_ref_mv` probe. +- oracle (`~/.cache/aom-oracle/src`): `EC_STACK` (stack dump at `EC_MODE_VAL`) and + `EC_TPL` (per probe, incl. the `INVALID_MV` arm); `ninja aomdec` rebuilt. + +## Residue + +- **accepted: `motion_field_projection` does not check the source frame's + frame_type.** libaom returns 0 for a KEY/INTRA_ONLY source; here an intra + frame's saved field has no cells set, so the projection is inert — but its + *return value* (which feeds `ref_stamp`) can differ. Unreached on every stream + swept; fix-now if a future stream shows a `ref_stamp` divergence. +- **deferred: the rect inter residual gate** stays `#[ignore]`d (lane-inter4's + own residue, unblocked by 16x8/8x16 rect inter leaves); its + `out_of_scope_mismatch` assert is what surfaced this defect and is now + satisfiable on the 8-bit arm. +- **deferred: film probe** — this diff lifts no refusal; both films still stop at + lane-rectchroma's intra-rect-strip refusal.