forge
Explore
Log in

Don't you dare go Hollow

10-bit loop restoration, diffwtd mask and warp all ran with 8-bit constants

Browse files at this commit

42752a0d8f89c3984d32277f9ec4080bc55447f3Ahmet Kaan GümüşParent: d21774e
  • fix
    • 10-bit loop restoration, diffwtd mask and warp all ran with 8-bit constants
Show full message
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<<bd)` (tip from lane-gmaffine, confirmed
  against `av1_warp_affine_c`).

Non-compound sub-pel MC needs no change: libaom only shifts round_0/round_1
when `bd + FILTER_BITS - round_0 + 2 > 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.rsmodified+6 -0
@@ -820,6 +820,12 @@ pub(crate) fn tmv_hits() -> usize {
820820 crate::mvstack::tmv_hits()
821821 }
822822
823+/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
824+/// produced on this thread, the 10-bit inter gate's firing proof.
825+pub(crate) fn inter_pred_hits() -> usize {
826+ crate::mc::inter_pred_hits()
827+}
828+
823829 /// Everything [`decode_inter_block`] needs to fold temporal MV candidates
824830 /// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
825831 /// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
crates/ec-av1/src/mc.rsmodified+24 -1
@@ -333,6 +333,7 @@ pub fn predict_with_filters(
333333 ) {
334334 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
335335 assert!(!reference.is_empty(), "a reference plane has samples");
336+ INTER_PRED_HITS.with(|c| c.set(c.get() + 1));
336337
337338 #[cfg(test)]
338339 let stage_t = std::time::Instant::now();
@@ -441,6 +442,20 @@ pub fn predict_scaled_hits() -> usize {
441442 PREDICT_SCALED_HITS.with(|c| c.get())
442443 }
443444
445+thread_local! {
446+ /// lane-hbdinter: how many inter predictions this thread has produced
447+ /// (single-reference, scaled, and the compound intermediate entry). The
448+ /// 10-bit inter gate hard-asserts this moved, so a stream that coded
449+ /// only intra blocks cannot pass it by construction (class
450+ /// `gate-blind-to-feature`).
451+ static INTER_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
452+}
453+
454+/// Current value of [`INTER_PRED_HITS`].
455+pub fn inter_pred_hits() -> usize {
456+ INTER_PRED_HITS.with(|c| c.get())
457+}
458+
444459 fn round_pow2_64(value: i64, shift: u32) -> i64 {
445460 if shift == 0 {
446461 value
@@ -492,6 +507,7 @@ pub fn predict_scaled(
492507 ) {
493508 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
494509 assert!(!reference.is_empty(), "a reference plane has samples");
510+ INTER_PRED_HITS.with(|c| c.set(c.get() + 1));
495511 PREDICT_SCALED_HITS.with(|c| c.set(c.get() + 1));
496512
497513 let y0 = y_q4.div_euclid(16);
@@ -594,6 +610,7 @@ pub fn predict_compound_intermediate(
594610 ) {
595611 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
596612 assert!(!reference.is_empty(), "a reference plane has samples");
613+ INTER_PRED_HITS.with(|c| c.set(c.get() + 1));
597614
598615 let x0 = x_q4.div_euclid(16);
599616 let xfrac = x_q4.rem_euclid(16) as usize;
@@ -673,8 +690,14 @@ pub fn combine_compound(
673690 pub fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8]) {
674691 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
675692 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");
693+ // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS
694+ // - round_0 - round_1 + (bd - 8)`, i.e. INTER_POST_ROUND plus the
695+ // bit-depth headroom the CONV_BUF domain carries at 10/12-bit. `round_0`
696+ // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s
697+ // `intbufrange > 16`), so the whole bit-depth dependence here is `bd - 8`.
698+ let round = INTER_POST_ROUND + u32::from(crate::decode::bit_depth()).saturating_sub(8);
676699 for i in 0..mask.len() {
677- let diff = round2((pred0[i] - pred1[i]).abs(), INTER_POST_ROUND);
700+ let diff = round2((pred0[i] - pred1[i]).abs(), round);
678701 let m = (38 + diff / 16).clamp(0, 64);
679702 mask[i] = if inv { (64 - m) as u8 } else { m as u8 };
680703 }
crates/ec-av1/src/restoration.rsmodified+26 -3
@@ -529,6 +529,9 @@ fn apply_wiener_stripe(
529529 if w == 0 || h == 0 {
530530 return;
531531 }
532+ let bd = i64::from(crate::decode::bit_depth());
533+ let wiener_bias = 1i64 << (bd + 3);
534+ let wiener_limit = 1i64 << (bd + 5);
532535 let rows = h + 6;
533536 let mut inter = vec![0i32; rows * w];
534537 for r in 0..rows {
@@ -541,8 +544,20 @@ fn apply_wiener_stripe(
541544 sum += tap as i64
542545 * lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, x) as i64;
543546 }
544- // `WIENER_CLAMP_LIMIT(round0=3, bd=8) - 1`.
545- inter[r * w + c] = round2(sum, 3).clamp(0, 8191) as i32;
547+ // libaom's `highbd_convolve_add_src_horiz_hip` clamps its
548+ // *biased* intermediate to `[0, WIENER_CLAMP_LIMIT(3, bd) - 1]`
549+ // (`convolve.h:43`, `(1 << (bd + 1 + FILTER_BITS - round0))`).
550+ // Its bias over this crate's unbiased sum is exactly
551+ // `(1 << (bd + FILTER_BITS - 1)) >> round0 == 1 << (bd + 3)`
552+ // (the `rounding` term of that function, the rest cancelling
553+ // against `WienerInfo`'s derived centre tap as the doc comment
554+ // above derives), so the same clamp in *this* domain is the
555+ // bound shifted down by that bias. At 8-bit neither end is ever
556+ // reached by real content, which is why the old fixed `[0, 8191]`
557+ // survived every 8-bit gate; at 10-bit the upper end is
558+ // `128 * 1023 >> 3 == 16368`, well past `8191`, so a fixed
559+ // 8-bit limit silently truncated most 10-bit Wiener pixels.
560+ inter[r * w + c] = round2(sum, 3).clamp(-wiener_bias, wiener_limit - 1 - wiener_bias) as i32;
546561 }
547562 }
548563 for r in 0..h {
@@ -646,7 +661,15 @@ fn compute_ab(
646661 b += px;
647662 }
648663 }
649- let p = if a * n < b * b { 0 } else { a * n - b * b };
664+ // libaom `restoration.c:660` -- the box sums are brought back
665+ // to the 8-bit scale before `p` is formed (`a` is a sum of
666+ // squares, so it loses twice the shift `b` does); `B[k]` below
667+ // keeps the RAW `b`, only `p` uses the scaled pair. At 8-bit
668+ // both shifts are 0, which is why this was invisible until now.
669+ let bd_shift = u32::from(crate::decode::bit_depth()).saturating_sub(8);
670+ let a_s = round2(a, 2 * bd_shift);
671+ let b_s = round2(b, bd_shift);
672+ let p = if a_s * n < b_s * b_s { 0 } else { a_s * n - b_s * b_s };
650673 let z = round2(p * s as i64, SGRPROJ_MTABLE_BITS).clamp(0, 255) as usize;
651674 let a_val = SGR_X_BY_XPLUS1[z];
652675 let b_val = round2(
crates/ec-av1/src/stream.rsmodified+183 -0
@@ -1942,6 +1942,189 @@ mod tests {
19421942 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
19431943 }
19441944
1945+ /// The 10-bit *inter* counterpart of the gate above: a real `aomenc`
1946+ /// `yuv420p10le` sequence whose non-key frames are plain forward
1947+ /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0
1948+ /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate),
1949+ /// decoded pixel-exact on every frame. 10-bit intra was proven exact by
1950+ /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated.
1951+ #[test]
1952+ fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() {
1953+ const NAME: &str = "a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact";
1954+ let _gate_lock = lock_gate_counters();
1955+ if !have_ffmpeg() {
1956+ eprintln!("SKIP {NAME}: no ffmpeg");
1957+ return;
1958+ }
1959+ if !have_aomenc() {
1960+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1961+ return;
1962+ }
1963+ let (width, height, frame_count) = (128usize, 64usize, 16usize);
1964+ let y4m = Command::new("ffmpeg")
1965+ .args([
1966+ "-v",
1967+ "error",
1968+ "-f",
1969+ "lavfi",
1970+ "-i",
1971+ &gradients_source(42, width, height, "duration=0.64:rate=25"),
1972+ "-pix_fmt",
1973+ "yuv420p10le",
1974+ "-strict",
1975+ "-1",
1976+ "-t",
1977+ "0.64",
1978+ "-f",
1979+ "yuv4mpegpipe",
1980+ "-",
1981+ ])
1982+ .stdin(Stdio::null())
1983+ .stdout(Stdio::piped())
1984+ .stderr(Stdio::piped())
1985+ .output()
1986+ .expect("ffmpeg failed to run");
1987+ assert!(
1988+ y4m.status.success(),
1989+ "ffmpeg failed to render the 10-bit fixture: {}",
1990+ String::from_utf8_lossy(&y4m.stderr)
1991+ );
1992+ let mut child = Command::new(aomenc_path())
1993+ .args([
1994+ "--codec=av1",
1995+ "--passes=1",
1996+ "--end-usage=q",
1997+ "--cq-level=15",
1998+ "--cpu-used=0",
1999+ "--threads=1",
2000+ "--row-mt=0",
2001+ "--sb-size=64",
2002+ "--input-bit-depth=10",
2003+ "--bit-depth=10",
2004+ "--lag-in-frames=0",
2005+ "--auto-alt-ref=0",
2006+ "--kf-max-dist=1000",
2007+ "--error-resilient=1",
2008+ "--aq-mode=0",
2009+ "--deltaq-mode=0",
2010+ "--enable-rect-partitions=0",
2011+ "--enable-ab-partitions=0",
2012+ "--enable-1to4-partitions=0",
2013+ "--enable-filter-intra=0",
2014+ "--enable-smooth-intra=0",
2015+ "--enable-paeth-intra=0",
2016+ "--enable-directional-intra=0",
2017+ "--enable-angle-delta=0",
2018+ "--enable-tx-size-search=0",
2019+ "--enable-cdef=1",
2020+ "--enable-restoration=1",
2021+ "--min-partition-size=16",
2022+ "--max-partition-size=32",
2023+ "--enable-palette=0",
2024+ "--enable-intrabc=0",
2025+ "--enable-cfl-intra=0",
2026+ "--enable-ref-frame-mvs=0",
2027+ "--obu",
2028+ "-o",
2029+ "-",
2030+ "-",
2031+ ])
2032+ .stdin(Stdio::piped())
2033+ .stdout(Stdio::piped())
2034+ .stderr(Stdio::piped())
2035+ .spawn()
2036+ .expect("aomenc failed to start");
2037+ child
2038+ .stdin
2039+ .take()
2040+ .expect("aomenc stdin")
2041+ .write_all(&y4m.stdout)
2042+ .expect("writing y4m to aomenc");
2043+ let out = child.wait_with_output().expect("aomenc failed to run");
2044+ assert!(
2045+ out.status.success(),
2046+ "aomenc refused the 10-bit fixture: {}",
2047+ String::from_utf8_lossy(&out.stderr)
2048+ );
2049+ let stream = out.stdout;
2050+ if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
2051+ std::fs::write(dump, &stream).expect("dump stream");
2052+ }
2053+ let mut probe = Av1Parser::new();
2054+ let mut pos = 0usize;
2055+ while pos < stream.len() && probe.sequence_header().is_none() {
2056+ let obu = probe.parse_obu(&stream[pos..]).unwrap();
2057+ pos += obu.total_size;
2058+ }
2059+ assert_eq!(
2060+ probe
2061+ .sequence_header()
2062+ .expect("stream has a sequence header OBU")
2063+ .color_config
2064+ .bit_depth,
2065+ 10,
2066+ "{NAME}: aomenc did not actually write a 10-bit sequence header"
2067+ );
2068+ let before_deblock = decode::deblock_hits();
2069+ let before_inter = decode::inter_pred_hits();
2070+ let before_lr = crate::restoration::wiener_hits()
2071+ + crate::restoration::sgrproj_hits()
2072+ + crate::restoration::switchable_hits();
2073+ let frames = match decode_stream(&stream) {
2074+ Ok(frames) => frames,
2075+ Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"),
2076+ };
2077+ assert!(
2078+ decode::inter_pred_hits() > before_inter,
2079+ "{NAME}: no inter-predicted block decoded -- the gate proves nothing"
2080+ );
2081+ assert!(
2082+ decode::deblock_hits() > before_deblock,
2083+ "{NAME}: no deblocking edge fired -- raise cq-level"
2084+ );
2085+ // Loop restoration is where the 10-bit inter/intra defect lived
2086+ // (lane-hbdinter r1: the self-guided box sums were never brought back
2087+ // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened
2088+ // to pick RESTORE_NONE would pass while proving nothing.
2089+ assert!(
2090+ crate::restoration::wiener_hits()
2091+ + crate::restoration::sgrproj_hits()
2092+ + crate::restoration::switchable_hits()
2093+ > before_lr,
2094+ "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level"
2095+ );
2096+ eprintln!(
2097+ "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}",
2098+ decode::inter_pred_hits() - before_inter,
2099+ decode::deblock_hits() - before_deblock,
2100+ decode::cdef_idx_hits(),
2101+ crate::restoration::wiener_hits(),
2102+ crate::restoration::sgrproj_hits(),
2103+ );
2104+ assert_eq!(frames.len(), frame_count);
2105+ let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count);
2106+ for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2107+ if got.y != want.y || got.u != want.u || got.v != want.v {
2108+ let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu");
2109+ let _ = std::fs::write(&pin, &stream);
2110+ let first = |a: &Vec<u16>, b: &Vec<u16>| {
2111+ a.iter()
2112+ .zip(b)
2113+ .enumerate()
2114+ .find(|(_, (x, y))| x != y)
2115+ .map(|(k, (x, y))| (k, *x, *y))
2116+ };
2117+ panic!(
2118+ "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}",
2119+ first(&got.y, &want.y),
2120+ first(&got.u, &want.u),
2121+ first(&got.v, &want.v),
2122+ pin.display()
2123+ );
2124+ }
2125+ }
2126+ }
2127+
19452128 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
19462129 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
19472130 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
crates/ec-av1/src/warp.rsmodified+11 -5
@@ -447,11 +447,17 @@ pub fn warp_affine(
447447 params.gamma as i64,
448448 params.delta as i64,
449449 );
450- const BD: i32 = 8;
451- let reduce_bits_horiz = 3; // conv_params->round_0, non-compound 8-bit (InterRound0)
450+ // lane-hbdinter r1: libaom's `av1_warp_affine_c` takes `bd` and every
451+ // offset/clip term below scales with it; this was `const BD: i32 = 8`,
452+ // so a 10-bit warped or global-motion block came out of the vertical
453+ // pass biased by `(1 << 9) + (1 << 8) - (1 << 11) - (1 << 10)` and then
454+ // clipped. `reduce_bits_horiz` is `conv_params->round_0`, which stays 3
455+ // for `bd < 12` (`convolve.h:83`'s `intbufrange > 16` threshold).
456+ let bd = i32::from(crate::decode::bit_depth());
457+ let reduce_bits_horiz = 3; // conv_params->round_0 (InterRound0), bd < 12
452458 let reduce_bits_vert = 2 * FILTER_BITS - reduce_bits_horiz; // InterRound1
453- let offset_bits_horiz = BD + FILTER_BITS - 1;
454- let offset_bits_vert = BD + 2 * FILTER_BITS - reduce_bits_horiz;
459+ let offset_bits_horiz = bd + FILTER_BITS - 1;
460+ let offset_bits_vert = bd + 2 * FILTER_BITS - reduce_bits_horiz;
455461
456462 let mut i = p_row;
457463 while i < p_row + p_height {
@@ -512,7 +518,7 @@ pub fn warp_affine(
512518 let out_row = (i - p_row + k + 4) as usize;
513519 let out_col = (j - p_col + l + 4) as usize;
514520 dst[out_row * p_stride as usize + out_col] =
515- clip_pixel(sum - (1 << (BD - 1)) - (1 << BD));
521+ clip_pixel(sum - (1 << (bd - 1)) - (1 << bd));
516522 sy += gamma;
517523 l += 1;
518524 }