diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index e730653c..485ea079 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -266,18 +266,36 @@ pub const EOB_PT_128_CHROMA_Q3: [u16; 9] = [ 24313, 26062, 28385, 30107, 31217, 31898, 32345, 32768, 0, ]; -/// `av1_default_eob_multi512_cdfs[*][1][*]` (`token_cdfs.h:874-901`, -/// lane-sbpart): the end-of-block group of a CHROMA transform with 512 coded -/// positions -- what a 32x16/16x32 chroma transform has (the chroma plane of -/// an intra `PARTITION_HORZ`/`VERT` 64x32/32x64 superblock strip, whose luma -/// coefficients truncate to the 64x64-superblock's own 32x32 corner-scan -/// (`TxbSet::Luma64`) but whose *chroma* plane, at 32x16, is small enough -/// that no truncation applies). Unlike every other `EOB_PT_*` table here, -/// libaom's default is the exact same flat distribution at all four -/// q-contexts and both `eob_multi_size` selectors (`token_cdfs.h` rows), so -/// one constant covers every q-context -- no `_Q0`/`_Q1`/`_Q3` siblings. +/// `av1_default_eob_multi512_cdfs[2][1][0]` (`token_cdfs.h:874-901`, +/// lane-part32 r4): the end-of-block group of a CHROMA transform with 512 +/// coded positions -- what a 32x16/16x32 chroma transform has (the chroma +/// plane of an intra `PARTITION_HORZ`/`VERT` 64x32/32x64 superblock strip, +/// whose luma coefficients truncate to the 64x64-superblock's own 32x32 +/// corner-scan (`TxbSet::Luma64`) but whose *chroma* plane, at 32x16, is +/// small enough that no truncation applies). +/// +/// lane-sbpart originally transcribed the `[1][1]` row -- the +/// `TX_CLASS_HORIZ`/`VERT` (1D) sibling, whose default IS the flat +/// `3277, 6554, ...` ramp at every q-context -- and wrote that flatness into +/// this comment as a property of the whole table. The 2D row this decoder +/// actually reads is q-dependent like every other `EOB_PT_*` family, so a +/// real `--cq-level=45` stream (q-context 3) read the wrong CDF and desynced +/// the tile at the first 32x16 chroma transform of the first SB-level +/// HORZ/VERT strip. pub const EOB_PT_512_CHROMA: [u16; 11] = [ - 3277, 6554, 9830, 13107, 16384, 19661, 22938, 26214, 29491, 32768, 0, + 12015, 14769, 19588, 22052, 24222, 25812, 27300, 29219, 32114, 32768, 0, +]; +/// [`EOB_PT_512_CHROMA`], q-context 0 (`base_q_idx` 0..=20). +pub const EOB_PT_512_CHROMA_Q0: [u16; 11] = [ + 5095, 6446, 9996, 13354, 16017, 17986, 20919, 26129, 29140, 32768, 0, +]; +/// [`EOB_PT_512_CHROMA`], q-context 1 (`base_q_idx` 21..=60). +pub const EOB_PT_512_CHROMA_Q1: [u16; 11] = [ + 7265, 9979, 15819, 19250, 21780, 23846, 26478, 28396, 31811, 32768, 0, +]; +/// [`EOB_PT_512_CHROMA`], q-context 3 (`base_q_idx` 121..=255). +pub const EOB_PT_512_CHROMA_Q3: [u16; 11] = [ + 21093, 23043, 25742, 27658, 29097, 29716, 30073, 30820, 31956, 32768, 0, ]; /// `Default_Dc_Sign_Cdf[2][0]` (spec 9.4): the sign of a luma DC coefficient, diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 330dcad8..c5d454c5 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -1010,9 +1010,13 @@ impl Cdfs { cdf::EOB_PT_128_CHROMA, cdf::EOB_PT_128_CHROMA_Q3, ), - // Flat default at every q-context (see the constant's own doc - // comment) -- no `pick()` needed. - eob_pt_512_chroma: cdf::EOB_PT_512_CHROMA, + eob_pt_512_chroma: pick( + q_ctx, + cdf::EOB_PT_512_CHROMA_Q0, + cdf::EOB_PT_512_CHROMA_Q1, + cdf::EOB_PT_512_CHROMA, + cdf::EOB_PT_512_CHROMA_Q3, + ), eob_extra_luma_32: pick( q_ctx, cdf::EOB_EXTRA_LUMA_32_Q0, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index c8d0bf28..ca717a46 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -758,6 +758,21 @@ pub(crate) fn sb_rect_hits() -> usize { SB_RECT_HITS.with(|c| c.get()) } +// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/ +// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64 +// strip) fired. Real aomenc picks these at 64 even with +// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is +// the counter the gate hard-asserts. +thread_local! { + static SB_AB_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`SB_AB_HITS`]. +pub(crate) fn sb_ab_hits() -> usize { + SB_AB_HITS.with(|c| c.get()) +} + // lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane // dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the // running-vs-stale-snapshot bug this round fixed is exercised by a gate, not @@ -1370,7 +1385,7 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> (TxClass::TwoD, _) | (_, None) => coding.eob_pt, (_, Some(class1)) => class1, }; - if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && eob_pt.len() == 12 { + if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() { let (range, value) = dec.debug_state(); eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}"); } @@ -1647,8 +1662,16 @@ fn read_coeffs_rect( sign_ctx: usize, default_tx_type: TxType, ) -> Result<(Vec, TxType)> { + let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some(); let mut grid = vec![0i32; w * h]; let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; + if ec_trace_coeff { + let (rng, _) = dec.debug_state(); + eprintln!( + "EC_COEFF_STEP tag=all_zero ctx={skip_ctx} all_zero={} rng={rng}", + all_zero as i32 + ); + } if all_zero { return Ok((grid, TxType::DctDct)); } @@ -1664,16 +1687,35 @@ fn read_coeffs_rect( )); } let eob = read_eob(dec, coding, TxClass::TwoD); + if ec_trace_coeff { + let (rng, _) = dec.debug_state(); + eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={rng}"); + } let mut levels = vec![0i32; w * h]; for scan_idx in (0..eob).rev() { let pos = scan[scan_idx] as usize; let (row, col) = (pos / w, pos % w); let level = if scan_idx == eob - 1 { let ctx = eob_coeff_ctx(scan_idx, w * h); - dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1 + let l = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1; + if ec_trace_coeff { + let (rng, _) = dec.debug_state(); + eprintln!( + "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={} rng={rng}", + l - 1 + ); + } + l } else { let ctx = base_ctx_rect(&levels, w, h, row, col); - dec.symbol(&mut coding.base[ctx]) as i32 + let l = dec.symbol(&mut coding.base[ctx]) as i32; + if ec_trace_coeff { + let (rng, _) = dec.debug_state(); + eprintln!( + "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={l} rng={rng}" + ); + } + l }; let level = if level > NUM_BASE_LEVELS { let ctx = br_ctx_rect(&levels, w, h, row, col); @@ -1681,6 +1723,12 @@ fn read_coeffs_rect( let mut sent = 0; loop { let k = dec.symbol(&mut coding.br[ctx]) as i32; + if ec_trace_coeff { + let (rng, _) = dec.debug_state(); + eprintln!( + "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={rng}" + ); + } level += k; sent += BR_STEP; if k < BR_STEP || sent >= COEFF_BASE_RANGE { @@ -1693,6 +1741,10 @@ fn read_coeffs_rect( }; levels[pos] = level; } + if ec_trace_coeff { + let (rng, _) = dec.debug_state(); + eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}"); + } for &pos in &scan[..eob] { let level = levels[pos as usize]; if level == 0 { @@ -4499,6 +4551,15 @@ impl PlaneBuf { smooth_neighbor: bool, ) { let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach); + if std::env::var_os("EC_DEBUG_EDGES").is_some() { + eprintln!( + "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}", + above.as_ref().map(|a| (a.len(), a[0])), + left.as_ref().map(|l| l.len()), + left.as_ref().map(|l| l[0]), + self.tile_x0, self.tile_y0, self.true_width, self.true_height + ); + } let mut prediction = vec![0u16; bw * bh]; if let Some(fi_mode) = filter_intra { crate::intra::predict_filter_intra( @@ -7688,10 +7749,93 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( tx_select, )?; } + PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => { + // lane-part32 r4: the four superblock-level AB arms, each + // two 32x32 squares plus one 64x32/32x64 strip, in + // libaom's own `decode_partition` order (decodeframe.c: + // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL, + // BR; VERT_A = TL, BL, right strip; VERT_B = left strip, + // TR, BR). The pieces are exactly the ones already proven + // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and + // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above. + SB_AB_HITS.with(|c| c.set(c.get() + 1)); + macro_rules! square32 { + ($at:expr) => { + decode_block( + &mut dec, + &mut cdfs, + &mut neighbours, + $at, + BLOCK, + TxbSet::Luma32, + TxbSet::Chroma16, + TX32, + TX16, + (&scan32, &scan16), + true, + &mut y, + &mut u, + &mut v, + base_q_idx, + enable_filter_intra, + allow_screen_content_tools, + allow_intrabc, + &scan32, + &scan16, + &scan8, + &scan4, + tx_select, + reduced_tx_set, + )? + }; + } + macro_rules! strip64 { + ($at:expr, $bw:expr, $bh:expr) => { + decode_block_rect64( + &mut dec, + &mut cdfs, + &mut neighbours, + $at, + $bw, + $bh, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + )? + }; + } + let (br, bc) = (at.0 + 2, at.1 + 2); + match part { + PARTITION_HORZ_A => { + square32!(at); + square32!((at.0, bc)); + strip64!((br, at.1), 64, 32); + } + PARTITION_HORZ_B => { + strip64!(at, 64, 32); + square32!((br, at.1)); + square32!((br, bc)); + } + PARTITION_VERT_A => { + square32!(at); + square32!((br, at.1)); + strip64!((at.0, bc), 32, 64); + } + _ => { + strip64!(at, 32, 64); + square32!((at.0, bc)); + square32!((br, bc)); + } + } + } _ => { return Err(unsupported( - "a superblock-level partition type other than NONE or SPLIT (this \ - decoder's intra tile path codes only those two at 64x64)", + "a superblock-level 1:4 partition (PARTITION_HORZ_4/VERT_4 at 64x64, \ + four 64x16/16x64 strips)", )); } } diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index fb771602..98db1545 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -47,7 +47,7 @@ const REFUSALS: &[&str] = &[ "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)", + "a superblock-level 1:4 partition (PARTITION_HORZ_4/VERT_4 at 64x64, four 64x16/16x64 strips)", "a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed for square blocks only)", "a HORZ/VERT intra strip with a split transform (per-unit rect prediction is not ported)", "a block that actually uses a palette (UV) -- reconstruction is out of scope", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 94e56e1c..0f3aee67 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -9512,6 +9512,167 @@ mod tests { ); } + /// lane-part32 r4: a real `aomenc` stream whose superblock-level + /// partition decision is one of the four AB arms (`PARTITION_HORZ_A`/ + /// `_B`/`VERT_A`/`_B` at 64x64: two 32x32 squares plus one 64x32/32x64 + /// strip) must decode pixel-exact. Same recipe as the HORZ/VERT sibling + /// above with `--enable-ab-partitions=1`; `sb_ab_hits() > 0` is a HARD + /// assert, so a run where aomenc's RD never picked an AB arm fails + /// rather than passing vacuously. + #[test] + fn a_real_aomenc_stream_with_a_superblock_level_ab_partition_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_with_a_superblock_level_ab_partition_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 1usize); + let mut named_refusals = 0u32; + let mut matched = 0u32; + let n_attempts: u32 = std::env::var("EC_SBAB_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(40); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + let duration = frame_count as f64 / 25.0; + let source = + gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-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 args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--enable-rect-partitions=1", + "--enable-ab-partitions=1", + "--enable-1to4-partitions=0", + "--min-partition-size=32", + "--max-partition-size=64", + "--enable-restoration=0", + "--enable-palette=0", + "--deltaq-mode=0", + "--enable-filter-intra=0", + "--enable-cfl-intra=0", + "--enable-intrabc=0", + "--enable-tx-size-search=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .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: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" + ); + // r2: `--enable-ab-partitions=0` does NOT stop aomenc + // choosing an SB-level HORZ_A/HORZ_B/VERT_A/VERT_B + // (`partition_w64` value 4-7) even with + // `--min/max-partition-size=32/64` -- a real, separate + // encoder quirk (AB-at-64 is a different, unlanded + // capability, lane-partab's territory is 32x32 and + // below only) discovered live this round, not this + // lane's HORZ/VERT gap. Only NONE/SPLIT/HORZ/VERT + // (values 0-3) are this gate's territory; a real + // HORZ/VERT (1/2) must still decode pixel-exact, which + // `sb_rect_hits() > 0` below hard-proves. + named_refusals += 1; + eprintln!("seed {seed} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if mismatched { + if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); + } + matched += 1; + } + assert!( + matched > 0, + "{NAME}: every attempt refused; the gate never decoded a stream" + ); + assert!( + crate::decode::sb_ab_hits() > 0, + "{NAME}: zero superblock-level AB blocks fired ({matched} matches, \ + {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run" + ); + eprintln!( + "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \ + {n_attempts}, sb_ab_hits={}", + crate::decode::sb_ab_hits() + ); + } + /// lane-part32 r2: prints the exact mismatch geometry (block coords, /// got/want pixels) of the pinned seed-42 stream captured off /// `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`