From 5b4ff4a4a6abedbc55a839e38b8dbb47683be6f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Sep 2026 07:11:20 +0300 Subject: [PATCH] fix(av1): a skipped intra block predicts per transform unit, not per block An intra block's tx_depth is read whether or not the block is skipped (only an INTER skip forces the largest transform), and spec 7.11.2 predicts one transform unit at a time -- each unit's edges are the units already written left/above of it inside the same block. Our two skip branches (decode_block, decode_leaf8) predicted the whole block in one call, which for a 32x32 DC block with 8x8 units gives 123 where libaom gives 124 sixteen times. Mid-film 3840x1608 10-bit key frame: 2403 luma samples wrong (|delta| <= 2) -> 0, all three planes bit-exact; the earlier key frame stays bit-exact. Stage split done with new 16-bit dump rungs on both sides (the 8-bit ones truncate the defect away) and a new EC_PREDND oracle rung (EC_PRED sat after the highbd early return and printed nothing on a 10-bit stream). New counter SKIP_SPLIT_TX_HITS: a skipped block codes no coefficients, so nothing but the pixels witnesses this path. No in-repo gate landed -- see lanes/hgkf-r2.report.md for the swept recipes and the deferral. --- crates/ec-av1/src/decode.rs | 206 +++++++++++++++++++++++++++++++----- lanes/hgkf-r2.report.md | 90 ++++++++++++++++ 2 files changed, 272 insertions(+), 24 deletions(-) create mode 100644 lanes/hgkf-r2.report.md diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index aa9402e9..a6c43c8c 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1309,6 +1309,24 @@ pub(crate) fn palette_split_tx_hits() -> usize { PALETTE_SPLIT_TX_HITS.with(|c| c.get()) } +// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform +// and which are therefore predicted one transform unit at a time (a skipped +// block codes no coefficients, so nothing else in the stream witnesses this +// path -- only the pixels do). +thread_local! { + static SKIP_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units). +pub fn skip_split_tx_hits() -> usize { + SKIP_SPLIT_TX_HITS.with(|c| c.get()) +} + +/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt. +pub fn reset_skip_split_tx_hits() { + SKIP_SPLIT_TX_HITS.with(|c| c.set(0)); +} + // lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth` // symbol split their luma transform, bucketed by block side (8, 16, 32, 64) -- // the gate's proof that the lifted path actually ran, per size. @@ -7690,6 +7708,26 @@ fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { /// [`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`. +/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of +/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) -- +/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE). +fn dump_stage16(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, fw: usize, fh: usize) { + 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, w, h) in [(y, fw, fh), (u, fw.div_ceil(2), fh.div_ceil(2)), (v, fw.div_ceil(2), fh.div_ceil(2))] { + for row in 0..h { + let mut bytes = Vec::with_capacity(w * 2); + for &s in &p.data[row * p.width..][..w] { + bytes.extend_from_slice(&s.to_le_bytes()); + } + let _ = f.write_all(&bytes); + } + } + } +} + fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) { use std::io::Write; if let Ok(path) = std::env::var(var) @@ -7835,6 +7873,7 @@ impl PlaneBuf { /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own /// already-rect-capable `(bw, bh)` pair. #[allow(clippy::too_many_arguments)] + #[track_caller] fn reconstruct_rect( &mut self, x: usize, @@ -7893,6 +7932,16 @@ impl PlaneBuf { } prediction }; + // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's + // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). + if std::env::var_os("EC_PRED").is_some() { + let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); + let row0: Vec = prediction[..bw.min(8)].to_vec(); + let col0: Vec = (0..bh.min(8)).map(|r| prediction[r * bw]).collect(); + eprintln!( + "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller() + ); + } for row in 0..bh { for col in 0..bw { let idx = row * bw + col; @@ -7912,6 +7961,7 @@ impl PlaneBuf { /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual /// order (cfl.c). + #[track_caller] fn reconstruct( &mut self, x: usize, @@ -7975,6 +8025,16 @@ impl PlaneBuf { } prediction }; + // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's + // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). + if std::env::var_os("EC_PRED").is_some() { + let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); + let row0: Vec = prediction[..side.min(8)].to_vec(); + let col0: Vec = (0..side.min(8)).map(|r| prediction[r * side]).collect(); + eprintln!( + "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller() + ); + } for row in 0..side { for col in 0..side { let idx = row * side + col; @@ -8306,18 +8366,69 @@ fn decode_block( if skip { // A skipped block codes no residual syntax at all (spec 5.11.34): // straight prediction, on every plane. - y.reconstruct( - px, - py, - side, - mode, - angle_delta_y, - reach, - &vec![0i32; side * side], - None, - filter_intra, - smooth_neighbor, - ); + // + // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it + // is skipped (only an INTER skip forces the largest transform), and + // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts + // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units + // already written left/above of it inside this same block. Predicting + // the whole `side`x`side` at once gives a different (uniformly off by + // ~1) answer, which is exactly the residue this lane was chasing. + // The palette/intrabc override path keeps the single-call shape (its + // per-TU windowing is the non-skip loop's own `palette_y_buf` slice, + // untested for skip and unreachable in these streams). + let split_tx_skip = + tx_select && logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none(); + if split_tx_skip { + SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + let n_axis = side / logical_tx; + for tu_row in 0..n_axis { + for tu_col in 0..n_axis { + let tu_px = px + tu_col * logical_tx; + let tu_py = py + tu_row * logical_tx; + if tu_px >= y.true_width || tu_py >= y.true_height { + continue; + } + let tu_reach = tu_reach( + side, + side, + tu_col * logical_tx, + tu_row * logical_tx, + logical_tx, + reach, + px, + py, + y.width, + y.height, + ); + y.reconstruct( + tu_px, + tu_py, + logical_tx, + mode, + angle_delta_y, + tu_reach, + &vec![0i32; logical_tx * logical_tx], + None, + filter_intra, + smooth_neighbor, + ); + } + } + } else { + y.reconstruct( + px, + py, + side, + mode, + angle_delta_y, + reach, + &vec![0i32; side * side], + None, + filter_intra, + smooth_neighbor, + ); + } let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone()); @@ -8735,18 +8846,59 @@ fn decode_leaf8( let (cpx, cpy) = (px / 2, py / 2); let (luma_grid, u_grid, v_grid); if skip { - y.reconstruct( - px, - py, - 8, - mode, - angle_delta_y, - reach, - &vec![0i32; 64], - None, - filter_intra, - smooth_neighbor, - ); + // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an + // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4 + // transform units, each off the units already written left/above of + // it inside this same leaf -- an intra block's transform size is read + // whether or not it is skipped, and spec 7.11.2 predicts per unit. + if resolved == 4 { + SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + for tu_row in 0..2 { + for tu_col in 0..2 { + let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4); + if tu_px >= y.true_width || tu_py >= y.true_height { + continue; + } + let tu_reach = tu_reach( + 8, + 8, + tu_col * 4, + tu_row * 4, + 4, + reach, + px, + py, + y.width, + y.height, + ); + y.reconstruct( + tu_px, + tu_py, + 4, + mode, + angle_delta_y, + tu_reach, + &vec![0i32; 16], + None, + filter_intra, + smooth_neighbor, + ); + } + } + } else { + y.reconstruct( + px, + py, + 8, + mode, + angle_delta_y, + reach, + &vec![0i32; 64], + None, + filter_intra, + smooth_neighbor, + ); + } let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8)); u.reconstruct( cpx, @@ -12721,6 +12873,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // that isolate whether a decode-order frame's mismatch already exists // in reconstruction (this dump) vs is introduced by the loop filter // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). + dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -12764,8 +12917,10 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // 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); + dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); + dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); 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); @@ -19843,6 +19998,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // that isolate whether a decode-order frame's mismatch already exists // in reconstruction (this dump) vs is introduced by the loop filter // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). + dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -19869,8 +20025,10 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // 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); + dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); + dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); 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/lanes/hgkf-r2.report.md b/lanes/hgkf-r2.report.md new file mode 100644 index 00000000..cb1a3d66 --- /dev/null +++ b/lanes/hgkf-r2.report.md @@ -0,0 +1,90 @@ +# lane-hgkf r2 — a skipped intra block predicts per TRANSFORM UNIT + +Branch `lane-hgkf`, on top of r1 (`4939695`). Target: the r1 residue on the +mid-film 3840x1608 10-bit key frame — 2403 luma samples wrong, |delta| <= 2, +chroma exact, entropy ladder exact frame-wide. + +## Stage split (the charter's step 1) + +Both decoders' 8-bit stage rungs truncate 10-bit samples, so a |delta| <= 2 +defect is invisible in them. Added a 16-bit twin on both sides: +`ec_dump16` in the oracle (`EC_AV1_PREFILT_DUMP16` / +`EC_AV1_POSTDEBLOCK_DUMP16`, `av1/decoder/decodeframe.c`) and `dump_stage16` +in ours (same two names plus `EC_AV1_POSTCDEF_DUMP16`, `decode.rs`). + +EVIDENCE: /home/user/.cache/hgkf-work/{o,a}_pre.f0, {o,a}_pdb.f0, o_fin.f0.yuv vs ref_kf_4500.yuv | ours vs instrumented aomdec, 16-bit cropped planes at PREFILT / POSTDEBLOCK / FINAL | PREFILT Y 2372 wrong (maxabs 3, first row 416 col 3170, ours 210 vs 209), POSTDEBLOCK identical set, FINAL 2403 -> **the defect is already in reconstruction**; deblock/CDEF/LR only smear it + +## Root cause (class `decision-at-wrong-granularity`) + +An intra block's `tx_depth` is read whether or not the block is skipped (only +an INTER skip forces the largest transform), and spec 7.11.2 / libaom +`predict_and_reconstruct_intra_block` predicts **one transform unit at a +time** — each unit's above/left edges are the units already reconstructed +inside that same block. Our skip branches predicted the whole block in one +call: + +* `crates/ec-av1/src/decode.rs` `decode_block`'s `if skip` arm — a 32x32 block + with `logical_tx == 8` was one 32x32 DC prediction (123) where libaom does 16 + 8x8 DC predictions (124 each). +* `crates/ec-av1/src/decode.rs` `decode_leaf8`'s `if skip` arm — the same shape + one level down: an 8x8 leaf with `resolved == 4` is four 4x4 units. + +Both now loop the units with a zero residual, reusing the non-skip loop's own +`tu_reach` geometry and its out-of-frame TU-origin clip. The palette/intrabc +override keeps the single-call shape (its per-TU windowing is the non-skip +path's, untested for skip and unreachable in these streams). + +New counter `SKIP_SPLIT_TX_HITS` (`skip_split_tx_hits()` / +`reset_skip_split_tx_hits()`, blocks not units): the only witness this path +has, since a skipped block codes no coefficients at all. + +## Evidence + +EVIDENCE: /home/user/.cache/hgkf-work/aom_pred.txt, our_pred.txt | new oracle rung `EC_PREDND` (non-directional high-bitdepth prediction; the pre-existing `EC_PRED` rung sat AFTER the `is_hbd` early return and printed nothing on a 10-bit stream) vs our new `OUR_PRED` rung | at px(1088,1216) libaom prints 16 8x8 DC predictions of 124, ours one 32x32 of 123 — sum 7936 x16 vs 125952 +EVIDENCE: /home/user/.cache/hgkf-work/fx_kf_4500.f0.yuv vs ref_kf_4500.yuv | `dump_yuv kf_4500.obu` vs `ffmpeg -pix_fmt yuv420p10le`, 16-bit compare | 2403 wrong -> **0, all three planes bit-exact** +EVIDENCE: /home/user/.cache/hgkf-work/fx_kf_0.f0.yuv vs ref_kf_0.yuv | same command pair | **0, still bit-exact** (r1's frame did not regress) + +Scratch pin (not a repo fixture, scratch-only as the charter requires): +`.../scratchpad/census2/kf_4500.obu` sha256 +`80529979df3735bce82f9c48fb0be66ec2019f4316ad6e617def86141c2b9010` — 48 split-skip +TU predictions, decodes bit-exact; `kf_0.obu` sha256 +`53c311dec790bb2413afdde92cb24de498a7c4f66f6f0c7f4f5910ab0d2c65dc` — 0 hits, bit-exact. + +## Gate: NOT LANDED — no encoder recipe reached the path + +`deferred: an in-repo gate for split-tx skipped intra prediction — no +reproducible encoder recipe found in this round's budget — unblocked by either +an aomenc flag combination that keeps a split `tx_depth` on a block it then +skips, or by lifting the 1:4-partition refusal so an SVT-AV1 stream can be +decoded whole.` + +Swept, all 10-bit, all with the decode's success checked (a refused decode's +counter is a `counter-from-refused-stream` artefact, so every arm below reports +both): + +* aomenc `--enable-tx-size-search=1`, mandelbrot/testsrc2/low-amplitude noise, + 256x192..1280x720, cq 12..55, cpu-used 0..8, aq-mode 0/1, 8- and 10-bit: + **0 hits on every arm that decoded**. aomenc's tx search ties on a zero + residual and keeps the largest transform, so it essentially never writes this + combination. +* ffmpeg `libsvtav1` (v3.1.2) preset 4, 1280x720 10-bit: **reaches the path** + (4..24 units at crf 25..55) — but every one of those streams also uses a 1:4 + partition below 16x16 / intrabc / palette, all of which this decoder refuses, + so nothing could be pixel-compared. +* `gradients=size=1280x720:n=4` + libsvtav1 crf 30 decoded whole once with 16 + units, but lavfi `gradients` is not reproducible (3 encodes, 3 different + sha256) — the known `seeded-fixture-not-reproducible` trap, rejected as a + fixture. + +## Same-shape sweep + +Every intra skip-prediction site in `decode.rs`: `decode_block` (fixed), +`decode_leaf8` (fixed), the 4x8/8x4 leaf at `decode.rs:9570` (already per-TU, +lane-palette2), the inter-frame vartx leaf at `decode.rs:16450` (already +per-TU), the 4x4 leaf (no split exists). Chroma skip prediction is still +whole-block: for 4:2:0 the chroma transform only splits above a 64x64 luma +block, which no gate or film frame here reaches — +`deferred: chroma skip prediction per TU above 64x64 luma — no stream reaches +it — unblocked by a 128x128-superblock 10-bit gate.` + +Suite: `cargo test -p ec-av1 --lib` (user unit, log `$HOME/.cache/hgkf-suite-r2.log`) -- **356 passed / 0 failed / 29 ignored**, 416s.