diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index c82e3b99..cb988e38 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -4199,15 +4199,17 @@ fn apply_deblock( v: &mut PlaneBuf, lf: &LoopFilterParams, n: &Neighbours, + frame_width: usize, + frame_height: usize, ) { if lf.level[0] != 0 || lf.level[1] != 0 { - deblock_plane(y, 0, lf, n); + deblock_plane(y, 0, lf, n, frame_width, frame_height); } if lf.level[2] != 0 { - deblock_plane(u, 1, lf, n); + deblock_plane(u, 1, lf, n, frame_width, frame_height); } if lf.level[3] != 0 { - deblock_plane(v, 2, lf, n); + deblock_plane(v, 2, lf, n, frame_width, frame_height); } } @@ -4716,9 +4718,33 @@ fn filter_edge( /// One plane's worth of spec 7.14: every vertical edge across the plane, /// then every horizontal edge (the order the spec and libaom both use). -fn deblock_plane(plane: &mut PlaneBuf, plane_idx: usize, lf: &LoopFilterParams, n: &Neighbours) { +fn deblock_plane( + plane: &mut PlaneBuf, + plane_idx: usize, + lf: &LoopFilterParams, + n: &Neighbours, + frame_width: usize, + frame_height: usize, +) { let chroma = plane_idx != 0; - let (tw, th, stride) = (plane.true_width, plane.true_height, plane.width); + // r7: libaom clips the deblock loop to the CODED frame's own + // width/height, not the mi-aligned `true_width`/`true_height` margin + // (the padding up to the next 8-pixel/superblock boundary that + // reconstruction still fills in but the loop filter never visits). + // Confirmed against the superres gate: with the margin included, the + // last coded mi column's horizontal edges were filtered when libaom's + // real output leaves them untouched (r6's post-deblock diff, 37 px, all + // in columns 44-47); clipping here closes it (3/3 frames pixel-exact). + let (cw, ch) = if chroma { + (frame_width.div_ceil(2), frame_height.div_ceil(2)) + } else { + (frame_width, frame_height) + }; + let (tw, th, stride) = ( + plane.true_width.min(cw), + plane.true_height.min(ch), + plane.width, + ); let mut y0 = 0usize; while y0 < th { let mut x0 = 4usize; @@ -4743,6 +4769,15 @@ fn deblock_plane(plane: &mut PlaneBuf, plane_idx: usize, lf: &LoopFilterParams, let mut y0 = 4usize; while y0 < th { if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) { + if std::env::var_os("EC_AV1_DEBLOCK_TRACE").is_some() + && plane_idx == 0 + && x0 == 44 + { + eprintln!( + "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}", + lf.sharpness + ); + } filter_edge( &mut plane.data, y0 * stride + x0, @@ -4946,6 +4981,23 @@ pub fn decode_key_frame_tile( .map(|(picture, _)| picture) } +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> = + 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 +/// 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()) +} + /// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec /// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from /// a prior frame's saved reference slot) when set, or the spec 8.4 defaults @@ -5529,11 +5581,37 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } else { PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); } - apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours); + if let Ok(path) = std::env::var("EC_AV1_PREFILT_WIDE_DUMP") { + use std::io::Write; + static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let crop_wide = |plane: &PlaneBuf| -> Vec { + let mut out = Vec::with_capacity(plane.true_width * plane.true_height); + for row in 0..plane.true_height { + out.extend_from_slice(&plane.data[row * plane.width..][..plane.true_width]); + } + out + }; + if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) { + let _ = f.write_all(&crop_wide(&y)); + let _ = f.write_all(&crop_wide(&u)); + let _ = f.write_all(&crop_wide(&v)); + } + } + apply_deblock( + &mut y, + &mut u, + &mut v, + loop_filter, + &neighbours, + frame_width as usize, + frame_height as usize, + ); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); 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); return Ok(( Picture { width, @@ -5552,13 +5630,49 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } out }; + // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4) + // is the real reconstructed extent -- columns `[fw, true_width)` hold + // genuine decoded samples (the last coding block straddles the frame + // edge whenever `frame_width` isn't 8-sample aligned), not padding. + // libaom's superres upscale runs on that buffer's own border-extended + // margin, so it reads those real columns, not a synthetic replicate of + // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real + // aomenc 43->64 stream pinned column-by-column against libaom's own + // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` -- + // `row6-realedgeval` proved the replicate-of-`fw-1` padding this + // decoder used before was off by 1 at the columns the tap window + // 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| { + *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") { + use std::io::Write; + static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) { + let _ = f.write_all(&yc); + } + } + Some(Picture { + width: true_width, + height: true_height, + y: yc, + u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)), + v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)), + }) + } else { + None + } + }); Ok(( Picture { width: fw, height: fh, y: crop(&y, fw, fh), - u: crop(&u, fw / 2, fh / 2), - v: crop(&v, fw / 2, fh / 2), + u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)), + v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)), }, result_cdfs, )) @@ -11227,7 +11341,15 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } else { PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); } - apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours); + apply_deblock( + &mut y, + &mut u, + &mut v, + loop_filter, + &neighbours, + frame_width as usize, + frame_height as usize, + ); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); let motion_field = build_motion_field( @@ -11264,8 +11386,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( width: fw, height: fh, y: crop(&y, fw, fh), - u: crop(&u, fw / 2, fh / 2), - v: crop(&v, fw / 2, fh / 2), + u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)), + v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)), }, result_cdfs, motion_field, diff --git a/crates/ec-av1/src/gate_coverage.rs b/crates/ec-av1/src/gate_coverage.rs index 0d1da08f..eb71c36f 100644 --- a/crates/ec-av1/src/gate_coverage.rs +++ b/crates/ec-av1/src/gate_coverage.rs @@ -18,8 +18,16 @@ //! feature's gate, which shrinks the derived set and fails this test until the //! list is updated -- the point being that the shrink is noticed. -/// aomenc coding tools that no real-`aomenc` gate exercises: switched off in -/// every gate that names them, on in none, defaulted in none. +/// aomenc coding tools that no real-`aomenc` gate is proven to exercise: +/// switched off in every gate that names them, and on in none. +/// +/// A gate that simply leaves the flag off its command line does NOT close the +/// hole. aomenc's default for these is content-dependent -- palette and +/// intrabc only come on for screen content -- so "defaulted" means "unknown", +/// not "exercised", and treating it as coverage would retire the entry +/// without a single stream proving the decoder ever saw the tool. Only an +/// explicit `--enable-=1` in a gate that then asserts the feature fired +/// closes one. /// /// Each entry is `(flag, why)`. Removing an entry is how a lane records that /// its tool is now covered by a real stream. @@ -72,11 +80,23 @@ mod tests { #[test] fn every_gate_disabling_a_tool_is_a_listed_coverage_hole() { let (gate_count, per_tool) = tool_settings(); + // A hole OPENS when every gate names the flag and every one of them + // says 0 -- then no real stream can exercise the tool. let derived: BTreeSet<&str> = per_tool .iter() .filter(|&(_, &(off, on, defaulted))| off == gate_count && on == 0 && defaulted == 0) .map(|(name, _)| name.as_str()) .collect(); + // A hole CLOSES only on positive evidence: some gate passes `=1`. + // A gate that merely leaves the flag off its command line proves + // nothing -- aomenc's default for palette and intrabc is content- + // dependent -- so "defaulted" must not retire an entry, or a listing + // would disappear the moment an unrelated gate is added. + let exercised: BTreeSet<&str> = per_tool + .iter() + .filter(|&(_, &(_, on, _))| on > 0) + .map(|(name, _)| name.as_str()) + .collect(); let listed: BTreeSet<&str> = NEVER_EXERCISED.iter().map(|&(flag, _)| flag).collect(); let unlisted: Vec<&&str> = derived.difference(&listed).collect(); @@ -84,13 +104,13 @@ mod tests { unlisted.is_empty(), "these aomenc tools are switched off in all {gate_count} real-aomenc gates and on in \ none, so no real stream exercises them, and they are not listed in NEVER_EXERCISED: \ - {unlisted:?} -- either enable the tool in its own gate or add it to the list with a \ - reason" + {unlisted:?} -- either enable the tool with `=1` in its own gate or add it to the \ + list with a reason" ); - let stale: Vec<&&str> = listed.difference(&derived).collect(); + let stale: Vec<&&str> = listed.intersection(&exercised).collect(); assert!( stale.is_empty(), - "NEVER_EXERCISED lists {stale:?}, but a gate now enables or defaults them -- delete \ + "NEVER_EXERCISED lists {stale:?}, but a gate now passes `=1` for them -- delete \ those entries, the coverage hole is closed" ); } diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index c346e506..ca80f861 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -32,6 +32,7 @@ pub mod obu; pub mod quant; mod refusal_inventory; pub mod sequence; +mod superres; pub mod stream; pub mod tile; pub mod transform; diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 607ca923..51d65674 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -42,6 +42,7 @@ 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)", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 0c60ee35..cda9e908 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -200,6 +200,26 @@ pub fn decode_stream(data: &[u8]) -> Result> { "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)", )); } + // lane-superres stage 2/3: `use_superres` adds/removes no per-block + // symbol (spec 7.16's upscaling is a pixel-domain post-process + // libaom's `decodeframe.c` runs between CDEF and loop restoration, + // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile + // 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)", + )); + } // 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) that this decoder never reads -- same @@ -416,6 +436,24 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.allow_intrabc, header.delta, )?; + // lane-superres stage 3, spec 7.16: upscale AFTER deblock+CDEF + // (both already applied inside `decode_key_frame_tile_with_cdfs`) + // and BEFORE this picture is stored as a reference or handed to + // the caller -- loop restoration is not yet ported, so there is + // 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(); + let picture = if header.use_superres { + crate::superres::upscale_picture( + &picture, + header.upscaled_width as usize, + wide_margin.as_ref(), + ) + } else { + picture + }; // A key frame codes no inter blocks -- its own saved motion // field has no cells set, matching libaom's own "intra frame // contributes nothing to a later projection" behaviour, but @@ -3991,6 +4029,226 @@ 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. + #[test] + fn a_real_aomenc_stream_with_superres_refuses_by_name() { + const NAME: &str = "a_real_aomenc_stream_with_superres_refuses_by_name"; + 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) = (64usize, 64usize, 4usize); + let duration = frame_count as f64 / 25.0; + let source = gradients_source(42, width, height, &format!("duration={duration}:rate=25")); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=32", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--superres-mode=1", + "--superres-denominator=12", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .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 fixture: {}", + 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(); + assert!( + msg.contains("use_superres"), + "{NAME}: refused, but not by the superres name -- this stream desynced into a \ + different refusal instead: {msg}" + ); + 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. + #[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"; + 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) = (64usize, 64usize, 3usize); + let duration = frame_count as f64 / 25.0; + let source = gradients_source(7, width, height, &format!("duration={duration}:rate=25")); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=32", + "--cpu-used=0", + "--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", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .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 fixture: {}", + 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"); + } + 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!( + 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() + ); + } + /// lane-interintra r1: `--enable-interintra-comp=1` streams must DECODE /// pixel-exact -- the interintra flag/mode/wedge-flag syntax and the /// non-wedge smooth blend are ported. A refusal naming interintra fails diff --git a/crates/ec-av1/src/superres.rs b/crates/ec-av1/src/superres.rs new file mode 100644 index 00000000..25d0bd8a --- /dev/null +++ b/crates/ec-av1/src/superres.rs @@ -0,0 +1,285 @@ +//! AV1 spec 7.16 upscaling process (`av1_upscale_normative_rows` in +//! libaom's `av1/common/resize.c`) -- the horizontal-only linear-filter +//! upscale that runs on the decoded frame after deblocking and CDEF (and, +//! once this crate supports loop restoration, BEFORE it -- libaom's +//! `decodeframe.c` calls `superres_post_decode()` between `av1_cdef_frame` +//! and `av1_loop_restoration_filter_frame`, not after LR; the charter's +//! anchor note that superres runs "after loop restoration" does not match +//! the source and is corrected here). +//! +//! Every constant and the 64x8 `av1_resize_filter_normative` coefficient +//! table below is copied verbatim from libaom `aom_dsp/aom_filter.h` and +//! `av1/common/resize.c` (`AOM_VERSION=v3.13.3`, `~/.cache/aom-oracle`). + +/// `RS_SUBPEL_BITS`. +const RS_SUBPEL_BITS: u32 = 6; +/// `RS_SCALE_SUBPEL_BITS`. +const RS_SCALE_SUBPEL_BITS: u32 = 14; +/// `RS_SCALE_SUBPEL_MASK`. +const RS_SCALE_SUBPEL_MASK: i64 = (1i64 << RS_SCALE_SUBPEL_BITS) - 1; +/// `RS_SCALE_EXTRA_BITS`. +const RS_SCALE_EXTRA_BITS: u32 = RS_SCALE_SUBPEL_BITS - RS_SUBPEL_BITS; +/// `RS_SCALE_EXTRA_OFF`. +const RS_SCALE_EXTRA_OFF: i64 = 1i64 << (RS_SCALE_EXTRA_BITS - 1); +/// `UPSCALE_NORMATIVE_TAPS`. +const UPSCALE_NORMATIVE_TAPS: usize = 8; +/// `FILTER_BITS`. +const FILTER_BITS: u32 = 7; + +/// `av1_resize_filter_normative`, libaom `av1/common/resize.c`. 64 subpel +/// phases x 8 taps. +#[rustfmt::skip] +const RESIZE_FILTER_NORMATIVE: [[i16; UPSCALE_NORMATIVE_TAPS]; 1 << RS_SUBPEL_BITS] = [ + [0, 0, 0, 128, 0, 0, 0, 0], [0, 0, -1, 128, 2, -1, 0, 0], + [0, 1, -3, 127, 4, -2, 1, 0], [0, 1, -4, 127, 6, -3, 1, 0], + [0, 2, -6, 126, 8, -3, 1, 0], [0, 2, -7, 125, 11, -4, 1, 0], + [-1, 2, -8, 125, 13, -5, 2, 0], [-1, 3, -9, 124, 15, -6, 2, 0], + [-1, 3, -10, 123, 18, -6, 2, -1], [-1, 3, -11, 122, 20, -7, 3, -1], + [-1, 4, -12, 121, 22, -8, 3, -1], [-1, 4, -13, 120, 25, -9, 3, -1], + [-1, 4, -14, 118, 28, -9, 3, -1], [-1, 4, -15, 117, 30, -10, 4, -1], + [-1, 5, -16, 116, 32, -11, 4, -1], [-1, 5, -16, 114, 35, -12, 4, -1], + [-1, 5, -17, 112, 38, -12, 4, -1], [-1, 5, -18, 111, 40, -13, 5, -1], + [-1, 5, -18, 109, 43, -14, 5, -1], [-1, 6, -19, 107, 45, -14, 5, -1], + [-1, 6, -19, 105, 48, -15, 5, -1], [-1, 6, -19, 103, 51, -16, 5, -1], + [-1, 6, -20, 101, 53, -16, 6, -1], [-1, 6, -20, 99, 56, -17, 6, -1], + [-1, 6, -20, 97, 58, -17, 6, -1], [-1, 6, -20, 95, 61, -18, 6, -1], + [-2, 7, -20, 93, 64, -18, 6, -2], [-2, 7, -20, 91, 66, -19, 6, -1], + [-2, 7, -20, 88, 69, -19, 6, -1], [-2, 7, -20, 86, 71, -19, 6, -1], + [-2, 7, -20, 84, 74, -20, 7, -2], [-2, 7, -20, 81, 76, -20, 7, -1], + [-2, 7, -20, 79, 79, -20, 7, -2], [-1, 7, -20, 76, 81, -20, 7, -2], + [-2, 7, -20, 74, 84, -20, 7, -2], [-1, 6, -19, 71, 86, -20, 7, -2], + [-1, 6, -19, 69, 88, -20, 7, -2], [-1, 6, -19, 66, 91, -20, 7, -2], + [-2, 6, -18, 64, 93, -20, 7, -2], [-1, 6, -18, 61, 95, -20, 6, -1], + [-1, 6, -17, 58, 97, -20, 6, -1], [-1, 6, -17, 56, 99, -20, 6, -1], + [-1, 6, -16, 53, 101, -20, 6, -1], [-1, 5, -16, 51, 103, -19, 6, -1], + [-1, 5, -15, 48, 105, -19, 6, -1], [-1, 5, -14, 45, 107, -19, 6, -1], + [-1, 5, -14, 43, 109, -18, 5, -1], [-1, 5, -13, 40, 111, -18, 5, -1], + [-1, 4, -12, 38, 112, -17, 5, -1], [-1, 4, -12, 35, 114, -16, 5, -1], + [-1, 4, -11, 32, 116, -16, 5, -1], [-1, 4, -10, 30, 117, -15, 4, -1], + [-1, 3, -9, 28, 118, -14, 4, -1], [-1, 3, -9, 25, 120, -13, 4, -1], + [-1, 3, -8, 22, 121, -12, 4, -1], [-1, 3, -7, 20, 122, -11, 3, -1], + [-1, 2, -6, 18, 123, -10, 3, -1], [0, 2, -6, 15, 124, -9, 3, -1], + [0, 2, -5, 13, 125, -8, 2, -1], [0, 1, -4, 11, 125, -7, 2, 0], + [0, 1, -3, 8, 126, -6, 2, 0], [0, 1, -3, 6, 127, -4, 1, 0], + [0, 1, -2, 4, 127, -3, 1, 0], [0, 0, -1, 2, 128, -1, 0, 0], +]; + +/// `av1_get_upscale_convolve_step` (`resize.c`). +fn upscale_convolve_step(in_length: i64, out_length: i64) -> i64 { + ((in_length << RS_SCALE_SUBPEL_BITS) + out_length / 2) / out_length +} + +/// `get_upscale_convolve_x0` (`resize.c`, static there). +fn upscale_convolve_x0(in_length: i64, out_length: i64, x_step_qn: i64) -> i64 { + let err = out_length * x_step_qn - (in_length << RS_SCALE_SUBPEL_BITS); + let x0 = (-((out_length - in_length) << (RS_SCALE_SUBPEL_BITS - 1)) + out_length / 2) + / out_length + + RS_SCALE_EXTRA_OFF + - err / 2; + x0.rem_euclid(1i64 << RS_SCALE_SUBPEL_BITS) & RS_SCALE_SUBPEL_MASK +} + +/// `av1_convolve_horiz_rs_c` (`convolve.c`): `clip_pixel(ROUND_POWER_OF_TWO(sum, FILTER_BITS))`. +fn round_power_of_two(sum: i32, bits: u32) -> i32 { + (sum + (1 << (bits - 1))) >> bits +} + +/// One row of the spec 7.16 horizontal upscale (`upscale_normative_rect` + +/// `av1_convolve_horiz_rs_c`, single-tile case: `pad_left`/`pad_right` both +/// true, replicating the row's own edge pixels rather than sampling a +/// neighbour tile). `in_width` and `out_width` must both be positive; +/// `row.len() == in_width` and `out.len() == out_width`. +pub(crate) fn upscale_row(row: &[u8], real_right_margin: &[u8], out_width: usize, out: &mut [u8]) { + let in_width = row.len(); + debug_assert!(in_width > 0 && out_width > 0); + debug_assert_eq!(out.len(), out_width); + let x_step_qn = upscale_convolve_step(in_width as i64, out_width as i64); + let x0_qn = upscale_convolve_x0(in_width as i64, out_width as i64, x_step_qn); + + // Right-edge padding: r1 assumed a pure edge-replicate of `row`'s own + // last column (matching `upscale_normative_rect`'s single-tile + // in-memory fill), but the real decoder's reconstructed buffer already + // holds genuine decoded samples past `frame_width` out to the + // 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 + // 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- + // harness.c`'s `row6-realedgeval` case (r3). + let pad = UPSCALE_NORMATIVE_TAPS + 2; + let mut padded = vec![0u8; in_width + 2 * pad]; + padded[..pad].fill(row[0]); + padded[pad..pad + in_width].copy_from_slice(row); + let real_n = real_right_margin.len().min(pad); + padded[pad + in_width..pad + in_width + real_n].copy_from_slice(&real_right_margin[..real_n]); + let replicate_from = real_right_margin.last().copied().unwrap_or(row[in_width - 1]); + padded[pad + in_width + real_n..].fill(replicate_from); + + // `av1_convolve_horiz_rs_c` is called with `input - 1` and itself + // subtracts `UPSCALE_NORMATIVE_TAPS/2 - 1` more; net offset from the + // real column-0 pixel is `-(UPSCALE_NORMATIVE_TAPS/2)` == -4. + let base = pad as i64 - (UPSCALE_NORMATIVE_TAPS as i64 / 2); + let mut x_qn = x0_qn; + for out_x in out.iter_mut() { + let int_pel = x_qn >> RS_SCALE_SUBPEL_BITS; + let filter_idx = ((x_qn & RS_SCALE_SUBPEL_MASK) >> RS_SCALE_EXTRA_BITS) as usize; + let filter = &RESIZE_FILTER_NORMATIVE[filter_idx]; + let mut sum = 0i32; + for (k, &c) in filter.iter().enumerate() { + let idx = base + int_pel + k as i64; + sum += padded[idx as usize] as i32 * c as i32; + } + *out_x = round_power_of_two(sum, FILTER_BITS).clamp(0, 255) as u8; + x_qn += x_step_qn; + } +} + +/// Spec 7.16, applied to a whole plane: `av1_upscale_normative_rows` +/// widened to every row (`height2 == height`, no vertical scaling -- the +/// spec only widens columns). `rows` is the plane's row-major byte buffer +/// at `in_width`; returns a new buffer at `out_width`. +pub(crate) fn upscale_plane( + rows: &[u8], + height: usize, + in_width: usize, + out_width: usize, + margin: Option<(&[u8], usize)>, +) -> Vec { + debug_assert_eq!(rows.len(), height * in_width); + let mut out = vec![0u8; height * out_width]; + for r in 0..height { + let src = &rows[r * in_width..(r + 1) * in_width]; + let dst = &mut out[r * out_width..(r + 1) * out_width]; + let real_right = match margin { + Some((margin_rows, margin_width)) if margin_width > in_width => { + &margin_rows[r * margin_width + in_width..(r + 1) * margin_width] + } + _ => &[], + }; + upscale_row(src, real_right, out_width, dst); + } + out +} + +thread_local! { + /// Firing count for the superres gate (class `gate-blind-to-feature`): + /// how many whole pictures actually ran through [`upscale_plane`]. + static SUPERRES_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`SUPERRES_HITS`]. +pub(crate) fn superres_hits() -> usize { + SUPERRES_HITS.with(|c| c.get()) +} + +/// A whole [`crate::encode::Picture`]'s Y/U/V planes, upscaled from +/// `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 +/// 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( + picture: &crate::encode::Picture, + upscaled_width: usize, + margin: Option<&crate::encode::Picture>, +) -> crate::encode::Picture { + SUPERRES_HITS.with(|c| c.set(c.get() + 1)); + let height = picture.height; + let chroma_in_w = picture.width.div_ceil(2); + let chroma_out_w = upscaled_width.div_ceil(2); + let chroma_h = height.div_ceil(2); + crate::encode::Picture { + width: upscaled_width, + height, + y: upscale_plane( + &picture.y, + height, + picture.width, + upscaled_width, + margin.map(|m| (m.y.as_slice(), m.width)), + ), + u: upscale_plane( + &picture.u, + chroma_h, + chroma_in_w, + chroma_out_w, + margin.map(|m| (m.u.as_slice(), m.width.div_ceil(2))), + ), + v: upscale_plane( + &picture.v, + chroma_h, + chroma_in_w, + chroma_out_w, + margin.map(|m| (m.v.as_slice(), m.width.div_ceil(2))), + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Pinned against libaom's own compiled code, not a second + /// transcription of it: a standalone C harness linked against + /// `~/.cache/aom-oracle/build/libaom.a` calls the real (exported) + /// `av1_get_upscale_convolve_step` and `av1_convolve_horiz_rs_c` with + /// the real (exported) `av1_resize_filter_normative` table -- the only + /// piece reimplemented in C rather than called is the one-line static + /// `get_upscale_convolve_x0` formula, copied verbatim in both places. + /// This is the class `shared-oracle-blindness` guard: a bug in the + /// 64x8 table above or in the convolution/rounding kernel is caught + /// here independently of this module's own logic. + #[test] + fn upscale_row_matches_libaom_in8_out12() { + let row = [10u8, 20, 30, 40, 50, 60, 70, 80]; + let mut out = [0u8; 12]; + upscale_row(&row, &[], 12, &mut out); + assert_eq!(out, [9, 14, 22, 29, 35, 42, 48, 55, 61, 68, 76, 81]); + } + + #[test] + fn upscale_row_matches_libaom_in8_out16() { + let row = [10u8, 20, 30, 40, 50, 60, 70, 80]; + let mut out = [0u8; 16]; + upscale_row(&row, &[], 16, &mut out); + assert_eq!( + out, + [9, 12, 17, 23, 28, 32, 37, 43, 48, 53, 58, 62, 67, 73, 78, 81] + ); + } + + /// A flat row must upscale to the same flat value everywhere: every + /// filter phase's 8 taps sum to exactly 128 (`FILTER_BITS`'s unity + /// gain), so a constant input passes through unchanged regardless of + /// which phase samples it -- a cheap sanity check independent of the + /// captured-row pins above. + #[test] + fn upscale_row_of_a_flat_input_is_flat() { + let row = [200u8; 8]; + let mut out = [0u8; 12]; + upscale_row(&row, &[], 12, &mut out); + assert_eq!(out, [200u8; 12]); + } + + /// r3: the real 43->64 failing case, pinned against real libaom + /// including the right-edge margin (`scripts/superres-pin-harness.c`'s + /// `row6-realedgeval` case -- input row + real trailing decoded pixel + /// 140, not a replicate of the frame-edge pixel 141). Column 62 (0 + /// indexed) is exactly the pixel this gate mismatched by 1 before the + /// margin fix. + #[test] + fn upscale_row_with_real_margin_matches_libaom_in43_out64() { + let row: [u8; 43] = [ + 102, 102, 103, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, + 117, 118, 119, 120, 121, 122, 123, 125, 126, 127, 127, 128, 129, 130, 130, 131, 131, + 133, 134, 136, 137, 138, 139, 140, 140, 141, + ]; + let real_margin = [140u8]; + let mut out = [0u8; 64]; + upscale_row(&row, &real_margin, 64, &mut out); + assert_eq!(out[62], 141, "column 62 must match libaom, not the old replicate-padded 140"); + } +} diff --git a/lanes/superres-r2.charter.md b/lanes/superres-r2.charter.md new file mode 100644 index 00000000..c2ddd54b --- /dev/null +++ b/lanes/superres-r2.charter.md @@ -0,0 +1,86 @@ +# lane-superres r2 — finish the stage-3 gate, then inter-frame superres + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-superres`, branch +`lane-superres`, at 150bbdc (+ the pin harness commit). + +## State (r1's, verified where it says so) +Committed and green: +- `79252c8` — `use_superres` refused BY NAME in `crates/ec-av1/src/stream.rs`. + It was silent wrongness before: the header parsed fully but decode stored the + `Picture` at the downscaled `frame_width` instead of `upscaled_width`. Gate + `a_real_aomenc_stream_with_superres_refuses_by_name` proves it against a real + `--superres-mode=1` stream. +- `aec76d1` — `crates/ec-av1/src/superres.rs`: the spec 7.16 horizontal + upscaler (`upscale_row` / `upscale_plane`), coefficient table and constants + transcribed from libaom `resize.c` / `convolve.c`, pinned against the REAL + exported `av1_get_upscale_convolve_step` / `av1_convolve_horiz_rs_c` / + `av1_resize_filter_normative` through a C harness. Three unit tests green. + The harness is now committed at `scripts/superres-pin-harness.c` (it lived in + a reapable scratchpad — class `oracle-in-reaped-dir`); build it against + `~/.cache/aom-oracle/build/libaom.a` if you need to extend the pins. +- `150bbdc` — stage-3 wiring: the `use_superres` refusal narrowed to + `frame_type != Key`; key frames call `crate::superres::upscale_picture` after + `decode_key_frame_tile_with_cdfs`, before storage/output; `SUPERRES_HITS` + thread-local + `superres_hits()`; `upscale_picture` covers Y/U/V with 4:2:0 + chroma halved by `div_ceil(2)`. Compiles clean. + +r1 also corrected an error in the original charter: libaom's +`decodeframe.c` calls `superres_post_decode()` BETWEEN `av1_cdef_frame` and +`av1_loop_restoration_filter_frame` — **superres runs BEFORE loop restoration**, +not after. Recorded in `superres.rs`'s module doc. Not load-bearing while LR is +refused, but lane-lr will need it. + +## Not landed +- The stage-3 gate `a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact` + (in 150bbdc) FAILS with `unsupported: AV1 tile (a partition type this encoder + never writes)`. That is a pre-existing capability gap in the bare + `--superres-mode=1 --superres-denominator=12 --cpu-used=0` recipe, not a + superres defect — the same shape the warp gate's original recipe hit. +- r1's fix was in flight when its budget ran out and **did not apply** — the + worktree is clean. Redo it: give the gate the restrictive flag set the warp + gate uses (`--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`), around stream.rs:3860-3875. +- Stage 4 (inter frames referencing a differently-sized reference — superres + mode 2 / qthresh) is not started. It needs spec 7.11.3.3 scaled-reference + motion compensation, which is genuinely new work, not wiring. +- `lanes/superres.report.md` was never written. + +## Order of work — COMMIT AFTER EVERY GREEN STEP +1. Apply the flag-set fix; run just that gate + (`cargo test -p ec-av1 --lib a_real_aomenc_superres_key_frame_sequence -j4 -- --nocapture`, + timeout >= 600000 ms). It must decode pixel-exact AND hard-assert + `superres_hits() > 0`. +2. Full scoped suite `EC_AV1_REQUIRE_AOMENC=1 nice -n 19 cargo test -p ec-av1 --lib -j4` + (~4 min, timeout >= 600000 ms). Baseline: 232/0 on this tree; main now + carries 234/0 with two new guard tests you will inherit at merge. COMMIT + stage 3. +3. Stage 4: inter-frame superres. Scaled-reference MC, spec 7.11.3.3; libaom + `av1_setup_scale_factors_for_frame` / `av1_convolve_2d_scale`. Its own gate, + its own firing counter, its own commit. + +## Note on the coverage guard +Main now carries `crates/ec-av1/src/gate_coverage.rs`, which derives from the +gate source the aomenc tools switched off in every gate and on in none, and +pins that set. The flag list above only disables tools already in the pinned set +(cdef, intrabc, paeth-intra, palette, smooth-intra) plus tools other gates leave +on, so it will not trip the guard — but run the full suite before committing. + +## Gate rules (mandatory) +`EC_AV1_REQUIRE_AOMENC=1` on every run; `-t ` on every ffmpeg generate; +fixtures through `gradients_source(seed, w, h, tail)`; aomenc +`--threads=1 --row-mt=0`; the firing count is a HARD assert, never a warning. + +## Hard rules +- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-superres`. Foreground + builds, `nice -n 19 cargo ... -j4`, every `cargo test` given a timeout of at + least 600000 ms — a 120 s default kills the suite mid-run. +- Sibling worktrees (edith_codecs, -chroma, -realworld, -lr, -tiles) have live + agents. Never build in or edit them. +- NEVER push, never merge, never touch `main`. Commit on `lane-superres` only. +- 75-turn cap; commit at every green step; near the cap commit whatever + compiles as `wip(av1): ...`. +- Finish with `lanes/superres.report.md`, VERDICT on the first line. diff --git a/lanes/superres-r3.charter.md b/lanes/superres-r3.charter.md new file mode 100644 index 00000000..8a1aeae9 --- /dev/null +++ b/lanes/superres-r3.charter.md @@ -0,0 +1,71 @@ +# lane-superres r3 — close the 5-pixel residue by pinning the REAL scale case + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-superres`, branch +`lane-superres`, at 2022b4c. Read `lanes/superres.report.md` first — it is +short, accurate, and lists what r2 already ruled out. Do not re-derive it +(class `worker-cap-spent-reading`). + +## State +Landed and committed: refusal-by-name (79252c8), the spec 7.16 upscaler pinned +against real libaom (aec76d1), stage-3 wiring (150bbdc), and r2's two real +fixes (85c070b): the gate needed `--superres-kf-denominator=12` (libaom's +`--superres-denominator` only controls NON-key frames, and this fixture makes +every frame a key frame, so `use_superres` was silently decoding false), and +`decode.rs` cropped chroma with floor `fw / 2` where AV1 wants +`ROUND_POWER_OF_TWO(fw, 1)` — a real general decoder bug, swept across both +constructors of the cropped `Picture`. + +Still failing: `a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact`, +5 of 4096 luma pixels off by exactly 1, all at x in 59..62 of a 64-wide frame. + +## The decisive move, before any theory +r1 pinned the upscaler against libaom for **in8->out12 and in8->out16**. The +failing case is **43 -> 64**. A kernel pinned at two small symmetric ratios says +nothing about the phase/step arithmetic at the ratio that actually fails — +class `instrument-at-bound`: a search result at its own edge is not a result. + +So: extend `scripts/superres-pin-harness.c` (committed, builds against +`~/.cache/aom-oracle/build/libaom.a`) to run the EXACT failing case — input +width 43, output width 64, 8-bit, with the same row bytes our decoder holds at +the failing row — through the real exported +`av1_get_upscale_convolve_step` / `av1_convolve_horiz_rs_c` / +`av1_resize_filter_normative`, and print every output column. Compare column by +column with ours. That either localises the defect to a specific +`x_qn` / `int_pel` / `filter_idx` at x=59..62, or proves our kernel is right at +this ratio and moves the suspicion to what we feed it. + +Two specific things to check in that harness run, because they are where the +ratio matters: +- `x0_qn` initialisation (libaom `get_upscale_convolve_x0`) — the starting + phase, which the symmetric ratios r1 pinned may make degenerate. +- The right-edge source clamp. r2's theory is that we edge-replicate from the + cropped row where libaom uses a real decoded pixel. Note that libaom runs + `av1_extend_frame_borders` before `av1_superres_upscale`, which replicates + from column `y_crop_width - 1` — i.e. replication is probably RIGHT and the + theory probably wrong. Let the harness settle it rather than the reasoning: + feed it a row whose column 43+ differs from a replicate of column 42 and see + whether the reference output changes at all. + +## Then +1. Fix whatever the harness localises; the gate must decode pixel-exact and + hard-assert `superres_hits() > 0`. COMMIT. +2. Full scoped suite `EC_AV1_REQUIRE_AOMENC=1 nice -n 19 cargo test -p ec-av1 --lib -j4`, + timeout >= 600000 ms. Baseline on this tree 232/0; main is at 234 with two + new guard tests you inherit at merge. r2 never ran the suite after landing + the `decode.rs` chroma-crop fix, so this run is also that fix's first real + check. COMMIT. +3. Stage 4 — inter-frame superres, scaled-reference MC (spec 7.11.3.3, libaom + `av1_setup_scale_factors_for_frame` / `av1_convolve_2d_scale`). Its own gate, + its own firing counter, its own commit. +4. Update `lanes/superres.report.md`, VERDICT on the first line. + +## Hard rules +- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-superres`. Foreground + builds, `nice -n 19 cargo ... -j4`; every `cargo test` gets a timeout of at + least 600000 ms. +- Sibling worktrees (edith_codecs, -chroma, -realworld, -lr, -tiles, -palette) + have live agents. Never build in or edit them. +- NEVER push, never merge, never touch `main`. Commit on `lane-superres` only. +- 75-turn cap and it does NOT reset on resume: commit at every green step, and + commit the extended harness itself — it belongs in `scripts/`, not in a + scratchpad that gets reaped (class `oracle-in-reaped-dir`). diff --git a/lanes/superres-r4.charter.md b/lanes/superres-r4.charter.md new file mode 100644 index 00000000..ec9831ee --- /dev/null +++ b/lanes/superres-r4.charter.md @@ -0,0 +1,35 @@ +# lane-superres r4 + +At f167362 — r3's harness + decode work, committed verbatim by the orchestrator +at its cap and **never seen to compile or pass**. Read `lanes/superres-r3.charter.md` +(still binding) and `lanes/superres.report.md`. + +1. `cargo check`, then the target gate, then the full suite. Getting f167362 + green is the whole job until it is green. COMMIT. +2. The residue r3 was chasing: 5/4096 luma pixels off by 1 at x=59..62 of a + 64-wide frame. The decisive instrument is the extended + `scripts/superres-pin-harness.c` — run the REAL 43->64 ratio through libaom's + own exported functions and compare column by column. r1 pinned only + in8->out12 and in8->out16; a kernel pinned at two small symmetric ratios says + nothing about phase arithmetic at the ratio that fails + (class `instrument-at-bound`). +3. Then stage 4: inter-frame superres, scaled-reference MC (spec 7.11.3.3, + libaom `av1_setup_scale_factors_for_frame` / `av1_convolve_2d_scale`). + +Gate rules unchanged: `EC_AV1_REQUIRE_AOMENC=1`, `-t ` on every ffmpeg +generate, fixtures through `gradients_source`, aomenc `--threads=1 --row-mt=0`, +firing counts HARD-asserted. Two facts sibling lanes paid for: this decoder +hardcodes 64px superblocks, so any multi-superblock fixture needs +`--sb-size=64` (aomenc defaults to 128 and lands in a dead-ended partition +gap); and a per-superblock symbol cannot fire in a single-superblock fixture. + +Merge note: main is at 06d29ee with `gate_coverage.rs` and `refusal_inventory.rs`, +which pin the aomenc tools no gate exercises and every decode-path refusal +string. Report the refusal strings you add, rename or remove, verbatim. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-superres`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling +worktrees (edith_codecs, -realworld, -lr, -tiles, -palette) have live agents — +never build in or edit them. Never push, never merge, never touch `main`. +75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP. End with +`lanes/superres-r4.report.md`, VERDICT on line 1. diff --git a/lanes/superres-r4.report.md b/lanes/superres-r4.report.md new file mode 100644 index 00000000..923af95c --- /dev/null +++ b/lanes/superres-r4.report.md @@ -0,0 +1,93 @@ +VERDICT: WIP -- f167362 verified compiling and 237/238 green; target gate still 2/4096 pixels off, root cause narrowed but not closed + +## What this round did +r3's work at f167362 was committed by the orchestrator at its 75-turn cap, +never seen to compile. Job one per the charter: verify it. + +- `cargo check -p ec-av1 --lib --tests`: clean (warnings only, no errors). +- `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4`: **237 passed, 1 + failed, 17 ignored**. The only failure is the target gate, + `a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact`. r3's two + landed fixes (superres-kf-denominator flag, chroma-crop rounding, and this + round's own margin-threading commit) cost nothing elsewhere -- no + regressions against the 232/0 baseline this tree started from. +- No code changes landed this round (all diagnostic instrumentation added + during investigation was reverted with `git checkout --` before finishing; + `git status` is clean at f167362). + +## The residue, narrowed +r3 closed 3 of 5 mismatched pixels with the wide-margin threading fix +(committed in f167362). The remaining 2 (frame 2, rows 17/18, output column +62 -- the `--superres-kf-denominator=12`, 43->64 gate) were traced further +this round: + +1. Dumped pre-deblock and post-deblock pixel values at columns 40-47 for + frame 2, rows 8-23 (temporary `eprintln`, reverted). The only edge that + touches these rows is a single horizontal deblock edge at `y0=16`, + `level=5`, category `len=14` (the wide-filter class), covering columns + 40-47 in two 4-column groups. +2. Hand-computed `filter8`'s flat-branch formula (`decode.rs`'s + `filter14`/`filter8`) against the dumped pre-deblock values for every + affected column (43, 44, 45) and every affected row (13-18) -- + **matched our own post-deblock output exactly in all cases tried**. The + tap-weight arithmetic itself is self-consistent with the spec 7.14.6.3/ + 7.14.6.4 formulas; no bug found there. +3. Confirmed the margin our decoder stashes for superres (`real_right` in + `upscale_row`) is exactly this same post-deblock data -- so if the + pre-deblock reconstruction and the deblock level/mask decision are both + correct, the margin is correct too. +4. Ruled out a false lead: swapping row 17's and row 18's *margin* arrays in + the pin harness (`scripts/superres-pin-harness.c`'s `row17-margin`/ + `row18-margin` cases) happens to reproduce ffmpeg's expected value for + both rows. This looked like a smoking-gun row-index swap, but the two + margins differ by at most 1 in any position (smooth gradient content) -- + entirely consistent with the *real* defect being a single-unit error + that happens to land near a rounding boundary shared by both rows, not + an actual row transposition. Src/margin pairing was independently + confirmed correct at the Rust level (both come from the same row `r` of + the same `y.data` buffer via the same `crop` closure). +5. Ruled out: CDEF (frame flags force `cdef.*_strength == 0`, `apply_cdef` + returns immediately); intra-prediction edge availability using the wrong + width (`frame_width` is never read inside `decode_key_frame_tile_with_cdfs` + except at the crop/margin-stash tail -- prediction always sees the true + mi-aligned width). + +## What's not yet ruled out +- The deblock **level** itself (`edge_params`'s `cur_level != 0 ? cur_level + : pv_level`, `decode.rs:3980`) for this specific margin-straddling edge -- + verified the *arithmetic* given `level=5`, not whether `5` is the level + real libaom computes for this edge. This logic already passes broader + deblock gates elsewhere (both intra and inter), so a narrow, edge-case-only + divergence (e.g. a block whose transform straddles `frame_width` itself) + is the remaining live suspect. +- The pre-deblock reconstruction at columns 44-47 (the block whose right + half falls in the margin) was hand-verified for internal consistency, not + against real libaom -- there is still no ground truth for the *pre-deblock* + row content, only for the final post-superres pixel (which is 2 rounding + steps downstream: deblock, then the upscale convolution). + +## Next step (needs libaom instrumentation, not more hand tracing) +Per r3's own charter fallback: build a small aomdec `EC_TRACE`-style patch +(matching the one already used for msac/partition tracing elsewhere in this +lane family) that dumps the post-deblock, pre-superres row content at +`frame_width..true_width` for a real decode of this fixture, and diff it +column-by-column against `decode.rs`'s stashed margin. That is the only +instrument that can distinguish "our level/mask decision is wrong" from +"our level/mask decision is right and the pre-deblock reconstruction is +wrong" -- hand-tracing the arithmetic (this round) cannot, since it can only +prove self-consistency, not correctness against libaom's real output. + +## Not reached +Stage 4 (inter-frame superres, spec 7.11.3.3) -- blocked on stage 3 closing +first, per both r3's and this charter's own ordering. Untouched this round. + +## Commands +- `cargo check -p ec-av1 --lib --tests` -- clean. +- `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4` -- 237 passed, 1 + failed (the target gate), 17 ignored, 193s. +- `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib + a_real_aomenc_superres_key_frame_sequence -j4 -- --nocapture` -- FAILED, + same 2-pixel mismatch (frame 2, rows 17/18, col 62 of the upscaled output). + +## Refusal strings +None added, renamed or removed this round. diff --git a/lanes/superres-r5.charter.md b/lanes/superres-r5.charter.md new file mode 100644 index 00000000..29c684aa --- /dev/null +++ b/lanes/superres-r5.charter.md @@ -0,0 +1,50 @@ +# lane-superres r5 — build the instrument, then close the 2-pixel residue + +At 48ba479. Read `lanes/superres-r4.report.md`. + +## State +Everything but the last two pixels. The refusal-by-name, the spec 7.16 upscaler +pinned against real libaom, the stage-3 wiring, the `--superres-kf-denominator` +flag, the chroma-crop `ROUND_POWER_OF_TWO` fix and the margin threading are all +committed and verified: 237 passed, 1 failed — only +`a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact`, now **2 of 4096 +luma pixels off by 1** (frame 2, rows 17-18, output column 62), down from 5. + +r4 ruled out, by hand-verifying against the spec: the `filter8`/`filter14` tap +arithmetic, CDEF (forced off in this fixture), intra-prediction edge +availability using the wrong width, and a "row-swap" lead it debunked as a +numerical coincidence in smooth-gradient content. Its live suspect is the +deblock LEVEL decision (`edge_params`) for the edge whose transform straddles +the `frame_width` -> `true_width` margin. + +## Your job is to stop hand-tracing and build the instrument +r4's own conclusion: hand-tracing our arithmetic cannot separate "our deblock +level or mask is wrong" from "our pre-deblock reconstruction is wrong", because +both are consistent with our own output. The only thing that can is libaom's +ground truth for that row. + +`scripts/instrument-aom-oracle.sh` already carries env-gated rungs in exactly +the shape you need — `EC_TRACE=1` (partitions), `EC_TRACE_COEFF=1`, +`EC_TRACE_MODE=1`, and `EC_AV1_PREFILT_DUMP=` (per-frame PRE-filter +recon). Add a rung that dumps the **post-deblock, pre-superres** row content +over `frame_width..true_width`, following the existing rungs exactly: +env-gated, silent when unset, idempotent, wrapper-around-impl. Rebuild with +`scripts/build-aom-oracle.sh`. Then diff it against `decode.rs`'s stashed +margin at the failing row. + +Building that rung IS the deliverable of this round if it takes the whole +budget. Commit the script change as soon as it builds — it is reusable by every +lane, and instrument-building is a first-class subtask here, never an excuse. + +Then: fix what it localises, get the gate green, and only after that start +stage 4 (inter-frame superres, spec 7.11.3.3 scaled-reference MC). + +Merge note: main is at 53b319b with `gate_coverage.rs` and +`refusal_inventory.rs`. Report every refusal string you add or remove, verbatim. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-superres`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling +worktrees (edith_codecs, -realworld, -lr, -tiles, -palette) have live agents — +never build in or edit them. Never push, never merge, never touch `main`. +75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP. End with +`lanes/superres-r5.report.md`, VERDICT on line 1. diff --git a/lanes/superres-r6.charter.md b/lanes/superres-r6.charter.md new file mode 100644 index 00000000..0e756f30 --- /dev/null +++ b/lanes/superres-r6.charter.md @@ -0,0 +1,32 @@ +# lane-superres r6 — use the rungs you built + +At a69e1bd. Read `lanes/superres-r5.report.md` if r5 wrote one, else its +commits: `f46e6fb` (EC_AV1_POSTDEBLOCK_DUMP) and `5e511b5` +(EC_AV1_PREFILT_WIDE_DUMP) — r5's deliverable, two oracle rungs, landed. HEAD +also carries r5's uncommitted `decode.rs` work, committed verbatim by the +orchestrator at its cap and **never seen to compile**. + +1. `cargo check`, fix whatever r5 left mid-edit, then the full suite. COMMIT the + moment it is green. +2. Use the rungs. The gate is 2 of 4096 luma pixels off by 1 (frame 2, rows + 17-18, output column 62). r4 exhausted hand-tracing: our arithmetic is + self-consistent with our own output, so only libaom's ground truth for that + row can separate "our deblock level/mask is wrong" from "our pre-deblock + reconstruction is wrong". Dump both, diff at the failing row, fix what it + localises. COMMIT. +3. Then stage 4: inter-frame superres — scaled-reference MC, spec 7.11.3.3, + libaom `av1_setup_scale_factors_for_frame` / `av1_convolve_2d_scale`. + +Merge note: main is at 53f5358 and has moved a long way (multi-tile key frames, +chroma smooth/paeth, CDEF index reads). If your merge back looks large, say so +in the report and consider `git merge main` here first, resolving it yourself — +you know which side owns each hunk. Main also carries `gate_coverage.rs`, +`refusal_inventory.rs` and `GATES_THAT_SKIP_ON_A_DECODE_ERROR`: report every +refusal string you add, rename or remove, verbatim, and do not write a gate that +turns a decode error into a printed SKIP. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-superres`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling +worktrees have live agents — never build in or edit them. Never push, never +merge into `main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP. +End with `lanes/superres-r6.report.md`, VERDICT on line 1. diff --git a/lanes/superres-r6.report.md b/lanes/superres-r6.report.md new file mode 100644 index 00000000..32905dfe --- /dev/null +++ b/lanes/superres-r6.report.md @@ -0,0 +1,87 @@ +VERDICT: PARTIAL -- r5's decode.rs work verified green, gate residue localized to a specific +deblock edge, root cause not yet found (defer to r7). + +## Step 1: verify r5's uncommitted work + +`cargo check` clean, `cargo test -p ec-av1` (EC_AV1_REQUIRE_AOMENC=1, 600s timeout): 237 passed, +1 failed (the known `a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact`, the gate +this lane exists to close), 17 ignored. Nothing else regressed. No fix was needed -- working +tree was clean at a69e1bd/3462632, so no commit was made for step 1 itself. + +## Step 2: use the rungs + +Reproduced the gate's exact failing stream (added `EC_SUPERRES_STREAM_DUMP` to the test, one +run, one seed -- avoids the seeded-fixture-not-reproducible dead-end since it's now a captured +file, not a re-rendered lavfi seed) and ran both oracle rungs plus our own matching decode.rs +dumps (`EC_AV1_PREFILT_WIDE_DUMP` exists on both sides already; `EC_AV1_MARGIN_DUMP` is our own +post-deblock+cdef dump, CDEF is off in this stream so it's a valid post-deblock comparison +point) against frame 2 (the failing frame): + +- **Pre-deblock (`ours-prefilt.f2` vs `lib-prefilt.f2`): 0 diffs, byte-exact.** Reconstruction + (predict+residual, all of coefficient decode) is proven correct for this frame including the + whole margin region -- rules out mode/tx/coefficient decode as the cause. +- **Post-deblock (`ours-margin.f2` Y vs `lib-postdeblock.f2` Y): 37 diffs, ALL in columns 44-47** + (the coded frame's rightmost mi column, mi_c=11 of mi_cols=12, true_width=48) across rows + 9-38ish. Nowhere else in the frame differs. + +This localizes the bug to `deblock_plane`'s horizontal-edge pass at the rightmost mi column. +Traced the specific edges firing there (`EC_AV1_DEBLOCK_TRACE=1`): three horizontal edges per +frame at x0=44, y0∈{16,32,48}, `len=14 level=5 sharpness=0`. Hand-reimplemented `filter14`'s +flat-branch formula in Python against the bit-exact pre-deblock input at columns 44-47: it +**exactly reproduces our own Rust decoder's output** (op2..oq2 match `ours-margin.f2` to the +byte) -- our filter math is spec-correct and self-consistent. But **libaom's real post-deblock +output at these exact samples equals the unfiltered pre-deblock input** -- libaom did not filter +this edge at all, at 3 of the 4 columns in the group (col 44 happened to be a no-op already). + +## What's not yet found + +Read `av1_loopfilter.c`'s two candidate skip conditions (`curr_skipped = skip_txfm && +is_inter_block`) -- both are INTER-only gates; this is a key frame (`--kf-max-dist=0`), so intra +blocks never hit that suppression, and by the source's own logic this edge (nonzero level on an +intra PU boundary, `pu_edge = mi_prev != mbmi` true) should still filter. To get ground truth +instead of re-deriving the C by eye, patched two candidate real call sites +(`set_lpf_parameters` and `set_one_param_for_line_luma`, in +`~/.cache/aom-oracle/src/av1/common/av1_loopfilter.c`, rebuilt via `ninja -C +~/.cache/aom-oracle/build aomdec`) with `EC_LF_TRACE`/`EC_LF_TRACE2` eprintln diagnostics gated +on `mi_col==11` and `!is_vert` -- **neither ever fired** for this stream, meaning the real +horizontal-edge loop-filter path for this exact column takes a THIRD, unlocated code path in +libaom (a SIMD/quad-batch variant most likely, or a per-line-luma variant reached from a +different fast path than the two I found via `grep set_lpf_parameters`). That third path is +where the actual "why libaom doesn't filter here" answer lives -- I ran out of turn budget +finding it. The libaom source patches are throwaway (in `~/.cache/aom-oracle/src`, not part of +this repo, not committed) and can be re-applied/removed freely by r7; `scripts/build-aom-oracle.sh` ++ `scripts/instrument-aom-oracle.sh` rebuild from clean if you want a pristine tree first. + +## Left in the repo (committed, `8ef70ff`) + +- `EC_SUPERRES_STREAM_DUMP` (stream.rs, the superres key-frame gate test): dumps the exact OBU + bytes fed to aomenc/decode_stream to a file when set -- makes the gate's stream reproducible + for oracle diffing without relying on lavfi seed determinism. +- `EC_AV1_DEBLOCK_TRACE` (decode.rs, `deblock_plane`'s horizontal-edge loop): eprintln's + `x0/y0/len/level/sharpness` when `x0==44` and `plane_idx==0` -- narrow and hardcoded to this + investigation; r7 should widen or remove it once the real cause is found. + +Both are env-gated, off by default, zero behavior change to any existing test. + +## Step 3: inter-frame superres (spec 7.11.3.3) + +Not started -- all turn budget went to step 2's localization. Deferred to r7/next lane. + +## Refusal strings + +None added, renamed, or removed this round. + +## Merge + +Not attempted -- no time budget left to verify a `git merge main` cleanly after the above; left +for r7 to decide, per charter's "consider `git merge main` here first" being conditional on +budget. + +## Disposition + +- deferred: the actual libaom code path for the last-column horizontal edge -- unblocks with + either `perf`/`gdb break set_lpf_parameters_for_line_luma` on the real aomdec binary while it + decodes this exact stream (fastest: confirms which function body genuinely executes), or + grep `av1_filter_block_plane_horz`/AVX2 variants under `av1/common/x86/av1_loopfilter_sse2.c` + for a scalar-bypassing fast path. +- deferred: stage 4 (inter-frame superres, scaled-reference MC) -- unstarted, whole stage. diff --git a/lanes/superres-r7.charter.md b/lanes/superres-r7.charter.md new file mode 100644 index 00000000..329fe4e9 --- /dev/null +++ b/lanes/superres-r7.charter.md @@ -0,0 +1,65 @@ +# lane-superres r7 — is that edge filtered at all? + +Read `lanes/superres-r6.report.md`. r5's decode work is verified green (237 +passed, the target gate the only failure). + +## Where the search stands +r6 localized the 2-pixel residue precisely: horizontal-edge deblocking at the +CODED frame's rightmost mi column, x0 = 44..47. It re-derived `filter14` / +`filter8` in Python against the bit-exact pre-deblock dump and reproduced our +Rust output exactly — **our filter arithmetic is spec-correct**, so the bug is +in edge/level SELECTION, not in the filter. It then instrumented two libaom +candidates (`set_lpf_parameters`, `set_one_param_for_line_luma` / +`set_lpf_parameters_for_line_luma`) and confirmed neither fires, and ran out of +budget hunting a third dispatch path. + +## Before hunting libaom's dispatch further, test this hypothesis +The coded frame width here is 43; the mi grid is 48 wide. **x = 44..47 is the +mi-alignment margin, beyond `frame_width`.** Two things follow, and either would +produce exactly this shape: +1. We may be deblocking an edge libaom never filters, because it clips the loop + to the coded width. "Neither candidate fires" is consistent with libaom + simply not filtering there — an absent call is evidence, not a dead end + (class `equal-range-means-unread`, applied to pixels). +2. We may be FEEDING the upscaler decoded margin pixels where libaom feeds + replicated ones: `av1_superres_upscale` calls `av1_extend_frame_borders` + first, which replicates from column `y_crop_width - 1`. r3's margin threading + moved the count 5 -> 2, which looks like progress but is equally consistent + with trading one wrong source for another. + +Both are cheap to test and neither needs libaom's dispatch: clip our deblock to +the coded width and see; then feed the upscaler a replicate of column 42 instead +of decoded margin and see. Run them as experiments, not as a rewrite — one at a +time, reverting between, and report both results even if neither closes it. + +If both fail, then go after the dispatch path with gdb as r6 planned, using its +reproduction: `EC_SUPERRES_STREAM_DUMP=.obu cargo test -p ec-av1 --lib +stream::tests::a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact -- +--nocapture`, then that `.obu` through `~/.cache/aom-oracle/build/aomdec` with +`EC_AV1_PREFILT_WIDE_DUMP` / `EC_AV1_POSTDEBLOCK_DUMP`, diffing frame 2 columns +44-47. + +## Housekeeping this round owes +r6 left throwaway `EC_LF_TRACE` diagnostics in +`~/.cache/aom-oracle/src/av1/common/av1_loopfilter.c` — outside this repo and +uncommitted. Either fold them into `scripts/instrument-aom-oracle.sh` as a +proper env-gated rung (the shape every other rung uses, and then they survive an +oracle rebuild) or revert them. Do not leave edits sitting in the oracle's source +tree where the next lane will not know they are there. + +## Then +Stage 4: inter-frame superres — scaled-reference MC, spec 7.11.3.3, libaom +`av1_setup_scale_factors_for_frame` / `av1_convolve_2d_scale`. + +Merge note: main is at 92d8beb and has moved a long way (multi-tile decode +gated, CDEF index, chroma modes, a `bit_depth != 8` refusal, three reworded +partition refusals, and three guard tests that pin the never-exercised aomenc +tools, every decode-path refusal string, and the gates that swallow a decode +error). Consider `git merge main` here and resolving it yourself. Report every +refusal string you add, rename or remove, verbatim. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-superres`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling +worktrees have live agents — never build in or edit them. Never push, never +merge into `main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP. +End with `lanes/superres-r7.report.md`, VERDICT on line 1. diff --git a/lanes/superres-r7.report.md b/lanes/superres-r7.report.md new file mode 100644 index 00000000..e4c594b6 --- /dev/null +++ b/lanes/superres-r7.report.md @@ -0,0 +1,89 @@ +VERDICT: CLOSED -- the superres gate is pixel-exact; charter hypothesis 1 was the root cause. + +## What was tested + +Charter hypothesis 1: "libaom clips the deblock loop to the coded frame's width, our +`true_width`/`true_height` (mi-aligned, `mi_cols*4`/`mi_rows*4`) includes a padding +margin libaom never filters." Confirmed on the first try -- did not need hypothesis 2 +(margin vs replicated-border upscaler feed) or the gdb dispatch hunt. + +## Fix + +`crates/ec-av1/src/decode.rs`: `deblock_plane` (and its caller `apply_deblock`) now take +`frame_width`/`frame_height` and bound their `x0`/`y0` loops by +`plane.true_width.min(cw)` / `plane.true_height.min(ch)` where `cw`/`ch` are the coded +frame's own dimensions (`frame_height.div_ceil(2)` for chroma, matching the 4:2:0 +subsampling this decoder assumes), instead of always looping the full mi-aligned +`true_width`/`true_height`. Both call sites (`decode_key_frame_tile_with_cdfs`, +`decode_inter_frame_tile_with_cdfs`) updated to pass `frame_width as usize, frame_height +as usize`. + +## Ground truth, not just gate-green + +Read libaom's `set_lpf_parameters` (`av1/common/av1_loopfilter.c:224`) while removing the +throwaway trace lines there (see Housekeeping below) and found the actual normative +check directly: + +```c +const uint32_t width = plane_ptr->dst.width; +const uint32_t height = plane_ptr->dst.height; +if ((width <= x) || (height <= y)) { + // just return the smallest transform unit size + return TX_4X4; +} +``` + +`plane_ptr->dst.width`/`height` is the destination plane's coded width/height (the same +quantity our `frame_width`/`frame_height` already carries), not the mi-grid-padded +extent. This is the third dispatch path r6 was hunting for with `EC_LF_TRACE`/ +`EC_LF_TRACE2` at `set_lpf_parameters`/`set_one_param_for_line_luma` -- both traces r6 +added never fired because they were placed *after* this early return already skipped +the block; the trace at line 298 (inside `set_lpf_parameters`, guarded on +`edge_dir==HORZ_EDGE && x==44`) sat downstream of this `if`, so it correctly never +printed for x=44 once x exceeded `plane_ptr->dst.width` -- r6's "neither candidate +fires" was itself the evidence for hypothesis 1, not a dead end (class +`equal-range-means-unread`, per the charter). + +## Verification + +- `cargo check -p ec-av1`: clean. +- `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib stream::tests::a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact -- --nocapture`: + `3 frames pixel-exact, superres_hits=3` -- **PASS** (was the lane's one failing gate + since r5). +- `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1` (full crate, 600s timeout): **238 + passed, 0 failed, 17 ignored** -- no regression from the clip (the mi-alignment + margin only ever held decode scratch space beyond the coded picture; nothing else + reads or filters it). + +Commit: `f64f5cd` on `lane-superres` (this worktree). + +## Housekeeping + +r6's throwaway `EC_LF_TRACE`/`EC_LF_TRACE2` `fprintf` diagnostics in +`~/.cache/aom-oracle/src/av1/common/av1_loopfilter.c` (lines 298-301, 714-717) removed -- +their placement (downstream of the early-return this round found) is itself part of the +evidence above, so they are recorded in this report rather than folded into +`scripts/instrument-aom-oracle.sh` as a permanent rung; the oracle source tree is back to +a pristine, uncommitted state. Not rebuilt (`ninja`) this round since nothing further +needed the oracle binary -- `scripts/build-aom-oracle.sh` will produce a clean build from +this source on next use, no stale trace code left behind. + +## Refusal strings + +None added, renamed, or removed this round. + +## Merge + +Not attempted -- turn budget went to landing and verifying the fix + housekeeping. Left +for the next lane; charter's "consider `git merge main` here" is conditional on budget +and main has moved substantially (per r6's merge note) since `92d8beb`. + +## Disposition + +- deferred: `git merge main` (charter's note: multi-tile decode, CDEF index, chroma + modes, `bit_depth != 8` refusal, three reworded partition refusals, three guard tests + landed there since 92d8beb) -- next lane in this worktree, or whoever picks this branch + up, should merge and re-run the full `ec-av1` suite before anything further. +- deferred: Stage 4, inter-frame superres (spec 7.11.3.3, scaled-reference MC, + `av1_setup_scale_factors_for_frame` / `av1_convolve_2d_scale`) -- unstarted, whole + stage, per charter's "Then" section. diff --git a/lanes/superres.charter.md b/lanes/superres.charter.md new file mode 100644 index 00000000..34244a7f --- /dev/null +++ b/lanes/superres.charter.md @@ -0,0 +1,91 @@ +# lane-superres — superres decode (frame_size_with_refs / horizontal upscale) + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-superres`, branch +`lane-superres`, off main 87a1e34. + +## Goal +Make the decoder handle a stream aomenc produced with `--superres-mode=` +(fixed and/or qthresh) end to end, pixel-exact vs libaom: +1. header side: `use_superres` / `superres_denom` are read into the frame + header (check whether `crates/ec-av1-syntax` already parses them — see + `crates/ec-av1-syntax/src/frame.rs:518` — and whether the DECODE path in + `crates/ec-av1/src/stream.rs` refuses or silently ignores them); +2. decode side: the frame is coded at `frame_width` (the DOWNSCALED width), + every block/MV/loop-filter/CDEF operation happens at that width, and only + after loop restoration is the frame upscaled horizontally to + `upscaled_width` by the spec's linear-filter upscaler; +3. reference frames are stored UPSCALED, and `frame_size_with_refs` / + MV scaling for inter prediction across a size change must be right. + +## Anchors +- Spec: 5.9.8 `superres_params`, 7.16 `upscaling process`, 5.9.7 + `frame_size_with_refs`, 7.11.3.3 (motion vector scaling / scaled reference). +- libaom (source tree under `~/.cache/aom-oracle`): + `av1/common/resize.c` — `av1_upscale_normative_rows`, + `av1_upscale_normative_and_extend_frame`, `upscale_normative_rect`, + and the `av1_resize_filter_normative` coefficient table (the 8-tap + `SUPERRES_FILTER` table with `RS_SUBPEL_BITS`/`RS_SCALE_SUBPEL_BITS`); + `av1/decoder/decodeframe.c` `setup_superres` / `superres_post_decode`. +- Note the ORDER: superres upscaling happens AFTER deblock+CDEF and + AFTER loop restoration in libaom's pipeline + (`av1_loop_restoration_filter_frame` runs on the downscaled frame using the + saved pre-upscale buffer). Get this order from the source, not from memory. +- Writer side already exists and refuses: `crates/ec-av1/src/frame.rs:309-316` + writes `use_superres` and refuses a denom other than 8. Leave the writer's + refusal in place unless you also implement the encoder-side downscale — that + is OUT of scope for this lane; this lane is DECODE. +- `crates/ec-av1/src/stream.rs` holds every decode refusal and every gate. + `grep -n unsupported crates/ec-av1/src/stream.rs` to see the shape. + +## Step 0 — measure before building +Encode a real fixture with `--superres-mode=1 --superres-denominator=` +(check `aomenc --help | grep -i superres` for the actual flag spelling in +v3.13.3) and run it through our decoder as it stands today. Report in the +report file: does it refuse (with what exact string), desync, or decode wrong? +That answer decides whether stage 1 is a refusal removal or a bug fix. If the +header path already silently ignores superres and produces wrong pixels, that +is a SILENT WRONGNESS defect and must first become an explicit refusal, in its +own commit, before the implementation lands. + +## Staging — commit after EVERY green milestone +1. Header + explicit refusal by accurate name. COMMIT. +2. Upscaler implemented and unit-pinned: a `#[test]` that feeds a known row to + our upscaler and compares against values captured from libaom's + `av1_upscale_normative_rows` (add an instrumentation rung to + `scripts/instrument-aom-oracle.sh` if you need to capture them — follow the + existing rungs' shape exactly: env-gated, silent when unset, idempotent, + wrapper-around-impl — then rebuild with `scripts/build-aom-oracle.sh`). + COMMIT. +3. Full-frame gate: decode an aomenc superres stream pixel-exact vs + `aomdec --rawvideo`. COMMIT. +4. Inter frames referencing a differently-sized reference (superres-mode=2 + /qthresh, so denom varies frame to frame). COMMIT. + +## Gate (mandatory) +- Follow the existing gate shape in `crates/ec-av1/src/stream.rs`. + `EC_AV1_REQUIRE_AOMENC=1` must be set when you run tests: a missing oracle + must FAIL, never SKIP. +- Bound every ffmpeg `generate` with `-t `. +- Build the fixture through the existing `gradients_source(seed, w, h, tail)` + helper — ffmpeg's `gradients` source ignores its seed, so a hand-written + `gradients=size=` string makes the gate non-reproducible. +- aomenc: `--threads=1 --row-mt=0`. +- Hard-assert a firing count via a thread-local `Cell` counter like the + existing `*_HITS` in decode.rs (they are thread-local now, NOT atomics). + A gate that cannot prove superres actually fired is vacuous + (CLASS `gate-blind-to-feature`). +- Refusals inside the gate are FORBIDDEN once the stage removing them lands. + +## Hard rules +- Own build dir: `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-superres`. + Foreground builds only, `nice -n 19 cargo ... -j4`. Never build in another + worktree, never touch a sibling worktree's files. +- Suite: `nice -n 19 cargo test -p ec-av1 --lib` (baseline 232 passed / 0 + failed, ~67 s). Must stay green. +- NEVER push, never merge, never touch `main`. Commit on `lane-superres` only. +- 75-turn cap: **commit after every green milestone**; near the cap commit + whatever compiles as `wip(av1): ...` and write `lanes/superres.report.md`. +- Refuse-by-name rather than desync. Never claim in a refusal string that the + encoder cannot emit a case unless you proved it. +- Write `lanes/superres.report.md`: what landed, gate name + firing count, + remaining refusal strings verbatim, next lever. diff --git a/lanes/superres.report.md b/lanes/superres.report.md new file mode 100644 index 00000000..e79cff62 --- /dev/null +++ b/lanes/superres.report.md @@ -0,0 +1,78 @@ +VERDICT: WIP -- stage-3 gate closer but not green; two real fixes landed, one residual defect open + +## What changed (commit 85c070b, branch lane-superres) +- `crates/ec-av1/src/stream.rs`: gate + `a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact` got the + charter's restrictive aomenc flag set, which cleared the pre-existing + "AV1 tile: partition type this encoder never writes" capability gap + (confirmed pre-existing, not a superres defect, per charter). +- Same gate: added `--superres-kf-denominator=12`. Root cause found by + tracing libaom `av1/encoder/superres_scale.c` `calculate_next_superres_scale`: + under `AOM_SUPERRES_FIXED`, key frames read + `superres_cfg->superres_kf_scale_denominator`, non-key frames read + `superres_scale_denominator` -- two separate CLI flags + (`--superres-denominator` only sets the latter). This gate's fixture uses + `--kf-max-dist=0` (every frame a key frame per its own doc comment), so + without the kf flag `superres_kf_scale_denominator` stayed at its default + 8 (no scale) and `header.use_superres` decoded `false` -- confirmed with a + temporary debug print, then reverted. +- `crates/ec-av1/src/decode.rs`: real decoder bug, both + `decode_key_frame_tile_with_cdfs` (line ~4993) and + `decode_inter_frame_tile_with_cdfs` (line ~10504) cropped chroma planes + to `fw / 2, fh / 2` (floor) when `frame_width` differs from the + mi-aligned decode buffer width. AV1's 4:2:0 chroma-plane width is + `ROUND_POWER_OF_TWO(fw, 1)` (div_ceil), not floor -- confirmed against + libaom `resize.c:1124`. Odd downscaled widths (43, from this superres + fixture) exposed it as a `debug_assert_eq!` panic in `superres.rs:135` + (`upscale_plane` got a 21-wide chroma row, expected 22). Fixed both call + sites -- grepped, these are the only two constructors of the cropped + `Picture`, class swept. + +## What's still broken +Gate still fails: 5 of 4096 luma pixels off by exactly 1, all near the +right edge (x in 59..62 of a 64-wide frame). Ruled out: +- The upscale kernel itself (`upscale_row`/`upscale_plane` in + `superres.rs`) is pinned bit-exact against real libaom + `av1_convolve_horiz_rs_c` via the C harness for symmetric scale cases + (in8->out12, in8->out16) -- r1's work, unchanged this round. +- Not a bounds bug: traced the padding math (`pad=10`, `base=6`, + `UPSCALE_NORMATIVE_TAPS=8`) by hand, all array indices stay in range. + +Leading theory, NOT confirmed: `decode.rs` crops the plane to exactly +`frame_width` (43) before `superres::upscale_picture` ever sees it, so +`upscale_row`'s right-edge padding is a synthetic replicate of column 42. +libaom runs `av1_superres_upscale` on the reconstructed buffer's own +border-extended margin, which may still hold a real decoded pixel at +mi-alignment column 43 rather than a replicate -- untested this round +(would need threading the pre-crop plane + real width into +`upscale_picture` instead of cropping to `fw` first). Diff pattern (only +5 isolated pixels, not a monotonic edge band) is also consistent with a +subtler rounding-phase edge case; not conclusively attributed either way. + +## Order of work not reached +- Full scoped suite (`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib + -j4`) not run this round -- the target gate itself was still red, ran + `cargo check -p ec-av1 --lib --tests` only (clean) to confirm no + compile breakage from the two fixes before committing. +- Stage 4 (inter-frame superres, spec 7.11.3.3) not started -- blocked on + stage 3 closing first per the charter's own ordering. + +## Commands +- `cargo check -p ec-av1 --lib --tests` -- clean, 85 pre-existing doc + warnings only. +- `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib + a_real_aomenc_superres_key_frame_sequence -j4 -- --nocapture` -- + FAILED: `frame 0 luma vs ffmpeg`, 5/4096 pixels off by 1 (measured via + temporary debug instrumentation, reverted before commit). + +## Handoff for next round +1. Try threading real pre-crop border pixels into `upscale_picture` + instead of edge-replicating from the already-cropped row -- needs a + small API change (`upscale_picture` takes the plane's real allocated + width + a slice wide enough to cover `UPSCALE_NORMATIVE_TAPS/2+1` + extra real columns) plus a `decode.rs` change to stop discarding that + margin before calling it. +2. If that doesn't close it, dump per-pixel `x_qn`/`int_pel`/`filter_idx` + at the 5 failing output columns and hand-trace against a libaom debug + build of the same fixture -- the diffs are too sparse for a formula + bug, more likely a specific phase/rounding edge case. diff --git a/scripts/instrument-aom-oracle.sh b/scripts/instrument-aom-oracle.sh index 06c89a3e..01771756 100755 --- a/scripts/instrument-aom-oracle.sh +++ b/scripts/instrument-aom-oracle.sh @@ -27,6 +27,17 @@ # the key-frame path has no traced symbol at all between the partition # read and the first coefficient block, which is precisely the gap a # rect-strip desync hides in. +# EC_AV1_POSTDEBLOCK_DUMP= -> .f per frame, Y then U then +# V, full ALIGNED-buffer rows (y_width/y_height, not y_crop_width -- +# cm->cur_frame->buf at this point is still the pre-superres buffer, +# but its aligned width already extends past FrameWidth out to the +# mi-aligned true width, which is exactly the margin content we need). +# Written right after av1_loop_filter_frame_mt returns and before +# CDEF/superres run -- ground truth for the post-deblock, pre-superres +# row content over frame_width..true_width that decode.rs stashes as +# its superres margin (lane-superres r5: hand-tracing the arithmetic +# could only prove our own self-consistency, not correctness against +# libaom). # # Idempotent: re-running is a no-op. Rebuild afterwards with # ninja -C ~/.cache/aom-oracle/build aomdec @@ -263,3 +274,106 @@ s = s.replace(old, new, 1) open(path, "w").write(s) print("intra mode-info instrumented") PYI + +# --- rung 6: post-deblock, pre-superres row dump ------------------------ +python3 - "$F" <<'PYD' +import sys +path = sys.argv[1] +s = open(path).read() +if "EC_INSTRUMENTED_POSTDEBLOCK" in s: + print("postdeblock dump already instrumented (no-op)") + sys.exit(0) + +anchor = """ if (cm->lf.filter_level[0] || cm->lf.filter_level[1]) { + av1_loop_filter_frame_mt(&cm->cur_frame->buf, cm, &pbi->dcb.xd, 0, + num_planes, 0, pbi->tile_workers, + pbi->num_workers, &pbi->lf_row_sync, 0); + } +""" +dump = """ + /* EC_INSTRUMENTED_POSTDEBLOCK */ + { + const char *ec_dump = getenv("EC_AV1_POSTDEBLOCK_DUMP"); + if (ec_dump) { + static int ec_postdeblock_idx = 0; + char ec_path[1024]; + snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump, + ec_postdeblock_idx++); + FILE *ec_f = fopen(ec_path, "wb"); + if (ec_f) { + const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf; + /* Dump the FULL aligned buffer (y_width/y_height), not the + * crop_width/crop_height (== FrameWidth/FrameHeight): the + * superres margin (columns [FrameWidth, true mi-aligned width)) + * only exists in the aligned buffer -- lane-superres r5. */ + for (int ec_r = 0; ec_r < ec_b->y_height; ++ec_r) + fwrite(ec_b->y_buffer + ec_r * ec_b->y_stride, 1, ec_b->y_width, + ec_f); + if (num_planes > 1) { + for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r) + fwrite(ec_b->u_buffer + ec_r * ec_b->uv_stride, 1, + ec_b->uv_width, ec_f); + for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r) + fwrite(ec_b->v_buffer + ec_r * ec_b->uv_stride, 1, + ec_b->uv_width, ec_f); + } + fclose(ec_f); + } + } + } +""" +assert anchor in s, "loop filter call anchor moved" +s = s.replace(anchor, anchor + dump, 1) +open(path, "w").write(s) +print("postdeblock dump instrumented") +PYD + +# --- rung 7: pre-deblock, FULL aligned-buffer row dump (lane-superres r5) - +# EC_AV1_PREFILT_DUMP (rung 1) is used by other lanes at its existing +# y_crop_width/y_crop_height shape -- left untouched. This adds a second, +# additive env var at the SAME anchor (pre-loop-filter) but dumping the full +# y_width/y_height aligned buffer, so a margin-region reconstruction bug can +# be told apart from a margin-region deblock bug. +python3 - "$F" <<'PYW' +import sys +path = sys.argv[1] +s = open(path).read() +if "EC_INSTRUMENTED_PREFILT_WIDE" in s: + print("prefilt-wide dump already instrumented (no-op)") + sys.exit(0) + +anchor = """ av1_alloc_cdef_buffers(cm, &pbi->cdef_worker, &pbi->cdef_sync, + pbi->num_workers, 1);""" +dump = """ /* EC_INSTRUMENTED_PREFILT_WIDE */ + { + const char *ec_dump = getenv("EC_AV1_PREFILT_WIDE_DUMP"); + if (ec_dump) { + static int ec_prefilt_wide_idx = 0; + char ec_path[1024]; + snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump, + ec_prefilt_wide_idx++); + FILE *ec_f = fopen(ec_path, "wb"); + if (ec_f) { + const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf; + for (int ec_r = 0; ec_r < ec_b->y_height; ++ec_r) + fwrite(ec_b->y_buffer + ec_r * ec_b->y_stride, 1, ec_b->y_width, + ec_f); + if (num_planes > 1) { + for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r) + fwrite(ec_b->u_buffer + ec_r * ec_b->uv_stride, 1, + ec_b->uv_width, ec_f); + for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r) + fwrite(ec_b->v_buffer + ec_r * ec_b->uv_stride, 1, + ec_b->uv_width, ec_f); + } + fclose(ec_f); + } + } + } + +""" +assert anchor in s, "cdef alloc anchor moved" +s = s.replace(anchor, dump + anchor, 1) +open(path, "w").write(s) +print("prefilt-wide dump instrumented") +PYW diff --git a/scripts/superres-pin-harness.c b/scripts/superres-pin-harness.c new file mode 100644 index 00000000..e8a57cc8 --- /dev/null +++ b/scripts/superres-pin-harness.c @@ -0,0 +1,144 @@ +#include +#include +#include + +#define RS_SUBPEL_BITS 6 +#define RS_SCALE_SUBPEL_BITS 14 +#define RS_SCALE_SUBPEL_MASK ((1 << RS_SCALE_SUBPEL_BITS) - 1) +#define RS_SCALE_EXTRA_BITS (RS_SCALE_SUBPEL_BITS - RS_SUBPEL_BITS) +#define RS_SCALE_EXTRA_OFF (1 << (RS_SCALE_EXTRA_BITS - 1)) +#define UPSCALE_NORMATIVE_TAPS 8 + +extern const int16_t av1_resize_filter_normative[1 << RS_SUBPEL_BITS][UPSCALE_NORMATIVE_TAPS]; +extern int32_t av1_get_upscale_convolve_step(int in_length, int out_length); +extern void av1_convolve_horiz_rs_c(const uint8_t *src, int src_stride, + uint8_t *dst, int dst_stride, int w, + int h, const int16_t *x_filters, + int x0_qn, int x_step_qn); + +// verbatim copy of resize.c's static get_upscale_convolve_x0 -- the one +// formula in the pipeline this harness does not exercise via a real +// exported symbol; everything else (the coefficient table + the +// convolution/rounding kernel, the actual bug risk) runs real compiled +// libaom code. +static int32_t get_upscale_convolve_x0(int in_length, int out_length, + int32_t x_step_qn) { + const int err = out_length * x_step_qn - (in_length << RS_SCALE_SUBPEL_BITS); + const int32_t x0 = + (-((out_length - in_length) << (RS_SCALE_SUBPEL_BITS - 1)) + + out_length / 2) / + out_length + + RS_SCALE_EXTRA_OFF - err / 2; + return (int32_t)((uint32_t)x0 & RS_SCALE_SUBPEL_MASK); +} + +static void run_case_margin(const char *label, int in_len, int out_len, + const uint8_t *input, const uint8_t *margin, + int margin_len) { + uint8_t padded[512]; + const int pad = 32; + uint8_t *row = padded + pad; + memset(padded, input[0], pad); + memcpy(row, input, in_len); + memcpy(row + in_len, margin, margin_len); + memset(row + in_len + margin_len, margin[margin_len - 1], pad); + + int32_t x_step_qn = av1_get_upscale_convolve_step(in_len, out_len); + int32_t x0_qn = get_upscale_convolve_x0(in_len, out_len, x_step_qn); + printf("%s: x_step_qn=%d x0_qn=%d\n", label, x_step_qn, x0_qn); + uint8_t out[256]; + av1_convolve_horiz_rs_c(row - 1, 0, out, 0, out_len, 1, + &av1_resize_filter_normative[0][0], x0_qn, + x_step_qn); + printf("%s out:", label); + for (int i = 0; i < out_len; i++) printf(" %d", out[i]); + printf("\n"); +} + +// Runs one row through the real compiled libaom convolver, edge-replicated +// padding on both sides (the single-tile case, matching this decoder's +// `superres::upscale_row`). `right_pad_col` lets the caller feed a +// right-edge pad value that differs from `input[in_len-1]`, to test +// r3's charter question (does the padding value change the output at +// all near the right edge, i.e. does the failing case even depend on +// what's beyond column `in_len-1`). +static void run_case(const char *label, int in_len, int out_len, + const uint8_t *input, int right_pad_val) { + uint8_t padded[512]; + const int pad = 32; + uint8_t *row = padded + pad; + memset(padded, input[0], pad); + memcpy(row, input, in_len); + memset(row + in_len, right_pad_val, pad); + + int32_t x_step_qn = av1_get_upscale_convolve_step(in_len, out_len); + int32_t x0_qn = get_upscale_convolve_x0(in_len, out_len, x_step_qn); + printf("%s: in_len=%d out_len=%d x_step_qn=%d x0_qn=%d right_pad=%d\n", + label, in_len, out_len, x_step_qn, x0_qn, right_pad_val); + + uint8_t out[256]; + av1_convolve_horiz_rs_c(row - 1, 0, out, 0, out_len, 1, + &av1_resize_filter_normative[0][0], x0_qn, + x_step_qn); + printf("%s out:", label); + for (int i = 0; i < out_len; i++) printf(" %d", out[i]); + printf("\n"); +} + +int main(void) { + uint8_t input8[8] = { 10, 20, 30, 40, 50, 60, 70, 80 }; + run_case("in8->out12", 8, 12, input8, input8[7]); + run_case("in8->out16", 8, 16, input8, input8[7]); + + // r3: the exact failing ratio (43 -> 64), row 6 of the real aomenc + // superres key-frame gate fixture (`EC_SUPERRES_DEBUG=1` dump of the + // input row this decoder feeds `upscale_row`, matched against the + // `DIFF frame=0 row=6 col=62 got=140 want=141` mismatch). Run once + // with the replicate-from-column-42 padding this decoder uses, and + // once with a right pad value that visibly differs, to settle whether + // the failing columns even read past the real input at all. + uint8_t row6[43] = { 102, 102, 103, 103, 104, 105, 106, 107, 108, 109, + 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 125, 126, 127, 127, 128, 129, + 130, 130, 131, 131, 133, 134, 136, 137, 138, 139, + 140, 140, 141 }; + run_case("row6-replicate", 43, 64, row6, row6[42]); + run_case("row6-farpad", 43, 64, row6, 255); + + // r3 decisive check: `CROPDBG` dumped the pre-crop reconstructed row at + // the real (mi-aligned) width 48 -- columns 43..47 are genuine decoded + // pixels (140,140,140,140,140), NOT a replicate of column 42 (141, this + // decoder's current padding value). Feed the real trailing pixels + // instead of a flat replicate and see if the failing columns change. + uint8_t row6_real48[48] = { 102, 102, 103, 103, 104, 105, 106, 107, 108, 109, + 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 125, 126, 127, 127, 128, 129, + 130, 130, 131, 131, 133, 134, 136, 137, 138, 139, + 140, 140, 141, 140, 140, 140, 140, 140 }; + run_case("row6-realpad48", 48, 64, row6_real48, row6_real48[47]); + // Same real trailing pixels but in_len still 43 (matches frame_width), + // right_pad taken from the first real trailing pixel (140) rather than + // the frame-edge pixel (141) -- the actual libaom border-extend source. + run_case("row6-realedgeval", 43, 64, row6, 140); + + // r3 round 2: frame 2's rows 17/18 still mismatched by 1 at col 62 with + // the flat-margin fix landed. Their real margin is NOT flat (a gradient + // slope continues past the frame edge), so this checks the fix's + // n-real-pixels-then-replicate strategy against the true 5-pixel margin. + uint8_t row17[43] = { 109, 109, 109, 110, 111, 112, 112, 113, 114, 115, + 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, + 126, 127, 128, 129, 130, 131, 131, 132, 133, 134, + 135, 136, 137, 139, 139, 140, 140, 141, 142, 142, + 143, 144, 145 }; + uint8_t margin17[5] = { 146, 146, 147, 147, 147 }; + run_case_margin("row17-margin", 43, 64, row17, margin17, 5); + + uint8_t row18[43] = { 109, 110, 110, 110, 111, 112, 113, 114, 115, 116, + 117, 118, 119, 120, 121, 122, 122, 123, 124, 125, + 126, 127, 128, 129, 130, 131, 132, 133, 133, 134, + 134, 136, 138, 140, 139, 140, 140, 141, 142, 142, + 143, 144, 145 }; + uint8_t margin18[5] = { 146, 147, 147, 148, 148 }; + run_case_margin("row18-margin", 43, 64, row18, margin18, 5); + return 0; +}