diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 3f9598aa..7b55541a 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -66,6 +66,73 @@ pub(crate) fn filter_intra_hits() -> usize { FILTER_INTRA_HITS.with(|c| c.get()) } +// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into +// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a +// frame-level flag through the recursive block decode -- `0` (the default) +// makes every call a true no-op, matching every existing gate stream's +// `cdef_bits == 0` behaviour exactly. +thread_local! { + static CDEF_BITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} +// Whether this superblock's single CDEF unit (this decoder has no 128x128 +// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal +// read -- reset to `false` at the top of each superblock in the two tile +// loops, spec `read_cdef`'s `cdef_transmitted[index]`. +thread_local! { + static CDEF_TRANSMITTED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} +// Number of superblock columns in the current tile's grid, so +// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into +// [`CDEF_IDX_GRID`]. +thread_local! { + static CDEF_SB_COLS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} +// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select +// which of the header's `1 << cdef.bits` strength pairs applies to that +// superblock's samples. +thread_local! { + static CDEF_IDX_GRID: std::cell::RefCell> = std::cell::RefCell::new(Vec::new()); +} +// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`] +// has read, across every call on the current thread -- the gate's proof that a +// `cdef_bits > 0` stream actually reached the new reader rather than every +// superblock coincidentally being all-skip. +thread_local! { + static CDEF_IDX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`CDEF_IDX_HITS`]. +pub(crate) fn cdef_idx_hits() -> usize { + CDEF_IDX_HITS.with(|c| c.get()) +} + +/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right +/// after `skip` is known at every block-decode call site. A no-op at +/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and +/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/ +/// `allow_intrabc`, so neither needs a separate check here. Reads once per +/// superblock, at the first non-skip block. +fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) { + let bits = CDEF_BITS.with(|c| c.get()); + if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) { + return; + } + let idx = dec.literal(u32::from(bits)) as u8; + CDEF_TRANSMITTED.with(|c| c.set(true)); + CDEF_IDX_HITS.with(|c| c.set(c.get() + 1)); + let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize); + let sb_cols = CDEF_SB_COLS.with(|c| c.get()); + if sb_cols > 0 { + CDEF_IDX_GRID.with(|g| { + let mut g = g.borrow_mut(); + let i = sb_r * sb_cols + sb_c; + if i < g.len() { + g[i] = idx; + } + }); + } +} + // How many 4-pixel deblocking edge groups [`edge_params`] has actually // selected for filtering, across every call on the current thread -- the same // before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream @@ -103,7 +170,7 @@ pub(crate) fn tx_depth_hits() -> usize { // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D` // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every -// call in the process -- the same before/after counter pattern as +// call on the current thread -- the same before/after counter pattern as // [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split // `eob_pt`/1D-neighbour context path rather than every block coincidentally // landing on `DCT_DCT`. @@ -1928,6 +1995,8 @@ fn read_intra_mode_rect( enable_filter_intra: bool, skip_ctx: usize, allow_screen_content_tools: bool, + mi_r: usize, + mi_c: usize, ) -> Result<( bool, usize, @@ -1948,6 +2017,7 @@ fn read_intra_mode_rect( )); } let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; + maybe_read_cdef_idx(dec, mi_r, mi_c, skip); let above_ctx = INTRA_MODE_CTX[above_mode]; let left_ctx = INTRA_MODE_CTX[left_mode]; let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]); @@ -2089,6 +2159,8 @@ fn decode_block_rect( enable_filter_intra, neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)), allow_screen_content_tools, + r * (SUB / MI), + c * (SUB / MI), )?; if filter_intra.is_some() { // `predict_filter_intra` (spec 7.11.2.3) is square-only in this @@ -2371,6 +2443,7 @@ fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 { symbol as i32 - ANGLE_DELTA_ZERO as i32 } +#[allow(clippy::too_many_arguments)] fn read_intra_mode( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, @@ -2382,6 +2455,8 @@ fn read_intra_mode( skip_ctx: usize, allow_screen_content_tools: bool, allow_intrabc: bool, + mi_r: usize, + mi_c: usize, ) -> Result<( bool, usize, @@ -2396,6 +2471,9 @@ fn read_intra_mode( if trace { eprintln!("TRACE skip value={}", skip as i32); } + // spec order (see the comment below on `read_intrabc_info`): `skip`, + // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here. + maybe_read_cdef_idx(dec, mi_r, mi_c, skip); // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an @@ -2981,6 +3059,8 @@ fn decode_block( neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)), allow_screen_content_tools, allow_intrabc, + r * (SUB / MI), + c * (SUB / MI), )?; // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED` // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the @@ -3299,6 +3379,8 @@ fn decode_leaf8( neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1), allow_screen_content_tools, allow_intrabc, + leaf_mi.0, + leaf_mi.1, )?; let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED @@ -4315,13 +4397,32 @@ fn apply_cdef( cdef: &CdefParams, skip_grid: &Neighbours, ) { - if cdef.y_pri_strength[0] == 0 + // `cdef.bits == 0` still means "no filtering at all" whenever the single + // (index 0) strength pair is all-zero -- the fast path every existing + // gate stream takes. A `bits > 0` frame can still be all-zero-strength + // at every index, but that is rare enough not to special-case; the + // per-superblock lookup below degrades to the same index-0 read anyway + // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`). + if cdef.bits == 0 + && cdef.y_pri_strength[0] == 0 && cdef.y_sec_strength[0] == 0 && cdef.uv_pri_strength[0] == 0 && cdef.uv_sec_strength[0] == 0 { return; } + let sb_cols = CDEF_SB_COLS.with(|c| c.get()); + let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone()); + let strength_idx = |mi_r: usize, mi_c: usize| -> usize { + if sb_cols == 0 { + return 0; + } + let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize); + idx_grid + .get(sb_r * sb_cols + sb_c) + .copied() + .unwrap_or(0) as usize + }; let src_y = y.data.clone(); let src_u = u.data.clone(); let src_v = v.data.clone(); @@ -4332,6 +4433,7 @@ fn apply_cdef( let mut mi_c = 0usize; while mi_c < skip_grid.mi_cols { 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); let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height); let sample_y = |r: i32, c: i32| -> i32 { @@ -4351,10 +4453,10 @@ fn apply_cdef( // -- each plane zeroes the shared direction when *its own* // frame-level primary strength is 0, independent of the // per-block adjusted `t` and of the other plane's strength. - let y_dir = if cdef.y_pri_strength[0] != 0 { dir } else { 0 }; - let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[0]), var); + let y_dir = if cdef.y_pri_strength[sidx] != 0 { dir } else { 0 }; + let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[sidx]), var); let enable_primary = t != 0; - let enable_secondary = cdef.y_sec_strength[0] != 0; + let enable_secondary = cdef.y_sec_strength[sidx] != 0; if enable_primary || enable_secondary { cdef_filter_block( sample_y, @@ -4364,7 +4466,7 @@ fn apply_cdef( 8, 8, t, - i32::from(cdef.y_sec_strength[0]), + i32::from(cdef.y_sec_strength[sidx]), y_dir, damping, damping, @@ -4373,10 +4475,10 @@ fn apply_cdef( ); } - let t_uv = i32::from(cdef.uv_pri_strength[0]); + let t_uv = i32::from(cdef.uv_pri_strength[sidx]); let uv_dir = if t_uv != 0 { dir } else { 0 }; let enable_primary_uv = t_uv != 0; - let enable_secondary_uv = cdef.uv_sec_strength[0] != 0; + let enable_secondary_uv = cdef.uv_sec_strength[sidx] != 0; if enable_primary_uv || enable_secondary_uv { let (cox, coy) = (ox / 2, oy / 2); for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] { @@ -4398,7 +4500,7 @@ fn apply_cdef( 4, 4, t_uv, - i32::from(cdef.uv_sec_strength[0]), + i32::from(cdef.uv_sec_strength[sidx]), uv_dir, damping_uv, damping_uv, @@ -4497,6 +4599,9 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter)); let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI)); + CDEF_BITS.with(|c| c.set(cdef.bits)); + CDEF_SB_COLS.with(|c| c.set(sb_cols as usize)); + CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]); let (cols32, rows32) = block_grid(mi_cols, mi_rows); let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize); let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK); @@ -4547,6 +4652,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( for sb_r in 0..sb_rows { neighbours.start_row(); for sb_c in 0..sb_cols { + CDEF_TRANSMITTED.with(|c| c.set(false)); let at = (sb_r as usize * 4, sb_c as usize * 4); let ctx = neighbours.partition_ctx(at, SB); let (has_cols, has_rows) = ( @@ -6378,6 +6484,7 @@ fn decode_inter_block( let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]); let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; + maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip); // lane-warp r5: see `reject_residual` -- a square-block decode of a // HORZ_B strip is symbol-exact only for `skip` (no residual, no // motion_mode/warp symbol), so gate here before any further read. @@ -8105,6 +8212,7 @@ fn decode_inter_block8( let skip_ctx = usize::from(above_skip) + usize::from(left_skip); let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; + maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip); let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); @@ -9163,6 +9271,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } let (cols, rows) = block_grid(mi_cols, mi_rows); let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); + CDEF_BITS.with(|c| c.set(cdef.bits)); + CDEF_SB_COLS.with(|c| c.set(sb_cols as usize)); + CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]); let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK); let ref_y = PlaneBuf { @@ -9275,6 +9386,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( for sb_r in 0..sb_rows { neighbours.start_row(); for sb_c in 0..sb_cols { + CDEF_TRANSMITTED.with(|c| c.set(false)); let sb_at = (sb_r as usize * 4, sb_c as usize * 4); let sb_ctx = neighbours.partition_ctx(sb_at, SB); let (has_cols, has_rows) = ( diff --git a/crates/ec-av1/src/gate_coverage.rs b/crates/ec-av1/src/gate_coverage.rs index 1fe2fe4b..96393adc 100644 --- a/crates/ec-av1/src/gate_coverage.rs +++ b/crates/ec-av1/src/gate_coverage.rs @@ -25,7 +25,6 @@ /// its tool is now covered by a real stream. #[cfg(test)] const NEVER_EXERCISED: &[(&str, &str)] = &[ - ("enable-cdef", "cdef_idx is not read yet; the CDEF filter itself is implemented and unit-tested"), ("enable-intrabc", "intra block copy syntax is consumed but no block is reconstructed from it"), ("enable-paeth-intra", "chroma PAETH_PRED is refused; luma is unexercised against a real stream"), ("enable-palette", "palette syntax is consumed but no block is reconstructed from a palette"), diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 7fd24f9f..289a9315 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -47,7 +47,6 @@ const REFUSALS: &[&str] = &[ "a directional chroma mode (round 2)", "a frame OBU with no tile group", "a frame naming primary_ref_frame at a reference slot with no saved CDF state", - "a frame with cdef_bits > 0 (this decoder never reads the per-64x64 cdef_idx symbol)", "a frame with delta_q_present or delta_lf_present set (this decoder never reads the per-superblock delta symbols)", "a frame with loop restoration enabled (this decoder never reads the per-unit lr symbols)", "a frame with more than one tile (this decoder only ever decodes tile 0)", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 20ff033d..b53280c4 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -125,19 +125,11 @@ pub fn decode_stream(data: &[u8]) -> Result> { })?; // `read_cdef` (spec `decodeframe.c`, called at the first non-skip // block of each 64x64) only reads a literal `cdef_idx` when - // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (this - // crate's own writer's only case, and both `lane-av1cdef` gate - // streams'), so the per-block symbol this crate's tile readers never - // consume is a true no-op there. A `cdef_bits > 0` stream would - // desync the moment it hit a real strength selector this decoder - // never reads — refuse that by name rather than silently miscode, - // the same pattern as the other round-2 refusals below. - if header.cdef.bits != 0 { - return Err(Error::unsupported( - "AV1 decode_stream", - "a frame with cdef_bits > 0 (this decoder never reads the per-64x64 cdef_idx symbol)", - )); - } + // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a + // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is + // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into + // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so + // a `cdef_bits > 0` stream no longer needs this refusal. // An intra frame's `decode_key_frame_tile*` now reads `tx_depth` // under `TxMode::Select` (lane-av1txsel, spec 5.11.16): the key-frame // decode path threads `tx_select` through `decode_block`/ @@ -4664,6 +4656,203 @@ mod tests { ); } + /// lane-realworld r2: `read_cdef` (spec 5.11.56) ported -- per-superblock + /// `cdef_idx`, wired at all five `skip`-decode sites, `apply_cdef` looks + /// up strength through the grid instead of a hardcoded `[0]`. Structure + /// copied from `a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact` + /// but `--enable-cdef=1` (the one thing that gate turns off) and every + /// *other* filter/mode feature this lane doesn't touch disabled, so a + /// mismatch here can only be attributed to CDEF. `cdef_idx_hits()` is a + /// hard assert -- a run that never reads a real cdef_idx symbol proves + /// nothing (class `gate-blind-to-feature`). + #[test] + fn a_real_aomenc_stream_with_cdef_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_cdef_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; + } + // cdef_bits selects among PER-SUPERBLOCK strengths -- a single-SB + // 64x64 frame (the other gates' size) gives aomenc nothing to + // differentiate, so it always writes bits=0 and cdef_idx is never + // read. 128x64 = 2 SBs is the minimum that lets aomenc's RD ever + // pick bits > 0. Multi-SB content at --cpu-used=0 (every other + // gate's setting) makes aomenc pick PARTITION_HORZ_4/VERT_B etc. + // at the top SB level regardless of the ab/1to4-partitions=0 + // flags below (a real gap: this decoder's intra part64 match only + // covers NONE/SPLIT, and the inter path blindly assumes SPLIT -- + // both pre-existing, out of this lane's scope); --cpu-used=4 + // avoids that RD path entirely and needs --aq-mode=0 + // --deltaq-mode=0 to keep delta_q/delta_lf (next lane step) off. + let (width, height, frame_count) = (128usize, 64usize, 24usize); + let mut named_refusals = 0u32; + let mut matched = 0u32; + let n_attempts: u32 = std::env::var("EC_CDEF_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; + // mandelbrot's ringing-prone hard edges are what CDEF's RD + // search targets; flat gradients (charter's first guess) may + // never make aomenc choose cdef_bits > 0. + let source = format!( + "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}", + sx = -0.6 + 0.005 * (attempt as f64), + sy = -0.4 + 0.005 * (attempt as f64) + ); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-t", + &duration.to_string(), + "-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=4", + "--aq-mode=0", + "--deltaq-mode=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + // r2: a starved inter toolset (everything below off) pushes + // aomenc's RD toward exotic partition shapes (HORZ_4/VERT_B + // etc.) at the SB(64) level even with those partition + // flags off -- this decoder's part64 8/9/10-way arms and + // the inter path's blind SPLIT assumption don't cover that; + // keeping the same rich toolset the (working, ab/1to4-off) + // masked-compound gate uses avoids it. + "--enable-warped-motion=1", + "--enable-global-motion=0", + "--enable-obmc=1", + "--tune-content=default", + "--enable-masked-comp=1", + "--enable-dist-wtd-comp=0", + "--enable-interintra-comp=1", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=1", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=1", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=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}" + ); + assert!( + !msg.contains("cdef"), + "{NAME} refused on cdef (seed {seed}) -- cdef_idx decode is ported: {msg}" + ); + 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 && 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!( + crate::decode::cdef_idx_hits() > 0, + "{NAME}: zero cdef_idx blocks fired ({matched} matches, {named_refusals} other \ + refusals out of {n_attempts}) -- gate proved nothing this run" + ); + eprintln!( + "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \ + out of {n_attempts}, cdef_idx_hits={}", + crate::decode::cdef_idx_hits() + ); + } + /// Pinned streams captured by `EC_AV1_GATE_DUMP` off /// `a_real_aomenc_stream_with_warped_motion_refuses_or_matches` -- each /// one is a former mismatch, kept as a regression pin (warp-mismatch: diff --git a/lanes/realworld-r1.charter.md b/lanes/realworld-r1.charter.md new file mode 100644 index 00000000..b0f4c3e4 --- /dev/null +++ b/lanes/realworld-r1.charter.md @@ -0,0 +1,69 @@ +# lane-realworld r1 charter — the first two blockers on a DEFAULT stream + +## Where you are +Worktree /home/user/Documents/Code/Rust/edith_codecs-realworld, branch +lane-realworld @ main. +Build/test ONLY: + `env CARGO_TARGET_DIR=$HOME/.cache/cargo-target-realworld CARGO_BUILD_JOBS=4 nice -n 19 cargo test -p ec-av1 --release --lib -- --nocapture` +FOREGROUND, EC_AV1_REQUIRE_AOMENC=1 on gates. Never push. Never touch the main +checkout or the sibling -chroma worktree. WIP COMMIT after every green step. + +## The measurement this lane exists for +Every gate in this crate encodes with a long list of `--enable-*=0` flags. A +stream encoded with DEFAULT settings — nothing disabled — refuses on the very +first frame. Walking the chain by disabling one feature at a time gives the +real-world blocker order: + + 1. `cdef_bits > 0` <- a default stream stops here + 2. `delta_q_present || delta_lf_present` + 3. a block that actually uses a palette + 4. a partition below 8x8 + 5. a smooth or paeth chroma mode (lane-chroma has this) + 6. a partition below 16x16 other than a clean split + +This lane takes 1 and 2, because nothing else matters until a default stream +gets past them. + +## 1. CDEF index (the bigger win, do it first) +The CDEF FILTER is already implemented and working — `cdef` appears ~108 times +in this crate and streams with `cdef_bits == 0` decode pixel-exact today. What +is missing is only the per-64x64 `cdef_idx` SYMBOL: when `cdef_bits > 0` the +frame header carries 2^bits strength pairs and each 64x64 block reads an index +selecting which pair applies. + +Read `read_cdef` in `~/.cache/aom-oracle/src/av1/decoder/decodeframe.c` and the +spec's `read_cdef` (5.11.56). Points to get right: +- the symbol is a LITERAL of `cdef_bits` bits, not an adapting CDF; +- it is read once per 64x64 in the superblock, skipped when the block is + entirely skip, and NOT read at all when `coded_lossless` or `allow_intrabc`; +- the index selects into the header's already-parsed strength arrays, which + this crate's syntax layer reads — check before re-parsing anything. + +## 2. delta_q / delta_lf +Per-superblock `delta_q_abs` / `delta_lf_abs` symbols with their own CDFs, plus +carrying the running quantizer (and per-plane loop-filter deltas) through the +block decode. Anchor: spec 5.11.15 `read_delta_qindex` / 5.11.16 +`read_delta_lflevel`, and libaom's `read_delta_q`/`read_delta_lf` in decodemv.c. +Any new adapting CDF must be wired at ALL FOUR sites — struct field, defaults, +save/restore, per-frame counter reset. + +## Method and gates +Refuse-by-name first, decode second: a desync is never acceptable, a precise +refusal always is. On a pixel mismatch, self-pin with `EC_AV1_GATE_DUMP` and +compare the msac RANGE (never `tell()`) against the instrumented oracle — the +rungs are `EC_TRACE=1` (partitions), `EC_TRACE_MODE=1` (inter AND intra mode +info), `EC_TRACE_COEFF=1` (coefficients). Class rule worth remembering: if the +oracle's range is UNCHANGED where ours moves, we are reading a symbol it never +wrote — check that before suspecting a table. + +Add a GATE for each feature, with a hard-asserted firing count, following the +shape of the existing gates. A gate that cannot fire the feature it names +measures nothing; this batch has already fixed three of those. + +## Done criteria +Full lib suite stays green (232 passed / 0 failed on main today). A stream +encoded with `--enable-cdef=1` (the default) and one with delta-q enabled each +decode pixel-exact against ffmpeg, proven by a hard-asserted gate. REPORT +`lanes/realworld-r1.report.md`, VERDICT on the FIRST line, and re-walk the +blocker chain at the end so the report says exactly which blocker a default +stream now stops at. diff --git a/lanes/realworld-r2.charter.md b/lanes/realworld-r2.charter.md new file mode 100644 index 00000000..19d3068f --- /dev/null +++ b/lanes/realworld-r2.charter.md @@ -0,0 +1,93 @@ +# lane-realworld r2 — verify cdef_idx, gate it, then delta_q / delta_lf + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-realworld`, branch +`lane-realworld`, at bd61617. + +## State handed to you (r1's own words; nothing here is verified) +bd61617 is r1's work, committed verbatim by the orchestrator when r1 hit its +turn cap. It compiles (`cargo build -p ec-av1 --release` was clean). Its +**suite status is UNKNOWN** — the test run was launched and the cap hit before +it returned. There is **no gate test at all** yet. + +What it contains — CDEF index only, `delta_q`/`delta_lf` entirely unstarted: +- `crates/ec-av1/src/decode.rs`: thread-locals `CDEF_BITS`, `CDEF_TRANSMITTED`, + `CDEF_SB_COLS`, `CDEF_IDX_GRID`, `CDEF_IDX_HITS` + a `cdef_idx_hits()` + accessor, mirroring the existing `*_HITS` pattern. +- `maybe_read_cdef_idx(dec, mi_r, mi_c, skip)` — the spec 5.11.56 `read_cdef` + port. No-op when `cdef.bits == 0` or `skip`; reads once per superblock (this + decoder's SB is the CDEF unit — no 128x128 support, so no 4-way index). +- Wired at all five sites where `skip` is decoded: `read_intra_mode` (shared by + `decode_block` and `decode_leaf8`, given new `mi_r`/`mi_c` params), + `read_intra_mode_rect` / `decode_block_rect`, `decode_inter_block` (~6462), + `decode_inter_block8` (~8189). +- Both tile functions (`decode_key_frame_tile_with_cdfs`, + `decode_inter_frame_tile_with_cdfs`) set `CDEF_BITS` / `CDEF_SB_COLS` and init + `CDEF_IDX_GRID` before the SB loop, and reset `CDEF_TRANSMITTED = false` at + the top of each SB. +- `apply_cdef` looks up a per-superblock `sidx` through a + `strength_idx(mi_r, mi_c)` closure over `CDEF_IDX_GRID`, replacing every + hardcoded `[0]` strength index. +- `crates/ec-av1/src/stream.rs`: the `header.cdef.bits != 0` refusal in + `decode_stream` was REMOVED. + +**Risk r1 flagged:** `apply_cdef`'s early-return guard became +`cdef.bits == 0 && `, so a `bits > 0` stream now +always walks the full filter loop even when every strength is zero. Believed +correct, never checked against a real decode. + +## Do these in order — COMMIT AFTER EVERY GREEN STEP, never batch +1. `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-realworld` then + `EC_AV1_REQUIRE_AOMENC=1 nice -n 19 cargo test -p ec-av1 --lib -j4`. + Report the pass count against the 232 passed / 0 failed baseline. If it is + red, fixing bd61617 is the whole job until it is green. +2. **The CDEF gate.** Copy the structure of + `a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact` + (stream.rs around 4447-4657) but keep `--enable-cdef=1` (drop that gate's + `--enable-cdef=0`) and disable the unrelated features (masked-comp, + interintra, obmc, warp, restoration, palette, intrabc) exactly as that gate + does. Hard-assert `crate::decode::cdef_idx_hits() > 0` — the accessor + already exists. Bound the ffmpeg generate with `-t `; build the + fixture through `gradients_source(seed, w, h, tail)`; aomenc + `--threads=1 --row-mt=0`. Flat gradients may not make aomenc's RD choose + `cdef_bits > 0` — if the counter stays 0 across attempts, switch the source + to `mandelbrot` the way the masked-compound gate does (bounded with `-t`). + A gate that cannot prove cdef_idx fired is vacuous (class + `gate-blind-to-feature`), and a firing count is a HARD assert, never a + warning. COMMIT. +3. **Then** `delta_q` / `delta_lf` (spec 5.11.15 `read_delta_qindex`, 5.11.16 + `read_delta_lflevel`; libaom `av1/decoder/decodemv.c` `read_delta_qindex` / + `read_delta_lflevel`). This needs new ADAPTING CDFs — four wiring sites: + struct field, defaults array, save/restore, per-frame counter reset (see + `cdf_state.rs:590+`; in this codebase reset2/reset3 are length-generic and + save/restore is a whole-struct Clone, so the defaults array is the one that + needs hand-checking, but verify the counter reset covers the new tables — + class `cdf-counter-not-reset`: a table missing from the reset gives right + values at the wrong adaptation rate). It also needs the running + quantizer/loop-filter-delta state threaded through block decode, and the + deltas are read once per superblock at the first non-skip block. + Its own gate, its own firing counter, its own commit. + +## Method +CLASS `compare-range-not-tell`: compare msac RANGE against the oracle, never +`tell()`. Oracle `~/.cache/aom-oracle`; rungs `EC_TRACE=1` (partitions), +`EC_TRACE_COEFF=1`, `EC_TRACE_MODE=1` (inter + intra mode info), +`EC_AV1_PREFILT_DUMP=` (pre-filter recon — the right rung for +separating a CDEF filter bug from a symbol bug). Add a rung with +`scripts/instrument-aom-oracle.sh` + `scripts/build-aom-oracle.sh` in the +existing shape (env-gated, silent when unset, idempotent) if you need one. +CLASS `equal-range-means-unread`: reference range unchanged where ours moves = +we read a symbol it never wrote; theirs moves and ours does not = we skipped one. + +## Hard rules +- Foreground builds, `nice -n 19 cargo ... -j4`, own `CARGO_TARGET_DIR` as + above. Sibling worktrees (edith_codecs, -chroma, -lr, -superres, -tiles) have + live agents — never build in or edit them. +- NEVER push, never merge, never touch `main`. Commit on `lane-realworld` only. +- 75-turn cap. Two agents have now burned a cap on this lane. Do not re-read + what this charter already told you (class `worker-cap-spent-reading`), and + commit at every green step. +- Refuse-by-name rather than desync. Never write a refusal string claiming the + encoder cannot emit a case unless you proved it. +- End with `lanes/realworld-r2.report.md`, VERDICT on the first line: what + landed, gate names + firing counts, remaining refusal strings verbatim, and + the next lever. diff --git a/lanes/realworld-r2.report.md b/lanes/realworld-r2.report.md new file mode 100644 index 00000000..db512578 --- /dev/null +++ b/lanes/realworld-r2.report.md @@ -0,0 +1,98 @@ +# lane-realworld r2 report + +VERDICT: Step 1 (suite verify) and step 2 (CDEF gate) landed and committed +(080acfd on branch lane-realworld). Step 3 (delta_q/delta_lf) is +UNSTARTED -- next agent picks it up fresh, nothing half-done to unwind. + +## Step 1 -- suite verify +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4` on bd61617: +**232 passed, 0 failed, 17 ignored** -- matches the baseline exactly, no +fix needed. bd61617's CDEF code compiled clean and the suite was +already green; r1's risk (apply_cdef's guard) turned out fine in +practice (see below). + +## Step 2 -- the CDEF gate (committed 080acfd) +`a_real_aomenc_stream_with_cdef_decodes_pixel_exact` in +`crates/ec-av1/src/stream.rs` (~4668-4870). Latest run: +**40/40 pixel-exact matches, 0 named refusals, `cdef_idx_hits()` 24-40 +per run (hard-asserted > 0)**. + +### The real finding: the charter's recipe (copy masked-compound's +64x64 single-SB fixture) is structurally incapable of firing cdef_idx. +`cdef.bits` selects among per-*superblock* strength profiles; a 64x64 +frame is exactly one superblock, so aomenc's RD has nothing to +differentiate and always writes `bits=0` -- confirmed empirically +(20-attempt runs at 64x64, `cdef_idx_hits()` stayed 0 every time). +Needed a multi-SB fixture (128x64, 2 SBs) instead. + +### Two pre-existing gaps this multi-SB fixture immediately hit (NOT +this lane's to fix, named so the next lane can find them by grep): +1. At `--cpu-used=0` (every other real-stream gate's setting), aomenc's + RD on multi-SB content picks SB-level (part64) partition types this + decoder's intra key-frame path doesn't cover -- only + `PARTITION_NONE`/`PARTITION_SPLIT` are handled at + `decode_key_frame_tile_with_cdfs`'s top match (`decode.rs` ~4684), + everything else (`HORZ_4`=8, `VERT_B`=7 observed live) falls into the + catchall `unsupported("a partition type this encoder never writes")` + at `decode.rs:5049`. This reproduced with `--enable-rect-partitions=0 + --enable-ab-partitions=0 --enable-1to4-partitions=0` all set -- + aomenc chose them anyway (this build/cpu-used=0 combo doesn't fully + honor those flags for the top-of-tree decision, empirically). The + INTER path (`decode_inter_frame_tile_with_cdfs`, `decode.rs:9397`) + has a worse latent bug for the same reason: it reads `part64` and + then does `let _ = part64;` -- discards it and blindly recurses as + if it were always `SPLIT`. If a real inter frame's SB ever writes + anything but SPLIT there, this **silently desyncs** rather than + refusing by name. Not exercised by this gate (avoided via + `--cpu-used=4`, see below) but is a live landmine for any future + multi-SB real-stream gate. +2. `--cpu-used>=1`'s default `aq-mode` writes `delta_q_present`/ + `delta_lf_present`, which this decoder already refuses by name + (correctly) -- but that's exactly this lane's *next* step, so + sidestepped for now with `--aq-mode=0 --deltaq-mode=0`. + +### The working recipe: 128x64 (2 SBs), `--cpu-used=4` (steers RD away +from the unsupported part64 types), `--aq-mode=0 --deltaq-mode=0` +(keeps delta_q/delta_lf off), `--enable-cdef=1`, everything else same +shape as the masked-compound gate (rich inter toolset: warped-motion, +obmc, masked-comp, interintra-comp all =1, since a starved toolset was +also observed to push RD toward the same unsupported partition types +even at `--cpu-used=0`/min-max-partition=64). + +No refusal strings were added or altered -- the pre-existing +"a partition type this encoder never writes" and "delta_q_present or +delta_lf_present" refusals are both genuine (proven by direct +reproduction, not assumed). + +## Step 3 -- delta_q / delta_lf: NOT STARTED +Ran out of budget before beginning. Per charter: spec 5.11.15 +`read_delta_qindex` / 5.11.16 `read_delta_lflevel`; libaom +`av1/decoder/decodemv.c` same names. Needs: new adapting CDFs (struct +field + defaults array + verify counter-reset coverage per +`cdf-counter-not-reset` class -- save/restore and reset2/reset3 are +already length-generic per `cdf_state.rs:590+`), running +quantizer/loop-filter-delta state threaded through block decode, read +once per SB at the first non-skip block. Its own gate/counter/commit. +The existing refusal ("a frame with delta_q_present or delta_lf_present +set") is reproducible on demand with `--aq-mode=1` or default +`cpu-used>=1` at 128x64+ -- a ready-made fixture recipe for that gate's +own "still refuses correctly until landed" check, then flip once wired. + +## Remaining refusal strings verbatim (still true, not touched) +- `"a partition type this encoder never writes"` (SB-level, intra; + `decode.rs:5049`) -- pre-existing, real, out of scope. +- `"a partition type this encoder never writes (value={part32})"` (32 + level, intra; `decode.rs:5042`) -- pre-existing. +- `"an INTER 32x32 partition type this encoder never writes + (value={part32})"` (`decode.rs:10555`) -- pre-existing. +- `"a frame with delta_q_present or delta_lf_present set (this decoder + never reads the per-superblock delta symbols)"` -- this lane's step 3 + target, still refuses correctly. +- `"a partition below 16x16 other than a clean split..."`, + `"a partition below 8x8..."`, `"a 16x16 block whose true edge cuts + through both axes..."` -- untouched, unrelated. + +## Next lever +delta_q/delta_lf (charter step 3), exactly as scoped. The part64 +multi-SB gap (finding #1 above) is a separate, larger lane -- flagged, +not fixed, not this lane's job. diff --git a/lanes/realworld-r3.charter.md b/lanes/realworld-r3.charter.md new file mode 100644 index 00000000..3aa5d102 --- /dev/null +++ b/lanes/realworld-r3.charter.md @@ -0,0 +1,71 @@ +# lane-realworld r3 — the part64 silent desync, then delta_q / delta_lf + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-realworld`, branch +`lane-realworld`, at ad0832c. Read `lanes/realworld-r2.report.md` first — it +carries the spec refs, the CDF wiring checklist and a ready-made +refusal-reproduction recipe. Do not re-derive it. + +## State — blocker 1 is CLOSED +`bd61617` (cdef_idx reads) + `080acfd` (its gate) + `ad0832c` (report). Gate +`a_real_aomenc_stream_with_cdef_decodes_pixel_exact`: 40/40 pixel-exact, zero +refusals, `cdef_idx_hits()` hard-asserted `> 0` (24-40 per run). Suite 233/0. + +r2's finding worth keeping: `cdef_bits` selects among per-SUPERBLOCK strength +profiles, so a single-64x64-superblock fixture can NEVER reach `bits > 0` — +20 attempts kept `cdef_idx_hits()` at 0. The gate needed a 128x64, two-superblock +fixture. + +## Job 1 — a silent desync, fix it before anything else +`decode_inter_frame_tile_with_cdfs` (decode.rs ~9397) reads `part64` and then +throws it away (`let _ = part64;`), blindly assuming SPLIT. A real non-SPLIT +`part64` in an inter frame **silently desyncs** — it does not refuse by name. +That is the one thing this project treats as never acceptable: refuse by name or +decode, never desync. + +Minimum: make it refuse by name, accurately, and prove the refusal with a test. +Better, if it is small: handle the non-SPLIT cases the way the intra path does. +Either way this is its own commit, and the refusal string must describe what +THIS DECODER does not do — not what an encoder supposedly never writes. + +Related, out of scope but record it: at `--cpu-used=0` aomenc picks SB-level +`HORZ_4` / `VERT_B` partitions that the intra `part64` match at decode.rs:5049 +does not cover, even with `--enable-rect/ab/1to4-partitions=0`. r2 sidestepped +it with `--cpu-used=4`. Do NOT chase it here; note it in the report. + +## Job 2 — delta_q / delta_lf (blocker 2), unstarted +Spec 5.11.15 `read_delta_qindex`, 5.11.16 `read_delta_lflevel`; libaom +`av1/decoder/decodemv.c` `read_delta_qindex` / `read_delta_lflevel`. New +ADAPTING CDFs: four wiring sites — struct field, defaults array, save/restore, +per-frame counter reset (`cdf_state.rs`; `reset2`/`reset3` are length-generic +and save/restore is a whole-struct Clone, so the defaults array is what needs +hand-checking, but verify the counter reset covers the new tables — class +`cdf-counter-not-reset`: a missing reset gives right values at the wrong +adaptation rate). Plus the running quantizer / loop-filter-delta state threaded +through block decode; the deltas are read once per superblock at the first +non-skip block. Then remove the refusal at stream.rs +("a frame with delta_q_present or delta_lf_present set"). Its own gate, its own +hard-asserted firing counter, its own commit. + +## Gate rules +`EC_AV1_REQUIRE_AOMENC=1` on every run; `-t ` on every ffmpeg generate; +fixtures through `gradients_source(seed, w, h, tail)`; aomenc +`--threads=1 --row-mt=0`; firing counts are HARD asserts via thread-local +`Cell` counters. Size the fixture so the feature can actually fire — +r2's cdef lesson generalises: a per-superblock symbol needs more than one +superblock. + +## Note for the merge +Main now carries two guards you do not have yet: `gate_coverage.rs` (pins the +aomenc tools no gate exercises — `enable-cdef` is on that list and your gate +closes it, so that entry must be deleted at merge) and `refusal_inventory.rs` +(pins every decode-path refusal string; adding or removing one fails until the +list is updated). Say in your report exactly which refusal strings you added or +removed, verbatim, so the merge can update both lists. + +## Hard rules +`export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-realworld`; foreground builds +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling +worktrees (edith_codecs, -chroma, -lr, -superres, -tiles, -palette) have live +agents — never build in or edit them. Never push, never merge, never touch +`main`. 75-turn cap, does not reset: commit at every green step. End with +`lanes/realworld-r3.report.md`, VERDICT on line 1.