diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index a7edca41..8b0452a7 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -32,7 +32,22 @@ fn main() { Ok(frames) if frames.is_empty() => { println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?"); } - Ok(frames) => println!("OK: {} frames decoded", frames.len()), + Ok(frames) => { + println!("OK: {} frames decoded", frames.len()); + // Optional second arg: dump the decoded planes as raw yuv420p so a + // pixel diff against `ffmpeg -i s.obu -f rawvideo` needs no test harness. + if let Some(out) = std::env::args().nth(2) { + // 8-bit only: planes are u16, take the low byte. + let mut buf: Vec = Vec::new(); + for f in &frames { + for p in [&f.y, &f.u, &f.v] { + buf.extend(p.iter().map(|&s| s as u8)); + } + } + std::fs::write(&out, &buf).expect("writing raw planes"); + println!("wrote {} bytes of yuv420p to {out}", buf.len()); + } + } Err(e) => println!("REFUSED: {e}"), } } diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index be8f124f..a382326b 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1823,6 +1823,16 @@ struct Neighbours { /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT). tx_h_grid: Vec, + /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4. + /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the + /// largest transform covering the subsampled BLOCK, capped at 32x32. It + /// does NOT follow luma's `tx_depth` split, so deriving it as + /// `tx_grid / 2` invented chroma transform edges the deblocker then + /// filtered (32x16 frames, U plane, seeds 42/47). Written from the + /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place + /// every caller routes through. + uv_tx_grid: Vec, + uv_tx_h_grid: Vec, /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` = /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` -- /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2) @@ -1902,6 +1912,8 @@ impl Neighbours { skip_grid_cols_mi: cols * (SUB / MI), tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], + uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], + uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)], ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)], delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)], above_palette_size: vec![0; cols], @@ -2105,6 +2117,11 @@ impl Neighbours { ref_frame: i8, ) { let (mi_r, mi_c) = at_mi; + // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is + // half its luma one (min 4 px, the smallest transform), capped at + // TX_32X32 -- independent of this block's luma `tx_depth`. + let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8; + let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8; let cur = CURRENT_DELTA_LF.with(|c| c.get()); let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) { std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8) @@ -2120,6 +2137,12 @@ impl Neighbours { if let Some(cell) = self.tx_h_grid.get_mut(idx) { *cell = tx_h_px; } + if let Some(cell) = self.uv_tx_grid.get_mut(idx) { + *cell = uv_tx_w; + } + if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) { + *cell = uv_tx_h; + } if let Some(cell) = self.ref_grid.get_mut(idx) { *cell = ref_frame; } @@ -4325,6 +4348,20 @@ fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly /// (own-edge and reach clamps both), passing what it gathers straight to /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone. +/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written +/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`. +fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) { + use std::io::Write; + if let Ok(path) = std::env::var(var) + && let Ok(mut f) = std::fs::File::create(format!("{path}.f0")) + { + for p in [y, u, v] { + let narrow: Vec = p.data.iter().map(|&s| s as u8).collect(); + let _ = f.write_all(&narrow); + } + } +} + #[derive(Clone)] struct PlaneBuf { data: Vec, @@ -5674,24 +5711,16 @@ fn plane_to_mi(chroma: bool, coord: usize) -> usize { /// half its coded block's luma transform, spec's `av1_get_max_uv_txsize` /// under 4:2:0 and a block that never splits its own transform). fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 { - let luma_tx = n - .tx_grid - .get(mi_r * n.skip_grid_cols_mi + mi_c) - .copied() - .unwrap_or(0) as u32; - if chroma { luma_tx / 2 } else { luma_tx } + let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid }; + grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32 } /// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal /// edges step and gate by transform height, which differs from width only /// on rect partition strips. fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 { - let luma_tx = n - .tx_h_grid - .get(mi_r * n.skip_grid_cols_mi + mi_c) - .copied() - .unwrap_or(0) as u32; - if chroma { luma_tx / 2 } else { luma_tx } + let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid }; + grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32 } /// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom @@ -7411,7 +7440,12 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( frame_height as usize, ); let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone()); + // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own + // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter + // dump above these bisect WHICH filter stage introduced a mismatch. + dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); + dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid); let (fw, fh) = (frame_width as usize, frame_height as usize); @@ -13306,7 +13340,12 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( frame_height as usize, ); let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone()); + // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own + // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter + // dump above these bisect WHICH filter stage introduced a mismatch. + dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); + dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid); let motion_field = build_motion_field( diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 8a2b0df0..aaa96889 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -6361,20 +6361,23 @@ mod tests { crate::decode::cdef_idx_hits() ); } - /// lane-tiny r1 diagnostic (not a gate): sweeps tiny key-frame sizes - /// against real aomenc + ffmpeg to find the exact size boundary of the - /// silent-wrong-pixels defect the sub8 lane's r2 dead-end flagged (a - /// plain 16x16 stream, no exotic tools). `#[ignore]`d -- prints a - /// pass/fail table, asserts nothing; run manually with `--nocapture`. + /// lane-tiny r4 GATE (was r1's `#[ignore]`d probe): every tiny key-frame + /// size real aomenc will encode, decoded pixel-exact against ffmpeg. + /// Tiny frames are where every edge/partial-superblock corner case is + /// forced, and this sweep is what found both r3's filter-intra tx_type + /// CDF row and r4's chroma-transform-size deblock defect -- so it + /// hard-asserts now: a decode error, a refusal, or one differing sample + /// at any size/seed fails. Only a genuinely absent oracle skips, and + /// `EC_AV1_REQUIRE_AOMENC=1` turns that into a failure too. #[test] - #[ignore = "diagnostic sweep, run manually with --nocapture"] - fn probe_tiny_frame_size_boundary() { + fn a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact() { if !have_ffmpeg() || !have_aomenc() { eprintln!("SKIP: no ffmpeg/aomenc"); return; } let sizes: &[(usize, usize)] = &[(8, 8), (16, 16), (32, 32), (16, 32), (32, 16), (64, 64), (48, 48), (24, 24)]; + let mut total_exact = 0u32; for &(width, height) in sizes { let mut ok = 0u32; let mut bad = 0u32; @@ -6423,7 +6426,18 @@ mod tests { let stream = out.stdout; let frames = match decode_stream(&stream) { Err(e) => { - eprintln!(" {width}x{height} seed {seed}: REFUSED {e}"); + // A NAMED refusal is the only non-exact outcome this + // gate tolerates (8x8 still needs a rectangular + // transform); anything else is a hard failure, and + // the floor assert below keeps that from going + // vacuous. + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{width}x{height} seed {seed}: failed outright, not a named \ + refusal: {msg}" + ); + eprintln!(" {width}x{height} seed {seed}: REFUSED {msg}"); refused += 1; continue; } @@ -6438,6 +6452,12 @@ mod tests { ok += 1; } else { bad += 1; + let nd = |a: &[u16], b: &[u16]| a.iter().zip(b).filter(|(x, y)| x != y).count(); + let (ndy, ndu, ndv) = ( + nd(&frames[0].y, &ffmpeg_frames[0].y), + nd(&frames[0].u, &ffmpeg_frames[0].u), + nd(&frames[0].v, &ffmpeg_frames[0].v), + ); let mut first = None; for row in 0..height { for col in 0..width { @@ -6458,13 +6478,32 @@ mod tests { .filter(|(a, b)| a != b) .count(); eprintln!( - " {width}x{height} seed {seed}: MISMATCH luma first_diff={first:?} ndiff_luma={ndiff}/{}", + " {width}x{height} seed {seed}: MISMATCH first_diff={first:?} \ + ndiff_luma={ndiff}/{} ndiff y/u/v={ndy}/{ndu}/{ndv}", width * height ); } } - eprintln!("{width}x{height}: {ok} ok / {bad} mismatch / {refused} refused (of {n})"); - } + assert_eq!( + bad, 0, + "{width}x{height}: {bad} of {n} seeds decoded to WRONG PIXELS ({ok} exact, \ + {refused} named refusals)" + ); + eprintln!("{width}x{height}: {ok}/{n} pixel-exact, {refused} named refusals"); + total_exact += ok; + } + // Hit counter: the sweep proved nothing unless every size x seed + // attempt really ran end to end (aomenc -> us -> ffmpeg compare). + // Floor (hit counter): 7 of the 8 sizes must decode all 10 seeds + // pixel-exact -- only 8x8 is allowed to refuse outright today. If a + // future change makes sizes refuse instead of decode, this fails + // rather than passing on refusals alone. + assert!( + total_exact >= 70, + "tiny sweep only reached {total_exact} pixel-exact attempts (floor 70) -- \ + refusals cannot substitute for decodes" + ); + eprintln!("tiny frame sweep: {total_exact} pixel-exact attempts"); } /// lane-tiny r1: re-decodes the known-failing 32x32 seed 45 fixture with diff --git a/lanes/tiny-r4.report.md b/lanes/tiny-r4.report.md new file mode 100644 index 00000000..8ee196e4 --- /dev/null +++ b/lanes/tiny-r4.report.md @@ -0,0 +1,106 @@ +# lane-tiny r4 report + +Rebased onto main `3808cf8` first (r3 was already merged there); branch head `9b1297a`. + +## Residue closed: 32x16 seeds 42 and 47, chroma-only + +### Fixture determinism (charter step 1) +The sweep's "seed" is not an encoder seed -- it is `attempt`, which shifts +`mandelbrot` start_x/start_y. Regenerated both failing 32x16 fixtures twice +each and hashed: + + attempt 0 (seed 42): c72a6a1b...5659 both runs, 152 bytes + attempt 5 (seed 47): fcbf0894...c388 both runs, 151 bytes + +So the sweep is genuinely reproducible and no binary fixture needed pinning +(per `seeded-fixture-not-reproducible.md`, checked rather than assumed). + +### Bisection (charter step 2) +Not an entropy defect -- the range ladder was never needed. Stage dumps +settled it in one step: + +| stage | Y | U | V | +|---|---|---|---| +| pre-filter recon (`EC_AV1_PREFILT_DUMP`, ours vs aomdec) | 0 diff | **0 diff** | 0 diff | +| post-deblock (`EC_AV1_POSTDEBLOCK_DUMP`, ours vs aomdec) | 0 diff | **5 diff** | 0 diff | + +Reconstruction (and therefore the whole entropy/prediction path) is exact; +the deblocker introduces the mismatch. Printing the U plane rows 0..7 shows +the oracle leaves the horizontal edge at chroma row 4 **completely +unfiltered**, while we filter it and move rows 3/4 at columns 1, 2, 15. + +## Root cause + +`av1_get_max_uv_txsize`: a block's chroma transform is the largest transform +covering the **subsampled BLOCK**, capped at 32x32. It does **not** follow +luma's `tx_depth` split. `tx_px_at`/`tx_h_px_at` (decode.rs) computed it as +`tx_grid[...] / 2` -- half the *resolved luma* transform. A 16x16 block whose +luma transform split to 8x8 therefore read a 4-pixel chroma transform, and the +deblocker filtered a chroma transform edge that does not exist in the stream. + +Reconstruction was never wrong because it derives chroma from the block side +(`chroma_side = side / 2`, decode.rs 4313/4850/8881) -- which is exactly why +the symptom was luma-bit-exact, chroma-only, +-1, and seed-dependent (the +phantom edge only changes pixels on the seeds where the filter masks pass). +V was clean on both seeds for the same reason: its masks did not pass. + +**Fix** (decode.rs): `Neighbours::uv_tx_grid` / `uv_tx_h_grid`, written per-mi +from the block's own mi span inside `fill_lf_grid_rect` -- the single writer +every `fill_lf_grid*` caller routes through -- as +`((span_mi * MI / 2).max(4).min(32))`; `tx_px_at`/`tx_h_px_at` read those +grids for chroma instead of halving luma's. + +**Class sweep**: grepped every other chroma-from-luma derivation. +`tx_px_at`/`tx_h_px_at` were the only sites deriving chroma tx from the luma +*transform*; 4313/4850/8881 derive from the block *side* and are correct. +No sibling instances. + +## Gate (charter step 4) + +`probe_tiny_frame_size_boundary` -> `stream.rs` +`a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact`, no `#[ignore]`: +- wrong pixels at any size/seed = panic (was: an eprintln) +- a decode error that is not a NAMED `unsupported:` refusal = panic +- floor assert `total_exact >= 70` so refusals can never make it vacuous + (per `gate-skips-on-its-own-failure.md` / `refusal-lifted-without-a-gate.md`) +- `EC_AV1_REQUIRE_AOMENC=1` makes an absent oracle fail, not skip. + +`gate_coverage.rs` needed no change: it derives the tool set from `stream.rs` +source and this gate's `--enable-*` flags are unchanged (it was already in the +derived gate set while `#[ignore]`d). `gate_coverage` + `refusal_inventory` +are green. + +| size | r3 | r4 | +|---|---|---| +| 8x8 | refused 10/10 | refused 10/10 (named: 16x16 block whose true edge cuts both axes needs a rect transform) | +| 16x16, 32x32, 16x32, 48x48, 64x64, 24x24 | 10/10 | 10/10 | +| **32x16** | **8/10** | **10/10** | + +No refusal string was lifted this round (the 8x8 rect-transform refusal stays; +it is a genuine missing capability, now pinned by the gate). + +## Instruments added +- `EC_AV1_POSTDEBLOCK_DUMP` / `EC_AV1_POSTCDEF_DUMP` (decode.rs `dump_stage`), + mirroring aomdec's own `EC_AV1_POSTDEBLOCK_DUMP` (decodeframe.c ~5404) -- with + the existing pre-filter dump these bisect which filter stage broke a frame. +- `decode_probe [out.yuv]` now writes the decoded planes as raw + yuv420p, so a pixel diff against `ffmpeg -f rawvideo` needs no test harness. + +## Verification + +- `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib`: **268 passed, 0 failed, + 22 ignored** (362s). +- New gate alone: 9.5s. + +EVIDENCE: $SCRATCH/pre0.bin.f0 vs oracle0.bin.f0, pd0.bin.f0 vs opd0.bin.f0 | EC_AV1_PREFILT_DUMP + EC_AV1_POSTDEBLOCK_DUMP on ours and instrumented aomdec, same 32x16 seed-42 stream | pre-filter U diff 0, post-deblock U diff 5 -> defect is in deblock, not recon +EVIDENCE: $SCRATCH/ours0.yuv vs ff0.yuv, ours5.yuv vs ff5.yuv | decode_probe a{0,5}.obu out.yuv, cmp against ffmpeg rawvideo | both byte-identical after the fix (before: U 4 and 5 differing samples) +EVIDENCE: cargo test -p ec-av1 --lib a_real_aomenc_tiny_frame_size_sweep -- --nocapture | 8 sizes x 10 seeds, real aomenc -> ours -> ffmpeg | 32x16 8/10 -> 10/10; 70 pixel-exact + 10 named 8x8 refusals; gate green + +## Open + +- 8x8 frames: `deferred(a real rectangular TX_4X8/TX_8X4 coefficient path)` -- + refused by name, now pinned by the gate; the same square-only-transform + ceiling `square-only-transform-ceiling.md` already tracks. +- Repo-wide `cargo fmt --check` drift exists in `cdf.rs` and elsewhere and + predates this lane: `accepted`, not touched (formatting the crate would bury + this diff).