diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index ff96665e..bd60274c 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -26220,6 +26220,7 @@ fn decode_inter_block( t.ref_order_hints[(ref1 - LAST_FRAME) as usize], ), allow_high_precision_mv, + force_integer_mv, }); let gm_table = build_gm_mv_table( global_motion, @@ -27444,6 +27445,7 @@ fn decode_inter_block( t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], ), allow_high_precision_mv, + force_integer_mv, }); let gm_table = build_gm_mv_table( global_motion, @@ -29829,6 +29831,7 @@ fn decode_inter_sub8_split4( t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], ), allow_high_precision_mv, + force_integer_mv, }); let stack = crate::mvstack::find_mv_stack_with_sign_bias( grid, @@ -30857,6 +30860,7 @@ fn decode_inter_sub8_rect2( t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], ), allow_high_precision_mv, + force_integer_mv, }); let stack = crate::mvstack::find_mv_stack_with_sign_bias( grid, @@ -31603,6 +31607,7 @@ fn decode_inter_block8( t.ref_order_hints[(ref1 - LAST_FRAME) as usize], ), allow_high_precision_mv, + force_integer_mv, }); // lane-av1comp: this leaf path has neither a real sign-bias // table nor `tpl_frame` (see this function's own doc on the @@ -32293,6 +32298,7 @@ fn decode_inter_block8( t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], ), allow_high_precision_mv, + force_integer_mv, }); let stack = crate::mvstack::find_mv_stack_with_sign_bias( grid, diff --git a/crates/ec-av1/src/motion_field.rs b/crates/ec-av1/src/motion_field.rs index e444e910..6a565113 100644 --- a/crates/ec-av1/src/motion_field.rs +++ b/crates/ec-av1/src/motion_field.rs @@ -174,11 +174,35 @@ fn get_mv_projection(mv: (i32, i32), num: i32, den: i32) -> (i32, i32) { (scale(mv.0), scale(mv.1)) } -/// `lower_mv_precision` (`mvref_common.h`), the `is_integer == false` half -/// only — every stream this decoder ever reaches has `force_integer_mv == -/// false` on an inter frame (`allow_screen_content_tools`, the only source -/// of a `true` value here, is refused outright at the stream level). -pub fn lower_mv_precision(mv: (i32, i32), allow_high_precision_mv: bool) -> (i32, i32) { +/// `lower_mv_precision` (`mvref_common.h`), both halves. lane-dgolomb: the +/// `is_integer` half used to be dropped as unreachable on the claim that +/// `allow_screen_content_tools` is refused at the stream level -- it is not, +/// and libaom turns screen-content tools on for dark, smooth FILM (its +/// `av1_set_screen_content_options` counts near-flat blocks), so a real +/// libaom stream carries `force_integer_mv == 1` on an inter frame and every +/// temporal MV candidate has to be rounded to full pel. Without it the +/// candidates were 1/8-pel values libaom never produces: a whole-frame +/// prediction mismatch behind a clean parse (class +/// `branch-dropped-as-unreachable`). +pub fn lower_mv_precision( + mv: (i32, i32), + allow_high_precision_mv: bool, + force_integer_mv: bool, +) -> (i32, i32) { + if force_integer_mv { + // `integer_mv_precision`: drop to the nearest full pel, ties away + // from zero (`abs(mod) > 4`). + let round = |v: i32| { + let m = v % 8; + match m { + 0 => v, + _ if m > 4 => v - m + 8, + _ if m < -4 => v - m - 8, + _ => v - m, + } + }; + return (round(mv.0), round(mv.1)); + } if allow_high_precision_mv { return mv; } @@ -526,6 +550,7 @@ pub fn add_tpl_ref_mv( blk_col: isize, cur_offset_0: i32, allow_high_precision_mv: bool, + force_integer_mv: bool, ) -> Option { let probe = tpl.probe(mi_row, mi_col).cell(blk_row, blk_col); if crate::envflags::env_flag!("EC_TRACE_TPL") { @@ -539,7 +564,13 @@ pub fn add_tpl_ref_mv( } let (fwd_mv, ref_frame_offset) = probe?; Some(TplCandidate { - mv: project_tpl_mv(fwd_mv, cur_offset_0, ref_frame_offset, allow_high_precision_mv), + mv: project_tpl_mv( + fwd_mv, + cur_offset_0, + ref_frame_offset, + allow_high_precision_mv, + force_integer_mv, + ), }) } @@ -552,9 +583,10 @@ pub fn project_tpl_mv( cur_offset: i32, ref_frame_offset: i32, allow_high_precision_mv: bool, + force_integer_mv: bool, ) -> (i32, i32) { let projected = get_mv_projection(fwd_mv, cur_offset, ref_frame_offset); - lower_mv_precision(projected, allow_high_precision_mv) + lower_mv_precision(projected, allow_high_precision_mv, force_integer_mv) } /// One query block's view of [`TplField`] (lane-tpl). `add_tpl_ref_mv`'s @@ -709,7 +741,37 @@ mod tests { // ref_frame_offset = get_relative_dist(2,1) = 1, scaling (-64,0) by // 2/1 -> (-128,0); get_block_position's sign_bias (dir=2) subtracts // the offset, landing at 8x8 cell (2, 0). - let cand = add_tpl_ref_mv(&tpl, 4, 0, 0isize, 0isize, get_relative_dist(7, 4, 2), true); + let cand = + add_tpl_ref_mv(&tpl, 4, 0, 0isize, 0isize, get_relative_dist(7, 4, 2), true, false); assert!(cand.is_some(), "expected a projected temporal candidate"); } + + /// lane-dgolomb: `lower_mv_precision`'s `force_integer_mv` half, which + /// this decoder used to drop as unreachable. The values are the ones a + /// real libaom stream (film B, `-cpu-used 6 -crf 35`, the one inter frame + /// whose header carries `force_integer_mv == 1`) produces at its first + /// 128x128 block: the same 16 temporal probes, projected and then rounded + /// to full pel, are what put `(16,0)`/`(16,-8)`/`(8,-40)` in libaom's own + /// traced mv stack where the eighth-pel values were `(14,-4)`/`(12,-2)`/ + /// `(12,-38)`/`(16,-4)`. + #[test] + fn force_integer_mv_rounds_a_projected_candidate_to_full_pel() { + // (mfmv0, ref_frame_offset) -> (eighth-pel value, full-pel value), + // all at cur_offset_0 == 1. + for (mv, rfo, eighth, integer) in [ + ((74, -20), 5, (14, -4), (16, 0)), + ((74, -24), 5, (14, -4), (16, -8)), + ((82, -24), 5, (16, -4), (16, -8)), + ((66, -16), 5, (12, -2), (16, 0)), + ((24, -76), 2, (12, -38), (8, -40)), + ] { + assert_eq!(project_tpl_mv(mv, 1, rfo, false, false), eighth, "{mv:?}"); + assert_eq!(project_tpl_mv(mv, 1, rfo, false, true), integer, "{mv:?}"); + } + // `integer_mv_precision`'s tie rule is away from zero on |mod| > 4 + // only, and it is signed-symmetric. + assert_eq!(lower_mv_precision((4, -4), false, true), (0, 0)); + assert_eq!(lower_mv_precision((5, -5), false, true), (8, -8)); + assert_eq!(lower_mv_precision((-12, 8), false, true), (-8, 8)); + } } diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index f061fe3e..ddf1a5b8 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -154,6 +154,10 @@ pub struct TplArgs<'a> { pub cur_offset_0: i32, /// The frame header's own `allow_high_precision_mv`. pub allow_high_precision_mv: bool, + /// The frame header's own `force_integer_mv` (`lower_mv_precision`'s + /// `is_integer`): a screen-content frame rounds every projected temporal + /// candidate to full pel. + pub force_integer_mv: bool, } /// [`MiInfo::ref_frame1`]'s "this unit was not coded compound" value. Slot 1 @@ -1036,6 +1040,7 @@ fn tpl_trace_sample( blk_col: isize, cur_offset: i32, allow_high_precision_mv: bool, + force_integer_mv: bool, ) -> Option<(i32, i32)> { crate::motion_field::add_tpl_ref_mv( field, @@ -1045,6 +1050,7 @@ fn tpl_trace_sample( blk_col, cur_offset, allow_high_precision_mv, + force_integer_mv, ) .map(|c| c.mv) } @@ -1061,6 +1067,7 @@ fn tpl_trace_sample_compound( blk_col: isize, cur_offsets: (i32, i32), allow_high_precision_mv: bool, + force_integer_mv: bool, ) { for off in [cur_offsets.0, cur_offsets.1] { let _ = crate::motion_field::add_tpl_ref_mv( @@ -1071,6 +1078,7 @@ fn tpl_trace_sample_compound( blk_col, off, allow_high_precision_mv, + force_integer_mv, ); } } @@ -1093,6 +1101,7 @@ fn tpl_sample( blk_col: isize, cur_offset: i32, allow_high_precision_mv: bool, + force_integer_mv: bool, ) -> Option<(i32, i32)> { if trace_tpl { return tpl_trace_sample( @@ -1103,6 +1112,7 @@ fn tpl_sample( blk_col, cur_offset, allow_high_precision_mv, + force_integer_mv, ); } let (fwd_mv, rfo) = probe.cell(blk_row, blk_col)?; @@ -1111,6 +1121,7 @@ fn tpl_sample( cur_offset, rfo, allow_high_precision_mv, + force_integer_mv, )) } @@ -1128,6 +1139,7 @@ fn tpl_sample_compound( blk_col: isize, cur_offsets: (i32, i32), allow_high_precision_mv: bool, + force_integer_mv: bool, ) -> Option<((i32, i32), (i32, i32))> { if trace_tpl { tpl_trace_sample_compound( @@ -1138,12 +1150,25 @@ fn tpl_sample_compound( blk_col, cur_offsets, allow_high_precision_mv, + force_integer_mv, ); } let (fwd_mv, rfo) = probe.cell(blk_row, blk_col)?; Some(( - crate::motion_field::project_tpl_mv(fwd_mv, cur_offsets.0, rfo, allow_high_precision_mv), - crate::motion_field::project_tpl_mv(fwd_mv, cur_offsets.1, rfo, allow_high_precision_mv), + crate::motion_field::project_tpl_mv( + fwd_mv, + cur_offsets.0, + rfo, + allow_high_precision_mv, + force_integer_mv, + ), + crate::motion_field::project_tpl_mv( + fwd_mv, + cur_offsets.1, + rfo, + allow_high_precision_mv, + force_integer_mv, + ), )) } @@ -1312,6 +1337,7 @@ pub fn find_mv_stack_with_sign_bias( field, cur_offset_0, allow_high_precision_mv, + force_integer_mv, }) = tpl { let mut any_hit = false; @@ -1342,6 +1368,7 @@ pub fn find_mv_stack_with_sign_bias( blk_col, cur_offset_0, allow_high_precision_mv, + force_integer_mv, ) }; let mut blk_row = 0usize; @@ -2116,6 +2143,7 @@ pub fn find_mv_stack_compound( cur_offset_0, cur_offset_1, allow_high_precision_mv, + force_integer_mv, }) = tpl { let mut any_hit = false; @@ -2144,6 +2172,7 @@ pub fn find_mv_stack_compound( blk_col, (cur_offset_0, cur_offset_1), allow_high_precision_mv, + force_integer_mv, ) }; let mut blk_row = 0usize; @@ -2411,6 +2440,10 @@ pub struct CompoundTplArgs<'a> { pub cur_offset_1: i32, /// The frame header's own `allow_high_precision_mv`. pub allow_high_precision_mv: bool, + /// The frame header's own `force_integer_mv` (`lower_mv_precision`'s + /// `is_integer`): a screen-content frame rounds every projected temporal + /// candidate to full pel. + pub force_integer_mv: bool, } /// The single-reference context shared by the `single_ref_p1`/`p3`/`p4` diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 8af6ab4e..608967a8 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -3758,6 +3758,115 @@ pub(crate) mod tests { } } + /// lane-dgolomb: the `force_integer_mv` gate. libaom turns screen-content + /// tools on for DARK, SMOOTH content -- its `av1_set_screen_content_options` + /// counts 16x16 blocks with 2..=4 distinct luma values -- and then sets + /// `force_integer_mv` on any inter frame whose source is pixel-identical to + /// the previously coded source (`av1_is_integer_mv`: `cs_rate >= 0.8` and + /// `C == T`, every collocated 8x8 block matching, is the only path that + /// returns 1). Both hold on his real AV1 films, and this decoder used to + /// drop `lower_mv_precision`'s `is_integer` half as unreachable, so every + /// temporal MV candidate on such a frame came out at eighth-pel: the frame + /// decoded without any error into a whole-frame prediction mismatch, and + /// the desync surfaced blocks later as "a Golomb tail longer than this + /// decoder reads". + /// + /// The source is SYNTHETIC (no film sample lives in `fixtures`): a + /// near-flat dark background at the film-B crop size, 1920x1024, with one + /// textured patch stepping 9 px every SECOND frame, so half the frames are + /// exact duplicates of their predecessor (the `C == T` trigger) while the + /// motion field still holds non-zero MVs whose projections are not + /// multiples of 8. The gate asserts both halves: at least one INTER frame + /// really carries `force_integer_mv` (class `gate-blind-to-feature`), and + /// every shown frame decodes sample-exact against ffmpeg's own decode. + #[test] + fn a_libaom_force_integer_mv_stream_decodes_exact() { + const NAME: &str = "a_libaom_force_integer_mv_stream_decodes_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + let (w, h, frames) = (1920usize, 1024usize, 12usize); + let mut raw = Vec::with_capacity(frames * w * h * 3 / 2); + for f in 0..frames { + let mut y = vec![0u8; w * h]; + for row in 0..h { + for col in 0..w { + // 2..=4 distinct values per 16x16 block, all dark: the + // screen-content detector's own counting rule. + y[row * w + col] = + 16 + ((col / 32 + row / 32) % 5) as u8 + ((col / 4 + row / 4) % 3) as u8; + } + } + let x0 = 200 + 9 * (f / 2); + for row in 300..428 { + for col in x0..x0 + 192 { + y[row * w + col] = + ((((col - x0) / 3) * 7 + ((row - 300) / 5) * 13) % 200 + 30) as u8; + } + } + raw.extend_from_slice(&y); + raw.extend(std::iter::repeat_n(128u8, w * h / 2)); + } + // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. + let src = std::env::temp_dir().join(format!("ec-av1-intmv-{}.yuv", std::process::id())); + std::fs::write(&src, &raw).expect("raw source"); + let out = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) + .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) + .arg(&src) + .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"]) + .args(["-cpu-used", "6", "-b:v", "0", "-crf", "35", "-f", "obu", "-"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + let _ = std::fs::remove_file(&src); + if !out.status.success() { + eprintln!( + "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})", + String::from_utf8_lossy(&out.stderr) + ); + return; + } + let stream = out.stdout; + + // Half of the gate: the stream must actually carry the feature. + let mut parser = Av1Parser::new(); + let (mut pos, mut int_mv_inter) = (0usize, 0usize); + while pos < stream.len() { + let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses"); + pos += obu.total_size.max(1); + let header = match &obu.kind { + ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h, + _ => continue, + }; + if header.force_integer_mv && !header.frame_is_intra && header.use_ref_frame_mvs { + int_mv_inter += 1; + } + } + assert!( + int_mv_inter > 0, + "{NAME} went blind: libaom coded no inter frame with force_integer_mv" + ); + + let ours = decode_stream(&stream).expect("libaom screen-content stream decodes"); + let theirs = ffmpeg_decode_sequence(&stream, w, h, frames); + assert_eq!(ours.len(), frames, "shown frame count"); + for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() { + for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { + let first = l.iter().zip(r.iter()).position(|(x, y)| x != y); + assert!( + first.is_none(), + "frame {i} plane {plane} differs from ffmpeg at sample {} \ + ({int_mv_inter} force_integer_mv inter frames in this stream)", + first.unwrap() + ); + } + } + } + /// Hardened past the report-only test above: a real libaom-av1 gradients /// stream, pinned deterministic (`gradients`' own `seed=`, plus /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search diff --git a/lanes/dgolomb.report.md b/lanes/dgolomb.report.md new file mode 100644 index 00000000..e2e22b48 --- /dev/null +++ b/lanes/dgolomb.report.md @@ -0,0 +1,89 @@ +# lane-dgolomb — libaom film-B decode (the "Golomb tail" refusal) + +## Root cause (closed) +`crates/ec-av1/src/motion_field.rs` `lower_mv_precision` implemented only the +`is_integer == false` half of libaom's function, on a comment claiming +`force_integer_mv` is unreachable because `allow_screen_content_tools` is +"refused outright at the stream level". Both halves of that claim are false: + +* libaom's `av1_set_screen_content_options` counts 16x16 blocks with 2..=4 + distinct luma values, so DARK, SMOOTH FILM reads as screen content — every + frame of the film-B gate clip has `allow_screen_content_tools = 1`; +* `av1_is_integer_mv` (encoder_utils.c:1357) returns 1 exactly when + `cs_rate >= 0.8` **and** `C == T`, i.e. when the source frame is + pixel-identical to the previously coded source. Film B has such frames. + +So a real libaom stream carries `force_integer_mv = 1` on an inter frame, and +every temporal MV candidate must be rounded to full pel. Ours stayed at +eighth-pel → the mv stack held values libaom never produced → whole-frame +prediction mismatch behind a clean parse, and the entropy desync surfaced +blocks later as `a Golomb tail longer than this decoder reads` +(class `refusal-names-a-correlate`). + +**Class: `branch-dropped-as-unreachable`** — a spec branch deleted on an +unreachability note that a later capability change silently invalidated. + +## First divergence (measured, not reasoned) +Film-B gate clip (1920x1024 crop, `-cpu-used 6 -crf 35 -g 12`), decode-order +frame 3 = order_hint 1, the ONE inter frame with `force_integer_mv = 1`, +block mi(0,0) (128x128, NEWMV, ref LAST): + +* `EC_TPL` field cells identical in both decoders (16 probes), range identical + (`rng=49952`) — so the field and the entropy state were right; +* instrumented aomdec stack: `(16,0)w16 (16,-8)w12 (8,-40)w4` +* ours before the fix: `(14,-4)w16 (12,-2)w8 (12,-38)w4 (16,-4)w4` +* `(74,-20)/5 → 15,-4 → integer → (16,0)` reproduces libaom exactly. + +## Fix +`lower_mv_precision(mv, allow_high_precision_mv, force_integer_mv)` with +libaom's `integer_mv_precision` (ties away from zero on `|mod| > 4`), threaded +through `project_tpl_mv`/`add_tpl_ref_mv`, `TplArgs`/`CompoundTplArgs` and the +six `decode.rs` construction sites. + +## Sweep (class + siblings) +* `grep` for unreachability claims over `ec-av1`/`ec-av1-syntax`: no other + "spec branch dropped because a header flag is refused" site. +* The other decoder-side `is_integer` consumers in libaom — + `av1_find_best_ref_mvs` (mvref_common.c:847) and the compound nearest/near + lowering (decodemv.c:1519) — are provably no-ops for us once the temporal + path is fixed: under `force_integer_mv` every other candidate source is + already integer (`read_mv_component` honours the flag, `warp.rs:128` honours + it for global MVs, spatial candidates are decoded MVs). Not implemented; if + a future defect lands here, this is the place. + +## Verification +* `crates/ec-av1/src/motion_field.rs` `force_integer_mv_rounds_a_projected_candidate_to_full_pel` + — the five (mfmv0, rfo) pairs of that first block, eighth-pel vs full-pel, + values taken from the oracle. Fails without the fix. PASSES. +* Film-B ladder, 48 frames, `-cpu-used 6 -g 48`, our `decode_stream` vs + `ffmpeg -c:v libdav1d`, sample-exact over all 48 shown frames: + crf 20 EXACT, crf 35 EXACT (was the Golomb refusal), crf 45 EXACT. + Same at `-g 12`. Before the fix: crf 20/45 25–28 dB garbage, crf 35 refused. +* `crates/ec-av1/src/stream.rs` `a_libaom_force_integer_mv_stream_decodes_exact` + — synthetic 1920x1024 source (no film sample in `fixtures`): near-flat dark + background (2..=4 luma values per 16x16 block, the detector's own rule) with + a textured patch stepping 9 px every SECOND frame, so half the frames are + exact duplicates (the `C == T` trigger). Asserts (a) libaom really coded an + inter frame with `force_integer_mv` + `use_ref_frame_mvs` (anti-blindness), + (b) all 12 shown frames decode sample-exact vs ffmpeg. PASSES, 2.1 s. + +## OPEN / deferred +1. **The synthetic gate is BLIND to this defect.** Re-run with the integer + branch stubbed out (`if false {`) and it still passes: on that source the + temporal candidates are already full-pel (or unused), so only the unit test + above actually regresses the fix. Fixing this needs a synthetic clip whose + duplicate frame still reads NON-multiple-of-8 projected temporal MVs — + e.g. motion of an odd number of half-pels between the earlier frames, with + the duplicate pair placed so the ARF's field survives into it. Unblocks: + one more recipe iteration against `EC_TPL`/`EC_STACK`. +2. **crf 5 still fails**: `-cpu-used 6 -crf 5 -g 48` desyncs on the KEY frame + (base_q 9, `delta_q_present`, `cdef_bits 3`), first divergent intra block + mi(184,344) — aomdec `EC_IMODE ... rng=49148` vs ours `rng=52010`, the + previous traced block being mi(188,340). Unrelated to temporal MVs; needs + its own bisect from that block's coefficient ladder (`EC_TRACE_COEFF`). +3. **Not done in this lane** (budget): the "reference streams decode exact + through our decoder" assertion inside `external_ladder`/the native gates; + the full `cargo test -p ec-av1 --release` run (started detached, was still + running at hand-off, log + `/tmp/claude-1000/.../scratchpad/suite.log`); `cargo check --workspace + --all-targets`; the byte pins (8590 / 28535) were not re-read.