forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-interbis' into lane-inter4

Browse files at this commit

7c85bedec61b100a4af104d16169eda44f2aabeaAhmet Kaan GümüşParent: e4c2a0be79d602
crates/ec-av1/src/decode.rsmodified+71 -12
@@ -1744,24 +1744,61 @@ pub(crate) fn build_motion_field(
17441744 mi_cols: usize,
17451745 mi_rows: usize,
17461746 order_hint: u32,
1747+ order_hint_bits: u32,
17471748 ref_order_hints: [u32; 7],
17481749 ) -> crate::motion_field::MotionField {
17491750 let mut field =
17501751 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
1752+ // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
1753+ // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
1754+ // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
1755+ // referencing one stores only its OTHER side's mv. With
1756+ // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
1757+ // nothing is skipped.
1758+ let other_side = |rf: i8| -> bool {
1759+ if order_hint_bits == 0 {
1760+ return false;
1761+ }
1762+ let oh = ref_order_hints[(rf - LAST_FRAME) as usize];
1763+ crate::motion_field::get_relative_dist(order_hint_bits, oh, order_hint) > 0
1764+ || oh == order_hint
1765+ };
1766+ // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
1767+ // capped at 12 bits per component; a longer one is not stored at all.
1768+ const REFMVS_LIMIT: i32 = (1 << 12) - 1;
17511769 for row in 0..mi_rows {
17521770 for col in 0..mi_cols {
1753- if let Some(info) = grid.get(row, col)
1754- && info.is_inter
1755- && info.ref_frame > 0
1756- {
1757- field.set(
1758- row,
1759- col,
1760- crate::motion_field::SavedMv {
1761- mv: info.mv,
1762- ref_frame: info.ref_frame,
1763- },
1764- );
1771+ let Some(info) = grid.get(row, col) else {
1772+ continue;
1773+ };
1774+ if !info.is_inter {
1775+ continue;
1776+ }
1777+ // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
1778+ // qualifying one wins -- a compound block stores its second
1779+ // reference's mv, never its first (unless the second is on the
1780+ // other side or over the limit). Storing slot 0 unconditionally
1781+ // put the wrong (mv, ref_frame_offset) pair in every compound
1782+ // block's cell, which a later frame's temporal candidate then
1783+ // projected with the wrong reference distance.
1784+ let mut saved: Option<crate::motion_field::SavedMv> = None;
1785+ for (rf, mv) in [
1786+ (info.ref_frame, Some(info.mv)),
1787+ (info.ref_frame1.unwrap_or(0), info.mv1),
1788+ ] {
1789+ let (Some(mv), true) = (mv, rf > 0) else {
1790+ continue;
1791+ };
1792+ if other_side(rf) {
1793+ continue;
1794+ }
1795+ if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
1796+ continue;
1797+ }
1798+ saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
1799+ }
1800+ if let Some(saved) = saved {
1801+ field.set(row, col, saved);
17651802 }
17661803 }
17671804 }
@@ -14499,6 +14536,10 @@ fn decode_inter_block(
1449914536 );
1450014537 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
1450114538 let mut is_globalmv = false;
14539+ // lane-interbis r1: which single-ref mode this block resolved to,
14540+ // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for
14541+ // the `EC_MODE_VAL` value ladder below.
14542+ let mut dbg_mode = 16u32;
1450214543 let (mv, is_new_mv) = if !not_new {
1450314544 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
1450414545 // read at most two `drl_mode` bits, one per stack entry past the
@@ -14531,9 +14572,11 @@ fn decode_inter_block(
1453114572 let mv = if !not_zero {
1453214573 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
1453314574 // computed at this block's own position in `gm_table`.
14575+ dbg_mode = 15;
1453414576 gm_table[(ref_frame - LAST_FRAME) as usize]
1453514577 } else {
1453614578 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
14579+ dbg_mode = if nearest { 13 } else { 14 };
1453714580 if nearest {
1453814581 stack.nearest_mv
1453914582 } else {
@@ -14555,6 +14598,21 @@ fn decode_inter_block(
1455514598 };
1455614599 (mv, false)
1455714600 };
14601+ if std::env::var_os("EC_TRACE_MODE").is_some() {
14602+ for (i, e) in stack.entries.iter().enumerate() {
14603+ eprintln!(
14604+ "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}",
14605+ e.mv.0, e.mv.1, e.weight
14606+ );
14607+ }
14608+ eprintln!(
14609+ "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={dbg_mode} ref0={ref_frame} ref1=-1 mv0=({},{}) stack={} rng={}",
14610+ mv.0,
14611+ mv.1,
14612+ stack.entries.len(),
14613+ dec.debug_state().0
14614+ );
14615+ }
1455814616 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
1455914617 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
1456014618 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
@@ -19165,6 +19223,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1916519223 mi_cols as usize,
1916619224 mi_rows as usize,
1916719225 order_hint,
19226+ order_hint_bits,
1916819227 ref_order_hints,
1916919228 );
1917019229
crates/ec-av1/src/motion_field.rsmodified+11 -1
@@ -420,7 +420,17 @@ pub fn add_tpl_ref_mv(
420420 if row8 < 0 || col8 < 0 {
421421 return None;
422422 }
423- let (fwd_mv, ref_frame_offset) = tpl.get(row8 as usize / 2, col8 as usize / 2)?;
423+ let probe = tpl.get(row8 as usize / 2, col8 as usize / 2);
424+ if std::env::var_os("EC_TRACE_TPL").is_some() {
425+ match probe {
426+ None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"),
427+ Some((m, rfo)) => eprintln!(
428+ "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) mfmv0=({},{}) rfo={rfo}",
429+ m.0, m.1
430+ ),
431+ }
432+ }
433+ let (fwd_mv, ref_frame_offset) = probe?;
424434 let projected = get_mv_projection(fwd_mv, cur_offset_0, ref_frame_offset);
425435 let mv = lower_mv_precision(projected, allow_high_precision_mv);
426436 Some(TplCandidate { mv })
crates/ec-av1/src/stream.rsmodified+138 -0
@@ -4743,6 +4743,144 @@ mod tests {
47434743 /// 8-bit AND 10-bit. Every decoded frame is compared to ffmpeg on Y, U and
47444744 /// V; a refusal is counted, never SKIPped; an attempt that carried no rect
47454745 /// inter residual is counted separately and still required pixel-exact.
4746+ /// Temporal (MFMV) motion-vector candidates, on a real aomenc stream
4747+ /// whose compound blocks feed the next frame's motion field
4748+ /// (`av1_copy_frame_mvs` -> `av1_setup_motion_field` -> `add_tpl_ref_mv`).
4749+ ///
4750+ /// lane-interbis r1 pinned this recipe because it is the one the rect
4751+ /// gate's attempt 1 decoded FULLY and still mismatched ffmpeg (a
4752+ /// 32x32 NEARESTMV block at mi (24, 40) of decode-order frame 5 took its
4753+ /// nearest candidate from a temporal cell holding the wrong reference:
4754+ /// `build_motion_field` stored a compound block's FIRST reference where
4755+ /// libaom stores its second). Every fully decoded attempt is compared
4756+ /// plane by plane; a refusal is counted, never SKIPped; the temporal
4757+ /// candidate counter must fire on a compared attempt, or the gate proves
4758+ /// nothing.
4759+ #[test]
4760+ fn a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact() {
4761+ const NAME: &str =
4762+ "a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact";
4763+ let _gate_lock = lock_gate_counters();
4764+ if !have_ffmpeg() {
4765+ eprintln!("SKIP {NAME}: no ffmpeg");
4766+ return;
4767+ }
4768+ if !have_aomenc() {
4769+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4770+ return;
4771+ }
4772+ let (width, height, frame_count) = (192usize, 128usize, 6usize);
4773+ for bit_depth in [8u32, 10u32] {
4774+ let (mut named_refusals, mut compared, mut tmv_proved) = (0u32, 0u32, 0usize);
4775+ for attempt in 0..2u32 {
4776+ let tx_search = if attempt == 0 { "0" } else { "1" };
4777+ let duration = frame_count as f64 / 25.0;
4778+ // The pinned source: horizontal structure translating along X
4779+ // at 3 px/frame, which makes aomenc code compound LAST+GOLDEN
4780+ // blocks whose stored motion field the last frame reads back.
4781+ let source = format!(
4782+ "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
4783+ geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)',format=yuv420p"
4784+ );
4785+ let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
4786+ let y4m = Command::new("ffmpeg")
4787+ .args([
4788+ "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
4789+ "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
4790+ ])
4791+ .stdin(Stdio::null())
4792+ .stdout(Stdio::piped())
4793+ .stderr(Stdio::piped())
4794+ .output()
4795+ .expect("ffmpeg failed to run");
4796+ assert!(
4797+ y4m.status.success(),
4798+ "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
4799+ String::from_utf8_lossy(&y4m.stderr)
4800+ );
4801+ let depth_arg = format!("--bit-depth={bit_depth}");
4802+ let input_depth_arg = format!("--input-bit-depth={bit_depth}");
4803+ let tx_arg = format!("--enable-tx-size-search={tx_search}");
4804+ let args: Vec<&str> = vec![
4805+ "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=34", "--cpu-used=0",
4806+ "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
4807+ "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
4808+ "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
4809+ "--lag-in-frames=0",
4810+ // Per-arm overrides go LAST (aomenc keeps the last
4811+ // occurrence of a repeated --enable-* flag).
4812+ &tx_arg,
4813+ "--enable-rect-partitions=1", "--enable-ab-partitions=0",
4814+ "--enable-1to4-partitions=0", "--min-partition-size=16",
4815+ "--max-partition-size=32",
4816+ "--obu", "-o", "-", "-",
4817+ ];
4818+ let mut child = Command::new(aomenc_path())
4819+ .args(&args)
4820+ .stdin(Stdio::piped())
4821+ .stdout(Stdio::piped())
4822+ .stderr(Stdio::piped())
4823+ .spawn()
4824+ .expect("aomenc failed to start");
4825+ child
4826+ .stdin
4827+ .take()
4828+ .expect("aomenc stdin")
4829+ .write_all(&y4m.stdout)
4830+ .expect("writing y4m to aomenc");
4831+ let out = child.wait_with_output().expect("aomenc failed to run");
4832+ assert!(
4833+ out.status.success(),
4834+ "aomenc refused the fixture: {}",
4835+ String::from_utf8_lossy(&out.stderr)
4836+ );
4837+ let stream = out.stdout;
4838+ let before = decode::tmv_hits();
4839+ let frames = match decode_stream(&stream) {
4840+ Err(e) => {
4841+ let msg = e.to_string();
4842+ assert!(
4843+ msg.contains("unsupported"),
4844+ "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
4845+ attempt {attempt}): {msg}"
4846+ );
4847+ named_refusals += 1;
4848+ eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
4849+ continue;
4850+ }
4851+ Ok(frames) => frames,
4852+ };
4853+ let tmv = decode::tmv_hits() - before;
4854+ let ffmpeg_frames = if bit_depth == 10 {
4855+ ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
4856+ } else {
4857+ ffmpeg_decode_sequence(&stream, width, height, frame_count)
4858+ };
4859+ assert_eq!(frames.len(), frame_count);
4860+ for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4861+ assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
4862+ assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
4863+ assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
4864+ }
4865+ compared += 1;
4866+ tmv_proved += tmv;
4867+ }
4868+ eprintln!(
4869+ "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
4870+ pixel-exact attempts, blocks with a temporal MV candidate={tmv_proved}"
4871+ );
4872+ assert!(
4873+ compared > 0,
4874+ "{NAME} ({bit_depth}-bit): every attempt refused -- gate proved nothing"
4875+ );
4876+ assert!(
4877+ tmv_proved > 0,
4878+ "{NAME} ({bit_depth}-bit): no compared attempt ever folded a temporal MV \
4879+ candidate into a block's stack -- gate proved nothing"
4880+ );
4881+ }
4882+ }
4883+
47464884 #[test]
47474885 // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter
47484886 // residual path IS implemented and reached, but no aomenc recipe swept
lanes/interbis-r1.report.mdadded+129 -0
@@ -0,0 +1,129 @@
1+# lane-interbis r1 — the "decodes fully, still mismatches" inter defect
2+
3+Branch `lane-interbis`, worktree `edith_codecs-interbis`, off lane-inter4 `d2d7327`.
4+No rebase (main unchanged since that base).
5+
6+## STEP 1 — reproduced and pinned
7+
8+The rect gate's 8-bit **attempt 1** is the one that decodes fully and mismatches:
9+192x128, 6 frames @25, `geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)'`, cq 34,
10+`--enable-tx-size-search=1`, `--min/max-partition-size=16/32`, cpu-used=0, lag 0.
11+Regenerated twice, byte-identical:
12+`fa70b7f68d311e577e3d14a86574909e6e58cac817b5a7fae04341c41ff50260`
13+(script `$HOME/.cache/interbis/gen.sh`; 10-bit twin
14+`67cad9bd5341db897de8a5308faecaedb1b0df761e4f315f1817156d124caef7`).
15+
16+Decode order == display order (no hidden frames; `--lag-in-frames=0`).
17+Frames 0..4 exact; **frame 5** luma only, 646 px, bbox x160-191 y93-127, max delta 39.
18+`EC_AV1_PREFILT_DUMP` (ours) vs the same rung from the instrumented aomdec:
19+frames 0-4 byte-identical, frame 5 differs in 640 luma px at x160-191 y96-127 —
20+i.e. **reconstruction**, not deblock/CDEF/LR, and exactly one 32x32 block:
21+mi (row 24, col 40), the frame's last block.
22+
23+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)
24+
25+## STEP 2 — first divergent element
26+
27+Entropy is **exact**: the msac range ladder agrees at that block's entry
28+(`EC_MODE ... rng=37852` both) and at the end of its mode read
29+(`rng=59818` both). Both decoders read mode 13 (NEARESTMV), ref0=2 (LAST2),
30+stack size 3. The **VALUE** differs:
31+
32+ ours EC_MODE_VAL mi_row=24 mi_col=40 mode=13 ref0=2 mv0=(0,72)
33+ aomdec EC_MODE_VAL mi_row=24 mi_col=40 mode=13 ref0=2 mv0=(0,-230)
34+
35+New `EC_STACK` rung (added to both decoders) shows entries 1 and 2 identical
36+(`(0,24) w=2`, `(0,-785) w=2`, the extra-search neighbours) and entry 0 —
37+the temporal (MFMV) candidate — wrong: ours `(0,72) w=32`, aomdec `(0,-230) w=16`.
38+
39+New `EC_TPL` rung (per `add_tpl_ref_mv` probe, both decoders) isolates it to the
40+projected motion field itself: over the 16 probes of that block, aomdec reads
41+`INVALID` at blk_col 0/2 and `mfmv0=(0,-230) rfo=3` at blk_col 4/6; ours reads
42+`mfmv0=(0,24) rfo=1` at all 16. `(0,24)*3/1 = (0,72)` — our wrong stored pair
43+projected exactly to the wrong candidate.
44+
45+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)
46+
47+## Root cause (decode.rs `build_motion_field`, spec 7.19 / libaom `av1_copy_frame_mvs`)
48+
49+Our per-frame saved motion field stored **`ref_frame[0]`/`mv[0]` of every inter
50+block**. libaom walks **both** reference slots and the **last qualifying one
51+wins**, skipping a slot when
52+
53+* `cm->ref_frame_side[ref]` is non-zero — the reference's OrderHint is ahead of
54+ (or equal to) this frame's (`av1_calculate_ref_frame_side`), or
55+* `|mv| > REFMVS_LIMIT` (`(1<<12)-1`).
56+
57+Every compound block in this stream is `LAST + GOLDEN` (both past), so libaom
58+stores GOLDEN's mv with `ref_frame_offset = 3` where we stored LAST's with
59+offset 1 — a wrong (mv, distance) pair in every compound block's 8x8 cell, which
60+the next frame's temporal candidate then projects with the wrong reference
61+distance. Class name: **saved-field-keeps-slot-0** — a per-frame/DPB *summary*
62+of a multi-slot field must replay the reference's own slot walk (order + skips),
63+not keep slot 0. (Sibling of `neighbour-votes-all-its-fields`: there the
64+consumer voted only one slot, here the producer stores only one.)
65+
66+Fix: `crates/ec-av1/src/decode.rs:1728-1800` (`build_motion_field` now takes
67+`order_hint_bits`, walks both slots last-wins, applies the side and
68+`REFMVS_LIMIT` skips); call site `decode.rs:19040`.
69+
70+## Sweep
71+
72+`build_motion_field` is the only writer of `MotionField`/`SavedMv`
73+(`grep -rn "SavedMv\|MotionField" crates/ec-av1/src`); the mv-stack neighbour
74+maps already carry both slots (`MiInfo::ref_frame1`/`mv1`), and
75+`motion_field_projection`/`setup_motion_field` were re-read line-for-line
76+against `mvref_common.c` this round and match (one known, unreached gap noted
77+below).
78+
79+## Gate — GREEN, and it binds
80+
81+`a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact`
82+(`crates/ec-av1/src/stream.rs`, next to the rect gate): the pinned recipe above,
83+2 tx-size-search arms x {8-bit, 10-bit}, every fully decoded attempt compared
84+Y/U/V against ffmpeg, refusals counted (never SKIPped), and `decode::tmv_hits()`
85+asserted > 0 per depth.
86+
87+ cargo test -p ec-av1 --lib temporal_mv_candidates -- --nocapture
88+ 8-bit: 1 named refusal, 1 pixel-exact attempt, temporal-MV blocks = 66
89+ 10-bit: 1 named refusal, 1 pixel-exact attempt, temporal-MV blocks = 67
90+ test result: ok. 1 passed; 0 failed
91+
92+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
93+
94+Negative control (gate binds): with the store put back to first-slot-wins the
95+same gate fails at `frame 5 luma vs ffmpeg (attempt 1, 8-bit)`.
96+
97+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
98+
99+## Instruments added (env-gated, both decoders)
100+
101+- ours: `EC_MODE_VAL` + `EC_STACK` on the single-ref path of `decode_inter_block`
102+ (byte-format-identical to the oracle's rung), `EC_TPL` per `add_tpl_ref_mv` probe.
103+- oracle (`~/.cache/aom-oracle/src`): `EC_STACK` (stack dump at `EC_MODE_VAL`) and
104+ `EC_TPL` (per probe, incl. the `INVALID_MV` arm); `ninja aomdec` rebuilt.
105+
106+## Residue
107+
108+- **accepted: `motion_field_projection` does not check the source frame's
109+ frame_type.** libaom returns 0 for a KEY/INTRA_ONLY source; here an intra
110+ frame's saved field has no cells set, so the projection is inert — but its
111+ *return value* (which feeds `ref_stamp`) can differ. Unreached on every stream
112+ swept; fix-now if a future stream shows a `ref_stamp` divergence.
113+- **deferred: the rect inter residual gate** stays `#[ignore]`d (lane-inter4's
114+ own residue, unblocked by 16x8/8x16 rect inter leaves); its
115+ `out_of_scope_mismatch` assert is what surfaced this defect and is now
116+ satisfiable on the 8-bit arm.
117+- **deferred: film probe** — this diff lifts no refusal; both films still stop at
118+ lane-rectchroma's intra-rect-strip refusal.
119+
120+## Suite
121+
122+ $HOME/.cache/interbis-suite.log (systemd-run unit, MemoryMax=10G)
123+ test result: ok. 324 passed; 0 failed; 31 ignored; finished in 443.08s
124+
125+323 (lane-inter4 r2 baseline) + this round's new gate. Siblings inside that run:
126+inter_sequence*, obmc, warp, globalmv, compound_*, altref/hidden-frame,
127+tx_select, refusal_inventory, gate_coverage — all green.
128+
129+EVIDENCE: $HOME/.cache/interbis-suite.log | ec-av1 --lib at 0527911 | 324 passed / 0 failed / 31 ignored