diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index e88ddcc6..64f333d2 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -5457,18 +5457,21 @@ pub fn decode_key_frame_tile( thread_local! { /// lane-superres r3: the real decoded margin beyond `frame_width` up to /// the mi-aligned `true_width`, set by the most recent - /// [`decode_key_frame_tile_with_cdfs`] call. See that function's own - /// comment at the write site. `None` when there was no margin to save. - static LAST_KEY_FRAME_WIDE_MARGIN: std::cell::RefCell> = + /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10) + /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop + /// their reconstructed buffer down from the same mi-aligned extent, so + /// they share this one slot. See each function's own comment at its + /// write site. `None` when there was no margin to save. + static LAST_FRAME_WIDE_MARGIN: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } -/// The margin [`decode_key_frame_tile_with_cdfs`] most recently stashed -/// (see [`LAST_KEY_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path -/// reads this immediately after the call, before any other key frame +/// The margin the most recent key- or inter-frame tile decode stashed +/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path +/// reads this immediately after the call, before any other frame /// decode can overwrite it. -pub(crate) fn take_last_key_frame_wide_margin() -> Option { - LAST_KEY_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take()) +pub(crate) fn take_last_frame_wide_margin() -> Option { + LAST_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take()) } /// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec @@ -6102,7 +6105,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( let (fw, fh) = (frame_width as usize, frame_height as usize); if fw == width && fh == height { - LAST_KEY_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None); + LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None); return Ok(( Picture { width, @@ -6135,7 +6138,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // reaches into that real margin; `None` when there is no margin (this // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a // non-superres frame whose width just isn't 32-block aligned). - LAST_KEY_FRAME_WIDE_MARGIN.with(|m| { + LAST_FRAME_WIDE_MARGIN.with(|m| { *m.borrow_mut() = if true_width > fw || true_height > fh { let yc = crop(&y, true_width, true_height); if let Ok(path) = std::env::var("EC_AV1_MARGIN_DUMP") { @@ -10479,9 +10482,16 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( return Err(unsupported("a frame with no mode-info grid")); } let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize); - if reference.width != true_width || reference.height != true_height { + // lane-superres r10: a width mismatch alone is no longer refused here -- + // `mc::predict_scaled` (spec 7.11.3.3, threaded through + // `decode_inter_block`'s single-ref branch) exists precisely for a + // `use_superres` reference at a different width than this frame's own + // true size. Height must still match: AV1 superres never scales height + // (r8's derivation, `mc.rs`'s own doc), and nothing in this decode path + // has a vertical scaling pass. + if reference.height != true_height { return Err(unsupported( - "a reference picture that is not this frame's own true size", + "a reference picture whose height does not match this frame's own true size", )); } let (cols, rows) = block_grid(mi_cols, mi_rows); @@ -11987,6 +11997,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( let (fw, fh) = (frame_width as usize, frame_height as usize); if fw == width && fh == height { + LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None); return Ok(( Picture { width, @@ -12006,6 +12017,24 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } out }; + // lane-superres r10: same real-margin stash as + // `decode_key_frame_tile_with_cdfs` (see that function's comment) -- an + // inter frame under `use_superres` crops from the same mi-aligned + // `width`/`height` down to `fw`/`fh`, and `stream.rs`'s upscale needs + // the same real border-extension columns, not a synthetic replicate. + LAST_FRAME_WIDE_MARGIN.with(|m| { + *m.borrow_mut() = if width > fw || height > fh { + Some(Picture { + width, + height, + y: crop(&y, width, height), + u: crop(&u, width.div_ceil(2), height.div_ceil(2)), + v: crop(&v, width.div_ceil(2), height.div_ceil(2)), + }) + } else { + None + } + }); Ok(( Picture { width: fw, diff --git a/crates/ec-av1/src/mc.rs b/crates/ec-av1/src/mc.rs index a7ff5f63..c5029e65 100644 --- a/crates/ec-av1/src/mc.rs +++ b/crates/ec-av1/src/mc.rs @@ -427,6 +427,20 @@ pub fn scale_factor(other_width: usize, this_width: usize) -> i64 { (((other_width as i64) << 14) + this_width as i64 / 2) / this_width as i64 } +thread_local! { + /// lane-superres r10: firing count for the bypass gate (class + /// `gate-blind-to-feature`) -- how many times [`predict_scaled`] itself + /// ran, so the gate can hard-assert the scaled MC path actually fired + /// rather than trust a pixel match alone (an unscaled reference would + /// pass the pixels and prove nothing). + static PREDICT_SCALED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`PREDICT_SCALED_HITS`]. +pub fn predict_scaled_hits() -> usize { + PREDICT_SCALED_HITS.with(|c| c.get()) +} + fn round_pow2_64(value: i64, shift: u32) -> i64 { if shift == 0 { value @@ -478,6 +492,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"); + PREDICT_SCALED_HITS.with(|c| c.set(c.get() + 1)); let y0 = y_q4.div_euclid(16); let yfrac = y_q4.rem_euclid(16) as usize; diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 112efb5a..82ded358 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -42,7 +42,6 @@ const REFUSALS: &[&str] = &[ "a stream whose bit depth is not 8 (this decoder reconstructs into 8-bit planes)", "a tx_type symbol outside its CDF's own set: {t}", "an INTER 32x32 partition type this decoder does not code (value={part32})", - "an inter frame with use_superres set (this decoder never scales its motion-compensated reference to match the current frame's downscaled size, spec 7.11.3.3)", "a superblock-level partition type other than NONE or SPLIT (this decoder's intra tile path codes only those two at 64x64)", "a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed for square blocks only)", "a HORZ/VERT intra strip with a split transform (per-unit rect prediction is not ported)", @@ -57,7 +56,7 @@ const REFUSALS: &[&str] = &[ "a palette block with a split luma transform (round 1)", "a reference frame other than LAST_FRAME (round 2)", "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it", - "a reference picture that is not this frame's own true size", + "a reference picture whose height does not match this frame's own true size", "a show_existing_frame header naming an empty reference slot", "an 8x8 leaf that coded WARPED_CAUSAL (motion_mode == 2): av1_find_projection/the affine warp filter are not ported, only motion_mode_allowed's alphabet choice is", "an inter frame using TxMode::Select (this decoder's inter path never reads a tx_depth symbol, so it desyncs after the first block's mode)", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index a2276602..5193aa14 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -254,19 +254,16 @@ pub fn decode_stream(data: &[u8]) -> Result> { // reads stay bit-exact in sync and `crate::superres::upscale_picture` // (below, after decode) makes its `Picture` the spec-correct // `upscaled_width` instead of silently staying at `frame_width`. - // An INTER frame under `use_superres` still refuses: its reference - // is stored upscaled while the current frame decodes at the - // downscaled `frame_width`, so `decode_inter_frame_tile_with_cdfs`'s - // motion compensation would sample a reference at the wrong scale - // (spec 7.11.3.3's scaled-reference path is not ported) -- - // SILENT WRONGNESS, not a desync, same as the key-frame case used - // to be. Left for a later stage of this lane. - if header.use_superres && header.frame_type != FrameType::Key { - return Err(Error::unsupported( - "AV1 decode_stream", - "an inter frame with use_superres set (this decoder never scales its motion-compensated reference to match the current frame's downscaled size, spec 7.11.3.3)", - )); - } + // lane-superres r10: an INTER frame under `use_superres` no longer + // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3) + // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/ + // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes + // at the downscaled `frame_width` and upscales its own output the + // same way the key-frame branch above does (see the inter branch + // below). The combinations `predict_scaled` does not cover + // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8 + // leaf) still refuse by name, deep in `decode.rs`, rather than + // silently mispredicting -- see `refusal_inventory.rs`. // Loop restoration carries per-restoration-unit symbols in the tile // (spec 5.11.57 `read_lr`, one group per LR unit reached from the // superblock walk) -- lane-lr r2 ported the reader @@ -490,8 +487,8 @@ pub fn decode_stream(data: &[u8]) -> Result> { // no LR step here for the upscale to precede. // r3: the real decoded margin beyond `frame_width` (set by the // call above, right before anything else can overwrite it) -- - // see `decode::take_last_key_frame_wide_margin`'s doc. - let wide_margin = crate::decode::take_last_key_frame_wide_margin(); + // see `decode::take_last_frame_wide_margin`'s doc. + let wide_margin = crate::decode::take_last_frame_wide_margin(); let picture = if header.use_superres { crate::superres::upscale_picture( &picture, @@ -551,7 +548,7 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.mi_cols as usize, ) }); - decode_inter_frame_tile_with_cdfs( + let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs( &tile_bufs, &header.tile_info, header.mi_cols, @@ -586,7 +583,26 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.allow_warped_motion, header.allow_screen_content_tools, header.delta, - )? + )?; + // lane-superres r10: mirrors the key-frame branch above -- + // `decode_inter_frame_tile_with_cdfs` decodes at the downscaled + // `frame_width`/`frame_height` and crops to it; upscale AFTER + // (deblock/CDEF/LR already applied inside that call) BEFORE this + // picture is stored as a reference or shown, same margin + // mechanism (`take_last_frame_wide_margin`, read immediately + // after the call, before any other frame decode can overwrite + // it). + let wide_margin = crate::decode::take_last_frame_wide_margin(); + let picture = if header.use_superres { + crate::superres::upscale_picture( + &picture, + header.upscaled_width as usize, + wide_margin.as_ref(), + ) + } else { + picture + }; + (picture, end_cdfs, motion_field) }; // lane-lr r4: the Wiener/self-guided pixel filters are wired // (`decode.rs::apply_loop_restoration`) -- no more refusal here, @@ -4223,18 +4239,17 @@ mod tests { ); } - /// lane-superres Step 0/stage 1: a real aomenc `--superres-mode=1` - /// stream must refuse BY NAME (`use_superres`), never desync into a - /// different error and never silently decode a wrong-sized picture. - /// `use_superres` adds no per-block symbol (spec 7.16's upscaler is a - /// pixel-domain post-process), so before the stream.rs refusal landed - /// this crate's tile readers stayed bit-exact in sync but stored the - /// `Picture` at the downscaled `frame_width` instead of - /// `upscaled_width` -- exactly the SILENT WRONGNESS the charter's Step 0 - /// called for turning into an explicit refusal first. + /// lane-superres stage 3: a real aomenc `--superres-mode=1` key-frame + /// sequence must decode pixel-exact vs ffmpeg/dav1d's own upscaled + /// output, and must actually run [`crate::superres::upscale_picture`] + /// (`superres_hits > 0`) -- a decoder that silently stopped upscaling + /// would otherwise pass vacuously (class `gate-blind-to-feature`). + /// `--kf-max-dist` set to the frame count keeps every frame a key + /// frame: inter-frame superres (a differently-scaled reference) is a + /// later stage of this lane, refused by name today. #[test] - fn a_real_aomenc_stream_with_superres_refuses_by_name() { - const NAME: &str = "a_real_aomenc_stream_with_superres_refuses_by_name"; + fn a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact"; let _gate_lock = lock_gate_counters(); if !have_ffmpeg() { eprintln!("SKIP {NAME}: no ffmpeg"); @@ -4244,9 +4259,9 @@ mod tests { eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); return; } - let (width, height, frame_count) = (64usize, 64usize, 4usize); + let (width, height, frame_count) = (64usize, 64usize, 3usize); let duration = frame_count as f64 / 25.0; - let source = gradients_source(42, width, height, &format!("duration={duration}:rate=25")); + let source = gradients_source(7, width, height, &format!("duration={duration}:rate=25")); let y4m = Command::new("ffmpeg") .args([ "-v", @@ -4277,11 +4292,28 @@ mod tests { "--end-usage=q", "--cq-level=32", "--cpu-used=0", - "--kf-max-dist=1000", + "--kf-max-dist=0", "--threads=1", "--row-mt=0", "--superres-mode=1", "--superres-denominator=12", + "--superres-kf-denominator=12", + "--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=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", "--obu", "-o", "-", @@ -4307,30 +4339,42 @@ mod tests { String::from_utf8_lossy(&out.stderr) ); let stream = out.stdout; - let err = decode_stream(&stream).expect_err( - "a real --superres-mode=1 stream must refuse -- superres decode is not implemented \ - and silently produces a wrong-sized picture otherwise", - ); - let msg = err.to_string(); + if let Ok(path) = std::env::var("EC_SUPERRES_STREAM_DUMP") { + std::fs::write(path, &stream).expect("dump stream"); + } + let frames = + decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}")); + assert_eq!(frames.len(), frame_count); + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 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"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg"); + } assert!( - msg.contains("use_superres"), - "{NAME}: refused, but not by the superres name -- this stream desynced into a \ - different refusal instead: {msg}" + crate::superres::superres_hits() > 0, + "{NAME}: matched but zero superres_hits -- the gate never actually exercised the \ + upscaler, it proves nothing" + ); + eprintln!( + "{NAME}: {frame_count} frames pixel-exact, superres_hits={}", + crate::superres::superres_hits() ); - eprintln!("{NAME}: refused by name: {msg}"); } - /// lane-superres stage 3: a real aomenc `--superres-mode=1` key-frame - /// sequence must decode pixel-exact vs ffmpeg/dav1d's own upscaled - /// output, and must actually run [`crate::superres::upscale_picture`] - /// (`superres_hits > 0`) -- a decoder that silently stopped upscaling - /// would otherwise pass vacuously (class `gate-blind-to-feature`). - /// `--kf-max-dist` set to the frame count keeps every frame a key - /// frame: inter-frame superres (a differently-scaled reference) is a - /// later stage of this lane, refused by name today. + /// lane-superres r10: a real aomenc key+inter `--superres-mode=1` + /// sequence must DECODE pixel-exact vs ffmpeg, with the frame-level + /// `use_superres` refusal LIFTED for inter frames -- `mc::predict_scaled` + /// (spec 7.11.3.3) is the only path this recipe can reach (warp/OBMC/ + /// compound/interintra/palette/intrabc/CDEF/LR are all off, matching the + /// scoped refusals' own unimplemented list). A pixel match alone would + /// pass just as well with an unscaled reference and prove nothing + /// (class `gate-blind-to-feature`) -- hard-assert + /// `crate::mc::predict_scaled_hits() > 0` so the gate can only pass if the + /// scaled MC path actually ran. #[test] - fn a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact() { - const NAME: &str = "a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact"; + fn a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact"; let _gate_lock = lock_gate_counters(); if !have_ffmpeg() { eprintln!("SKIP {NAME}: no ffmpeg"); @@ -4342,7 +4386,7 @@ mod tests { } let (width, height, frame_count) = (64usize, 64usize, 3usize); let duration = frame_count as f64 / 25.0; - let source = gradients_source(7, width, height, &format!("duration={duration}:rate=25")); + let source = gradients_source(11, width, height, &format!("duration={duration}:rate=25")); let y4m = Command::new("ffmpeg") .args([ "-v", @@ -4373,12 +4417,33 @@ mod tests { "--end-usage=q", "--cq-level=32", "--cpu-used=0", - "--kf-max-dist=0", + // `--kf-max-dist` above `frame_count` keeps only frame 0 a key + // frame -- frames 1/2 are the inter frames whose `use_superres` + // refusal this round lifts. + "--kf-max-dist=1000", + "--lag-in-frames=0", + "--auto-alt-ref=0", "--threads=1", "--row-mt=0", + "--sb-size=64", "--superres-mode=1", "--superres-denominator=12", "--superres-kf-denominator=12", + // Forces every inter block onto the single-ref, non-warp/OBMC/ + // interintra branch `decode_inter_block` threads `predict_scaled` + // through -- the only branch this round's scoped refusals leave + // unrefused under a scaled reference. + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-dist-wtd-comp=0", + "--enable-diff-wtd-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-order-hint=0", + "--enable-ref-frame-mvs=0", "--enable-rect-partitions=0", "--enable-ab-partitions=0", "--enable-1to4-partitions=0", @@ -4420,8 +4485,8 @@ mod tests { String::from_utf8_lossy(&out.stderr) ); let stream = out.stdout; - if let Ok(path) = std::env::var("EC_SUPERRES_STREAM_DUMP") { - std::fs::write(path, &stream).expect("dump stream"); + if let Ok(path) = std::env::var("EC_SUPERRES_INTER_STREAM_DUMP") { + std::fs::write(&path, &stream).expect("dump stream"); } let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}")); @@ -4434,12 +4499,18 @@ mod tests { } assert!( crate::superres::superres_hits() > 0, - "{NAME}: matched but zero superres_hits -- the gate never actually exercised the \ - upscaler, it proves nothing" + "{NAME}: matched but zero superres_hits -- the upscaler never ran" + ); + assert!( + crate::mc::predict_scaled_hits() > 0, + "{NAME}: matched but zero predict_scaled_hits -- every block took the unscaled MC \ + path, which proves nothing about the scaled-reference code this round adds \ + (class gate-blind-to-feature)" ); eprintln!( - "{NAME}: {frame_count} frames pixel-exact, superres_hits={}", - crate::superres::superres_hits() + "{NAME}: {frame_count} frames pixel-exact, superres_hits={}, predict_scaled_hits={}", + crate::superres::superres_hits(), + crate::mc::predict_scaled_hits() ); } diff --git a/crates/ec-av1/src/superres.rs b/crates/ec-av1/src/superres.rs index 25d0bd8a..679b33bd 100644 --- a/crates/ec-av1/src/superres.rs +++ b/crates/ec-av1/src/superres.rs @@ -103,7 +103,7 @@ pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize // mi-aligned `true_width` (the coding block straddling the frame edge) // -- libaom's border extension replicates from THAT last real column, // not from `frame_width - 1`. `real_right_margin` (from - // `decode::take_last_key_frame_wide_margin`) supplies those real + // `decode::take_last_frame_wide_margin`) supplies those real // pixels first; only once it runs out (or is empty, e.g. `fw` was // already mi-aligned) does this fall back to r1's replicate. Pinned // column-by-column against real libaom via `scripts/superres-pin- @@ -178,7 +178,7 @@ pub(crate) fn superres_hits() -> usize { /// `frame_width`/`frame_height` (4:2:0 chroma) to `upscaled_width` at the /// same height -- spec 7.16 is horizontal-only. Increments /// [`SUPERRES_HITS`] once per call. `margin`, when set (r3, from -/// `decode::take_last_key_frame_wide_margin`), is the real decoded pixels +/// `decode::take_last_frame_wide_margin`), is the real decoded pixels /// beyond `picture`'s own width out to the mi-aligned `true_width` -- see /// [`upscale_row`]'s doc for why the right-edge padding needs it. pub(crate) fn upscale_picture(