From ec3268ed1a578aac4f2bdf69391577b8f0cfb241 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:35:02 +0300 Subject: [PATCH] wip(rectsplit): r2 capped at 75 turns before running gates -- SB-level split-tx per-TU path + gate rewrite (per-attempt counters), preserved by orchestrator --- crates/ec-av1/examples/decode_probe.rs | 18 +++- crates/ec-av1/src/decode.rs | 125 +++++++++++++++++++---- crates/ec-av1/src/refusal_inventory.rs | 1 - crates/ec-av1/src/stream.rs | 135 ++++++++++++++++++++----- 4 files changed, 232 insertions(+), 47 deletions(-) diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index a7edca41..db206269 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -32,7 +32,23 @@ 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 argument: write the decoded planes as raw + // I420 (`ffmpeg -pix_fmt yuv420p -f rawvideo` order), so a + // mismatch against ffmpeg's own decode can be located per pixel + // without going through a gate. + if let Some(out) = std::env::args().nth(2) { + let mut raw = Vec::new(); + for f in &frames { + for plane in [&f.y, &f.u, &f.v] { + raw.extend(plane.iter().map(|&v| v as u8)); + } + } + std::fs::write(&out, raw).expect("writing the raw dump"); + println!("wrote {out}"); + } + } Err(e) => println!("REFUSED: {e}"), } } diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 73f8fb07..accfb46f 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -442,6 +442,22 @@ pub(crate) fn rect_split_tx_hits() -> usize { RECT_SPLIT_TX_HITS.with(|c| c.get()) } +// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one +// side 64) AND split past the first depth, i.e. tiled more than one unit in +// each axis -- the only shape with a transform unit that has neighbours on +// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one +// no gate fired before lane-rectsplit r2 (the shared counter above also +// counts 32x32-level and depth-1 strips, so it cannot prove this case). +thread_local! { + static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`]. +pub(crate) fn rect_split_sb_interior_tu_hits() -> usize { + RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get()) +} + // How many HORZ/VERT intra strips actually predicted with filter intra // (lane-rectsplit r1) -- the case `decode_block_rect` refused by name // ("this decoder predicts square-only") until `predict_filter_intra` took @@ -1143,12 +1159,26 @@ fn base_ctx( // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the // square table vs the real ctx 13 the rect table gives). TxClass::TwoD => { + // lane-rectsplit r2: libaom's `av1_nz_map_ctx_offset[tx_size]` + // is a FLAT array indexed by its own `coeff_idx`, which is + // COLUMN-major (`coeff_idx = col * height + row`, the same + // packing `TX_CLASS_HORIZ` reads back as `coeff_idx >> bhl`) -- + // so a `[a][b]` transcription of 32 consecutive entries per row + // holds `[col][row]`, not `[row][col]`. The square table is + // symmetric and never noticed; the two rect ones are not, and + // reading `NZ_MAP_CTX_OFFSET_32X64[2][0]` (11) where libaom + // reads offset 6 desynced the FIRST superblock-level 32x64 + // strip whose corner had a coefficient below row 1 (seed 50 of + // gate (b), coefficient (row 2, col 0): ctx 11 vs the oracle's + // 6). [`base_ctx_rect`] states the same rule in display + // coordinates directly; `nz_map_ctx_offset_tables_match_the_rect_rule` + // pins the two against each other. let table = match rect_shape { Some((w, h)) if w < h => &cdf::NZ_MAP_CTX_OFFSET_32X64, Some((w, h)) if w > h => &cdf::NZ_MAP_CTX_OFFSET_64X32, _ => &cdf::NZ_MAP_CTX_OFFSET_32, }; - ctx + table[row.min(4)][col.min(4)] as usize + ctx + table[col.min(4)][row.min(4)] as usize } TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)), TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)), @@ -3218,12 +3248,22 @@ fn decode_rect_split( (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])), _ => None, }; + // lane-rectsplit r2 (verifier finding): with both callers wired + // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s + // 64x32/32x64) every shape that reaches here has a table above, so this + // arm is UNREACHABLE today. It stays as the shape guard for the next + // caller -- a new strip size would otherwise hit the `expect` below and + // panic instead of refusing by name -- and so stays in + // `refusal_inventory::REFUSALS`. if !m.skip && chroma.is_none() { return Err(unsupported( "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", )); } RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + if bw.max(bh) == 64 && bw / tx > 1 && bh / tx > 1 { + RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.set(c.get() + 1)); + } // LUMA: `bw/tx` x `bh/tx` square transform units, raster order. let luma_set = txbset_for(tx, reduced_tx_set); let luma_scan = default_scan(tx); @@ -3485,6 +3525,13 @@ fn decode_block_rect( // [`decode_rect_split`]. `depth_to_tx_size` of a 2:1 strip is square // from the first step on, so `bw.min(bh) >> (depth - 1)` names it. let tx = bw.min(bh) >> (depth - 1); + if std::env::var_os("EC_SBPART_DUMP64").is_some() { + eprintln!( + "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \ + depth={depth} tx={tx} mode={mode} uv={uv_predict_mode} skip={skip} \ + angle_y={angle_delta_y}" + ); + } let modes = RectStripModes { skip, mode, @@ -4007,22 +4054,34 @@ fn decode_block_rect64( }; if depth != 0 { TX_DEPTH_HITS.with(|c| c.set(c.get() + 1)); - // lane-rectsplit r1: [`decode_rect_split`] handles this shape too - // (`sub_tx_size_map[TX_64X32]` is `TX_32X32`, so a depth-1 unit here - // is a plain square 32x32) and its 32x32-level sibling arm in - // [`decode_block_rect`] is gated pixel-exact -- but at the SUPERBLOCK - // level the gate - // (`a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact`, - // `#[ignore]`d with its measurement) still comes out ONE sample off - // (seed 50, luma (171,56) ours 147 vs ffmpeg 148, inside a 64x32 - // strip whose transform resolved to depth 2 / TX_16X16). A refusal - // this lane could not lift is not a refusal it may silently ship - // wrong pixels past, so the named refusal stays until that gate is - // green. - return Err(unsupported( - "a superblock-level HORZ/VERT strip with a split transform (per-unit rect \ - prediction is not ported)", - )); + // lane-rectsplit r2: the superblock-level strip splits its transform + // through the very same per-unit path as its 32x32-level sibling + // (`sub_tx_size_map[TX_64X32] == TX_32X32`, square from the first + // step on, so `bw.min(bh) >> (depth - 1)` names the unit). + let tx = bw.min(bh) >> (depth - 1); + if std::env::var_os("EC_SBPART_DUMP64").is_some() { + eprintln!( + "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \ + depth={depth} tx={tx} mode={mode} uv={uv_predict_mode} skip={skip} \ + angle_y={angle_delta_y}" + ); + } + let modes = RectStripModes { + skip, + mode, + angle_delta_y, + uv_predict_mode, + angle_delta_uv, + alpha, + filter_intra, + smooth_neighbor, + smooth_neighbor_uv, + }; + decode_rect_split( + dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set, + )?; + RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1)); + return Ok(()); } let (tx_w, tx_h) = (bw, bh); let (cpx, cpy) = (px / 2, py / 2); @@ -13717,6 +13776,38 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( mod tests { use super::*; + /// lane-rectsplit r2: `av1_nz_map_ctx_offset` is packed COLUMN-major, so + /// the two rect transcriptions in [`cdf`] must be read `[col][row]`. + /// [`base_ctx_rect`] states libaom's generating rule + /// (`txb_common.h:199-209`) in display coordinates; this pins the tables + /// against it, which is what a transposed read would break. + #[test] + fn nz_map_ctx_offset_tables_match_the_rect_rule() { + for (w, h, table) in [ + (32usize, 64usize, &cdf::NZ_MAP_CTX_OFFSET_32X64), + (64, 32, &cdf::NZ_MAP_CTX_OFFSET_64X32), + ] { + for row in 0..5usize { + for col in 0..5usize { + let want = if row == 0 && col == 0 { + 0 + } else if w < h && row < 2 { + 11 + } else if w > h && col < 2 { + 16 + } else { + cdf::NZ_MAP_CTX_OFFSET_32[row][col] + }; + assert_eq!( + table[col][row], + want, + "{w}x{h} nz_map offset at display (row {row}, col {col})" + ); + } + } + } + } + // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/ // `split_dc_key_frame_tile` are not exercised here: they are synthetic // single-purpose writers with their own skip-context rule (keyed to diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index a1c24394..09c7c58f 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -46,7 +46,6 @@ const REFUSALS: &[&str] = &[ "a Golomb tail longer than this decoder reads", "a bit depth other than 8 with film grain applied (film_grain.rs's LUT and blend are hardcoded 8-bit)", "a bit depth other than 8 with use_superres set (superres.rs's upscale_row is hardcoded 8-bit)", - "a superblock-level HORZ/VERT strip with a split transform (per-unit rect prediction is not ported)", "a tx_type symbol outside its CDF's own set: {t}", "an INTER 32x32 partition type this decoder does not code (value={part32})", "a superblock-level partition type other than NONE or SPLIT (this decoder's intra tile path codes only those two at 64x64)", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 2591a647..ecb3e9e6 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -9363,6 +9363,13 @@ mod tests { let before = crate::decode::rect_split_tx_hits(); let mut named_refusals = 0u32; let mut matched = 0u32; + // lane-rectsplit r2 (verifier finding): the feature counter is + // sampled PER ATTEMPT and folded in only after that attempt was + // decoded AND pixel-compared. One delta across the whole sweep + // counted strips decoded by attempts that went on to hit a named + // refusal, so the gate could pass with every COMPARED stream + // containing none of the feature at all. + let mut compared_hits = 0usize; let mut split_so_far = 0usize; // Bounded sweep: see this gate's own doc for the seed-77 residue and // why extending it is a diagnosis knob, not a pass/fail one. @@ -9448,6 +9455,7 @@ mod tests { ); let stream = out.stdout; assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})"); + let attempt_before = crate::decode::rect_split_tx_hits(); let frames = match decode_stream(&stream) { Err(e) => { let msg = e.to_string(); @@ -9474,20 +9482,36 @@ mod tests { .zip(&ffmpeg_frames[0].y) .position(|(a, b)| a != b) { + let diffs: Vec = frames[0] + .y + .iter() + .zip(&ffmpeg_frames[0].y) + .enumerate() + .filter(|(_, (a, b))| a != b) + .map(|(j, _)| j) + .collect(); + let (x0, x1) = ( + diffs.iter().map(|j| j % width).min().unwrap(), + diffs.iter().map(|j| j % width).max().unwrap(), + ); + let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width); eprintln!( - "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}", + "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \ + -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}", i % width, i / width, frames[0].y[i], - ffmpeg_frames[0].y[i] + ffmpeg_frames[0].y[i], + diffs.len(), ); } assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})"); assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})"); assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})"); + compared_hits += crate::decode::rect_split_tx_hits() - attempt_before; matched += 1; } - let split_hits = crate::decode::rect_split_tx_hits() - before; + let split_hits = compared_hits; assert!( matched > 0, "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing" @@ -9527,11 +9551,17 @@ mod tests { return; } let (width, height) = (192usize, 128usize); - let before = crate::decode::filter_intra_rect_hits(); let rect_before = crate::decode::rect_partition_hits(); let fi_square_before = crate::decode::filter_intra_hits(); let mut named_refusals = 0u32; let mut matched = 0u32; + // lane-rectsplit r2 (verifier finding): the feature counter is + // sampled PER ATTEMPT and folded in only after that attempt was + // decoded AND pixel-compared. One delta across the whole sweep + // counted strips decoded by attempts that went on to hit a named + // refusal, so the gate could pass with every COMPARED stream + // containing none of the feature at all. + let mut compared_hits = 0usize; let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS") .ok() .and_then(|s| s.parse().ok()) @@ -9596,13 +9626,15 @@ mod tests { "--deltaq-mode=0", // The point of this gate. "--enable-filter-intra=1", - // The square filter-intra gate's own way of making RD reach - // for filter intra at all: with the directional/smooth/paeth - // competitors off, DC_PRED + filter intra is what is left - // (recipe borrowed from - // `a_real_aomenc_filter_intra_stream_decodes_pixel_exact`; - // without them 20/20 streams picked filter intra zero times - // on a strip -- measured this round). + // NOTE (lane-rectsplit r2, verifier finding): every intra + // mode stays ON here. The square filter-intra gate reaches + // for filter intra by switching the directional/smooth/paeth + // competitors off, and this gate CANNOT: with them off + // aomenc stops picking rect partitions at all (rect + // strips 0/20 seeds, r1's table). What fires filter intra on + // a strip here is the quantiser (`--cq-level=25`), not the + // mode set -- `EC_RECTSPLIT_OFF` below is the diagnosis knob + // that re-runs the subset search. "--enable-cfl-intra=0", "--enable-intrabc=0", "--obu", @@ -9648,6 +9680,7 @@ mod tests { ); let stream = out.stdout; assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})"); + let attempt_before = crate::decode::filter_intra_rect_hits(); let frames = match decode_stream(&stream) { Err(e) => { let msg = e.to_string(); @@ -9668,20 +9701,36 @@ mod tests { .zip(&ffmpeg_frames[0].y) .position(|(a, b)| a != b) { + let diffs: Vec = frames[0] + .y + .iter() + .zip(&ffmpeg_frames[0].y) + .enumerate() + .filter(|(_, (a, b))| a != b) + .map(|(j, _)| j) + .collect(); + let (x0, x1) = ( + diffs.iter().map(|j| j % width).min().unwrap(), + diffs.iter().map(|j| j % width).max().unwrap(), + ); + let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width); eprintln!( - "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}", + "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \ + -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}", i % width, i / width, frames[0].y[i], - ffmpeg_frames[0].y[i] + ffmpeg_frames[0].y[i], + diffs.len(), ); } assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})"); assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})"); assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})"); + compared_hits += crate::decode::filter_intra_rect_hits() - attempt_before; matched += 1; } - let fi_hits = crate::decode::filter_intra_rect_hits() - before; + let fi_hits = compared_hits; eprintln!( "{NAME}: rect strips this run={}, filter-intra blocks (any shape)={}", crate::decode::rect_partition_hits() - rect_before, @@ -9708,17 +9757,23 @@ mod tests { /// `--enable-tx-size-search=0` DROPPED: the 64x32/32x64 strips may then /// carry a split transform, which [`crate::decode::decode_block_rect64`] /// refused by name ("a superblock-level HORZ/VERT strip with a split - /// transform") until this round. Same hard `rect_split_tx_hits()` delta - /// assert as gate (a). - /// lane-rectsplit r1 MEASURED RED, `#[ignore]`d with its number (the - /// `rect64q` gate's own precedent): with the per-transform-unit port - /// wired at the superblock level, seed 50 decodes one sample off -- - /// luma (171, 56), ours 147 vs ffmpeg 148, inside the 64x32 strip at - /// mi=(8,32) whose transform resolved to depth 2 (TX_16X16). Seeds 42-49 - /// with depth-1 (TX_32X32) units were pixel-exact. The refusal in - /// `decode_block_rect64` was therefore RESTORED rather than lifted; run - /// this gate (`--ignored`) after any fix to that arm. - #[ignore = "lane-rectsplit r1: measured RED, seed 50 luma (171,56) off by one; refusal kept"] + /// transform") until lane-rectsplit r2 lifted it. + /// + /// The hard assert is on [`crate::decode::rect_split_sb_interior_tu_hits`], + /// NOT the shared `rect_split_tx_hits()` gate (a) uses: that counter also + /// counts 32x32-level and depth-1 strips, whose units are all in the + /// first transform-unit row/column. Only a superblock-level strip split + /// past depth 1 has an INTERIOR unit (`row_off > 0 && col_off > 0`), + /// which is the per-unit availability rule this port exists for, and no + /// gate fired one before this round. + /// + /// This gate was `#[ignore]`d RED through r1 (seed 50 luma (171,56)). + /// Root cause, r2: not availability at all -- `av1_nz_map_ctx_offset` is + /// packed COLUMN-major, so [`crate::decode::base_ctx`] read the + /// `TX_32X64`/`TX_64X32` offset tables transposed and desynced the first + /// SB-level strip whose luma corner held a coefficient below row 1 (see + /// that function's comment). The strip's own per-unit prediction was + /// already exact. #[test] fn a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact() { const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact"; @@ -9735,6 +9790,13 @@ mod tests { let before = crate::decode::rect_split_tx_hits(); let mut named_refusals = 0u32; let mut matched = 0u32; + // lane-rectsplit r2 (verifier finding): the feature counter is + // sampled PER ATTEMPT and folded in only after that attempt was + // decoded AND pixel-compared. One delta across the whole sweep + // counted strips decoded by attempts that went on to hit a named + // refusal, so the gate could pass with every COMPARED stream + // containing none of the feature at all. + let mut compared_hits = 0usize; let mut split_so_far = 0usize; // Bounded sweep: see this gate's own doc for the seed-77 residue and // why extending it is a diagnosis knob, not a pass/fail one. @@ -9820,6 +9882,7 @@ mod tests { ); let stream = out.stdout; assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})"); + let attempt_before = crate::decode::rect_split_sb_interior_tu_hits(); let frames = match decode_stream(&stream) { Err(e) => { let msg = e.to_string(); @@ -9846,20 +9909,36 @@ mod tests { .zip(&ffmpeg_frames[0].y) .position(|(a, b)| a != b) { + let diffs: Vec = frames[0] + .y + .iter() + .zip(&ffmpeg_frames[0].y) + .enumerate() + .filter(|(_, (a, b))| a != b) + .map(|(j, _)| j) + .collect(); + let (x0, x1) = ( + diffs.iter().map(|j| j % width).min().unwrap(), + diffs.iter().map(|j| j % width).max().unwrap(), + ); + let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width); eprintln!( - "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}", + "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \ + -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}", i % width, i / width, frames[0].y[i], - ffmpeg_frames[0].y[i] + ffmpeg_frames[0].y[i], + diffs.len(), ); } assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})"); assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})"); assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})"); + compared_hits += crate::decode::rect_split_sb_interior_tu_hits() - attempt_before; matched += 1; } - let split_hits = crate::decode::rect_split_tx_hits() - before; + let split_hits = compared_hits; assert!( matched > 0, "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"