From a3613e4e77c0a7437ee361e003192a4f24b3c494 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 1 Sep 2026 22:06:49 +0300 Subject: [PATCH] fix(av1): cherry-pick lane-tiny 9b1297a (chroma tx size in the deblocker) + lane-sub8 r4 report Round 4 disproved the lane's own premise: instrumented aomdec shows the gate's streams contain only PARTITION_NONE/SPLIT, so every rect/AB refusal rounds 2-3 attributed to the encoder was our own desync. With the mi-exact mode neighbours and has_tr_4x4/has_bl_4x4 in place the symbol ladder is exact (324/324, 318/318) and luma is bit-exact; 4 chroma pixels remain. --- crates/ec-av1/examples/decode_probe.rs | 17 +++++- crates/ec-av1/src/decode.rs | 63 +++++++++++++++++----- crates/ec-av1/src/stream.rs | 61 +++++++++++++++++---- lanes/sub8-r4.report.md | 74 ++++++++++++++++++++++++++ 4 files changed, 191 insertions(+), 24 deletions(-) create mode 100644 lanes/sub8-r4.report.md 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 1997ba45..39e90f55 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1851,6 +1851,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) @@ -1932,6 +1942,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], @@ -2135,6 +2147,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) @@ -2150,6 +2167,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; } @@ -4397,6 +4420,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, @@ -6026,24 +6063,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 @@ -7850,7 +7879,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); @@ -13745,7 +13779,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 11b06a98..6c80a65d 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/sub8-r4.report.md b/lanes/sub8-r4.report.md new file mode 100644 index 00000000..4f422fa9 --- /dev/null +++ b/lanes/sub8-r4.report.md @@ -0,0 +1,74 @@ +# lane-sub8 report (round 4) + +## Premise correction (this is the round's main result) +Round 2/3 assumed aomenc was really choosing `PARTITION_HORZ`/`VERT` below 8x8 +and AB partitions in this gate's recipe. **It is not.** Instrumented aomdec on +the gate's own stream (seed=117 cq=8, `--enable-rect-partitions=0`) reads only +`value=0` (NONE) and `value=3` (SPLIT) at every level: + +``` +EC_TRACE=1 ~/.cache/aom-oracle/build/aomdec --rawvideo -o /dev/null s117.obu \ + | grep EC_PART_VAL | awk '{print $4,$5}' | sort | uniq -c + 42 bsize=3 value=0 22 bsize=3 value=3 16 bsize=6 value=3 + 4 bsize=9 value=3 1 bsize=12 value=3 +``` + +So all 40 of the gate's "refusals" (`HORZ/VERT below 8x8`, `HORZ_A/B/VERT_A +below 16x16`, `a 32x32 partition type value=4/8/9`) were **hallucinated symbols +from our own desync**, not encoder choices. `--enable-rect-partitions=0` IS +honoured. Every refusal-shaped conclusion in rounds 2-3 was measuring the +desync. + +## Root causes found and fixed (commit "mi-exact intra mode neighbours ...") +1. **Coarse mode neighbours (`context-read-from-one-cell` class).** + `above_mode`/`left_mode` are one slot per 16x16; a split cell leaves two + (8x8) or four (4x4) different modes behind, and a leaf whose above/left + neighbour sits in such a cell read the wrong `kf_y_mode` CDF row -> desync. + `Neighbours` now keeps a mi-granular map (`sub8_mode_col`/`sub8_mode_row`, + `record_mode_mi`), written by `record_rect`, `record_split_luma`, + `decode_leaf8` and every 4x4 leaf, read back with an exact-position guard + (`mode_above_mi`/`mode_left_mi`) that falls back to the coarse slot. +2. **`has_tr_4x4`/`has_bl_4x4` never transcribed** (`encode.rs`, the + `corner-cut` comment that named this exact ceiling). Side-4 blocks clamped + into the 8x8 table, so a directional 4x4 leaf predicted from above-right + samples the decoder has not written yet -- all-zero pixels in the leaf's + bottom-right triangle. Both tables transcribed verbatim from + `~/.cache/aom-oracle/src/av1/common/reconintra.c:65,254`; `Reach::table` + maps side 4 to the new row. +3. Cherry-picked lane-tiny `9b1297a` (deblocker chroma tx size from the block + span) per the charter -- it does not change this lane's residue but keeps + the branch aligned with main's fix. + +## Gate result +`a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact` -- **still RED**, +but for a 4-pixel chroma residue instead of a desync: +- symbol ladder vs instrumented aomdec is now **exact** on both sampled + streams (324/324 elements seed=117, 318/318 seed=100), no refusal, decode + completes; +- luma is **bit-exact** on seed=100; +- chroma differs on 4 pixels: U/V (row 20, cols 18-19), deltas 1..3. + +EVIDENCE: /tmp/.../scratchpad/{ref100.yuv,ours100.yuv} | aomenc seed=100 cq=6 recipe from the gate, decoded by ec-av1 and by ffmpeg | 4096/4096 luma bytes equal, 4/2048 chroma bytes differ (max |delta| 3); before this round the same stream refused at a hallucinated partition symbol +EVIDENCE: /tmp/.../scratchpad/{ref.txt,ours.txt} + ladder.py | EC_TRACE/EC_TRACE_MODE_STEP ladder, ours vs instrumented aomdec, seed=117 | 324 elements, no divergence (was: first divergence at element 62) + +## Suite +`cargo test -p ec-av1 --lib` (EC_AV1_REQUIRE_AOMENC=1): **267 passed, 2 failed, +22 ignored**, 1124 s. +- `stream::a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact` -- the + 4-pixel chroma residue above. +- `refusal_inventory::the_decode_path_refuses_exactly_the_listed_cases` -- + NOT investigated this round (budget). Expected shape: a refusal the + inventory expects to fire no longer fires now that the desync is gone + (that is what the fix was for), but it is a RED test and no refusal string + was lifted this round. + +## Open +- fix-now: the 4-pixel chroma residue (U/V row 20, cols 18-19 of the 64x64 + seed=100 frame; block = chroma 4x4 at (20,16), luma 8x8 group mi(10,8)). + Tried and REVERTED (no effect on these pixels): OR-ing the subsampling scale + into the chroma edge's mi (`set_lpf_parameters`' `scale_vert | ...`) in + `edge_params`. Next step: dump post-reconstruction vs `EC_AV1_PREFILT_DUMP` + to separate recon from deblock before touching either. +- fix-now: `refusal_inventory` red (see above). +- deferred(gate green): lifting any refusal string -- nothing lifted, none + proven.