From e7460a02f64339f1ed0335e3c126827074f82ddb 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 09:34:39 +0300 Subject: [PATCH] fix(av1): CDEF filtered 8x8 units libaom skips, and searched direction on clamped edge pixels decode_inter_block8 (the leaf path --min-partition-size=4 picks for a 16x16 group) wrote the mi map and the loop-filter grid at both exits but never the per-8x8 CDEF skip band, so an all-skip 8x8 group was judged by the PREVIOUS frame's flags and got filtered where libaom's is_8x8_block_skip (cdef.c:29-38) excludes it from av1_cdef_compute_sb_list's dlist: 3 luma samples |d|=1 on decode-order frames 3 and 4 of a 192x128 6-frame inter stream at cq 8 and cq 10, all in the frame's last 8x8 column. apply_cdef's direction search also clamped to the last real sample instead of reading the CDEF_VERY_LARGE padding libaom's cdef_prepare_fb writes past the mi-rounded extent (cdef.c:249-256), so every 8x8 straddling an odd-mi crop edge picked a different var, hence a different adjust_strength: a 68x192 stream goes 145 luma samples wrong on frame 1 to 0 on all five frames (its chroma residue is a separate, still-open defect). Gate: a_real_aomenc_stream_with_cdef_and_sub16_inter_leaves_decodes_pixel_exact, real aomenc with --min-partition-size=4 --enable-cdef=1, every decode-order frame on all three planes, hard-asserting both new counters (an 8x8 unit excluded by the all-skip rule, and the leaf that now writes the band). Also: dump_stage/dump_stage16 indexed per frame (they overwrote .f0 every frame, which is why filter-stage bisection kept reading the LAST frame). --- crates/ec-av1/src/decode.rs | 76 +++++++++++++++++-- crates/ec-av1/src/stream.rs | 145 ++++++++++++++++++++++++++++++++++++ lanes/cdef-r1.handoff.md | 66 ++++++++++++++++ 3 files changed, 281 insertions(+), 6 deletions(-) create mode 100644 lanes/cdef-r1.handoff.md diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 0bcd964e..10da918d 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -2543,6 +2543,28 @@ thread_local! { static SUB8_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } +// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all +// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38` +// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how +// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all. +// (b) was 0 for every stream before this round -- the leaf path never touched +// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got +// filtered where libaom skips it. A gate asserts both are non-zero. +thread_local! { + static CDEF_SKIPPED_UNITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static INTER8_SKIP_BAND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of `CDEF_SKIPPED_UNITS`. +pub(crate) fn cdef_skipped_units() -> usize { + CDEF_SKIPPED_UNITS.with(|c| c.get()) +} + +/// Current value of `INTER8_SKIP_BAND_HITS`. +pub(crate) fn inter8_skip_band_hits() -> usize { + INTER8_SKIP_BAND_HITS.with(|c| c.get()) +} + /// Current value of [`SUB8_SPLIT_HITS`]. pub(crate) fn sub8_split_hits() -> usize { SUB8_SPLIT_HITS.with(|c| c.get()) @@ -8822,7 +8844,7 @@ fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { 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")) + && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var))) { 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 { @@ -8836,10 +8858,25 @@ fn dump_stage16(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, fw: usize, } } +/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a +/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so +/// every frame overwrote the previous one and only the LAST frame survived, +/// which silently defeats any per-frame filter-stage bisection. +fn dump_stage_idx(var: &str) -> usize { + use std::collections::HashMap; + use std::sync::{Mutex, OnceLock}; + static IDX: OnceLock>> = OnceLock::new(); + let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap(); + let e = m.entry(var.to_string()).or_insert(0); + let i = *e; + *e += 1; + i +} + 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")) + && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var))) { for p in [y, u, v] { let narrow: Vec = p.data.iter().map(|&s| s as u8).collect(); @@ -10352,6 +10389,7 @@ fn decode_leaf8( neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]); neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]); } + INTER8_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1)); neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid(leaf_mi, 2, 8, 0); neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode); @@ -12664,6 +12702,9 @@ fn apply_cdef( while mi_r < skip_grid.mi_rows { let mut mi_c = 0usize; while mi_c < skip_grid.mi_cols { + if skip_grid.is_skip_txfm(mi_r, mi_c) { + CDEF_SKIPPED_UNITS.with(|c| c.set(c.get() + 1)); + } if !skip_grid.is_skip_txfm(mi_r, mi_c) { let sidx = strength_idx(mi_r, mi_c); let (ox, oy) = (mi_c * 4, mi_r * 4); @@ -12676,10 +12717,15 @@ fn apply_cdef( i32::from(src_y[ny as usize * y_stride + nx as usize]) } }; - let (dir, var) = cdef_find_dir(coeff_shift, |r, c| { - let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1)); - i32::from(src_y[ny * y_stride + nx]) - }); + // lane-cdef r1: the direction search reads the SAME padded + // block the taps do -- libaom runs `cdef_find_dir` on the + // prepared filter block (`cdef_block.c:296-320` over + // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns + // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE. + // Clamping to the last real sample instead made every straddling + // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence + // a different `adjust_strength`, hence a +-1 band at the crop edge. + let (dir, var) = cdef_find_dir(coeff_shift, |r, c| sample_y(r as i32, c as i32)); // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0` // -- each plane zeroes the shared direction when *its own* @@ -12689,6 +12735,12 @@ fn apply_cdef( let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift; let y_dir = if y_pri_strength != 0 { dir } else { 0 }; let t = cdef_adjust_strength(y_pri_strength, var); + // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit. + if std::env::var_os("EC_AV1_CDEF_DBG").is_some() { + eprintln!( + "EC_CDEF mi_r={mi_r} mi_c={mi_c} x={ox} y={oy} sidx={sidx} dir={dir} var={var} t={t} pri={y_pri_strength} sec={y_sec_strength} damp={damping}" + ); + } let enable_primary = t != 0; let enable_secondary = y_sec_strength != 0; if enable_primary || enable_secondary { @@ -19668,6 +19720,14 @@ fn decode_inter_block8( // so the 16x16 below a split block read partition ctx 0 // instead of 1 and mis-read PARTITION_SPLIT as NONE. neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]); + // lane-cdef r1: ... and the CDEF skip band too. `apply_cdef`'s + // `is_8x8_block_skip` (libaom `cdef.c:29-38`) reads all four mi + // cells of the 8x8; this leaf wrote none of them, so a 64x64 + // whose bottom-right 16x16 is an all-skip 8x8-leaf group kept + // the PREVIOUS frame's flags and got filtered where libaom's + // dlist excludes it (3 luma samples on a 192x128 inter frame). + INTER8_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1)); + neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid( leaf_mi, 2, @@ -20473,6 +20533,10 @@ fn decode_inter_block8( // lane-gmaffine r2: the deblock grid's ref id is the leaf's OWN reference // (r1 taught this leaf non-LAST refs; the hardcoded LAST_FRAME made every // GOLDEN/ALTREF leaf read as LAST at the loop-filter's ref/mv edge test). + // lane-cdef r1: the fall-through twin of the compound arm's skip-band + // write above -- `skip` is one flag for the whole 8x8 leaf (read at + // `decode.rs`'s `skip_ctx` site), `split8` only splits its transform. + neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid( leaf_mi, 2, diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 9ed2eab8..25d6ae74 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -15223,6 +15223,151 @@ mod tests { ); } + /// lane-cdef r1: CDEF's per-8x8 skip band under sub-16x16 inter leaves. + /// + /// `apply_cdef` excludes an 8x8 luma unit whose four mi cells are all + /// `skip_txfm` (libaom `cdef.c:29-38 is_8x8_block_skip`, called from + /// `av1_cdef_compute_sb_list`'s dlist loop). `decode_inter_block8` -- the + /// leaf path `--min-partition-size=4` makes aomenc pick for a 16x16 group + /// -- wrote the loop-filter grid but never that skip band, so an all-skip + /// group kept the PREVIOUS frame's flags and got filtered where libaom + /// skips it (3 luma samples, decode-order frames 3 and 4 of the 192x128 + /// cq-8 stream below, at the frame's last 8x8 column). + /// + /// Both counters are hard asserts per compared attempt: `cdef_skipped_units` + /// proves the all-skip dlist exclusion was actually reached, and + /// `inter8_skip_band_hits` proves the 8x8 leaf path (the writer that used + /// to be missing) ran on the same stream. + #[test] + fn a_real_aomenc_stream_with_cdef_and_sub16_inter_leaves_decodes_pixel_exact() { + if !have_aomenc() { + return; + } + let (width, height, frames) = (192usize, 128usize, 6usize); + let mut refusals: Vec = Vec::new(); + let mut fired = 0u32; + for (depth, cq, sp) in [(8u32, 8u32, 3u32), (8, 10, 3), (8, 12, 6), (10, 8, 3), (10, 12, 6)] { + let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let src = format!( + "color=c=gray:s={width}x{height}:d=0.24:r=25,format=gray,\ + geq=lum='128+58*sin((X+N*{sp})/6)+18*sin(Y/23)',format=yuv420p" + ); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &src, "-t", "0.24", "-pix_fmt", pix, + "-strict", "-1", "-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 mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &format!("--cq-level={cq}"), + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + &format!("--bit-depth={depth}"), + &format!("--input-bit-depth={depth}"), + "--enable-restoration=0", + "--enable-palette=0", + "--deltaq-mode=0", + "--enable-filter-intra=0", + "--enable-cfl-intra=0", + "--enable-intrabc=0", + "--lag-in-frames=0", + "--enable-obmc=0", + "--enable-tx-size-search=1", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--min-partition-size=4", + "--max-partition-size=16", + // Last occurrence of a repeated --enable-* flag wins + // (aomenc-last-flag-wins): CDEF stays ON, and the two + // counters below prove the filter really ran. + "--enable-cdef=1", + "--obu", + "-o", + "-", + "-", + ]) + .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 (depth={depth} cq={cq})" + ); + let stream = out.stdout; + let skipped_before = decode::cdef_skipped_units(); + let leaves_before = decode::inter8_skip_band_hits(); + let decoded = match decode_stream(&stream) { + Ok(f) => f, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.starts_with("unsupported: "), + "decode error that is not a named refusal \ + (depth={depth} cq={cq}): {msg}" + ); + refusals.push(format!("depth={depth} cq={cq}: {msg}")); + continue; + } + }; + assert_eq!(decoded.len(), frames, "frame count (depth={depth} cq={cq})"); + assert!( + decode::cdef_skipped_units() > skipped_before, + "no 8x8 CDEF unit was excluded by the all-skip rule \ + (depth={depth} cq={cq})" + ); + assert!( + decode::inter8_skip_band_hits() > leaves_before, + "no sub-16x16 inter leaf wrote the CDEF skip band \ + (depth={depth} cq={cq})" + ); + let reference = if depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frames) + } else { + ffmpeg_decode_sequence(&stream, width, height, frames) + }; + for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() { + assert_eq!(ours.y, theirs.y, "luma frame {i} (depth={depth} cq={cq})"); + assert_eq!(ours.u, theirs.u, "U frame {i} (depth={depth} cq={cq})"); + assert_eq!(ours.v, theirs.v, "V frame {i} (depth={depth} cq={cq})"); + } + fired += 1; + } + // Three of the five arms land on OTHER open refusals (a non-DC chroma + // mode on an 8x8 inter leaf; inter partitions below 8x8) -- the two + // 8-bit cq 8/10 arms ARE the streams the defect was found on, and each + // hard-asserts both counters plus all six frames on all three planes. + assert!( + fired >= 2, + "fewer than 2 firing+pixel-exact attempts:\n{}", + refusals.join("\n") + ); + } + /// lane-sub8 r1: `--min-partition-size=4` on fine-detail noisy gradients /// at low cq reliably makes aomenc split an 8x8 block all the way to /// four `BLOCK_4X4` leaves (`PARTITION_SPLIT` below 8x8, spec diff --git a/lanes/cdef-r1.handoff.md b/lanes/cdef-r1.handoff.md new file mode 100644 index 00000000..a6479dec --- /dev/null +++ b/lanes/cdef-r1.handoff.md @@ -0,0 +1,66 @@ +# lane-cdef r1 -- HANDOFF (2 CDEF defects rooted, both fixed, gate GREEN; one residue open) + +Base: main 48b35ab. Suite unit `cdef-suite-1788330834.service` -> `$HOME/.cache/cdef-suite-r1.log` +(started at the turn cap; FIRST THING NEXT ROUND: `grep -E "^test result|FAILED" $HOME/.cache/cdef-suite-r1.log`). + +## Defect A -- per-8x8 CDEF skip band never written by the 8x8 inter leaf (charter hypothesis (a), variant) + +* Stream: `~/.cache/cdef-tmp/a0_8.obu`, sha256 `aa40f17f6e49eca2bb8c9d9ab99a175312134bdcf45c39b8a76b6757d8536751` + (hashed twice, identical), `~/.cache/cdef-tmp/gen.sh 8 3 8 a0_8.obu` = lane-intersub8's recipe, + 192x128, 6 frames, `--min-partition-size=4`, cq 8, 8-bit. +* Stage attribution: reconstruction and post-deblock are EXACT (`EC_AV1_POSTDEBLOCK_DUMP` ours vs + the instrumented aomdec: 0/24576 luma on decode-order frame 3); the 3 samples enter at CDEF. + NOTE: aomdec's `EC_AV1_PREFILT_DUMP` is ALREADY POST-DEBLOCK on this build (r_pre.fN == r_pd.fN + for 5 of 6 frames) -- ours is genuinely pre-deblock, so the two rungs are NOT the same stage. +* Root cause: `decode_inter_block8` (decode.rs, the leaf path `--min-partition-size=4` picks for a + 16x16 group) wrote `record_mi` + `fill_lf_grid` at both exits but NEVER `fill_skip_grid`. The + bottom-right 16x16 of decode-order frame 3 was therefore judged by the PREVIOUS frame's flags: + our 8x8 units at mi(28,46)/(30,46) read skip=false and were filtered, while libaom's + `is_8x8_block_skip` (cdef.c:29-38, called from `av1_cdef_compute_sb_list` cdef.c:40-71) excludes + an all-skip 8x8 from the dlist. Proof: a python model of `cdef_block.c` reproduces the reference + for all 16 units of the last column at (sec=1,damp=3) EXCEPT those two, where only "unfiltered" + matches; frame-3 fill log showed 0 of 95 skip fills covering mi(28,44)+16x16. +* Fix: `neighbours.fill_skip_grid(leaf_mi, 2, skip)` at both `decode_inter_block8` exits (compound + early return + fall-through), each bumping `INTER8_SKIP_BAND_HITS`. +* Before/after on the pinned stream: frames 3 and 4 had 3 luma samples |d|=1 each + ((189,116/120/124) and (186,116/120/124)); after, all 6 frames pixel-exact on Y/U/V. + +## Defect B -- CDEF direction search clamped at the crop edge instead of reading CDEF_VERY_LARGE + +* Stream: `~/.cache/golomb-tmp/s68.obu` (68x192, 5 frames, 8-bit, cq 35) -- lane-golomb r9's + deferred "straddle band". +* Root cause: `apply_cdef`'s `cdef_find_dir` closure clamped to `true_w-1`/`true_h-1`, but libaom + runs `cdef_find_dir` over `cdef_prepare_fb`'s buffer (cdef.c:249-256 `frame_boundary[RIGHT]` + fill, cdef_block.c:296-320), whose columns/rows past the mi-rounded extent are CDEF_VERY_LARGE. + With odd `mi_cols` (68 px -> 17 mi) the last 8x8 straddles, so var/`adjust_strength` differed. +* Fix: the direction search now reads the SAME padded `sample_y` the taps use (one line). +* Before/after: frame 1 luma 145 diffs -> **0**; all 5 frames luma exact. +* RESIDUE (open, NOT fixed): the same stream still differs in CHROMA from frame 1 on + (U/V 194/401/466/551 samples, |d| up to 6, spread over ~37 chroma 4x4 units, frame 0 exact). + Not attributable yet: `EC_AV1_DEBUG_SKIP_CDEF=1` cannot bisect inter frames (it also breaks the + reference frames), so the postdeblock rung is only valid for frame 0 here. Next step: dump + per-4x4 chroma CDEF params (uv pri/sec, damping-1, shared luma dir) for frame 1's first + differing unit and model it against `cdef_block.c` the way defect A was modelled + (`~/.cache/cdef-tmp/model.py` is a complete python port of cdef_block.c + find_dir + adjust). + +## Gate +`stream.rs::a_real_aomenc_stream_with_cdef_and_sub16_inter_leaves_decodes_pixel_exact` -- real +aomenc, `--min-partition-size=4 --enable-cdef=1` (last flag wins), 5 arms (8-bit cq 8/10/12, +10-bit cq 8/12), every decode-order frame compared on Y/U/V, hard asserts +`decode::cdef_skipped_units()` (an 8x8 unit really excluded by the all-skip rule) and +`decode::inter8_skip_band_hits()` (the leaf that used to write nothing) both grew per compared +attempt. 2 of 5 arms fire; the other 3 hit UNRELATED open refusals (non-DC chroma mode on an 8x8 +inter leaf; inter partition below 8x8) -- widening to 10-bit needs those lifted first. +`cargo test -p ec-av1 --lib cdef_and_sub16` -> ok, 1 passed / 0 failed. + +## Other +* `dump_stage`/`dump_stage16` wrote `.f0` for EVERY frame (each overwrote the last), so + `EC_AV1_POSTDEBLOCK_DUMP`/`POSTCDEF_DUMP` were unusable for per-frame bisection. Now indexed + per env var (`dump_stage_idx`), matching aomdec's own `.fN`. +* New rung `EC_AV1_CDEF_DBG=1`: one line per filtered 8x8 luma unit + (`EC_CDEF mi_r= mi_c= x= y= sidx= dir= var= t= pri= sec= damp=`). +* Class sweep for "per-8x8 map read at the top-left mi only under sub-8x8 partitions": the skip + grid is written by every OTHER leaf path (grep `fill_skip_grid`), `decode_inter_block8` was the + only writer missing; `is_skip_txfm` already gathers all four cells; the deblock/tx grid has a + `fill_lf_grid` at every one of those sites including both `decode_inter_block8` exits. +* Not done: `--tile-columns=1` arm on the new gate (COMMON neighbour-map rule) -- deferred.