From 42752a0d8f89c3984d32277f9ec4080bc55447f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 1 Sep 2026 22:20:19 +0300 Subject: [PATCH] fix(av1): 10-bit loop restoration, diffwtd mask and warp all ran with 8-bit constants lane-hbdinter r1. The charter's premise (a 10-bit inter frame 2 mismatch) did NOT reproduce with the tool-restricted inter recipe; widening the recipe to real loop restoration did, and the defect turned out to be bit-depth-wide, not inter-specific -- it fires on the KEY frame too, and lane-hbd's 10-bit gate simply had `--enable-restoration=0`. Four sites carried hardcoded 8-bit constants, all checked against the oracle source (~/.cache/aom-oracle/src): - restoration.rs `compute_ab`: libaom `restoration.c:660-662` scales the box sums back to the 8-bit range before forming `p` (`a = Round2(A, 2*(bd-8))`, `b = Round2(B, bd-8)`; `B[k]` keeps the raw sum). We never did -> wrong `z`, wrong blend factor at 10-bit. This is the site the gate attributes the mismatch to (ablation below). - restoration.rs `apply_wiener_stripe`: the horizontal intermediate was clamped to a fixed `[0, 8191]`, i.e. `WIENER_CLAMP_LIMIT(3, bd=8) - 1` (`convolve.h:43`), in this crate's *unbiased* domain. Correct bounds are the libaom limit shifted down by its `1 << (bd + 3)` bias. At 8-bit neither end is reachable (which is why every 8-bit gate passed); at 10-bit the top of the range is 16368, so most Wiener intermediates were truncated. - mc.rs `diffwtd_mask`: libaom `reconinter.c:307` rounds the CONV_BUF difference by `INTER_POST_ROUND + (bd - 8)`; we used the constant 4. - warp.rs `warp_affine`: `const BD: i32 = 8` fed both offset terms and the final `sum - (1<<(bd-1)) - (1< 16` (`convolve.h:83`), which is 12-bit only -- 10-bit keeps 3/11 and 3/7. Gate: `a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact` (stream.rs) -- real aomenc yuv420p10le, 128x64, 16 frames, forward P frames, deblock + loop restoration on, hard-asserting the new `mc::inter_pred_hits` counter, `deblock_hits`, and a non-RESTORE_NONE LR filter, comparing all 16 frames against ffmpeg's own 10-bit decode. Green with the fix; reverting only the `compute_ab` scaling turns it red at frame 0 (V plane, sample 52: ours 289, ffmpeg 288). cargo test -p ec-av1 --lib: 268 passed, 0 failed, 23 ignored (664s). --- crates/ec-av1/src/decode.rs | 6 + crates/ec-av1/src/mc.rs | 25 ++++- crates/ec-av1/src/restoration.rs | 29 ++++- crates/ec-av1/src/stream.rs | 183 +++++++++++++++++++++++++++++++ crates/ec-av1/src/warp.rs | 16 ++- 5 files changed, 250 insertions(+), 9 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index be8f124f..03adecce 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -820,6 +820,12 @@ pub(crate) fn tmv_hits() -> usize { crate::mvstack::tmv_hits() } +/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions +/// produced on this thread, the 10-bit inter gate's firing proof. +pub(crate) fn inter_pred_hits() -> usize { + crate::mc::inter_pred_hits() +} + /// Everything [`decode_inter_block`] needs to fold temporal MV candidates /// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]: /// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s diff --git a/crates/ec-av1/src/mc.rs b/crates/ec-av1/src/mc.rs index 3e927d5a..b07bc2cc 100644 --- a/crates/ec-av1/src/mc.rs +++ b/crates/ec-av1/src/mc.rs @@ -333,6 +333,7 @@ pub fn predict_with_filters( ) { assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); assert!(!reference.is_empty(), "a reference plane has samples"); + INTER_PRED_HITS.with(|c| c.set(c.get() + 1)); #[cfg(test)] let stage_t = std::time::Instant::now(); @@ -441,6 +442,20 @@ pub fn predict_scaled_hits() -> usize { PREDICT_SCALED_HITS.with(|c| c.get()) } +thread_local! { + /// lane-hbdinter: how many inter predictions this thread has produced + /// (single-reference, scaled, and the compound intermediate entry). The + /// 10-bit inter gate hard-asserts this moved, so a stream that coded + /// only intra blocks cannot pass it by construction (class + /// `gate-blind-to-feature`). + static INTER_PRED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`INTER_PRED_HITS`]. +pub fn inter_pred_hits() -> usize { + INTER_PRED_HITS.with(|c| c.get()) +} + fn round_pow2_64(value: i64, shift: u32) -> i64 { if shift == 0 { value @@ -492,6 +507,7 @@ pub fn predict_scaled( ) { assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); assert!(!reference.is_empty(), "a reference plane has samples"); + INTER_PRED_HITS.with(|c| c.set(c.get() + 1)); PREDICT_SCALED_HITS.with(|c| c.set(c.get() + 1)); let y0 = y_q4.div_euclid(16); @@ -594,6 +610,7 @@ pub fn predict_compound_intermediate( ) { assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); assert!(!reference.is_empty(), "a reference plane has samples"); + INTER_PRED_HITS.with(|c| c.set(c.get() + 1)); let x0 = x_q4.div_euclid(16); let xfrac = x_q4.rem_euclid(16) as usize; @@ -673,8 +690,14 @@ pub fn combine_compound( pub fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8]) { assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block"); assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel"); + // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS + // - round_0 - round_1 + (bd - 8)`, i.e. INTER_POST_ROUND plus the + // bit-depth headroom the CONV_BUF domain carries at 10/12-bit. `round_0` + // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s + // `intbufrange > 16`), so the whole bit-depth dependence here is `bd - 8`. + let round = INTER_POST_ROUND + u32::from(crate::decode::bit_depth()).saturating_sub(8); for i in 0..mask.len() { - let diff = round2((pred0[i] - pred1[i]).abs(), INTER_POST_ROUND); + let diff = round2((pred0[i] - pred1[i]).abs(), round); let m = (38 + diff / 16).clamp(0, 64); mask[i] = if inv { (64 - m) as u8 } else { m as u8 }; } diff --git a/crates/ec-av1/src/restoration.rs b/crates/ec-av1/src/restoration.rs index ac35db2a..65a50043 100644 --- a/crates/ec-av1/src/restoration.rs +++ b/crates/ec-av1/src/restoration.rs @@ -529,6 +529,9 @@ fn apply_wiener_stripe( if w == 0 || h == 0 { return; } + let bd = i64::from(crate::decode::bit_depth()); + let wiener_bias = 1i64 << (bd + 3); + let wiener_limit = 1i64 << (bd + 5); let rows = h + 6; let mut inter = vec![0i32; rows * w]; for r in 0..rows { @@ -541,8 +544,20 @@ fn apply_wiener_stripe( sum += tap as i64 * lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, x) as i64; } - // `WIENER_CLAMP_LIMIT(round0=3, bd=8) - 1`. - inter[r * w + c] = round2(sum, 3).clamp(0, 8191) as i32; + // libaom's `highbd_convolve_add_src_horiz_hip` clamps its + // *biased* intermediate to `[0, WIENER_CLAMP_LIMIT(3, bd) - 1]` + // (`convolve.h:43`, `(1 << (bd + 1 + FILTER_BITS - round0))`). + // Its bias over this crate's unbiased sum is exactly + // `(1 << (bd + FILTER_BITS - 1)) >> round0 == 1 << (bd + 3)` + // (the `rounding` term of that function, the rest cancelling + // against `WienerInfo`'s derived centre tap as the doc comment + // above derives), so the same clamp in *this* domain is the + // bound shifted down by that bias. At 8-bit neither end is ever + // reached by real content, which is why the old fixed `[0, 8191]` + // survived every 8-bit gate; at 10-bit the upper end is + // `128 * 1023 >> 3 == 16368`, well past `8191`, so a fixed + // 8-bit limit silently truncated most 10-bit Wiener pixels. + inter[r * w + c] = round2(sum, 3).clamp(-wiener_bias, wiener_limit - 1 - wiener_bias) as i32; } } for r in 0..h { @@ -646,7 +661,15 @@ fn compute_ab( b += px; } } - let p = if a * n < b * b { 0 } else { a * n - b * b }; + // libaom `restoration.c:660` -- the box sums are brought back + // to the 8-bit scale before `p` is formed (`a` is a sum of + // squares, so it loses twice the shift `b` does); `B[k]` below + // keeps the RAW `b`, only `p` uses the scaled pair. At 8-bit + // both shifts are 0, which is why this was invisible until now. + let bd_shift = u32::from(crate::decode::bit_depth()).saturating_sub(8); + let a_s = round2(a, 2 * bd_shift); + let b_s = round2(b, bd_shift); + let p = if a_s * n < b_s * b_s { 0 } else { a_s * n - b_s * b_s }; let z = round2(p * s as i64, SGRPROJ_MTABLE_BITS).clamp(0, 255) as usize; let a_val = SGR_X_BY_XPLUS1[z]; let b_val = round2( diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 8a2b0df0..7ed0abbb 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -1942,6 +1942,189 @@ mod tests { assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)"); } + /// The 10-bit *inter* counterpart of the gate above: a real `aomenc` + /// `yuv420p10le` sequence whose non-key frames are plain forward + /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0 + /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate), + /// decoded pixel-exact on every frame. 10-bit intra was proven exact by + /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated. + #[test] + fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_10bit_inter_sequence_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) = (128usize, 64usize, 16usize); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &gradients_source(42, width, height, "duration=0.64:rate=25"), + "-pix_fmt", + "yuv420p10le", + "-strict", + "-1", + "-t", + "0.64", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg failed to render the 10-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=15", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--input-bit-depth=10", + "--bit-depth=10", + "--lag-in-frames=0", + "--auto-alt-ref=0", + "--kf-max-dist=1000", + "--error-resilient=1", + "--aq-mode=0", + "--deltaq-mode=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=1", + "--enable-restoration=1", + "--min-partition-size=16", + "--max-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]) + .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 10-bit fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(dump, &stream).expect("dump stream"); + } + let mut probe = Av1Parser::new(); + let mut pos = 0usize; + while pos < stream.len() && probe.sequence_header().is_none() { + let obu = probe.parse_obu(&stream[pos..]).unwrap(); + pos += obu.total_size; + } + assert_eq!( + probe + .sequence_header() + .expect("stream has a sequence header OBU") + .color_config + .bit_depth, + 10, + "{NAME}: aomenc did not actually write a 10-bit sequence header" + ); + let before_deblock = decode::deblock_hits(); + let before_inter = decode::inter_pred_hits(); + let before_lr = crate::restoration::wiener_hits() + + crate::restoration::sgrproj_hits() + + crate::restoration::switchable_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"), + }; + assert!( + decode::inter_pred_hits() > before_inter, + "{NAME}: no inter-predicted block decoded -- the gate proves nothing" + ); + assert!( + decode::deblock_hits() > before_deblock, + "{NAME}: no deblocking edge fired -- raise cq-level" + ); + // Loop restoration is where the 10-bit inter/intra defect lived + // (lane-hbdinter r1: the self-guided box sums were never brought back + // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened + // to pick RESTORE_NONE would pass while proving nothing. + assert!( + crate::restoration::wiener_hits() + + crate::restoration::sgrproj_hits() + + crate::restoration::switchable_hits() + > before_lr, + "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level" + ); + eprintln!( + "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}", + decode::inter_pred_hits() - before_inter, + decode::deblock_hits() - before_deblock, + decode::cdef_idx_hits(), + crate::restoration::wiener_hits(), + crate::restoration::sgrproj_hits(), + ); + assert_eq!(frames.len(), frame_count); + let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + if got.y != want.y || got.u != want.u || got.v != want.v { + let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu"); + let _ = std::fs::write(&pin, &stream); + let first = |a: &Vec, b: &Vec| { + a.iter() + .zip(b) + .enumerate() + .find(|(_, (x, y))| x != y) + .map(|(k, (x, y))| (k, *x, *y)) + }; + panic!( + "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}", + first(&got.y, &want.y), + first(&got.u, &want.u), + first(&got.v, &want.v), + pin.display() + ); + } + } + } + /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2` /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above, diff --git a/crates/ec-av1/src/warp.rs b/crates/ec-av1/src/warp.rs index 96e7124b..bd08acea 100644 --- a/crates/ec-av1/src/warp.rs +++ b/crates/ec-av1/src/warp.rs @@ -447,11 +447,17 @@ pub fn warp_affine( params.gamma as i64, params.delta as i64, ); - const BD: i32 = 8; - let reduce_bits_horiz = 3; // conv_params->round_0, non-compound 8-bit (InterRound0) + // lane-hbdinter r1: libaom's `av1_warp_affine_c` takes `bd` and every + // offset/clip term below scales with it; this was `const BD: i32 = 8`, + // so a 10-bit warped or global-motion block came out of the vertical + // pass biased by `(1 << 9) + (1 << 8) - (1 << 11) - (1 << 10)` and then + // clipped. `reduce_bits_horiz` is `conv_params->round_0`, which stays 3 + // for `bd < 12` (`convolve.h:83`'s `intbufrange > 16` threshold). + let bd = i32::from(crate::decode::bit_depth()); + let reduce_bits_horiz = 3; // conv_params->round_0 (InterRound0), bd < 12 let reduce_bits_vert = 2 * FILTER_BITS - reduce_bits_horiz; // InterRound1 - let offset_bits_horiz = BD + FILTER_BITS - 1; - let offset_bits_vert = BD + 2 * FILTER_BITS - reduce_bits_horiz; + let offset_bits_horiz = bd + FILTER_BITS - 1; + let offset_bits_vert = bd + 2 * FILTER_BITS - reduce_bits_horiz; let mut i = p_row; while i < p_row + p_height { @@ -512,7 +518,7 @@ pub fn warp_affine( let out_row = (i - p_row + k + 4) as usize; let out_col = (j - p_col + l + 4) as usize; dst[out_row * p_stride as usize + out_col] = - clip_pixel(sum - (1 << (BD - 1)) - (1 << BD)); + clip_pixel(sum - (1 << (bd - 1)) - (1 << bd)); sy += gamma; l += 1; }