diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs new file mode 100644 index 00000000..a7edca41 --- /dev/null +++ b/crates/ec-av1/examples/decode_probe.rs @@ -0,0 +1,38 @@ +//! Where does a real stream stop? Decode one AV1 file and print the answer. +//! +//! The gates in [`ec_av1::stream`] each pin one capability against one encoder +//! recipe. This asks the complementary question -- given a stream someone +//! actually produced, which refusal comes first -- and it is how the refusal +//! distribution in commit 2be815f was measured rather than reasoned about: +//! +//! ```text +//! aomenc --codec=av1 --obu -o s.obu --passes=1 --cpu-used=4 --limit=4 in.y4m +//! cargo run -p ec-av1 --example decode_probe -- s.obu +//! ``` +//! +//! Note `--obu`: [`ec_av1::stream::decode_stream`] takes a raw OBU stream, and +//! an IVF file decodes as zero frames rather than as an error. +//! +//! That run is also what disproved three refusal strings claiming an encoder +//! never writes a case it demonstrably writes, so this is a first-class +//! instrument, not a scratch file. +fn main() { + let Some(path) = std::env::args().nth(1) else { + eprintln!("usage: decode_probe "); + std::process::exit(2); + }; + let data = match std::fs::read(&path) { + Ok(data) => data, + Err(e) => { + eprintln!("{path}: {e}"); + std::process::exit(2); + } + }; + match ec_av1::stream::decode_stream(&data) { + 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()), + Err(e) => println!("REFUSED: {e}"), + } +} diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 4169b0e8..6f940f2c 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -21,7 +21,7 @@ //! too). Anything outside that refuses with [`Error::unsupported`] rather than //! silently miscoding. -use ec_av1_syntax::{CdefParams, LoopFilterParams}; +use ec_av1_syntax::{CdefParams, LoopFilterParams, TileInfo}; use ec_core::{Error, Result}; use crate::cdf; @@ -66,6 +66,117 @@ 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 key-frame luma blocks resolved `smooth_neighbor` (spec +// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after +// counter, proving a stream actually put a directional block next to a +// smooth-predicted neighbour rather than every block reading the (previously +// hardcoded `false`) edge-filter strength bucket unchanged. +thread_local! { + static SMOOTH_LUMA_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`SMOOTH_LUMA_HITS`]. +pub(crate) fn smooth_luma_hits() -> usize { + SMOOTH_LUMA_HITS.with(|c| c.get()) +} + +// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12), +// across every call on the current thread -- lane-chroma r3's own before/after +// counter, proving a stream actually exercised chroma's smooth/paeth +// predictor (the previously-refused round-2 gap) rather than every block +// landing on DC/CFL/directional. +thread_local! { + static SMOOTH_UV_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`SMOOTH_UV_HITS`]. +pub(crate) fn smooth_uv_hits() -> usize { + SMOOTH_UV_HITS.with(|c| c.get()) +} + +// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a +// full superblock walk over, across every call on the current thread -- +// lane-tiles r2's own gate-blind-to-feature guard: a gate over a +// multi-tile stream must prove more than one tile actually fired, not just +// that the stream carried tile_info.cols > 1. +thread_local! { + static TILE_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} +/// Current value of [`TILE_HITS`]. +pub(crate) fn tile_hits() -> usize { + TILE_HITS.with(|c| c.get()) +} + // 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 +214,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`. @@ -977,6 +1088,13 @@ fn default_intra_tx_type(mode: u8) -> TxType { } } +/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED` +/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own +/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth. +fn is_smooth_mode(mode: usize) -> bool { + (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode) +} + fn read_coeffs( dec: &mut SymbolDecoder, coding: &mut TxbTables, @@ -1268,6 +1386,17 @@ struct Neighbours { left: Vec<[Neighbour; 3]>, above_mode: Vec, left_mode: Vec, + /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma + /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec + /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the + /// luma one -- the same block can (and often does) code a different + /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`; + /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real + /// within-block neighbour finer than this grid) is luma-only -- a known, + /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs` + /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this). + above_uv_mode: Vec, + left_uv_mode: Vec, above_side: Vec, left_side: Vec, /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4) @@ -1364,6 +1493,15 @@ struct Neighbours { left_palette_size: Vec, above_palette_colors: Vec<[u16; 8]>, left_palette_colors: Vec<[u16; 8]>, + /// This tile's own top-left corner, in 4x4 mode-info units (spec + /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a + /// neighbour" check compares against this instead of literal `0`, since a + /// block at the tile's own top/left edge has no usable neighbour even + /// though a decoded block sits there in the picture (spec `decode_tile`'s + /// per-tile `clear_above_context`/`left_available`/`up_available`). + /// `0` for a single-tile frame, matching every existing caller exactly. + tile_row0_mi: usize, + tile_col0_mi: usize, } impl Neighbours { @@ -1375,6 +1513,8 @@ impl Neighbours { left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)], above_mode: vec![DC_PRED; cols], left_mode: vec![DC_PRED; rows], + above_uv_mode: vec![DC_PRED; cols], + left_uv_mode: vec![DC_PRED; rows], above_side: vec![SB; cols], left_side: vec![SB; rows], above_side_mi: vec![SB; cols * (SUB / MI)], @@ -1406,6 +1546,40 @@ impl Neighbours { left_palette_size: vec![0; rows], above_palette_colors: vec![[0u16; 8]; cols], left_palette_colors: vec![[0u16; 8]; rows], + tile_row0_mi: 0, + tile_col0_mi: 0, + } + } + + /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this + /// tile's own column span (`col1_mi` exclusive), plus recording + /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every + /// availability check below. Left context resets every superblock row + /// regardless of tile ([`Self::start_row`], already called once per SB + /// row by every caller) so it needs no tile-specific reset here. + fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) { + self.tile_row0_mi = row0_mi; + self.tile_col0_mi = col0_mi; + let end = col1_mi.min(self.above.len()); + for i in col0_mi.min(end)..end { + self.above[i] = Default::default(); + self.above_side_mi[i] = SB; + } + let (sc0, sc1) = ( + col0_mi / (SUB / MI), + (col1_mi / (SUB / MI)).min(self.above_mode.len()), + ); + for i in sc0.min(sc1)..sc1 { + self.above_mode[i] = DC_PRED; + self.above_side[i] = SB; + self.above_skip[i] = false; + self.above_skip_mode[i] = false; + self.above_inter[i] = false; + self.above_ref[i] = -1; + self.above_ref1[i] = None; + self.above_comp_group_idx[i] = 0; + self.above_compound_idx[i] = 0; + self.above_filter[i] = [3u8; 2]; } } @@ -1562,8 +1736,8 @@ impl Neighbours { /// with an absent neighbour contributing 0. The mi grid is per tile, so /// row/column 0 is a tile edge and has no neighbour on that axis. fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize { - usize::from(mi_r > 0 && self.skip_at(mi_r - 1, mi_c)) - + usize::from(mi_c > 0 && self.skip_at(mi_r, mi_c - 1)) + usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c)) + + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1)) } fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool { @@ -1580,6 +1754,7 @@ impl Neighbours { fn start_row(&mut self) { self.left.iter_mut().for_each(|l| *l = Default::default()); self.left_mode.iter_mut().for_each(|m| *m = DC_PRED); + self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED); self.left_side.iter_mut().for_each(|s| *s = SB); self.left_side_mi.iter_mut().for_each(|s| *s = SB); self.left_skip.iter_mut().for_each(|s| *s = false); @@ -1811,8 +1986,15 @@ impl Neighbours { /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`, /// not from this block's own side). - fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec; 3]) { - self.record_rect(at, side, side, mode, grids); + fn record( + &mut self, + at: (usize, usize), + side: usize, + mode: usize, + uv_mode: usize, + grids: &[Vec; 3], + ) { + self.record_rect(at, side, side, mode, uv_mode, grids); } /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in @@ -1826,15 +2008,18 @@ impl Neighbours { w: usize, h: usize, mode: usize, + uv_mode: usize, grids: &[Vec; 3], ) { let (r, c) = at; for cell in 0..w / SUB { self.above_mode[c + cell] = mode; + self.above_uv_mode[c + cell] = uv_mode; self.above_side[c + cell] = w; } for cell in 0..h / SUB { self.left_mode[r + cell] = mode; + self.left_uv_mode[r + cell] = uv_mode; self.left_side[r + cell] = h; } self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids); @@ -1933,12 +2118,15 @@ impl Neighbours { at: (usize, usize), side: usize, mode: usize, + uv_mode: usize, chroma_grids: [&[i32]; 2], ) { let (r, c) = at; for cell in 0..side / SUB { self.above_mode[c + cell] = mode; self.left_mode[r + cell] = mode; + self.above_uv_mode[c + cell] = uv_mode; + self.left_uv_mode[r + cell] = uv_mode; self.above_side[c + cell] = side; self.left_side[r + cell] = side; } @@ -2214,6 +2402,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, @@ -2234,6 +2424,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]); @@ -2253,7 +2444,7 @@ fn read_intra_mode_rect( None }; if (9..=12).contains(&uv_mode) { - return Err(unsupported("a smooth or paeth chroma mode (round 2)")); + SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1)); } let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1)); @@ -2307,8 +2498,8 @@ fn tx_size_context_rect( own_w: usize, own_h: usize, ) -> usize { - let above = mi_r > 0 && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w; - let left = mi_c > 0 && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h; + let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w; + let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h; usize::from(above) + usize::from(left) } @@ -2375,7 +2566,19 @@ 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), )?; + let smooth_neighbor = + is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]); + if smooth_neighbor { + SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); + } + // lane-chroma r3: chroma's own edge-filter-strength neighbour check + // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's + // `uv_mode`, not the luma one. + let smooth_neighbor_uv = + is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]); if filter_intra.is_some() { // `predict_filter_intra` (spec 7.11.2.3) is square-only in this // decoder (`assert_eq!(dst.len(), side*side)`) -- a real symbol was @@ -2441,6 +2644,7 @@ fn decode_block_rect( &vec![0i32; bw * bh], None, filter_intra, + smooth_neighbor, ); let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh)); u.reconstruct_rect( @@ -2454,6 +2658,7 @@ fn decode_block_rect( &vec![0i32; chroma_w * chroma_h], alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, + smooth_neighbor_uv, ); v.reconstruct_rect( cpx, @@ -2466,12 +2671,14 @@ fn decode_block_rect( &vec![0i32; chroma_w * chroma_h], alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, + smooth_neighbor_uv, ); neighbours.record_rect( at, bw, bh, mode, + uv_predict_mode, &[ vec![0i32; bw * bh], vec![0i32; chroma_w * chroma_h], @@ -2559,6 +2766,7 @@ fn decode_block_rect( &luma_residual, None, filter_intra, + smooth_neighbor, ); let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh)); let u_default_tx = default_intra_tx_type(uv_predict_mode as u8); @@ -2597,6 +2805,7 @@ fn decode_block_rect( &u_residual, alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, + smooth_neighbor_uv, ); let v_default_tx = default_intra_tx_type(uv_predict_mode as u8); let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); @@ -2634,8 +2843,9 @@ fn decode_block_rect( &v_residual, alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, + smooth_neighbor_uv, ); - neighbours.record_rect(at, bw, bh, mode, &[luma_levels, u_levels, v_levels]); + neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]); RECT_COEFF_HITS.with(|c| c.set(c.get() + 1)); } } @@ -2657,6 +2867,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, @@ -2676,6 +2887,8 @@ fn read_intra_mode( // decoder reads either way -- but refuse by name the moment it fires, // exactly the old behaviour. palette: Option<(usize, &[u16])>, + mi_r: usize, + mi_c: usize, ) -> Result<( bool, usize, @@ -2691,6 +2904,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 @@ -2750,7 +2966,7 @@ fn read_intra_mode( // bug in that fallback this lane's own scope does not cover. Keep it // refused here rather than ship a silently-wrong decode. if (9..=12).contains(&uv_mode) { - return Err(unsupported("a smooth or paeth chroma mode (round 2)")); + SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1)); } // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads @@ -2944,6 +3160,16 @@ struct PlaneBuf { /// real decoder's edge or reach reads. true_width: usize, true_height: usize, + /// This plane's own tile's top-left pixel origin (spec: intra prediction + /// never reaches across a tile boundary even though an earlier-decoded + /// tile's real pixels sit right there in the shared buffer) — set via + /// [`Self::set_tile_origin`] before each tile's own superblock walk, + /// `0` for the single-tile case. lane-tiles r2: only the left/top bound + /// is threaded (the two-tile column-split stage 1 fixture's tile always + /// ends at the frame's own right/bottom edge); a non-last tile's own + /// right/bottom reach bound is still open, tracked in the report. + tile_x0: usize, + tile_y0: usize, } /// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/ @@ -2955,6 +3181,15 @@ struct PlaneBuf { type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8]; impl PlaneBuf { + /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/ + /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0` + /// are already in this plane's own units (luma pixels for `y`, chroma + /// pixels — halved — for `u`/`v`). + fn set_tile_origin(&mut self, x0: usize, y0: usize) { + self.tile_x0 = x0; + self.tile_y0 = y0; + } + fn edges( &self, x: usize, @@ -2976,14 +3211,15 @@ impl PlaneBuf { own_down } .min(self.height); - let above = (y > 0 && across > x) + let above = (y > self.tile_y0 && across > x) .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec()); - let left = (x > 0 && down > y).then(|| { + let left = (x > self.tile_x0 && down > y).then(|| { (y..down) .map(|row| self.data[row * self.width + x - 1]) .collect::>() }); - let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]); + let corner = + (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]); (above, left, corner) } @@ -3012,14 +3248,15 @@ impl PlaneBuf { own_down } .min(self.height); - let above = (y > 0 && across > x) + let above = (y > self.tile_y0 && across > x) .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec()); - let left = (x > 0 && down > y).then(|| { + let left = (x > self.tile_x0 && down > y).then(|| { (y..down) .map(|row| self.data[row * self.width + x - 1]) .collect::>() }); - let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]); + let corner = + (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]); (above, left, corner) } @@ -3039,6 +3276,7 @@ impl PlaneBuf { residual: &[i32], cfl: Option<(i32, &[i32])>, filter_intra: Option, + smooth_neighbor: bool, ) { let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach); let mut prediction = vec![0u8; bw * bh]; @@ -3062,7 +3300,7 @@ impl PlaneBuf { bw, bh, enable_edge_filter, - false, + smooth_neighbor, &mut prediction, ); } @@ -3096,6 +3334,15 @@ impl PlaneBuf { residual: &[i32], cfl: Option<(i32, &[i32])>, filter_intra: Option, + // `smooth_neighbor` (spec `get_intra_edge_filter_type` / + // libaom `get_filt_type`): true when the block's above OR left + // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`). + // Callers pass their own plane's neighbour-mode check + // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its + // callers until a smooth/paeth `uv_mode` can reach this call at all + // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which + // keeps `false` exact for chroma without this fn needing to know why. + smooth_neighbor: bool, ) { // A palette block's own [`PALETTE_PRED`] override (lane-palette r2) // takes priority over `predict()`/`predict_filter_intra` entirely -- @@ -3121,13 +3368,7 @@ impl PlaneBuf { // `read_plane`/`decode_block`/`decode_leaf8` call would touch two // dozen sites for a value that never changes mid-decode, so it // rides a thread-local instead (this decoder is single-threaded - // per stream). `smooth_neighbor` (spec `get_intra_edge_filter_type`) - // is left `false`: exact for chroma here (a smooth `uv_mode` is - // refused before decode reaches this call) and a corner-cut for - // luma -- ceiling is one wrong filter-strength bucket on a block - // whose real neighbour predicted smooth; upgrade path is - // threading `Neighbours::above_mode`/`left_mode`'s - // `SMOOTH_PRED..=SMOOTH_H_PRED` membership down instead of `false`. + // per stream). let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get); predict( mode as u8, @@ -3138,7 +3379,7 @@ impl PlaneBuf { side, side, enable_edge_filter, - false, + smooth_neighbor, &mut prediction, ); } @@ -3190,6 +3431,8 @@ fn read_plane( // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours // formula below. luma_skip_ctx: Option, + // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check. + smooth_neighbor: bool, ) -> Result> { let skip_ctx = if plane_idx == 0 { luma_skip_ctx.unwrap_or(0) @@ -3255,6 +3498,7 @@ fn read_plane( &residual, cfl, filter_intra, + smooth_neighbor, ); Ok(if tx_side == side { residual_grid_placeholder(&levels, side) @@ -3317,6 +3561,8 @@ fn decode_block( allow_screen_content_tools, allow_intrabc, Some((palette_ctx, &palette_cache)), + 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 @@ -3326,6 +3572,13 @@ fn decode_block( } else { uv_mode }; + let smooth_neighbor = + is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]); + if smooth_neighbor { + SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); + } + let smooth_neighbor_uv = + is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]); if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \ @@ -3384,6 +3637,7 @@ fn decode_block( &vec![0i32; side * side], None, filter_intra, + smooth_neighbor, ); let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); u.reconstruct( @@ -3396,6 +3650,7 @@ fn decode_block( &vec![0i32; chroma_side * chroma_side], alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, + smooth_neighbor_uv, ); v.reconstruct( cpx, @@ -3407,11 +3662,12 @@ fn decode_block( &vec![0i32; chroma_side * chroma_side], alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, + smooth_neighbor_uv, ); let luma_grid = vec![0i32; side * side]; let u_grid = vec![0i32; chroma_side * chroma_side]; let v_grid = vec![0i32; chroma_side * chroma_side]; - neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]); + neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]); } else if !tx_select || logical_tx == side { // A single luma transform unit -- the old path, unchanged (including // the 64x64 corner case, `logical_tx == side == 64` with @@ -3437,6 +3693,7 @@ fn decode_block( None, filter_intra, None, + smooth_neighbor, )?; let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); let u_grid = read_plane( @@ -3459,6 +3716,7 @@ fn decode_block( alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, + smooth_neighbor_uv, )?; if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( @@ -3486,8 +3744,9 @@ fn decode_block( alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, + smooth_neighbor_uv, )?; - neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]); + neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]); } else { // Several luma transform units, raster order (spec // `transform_block`'s loop): the block's resolved transform is @@ -3531,6 +3790,7 @@ fn decode_block( None, filter_intra, Some(tu_skip_ctx), + smooth_neighbor, )?; if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( @@ -3565,6 +3825,7 @@ fn decode_block( alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, + smooth_neighbor_uv, )?; let v_grid = read_plane( dec, @@ -3586,8 +3847,9 @@ fn decode_block( alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, + smooth_neighbor_uv, )?; - neighbours.record_split_luma(at, side, mode, [&u_grid, &v_grid]); + neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&u_grid, &v_grid]); } // Unconditional, `size == 0` for a non-palette block: clears any stale // neighbour palette state the same way [`Neighbours::record`] always @@ -3646,6 +3908,12 @@ fn decode_leaf8( left_mode = pmode; } } + // See [`PlaneBuf::reconstruct`]'s doc: chroma stays `false` (exact) until + // a smooth/paeth `uv_mode` can reach decode at all. + let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); + if smooth_neighbor { + SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); + } // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other // `decode_block` caller at 16x16 and up. @@ -3662,6 +3930,8 @@ fn decode_leaf8( allow_screen_content_tools, allow_intrabc, None, + leaf_mi.0, + leaf_mi.1, )?; let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED @@ -3693,6 +3963,7 @@ fn decode_leaf8( &vec![0i32; 64], None, filter_intra, + smooth_neighbor, ); let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8)); u.reconstruct( @@ -3705,6 +3976,7 @@ fn decode_leaf8( &vec![0i32; 16], alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, + false, ); v.reconstruct( cpx, @@ -3716,6 +3988,7 @@ fn decode_leaf8( &vec![0i32; 16], alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, + false, ); luma_grid = vec![0i32; 64]; u_grid = vec![0i32; 16]; @@ -3746,6 +4019,7 @@ fn decode_leaf8( None, filter_intra, None, + smooth_neighbor, )?; let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8)); u_grid = read_plane( @@ -3768,6 +4042,7 @@ fn decode_leaf8( alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, + false, )?; v_grid = read_plane( dec, @@ -3789,6 +4064,7 @@ fn decode_leaf8( alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, + false, )?; } else { // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order @@ -3829,6 +4105,7 @@ fn decode_leaf8( None, filter_intra, Some(tu_skip_ctx), + smooth_neighbor, )?; if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( @@ -3863,6 +4140,7 @@ fn decode_leaf8( alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, + false, )?; v_grid = read_plane( dec, @@ -3884,6 +4162,7 @@ fn decode_leaf8( alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, + false, )?; // `record_split_luma` expects a `record`-style `(r, c)` position in // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is @@ -4171,8 +4450,8 @@ fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 { /// to the left (at its own topmost mi row) coded a transform at least as wide /// as `own_side`. fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize { - let above = mi_r > 0 && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side; - let left = mi_c > 0 && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side; + let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side; + let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side; usize::from(above) + usize::from(left) } @@ -4678,13 +4957,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(); @@ -4695,6 +4993,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 { @@ -4714,10 +5013,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, @@ -4727,7 +5026,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, @@ -4736,10 +5035,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)] { @@ -4761,7 +5060,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, @@ -4810,8 +5109,14 @@ pub fn decode_key_frame_tile( allow_screen_content_tools: bool, allow_intrabc: bool, ) -> Result { + let single_tile = TileInfo { + mi_col_starts: vec![0, mi_cols], + mi_row_starts: vec![0, mi_rows], + ..TileInfo::default() + }; decode_key_frame_tile_with_cdfs( - data, + &[data], + &single_tile, mi_cols, mi_rows, base_q_idx, @@ -4839,7 +5144,8 @@ pub fn decode_key_frame_tile( /// alongside the picture, for the caller to save into whichever reference /// slots this frame's `refresh_frame_flags` names. pub(crate) fn decode_key_frame_tile_with_cdfs( - data: &[u8], + tiles: &[&[u8]], + tile_info: &TileInfo, mi_cols: u32, mi_rows: u32, base_q_idx: u8, @@ -4860,6 +5166,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); @@ -4870,6 +5179,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( height, true_width, true_height, + tile_x0: 0, + tile_y0: 0, }; let mut u = PlaneBuf { data: vec![0u8; width * height / 4], @@ -4877,6 +5188,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( height: height / 2, true_width: true_width / 2, true_height: true_height / 2, + tile_x0: 0, + tile_y0: 0, }; let mut v = PlaneBuf { data: vec![0u8; width * height / 4], @@ -4884,6 +5197,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( height: height / 2, true_width: true_width / 2, true_height: true_height / 2, + tile_x0: 0, + tile_y0: 0, }; let scan32 = default_scan(TX32); @@ -4891,15 +5206,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( let scan8 = default_scan(TX8); let scan4 = default_scan(TX4); - let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx))); - if std::env::var_os("EC_AV1_TRACE").is_some() { - eprintln!( - "TRACE key_tile_bytes len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}", - data.len(), - &data[..data.len().min(8)] - ); - } - let mut dec = SymbolDecoder::new(data); + let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx))); + let mut result_cdfs = base_cdfs.clone(); let mut neighbours = Neighbours::new( cols32 as usize * 2, rows32 as usize * 2, @@ -4907,9 +5215,51 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( mi_rows as usize, ); - for sb_r in 0..sb_rows { + // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its + // own byte range and its own fresh copy of the frame's initial CDFs + // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by + // `context_update_tile_id` has its end-of-tile adapted table kept as the + // frame's own output (spec `exit_symbol`) -- every other tile's + // adaptation is discarded, matching the refusal this replaces. + for (tile_idx, &tile_bytes) in tiles.iter().enumerate() { + let tile_num = tile_idx as u32; + let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols); + let mi_row0 = tile_info.mi_row_starts[trow as usize]; + let mi_row1 = tile_info.mi_row_starts[trow as usize + 1]; + let mi_col0 = tile_info.mi_col_starts[tcol as usize]; + let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1]; + // Tile boundaries are always superblock-aligned in mi units (spec + // 5.9.15's uniform/non-uniform derivation both only ever emit + // multiples of the superblock's own mi size), so plain division is + // exact here -- no rounding needed. + // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior + // tile boundary) are always superblock-aligned by spec 5.9.15; the + // frame's own true final edge (`mi_row_starts`/`mi_col_starts`' + // last entry) is not, so the upper bound needs `div_ceil` the same + // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the + // trailing partial superblock row/column in scope. + let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows)); + let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols)); + + let mut cdfs = base_cdfs.clone(); + if std::env::var_os("EC_AV1_TRACE").is_some() { + eprintln!( + "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}", + tile_bytes.len(), + &tile_bytes[..tile_bytes.len().min(8)] + ); + } + let mut dec = SymbolDecoder::new(tile_bytes); + neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize); + y.set_tile_origin(mi_col0 as usize * 4, mi_row0 as usize * 4); + u.set_tile_origin(mi_col0 as usize * 2, mi_row0 as usize * 2); + v.set_tile_origin(mi_col0 as usize * 2, mi_row0 as usize * 2); + TILE_HITS.with(|c| c.set(c.get() + 1)); + + for sb_r in sb_r0..sb_r1 { neighbours.start_row(); - for sb_c in 0..sb_cols { + for sb_c in sb_c0..sb_c1 { + 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) = ( @@ -5296,19 +5646,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } _ => { return Err(unsupported(format!( - "a partition type this encoder never writes (value={part32})" + "a 32x32 partition type this decoder does not code (value={part32})" ))); } } } } _ => { - return Err(unsupported("a partition type this encoder never writes")); + 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)", + )); } } } } + if tile_num == tile_info.context_update_tile_id { + result_cdfs = cdfs; + } + } + // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against // that isolate whether a decode-order frame's mismatch already exists @@ -5338,7 +5696,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( u: u.data, v: v.data, }, - cdfs, + result_cdfs, )); } let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec { @@ -5356,7 +5714,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( u: crop(&u, fw / 2, fh / 2), v: crop(&v, fw / 2, fh / 2), }, - cdfs, + result_cdfs, )) } @@ -6741,6 +7099,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. @@ -6750,7 +7109,10 @@ fn decode_inter_block( )); } - let (has_above, has_left) = (r > 0, c > 0); + let (has_above, has_left) = ( + r > neighbours.tile_row0_mi / (SUB / MI), + c > neighbours.tile_col0_mi / (SUB / MI), + ); let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; @@ -6762,6 +7124,7 @@ fn decode_inter_block( } let mode_for_tx; + let uv_predict_mode; let (luma_grid, u_grid, v_grid); let block_filter; let ref_frame_for_lf; @@ -6906,6 +7269,7 @@ fn decode_inter_block( globalmv_for_lf = is_globalmv; ref_frame_for_lf = ref0; mode_for_tx = 0; + uv_predict_mode = DC_PRED; // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from // `neighbours`) must be stamped with the block's true footprint // too -- a square `bw4`x`bw4` stamp here claims a rect strip's @@ -7926,6 +8290,7 @@ fn decode_inter_block( } } mode_for_tx = 0; + uv_predict_mode = DC_PRED; let mut pred_y = vec![0u8; side * side]; mc::predict_with_filters( @@ -8141,13 +8506,36 @@ fn decode_inter_block( } } let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]); + if (9..=12).contains(&uv_mode) { + SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1)); + } let alpha = if uv_mode == DC_PRED { None } else if uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { - return Err(unsupported("a directional chroma mode (round 2)")); + None + }; + // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for + // the angle-delta question, same as [`read_intra_mode`]'s own copy + // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the + // `else` branch below is exact for it either way. + let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { + DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1)); + read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) + } else { + 0 }; + uv_predict_mode = if uv_mode == UV_CFL_PRED { + DC_PRED + } else { + uv_mode + }; + // lane-chroma r4: same chroma edge-filter-strength neighbour check + // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA + // neighbour's own `uv_mode`, not the luma one. + let smooth_neighbor_uv = + is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]); // `read_palette_mode_info` (decodemv.c:567, called from // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same // gating and same corner-cut as `read_intra_mode`'s own copy above @@ -8206,29 +8594,32 @@ fn decode_inter_block( &vec![0i32; side * side], None, None, + false, ); let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); u.reconstruct( cpx, cpy, chroma_side, - DC_PRED, - 0, + uv_predict_mode, + angle_delta_uv, reach, &vec![0i32; chroma_side * chroma_side], alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, + smooth_neighbor_uv, ); v.reconstruct( cpx, cpy, chroma_side, - DC_PRED, - 0, + uv_predict_mode, + angle_delta_uv, reach, &vec![0i32; chroma_side * chroma_side], alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, + smooth_neighbor_uv, ); luma_grid = vec![0i32; side * side]; u_grid = vec![0i32; chroma_side * chroma_side]; @@ -8255,6 +8646,7 @@ fn decode_inter_block( None, None, None, + false, )?; let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); u_grid = read_plane( @@ -8265,8 +8657,8 @@ fn decode_inter_block( 1, around[1], mode, - DC_PRED, - 0, + uv_predict_mode, + angle_delta_uv, reach, u, cpx, @@ -8277,6 +8669,7 @@ fn decode_inter_block( alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, + smooth_neighbor_uv, )?; v_grid = read_plane( dec, @@ -8286,8 +8679,8 @@ fn decode_inter_block( 2, around[2], mode, - DC_PRED, - 0, + uv_predict_mode, + angle_delta_uv, reach, v, cpx, @@ -8298,6 +8691,7 @@ fn decode_inter_block( alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, + smooth_neighbor_uv, )?; } } @@ -8313,7 +8707,14 @@ fn decode_inter_block( r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0 ); } - neighbours.record_rect(at, write_w, write_h, mode_for_tx, &[luma_grid, u_grid, v_grid]); + neighbours.record_rect( + at, + write_w, + write_h, + mode_for_tx, + uv_predict_mode, + &[luma_grid, u_grid, v_grid], + ); neighbours.record_inter_rect( at, write_w, @@ -8468,8 +8869,12 @@ 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 (has_above, has_left) = ( + leaf_mi.0 > neighbours.tile_row0_mi, + leaf_mi.1 > neighbours.tile_col0_mi, + ); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; @@ -9279,6 +9684,7 @@ fn decode_inter_block8( &vec![0i32; SIDE * SIDE], None, None, + false, ); u.reconstruct( cpx, @@ -9290,6 +9696,7 @@ fn decode_inter_block8( &vec![0i32; CHROMA_SIDE * CHROMA_SIDE], None, None, + false, ); v.reconstruct( cpx, @@ -9301,6 +9708,7 @@ fn decode_inter_block8( &vec![0i32; CHROMA_SIDE * CHROMA_SIDE], None, None, + false, ); luma_grid = vec![0i32; SIDE * SIDE]; u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; @@ -9327,6 +9735,7 @@ fn decode_inter_block8( None, None, None, + false, )?; u_grid = read_plane( dec, @@ -9348,6 +9757,7 @@ fn decode_inter_block8( None, None, None, + false, )?; v_grid = read_plane( dec, @@ -9369,6 +9779,7 @@ fn decode_inter_block8( None, None, None, + false, )?; } } @@ -9526,6 +9937,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 { @@ -9534,6 +9948,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( height: reference.height, true_width: reference.width, true_height: reference.height, + tile_x0: 0, + tile_y0: 0, }; let ref_u = PlaneBuf { data: reference.u.clone(), @@ -9541,6 +9957,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( height: reference.height / 2, true_width: reference.width / 2, true_height: reference.height / 2, + tile_x0: 0, + tile_y0: 0, }; let ref_v = PlaneBuf { data: reference.v.clone(), @@ -9548,6 +9966,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( height: reference.height / 2, true_width: reference.width / 2, true_height: reference.height / 2, + tile_x0: 0, + tile_y0: 0, }; // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx` // names a live DPB slot for (lane-av1refs: generalised from the old @@ -9567,6 +9987,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( height: g.height, true_width: g.width, true_height: g.height, + tile_x0: 0, + tile_y0: 0, }, PlaneBuf { data: g.u.clone(), @@ -9574,6 +9996,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( height: g.height / 2, true_width: g.width / 2, true_height: g.height / 2, + tile_x0: 0, + tile_y0: 0, }, PlaneBuf { data: g.v.clone(), @@ -9581,6 +10005,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( height: g.height / 2, true_width: g.width / 2, true_height: g.height / 2, + tile_x0: 0, + tile_y0: 0, }, ) }) @@ -9594,6 +10020,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( height, true_width, true_height, + tile_x0: 0, + tile_y0: 0, }; let mut u = PlaneBuf { data: vec![0u8; width * height / 4], @@ -9601,6 +10029,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( height: height / 2, true_width: true_width / 2, true_height: true_height / 2, + tile_x0: 0, + tile_y0: 0, }; let mut v = PlaneBuf { data: vec![0u8; width * height / 4], @@ -9608,6 +10038,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( height: height / 2, true_width: true_width / 2, true_height: true_height / 2, + tile_x0: 0, + tile_y0: 0, }; let scan32 = default_scan(TX32); @@ -9638,31 +10070,47 @@ 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) = ( sb_c * SB_MI + SB_MI / 2 < mi_cols, sb_r * SB_MI + SB_MI / 2 < mi_rows, ); - match (has_cols, has_rows) { + // The straddle cases (one or both halves outside the true + // frame) never carry a real alphabet symbol -- spec forces + // SPLIT there (mirrors the intra key-frame tile's own + // three-way write above). Only the (true, true) case can name + // a non-SPLIT value, and this loop below only ever recurses as + // SPLIT -- so a real non-SPLIT part64 here must refuse by name + // instead of silently decoding as SPLIT and desyncing. + let part64 = match (has_cols, has_rows) { (true, true) => { - let part64 = dec.symbol(&mut cdfs.partition_w64[sb_ctx]); + let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]); if std::env::var_os("EC_AV1_TRACE").is_some() { eprintln!( - "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={part64}", + "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p}", sb_r * SB_MI, sb_c * SB_MI ); } - let _ = part64; + p } (true, false) => { dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)); + PARTITION_SPLIT } (false, true) => { dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)); + PARTITION_SPLIT } - (false, false) => {} + (false, false) => PARTITION_SPLIT, + }; + if part64 != PARTITION_SPLIT { + return Err(unsupported( + "an inter SB-level partition type other than SPLIT (this decoder's \ + inter tile path only recurses a superblock as SPLIT)", + )); } for quadrant in 0..4 { @@ -10803,7 +11251,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } _ => { return Err(unsupported(format!( - "an INTER 32x32 partition type this encoder never writes (value={part32})" + "an INTER 32x32 partition type this decoder does not code (value={part32})" ))); } } @@ -11091,6 +11539,46 @@ mod tests { ); } + /// An inter tile's SB-level `part64` used to be read and thrown away + /// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real + /// non-SPLIT value there silently desynced the whole tile instead of + /// refusing. Hand-writes a single whole superblock's `part64 = HORZ` + /// symbol (never produced by this crate's own encoder, which only ever + /// writes NONE/SPLIT at this level, but a real aomenc-class encoder can) + /// and asserts this decoder refuses by name rather than decoding garbage. + #[test] + fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() { + use crate::msac::SymbolEncoder; + let mut cdfs = Cdfs::new(q_ctx_of(40)); + let mut enc = SymbolEncoder::new(); + enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]); + let data = enc.finish(); + let reference = crate::encode::Picture::grey(64, 64); + let err = decode_inter_frame_tile( + &data, + 16, + 16, + 40, + 64, + 64, + &reference, + [None; 8], + &CdefParams::default(), + &LoopFilterParams::default(), + false, + false, + Some(mc::InterpFilterKind::Regular), + false, + false, + ) + .unwrap_err(); + let msg = err.to_string(); + assert!( + msg.contains("SPLIT"), + "expected the named inter-SB-partition refusal, got: {msg}" + ); + } + // ffmpeg cross-oracle: an independent decoder (not this crate's own // encoder-side reconstruction) agrees with what this module decodes, // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same @@ -11494,6 +11982,8 @@ mod tests { height: height / scale, true_width: width / scale, true_height: height / scale, + tile_x0: 0, + tile_y0: 0, }; let ref_y = PlaneBuf { data: ref_pattern.clone(), @@ -11501,6 +11991,8 @@ mod tests { height, true_width: width, true_height: height, + tile_x0: 0, + tile_y0: 0, }; let ref_u = ref_plane(2); let ref_v = ref_plane(2); @@ -11511,6 +12003,8 @@ mod tests { height, true_width: width, true_height: height, + tile_x0: 0, + tile_y0: 0, }; let mut u = PlaneBuf { data: vec![0u8; (width / 2) * (height / 2)], @@ -11518,6 +12012,8 @@ mod tests { height: height / 2, true_width: width / 2, true_height: height / 2, + tile_x0: 0, + tile_y0: 0, }; let mut v = PlaneBuf { data: vec![0u8; (width / 2) * (height / 2)], @@ -11525,6 +12021,8 @@ mod tests { height: height / 2, true_width: width / 2, true_height: height / 2, + tile_x0: 0, + tile_y0: 0, }; let mut cdfs = Cdfs::new(q_ctx_of(100)); diff --git a/crates/ec-av1/src/gate_coverage.rs b/crates/ec-av1/src/gate_coverage.rs index 088152d0..015cc1e1 100644 --- a/crates/ec-av1/src/gate_coverage.rs +++ b/crates/ec-av1/src/gate_coverage.rs @@ -25,10 +25,7 @@ /// 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-smooth-intra", "chroma SMOOTH_PRED is refused, and the intra edge filter's smooth-neighbour bucket is a known corner-cut"), ]; #[cfg(test)] diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 1c78afb5..c346e506 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -30,6 +30,7 @@ pub mod msac; pub mod mvstack; pub mod obu; pub mod quant; +mod refusal_inventory; pub mod sequence; pub mod stream; pub mod tile; diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs new file mode 100644 index 00000000..1903a31f --- /dev/null +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -0,0 +1,254 @@ +//! An inventory of what this decoder refuses, and a check on the claims those +//! refusals make. +//! +//! Two rules this repository keeps learning the hard way: +//! +//! 1. A refusal string is a **claim**. "This encoder never writes one" asserts +//! that a real encoder cannot emit the case -- and one such string was +//! disproved by the very gate that carried it (the wedge-interintra hang, +//! 2026-08-30): the refusal was written from a mismatching frame's header +//! state, so it named a correlate rather than the defect. Any refusal +//! phrased as a capability claim about the ENCODER, rather than about this +//! decoder, needs evidence, and this module makes the set of such strings +//! explicit instead of letting it grow quietly. +//! 2. Refusals accumulate silently. A lane that adds one to unblock itself is +//! doing the right thing (refuse by name rather than desync), but the total +//! is the distance to a decoder that handles a default-settings stream, and +//! nobody sees a total that nothing prints. +//! +//! So the test below re-derives every `unsupported(...)` reason reachable on +//! the decode path -- `decode.rs` and `stream.rs` -- and pins it. Adding or +//! removing a refusal fails until the list is updated, which is the point: the +//! diff of this file is the decoder's capability delta, in one place, in +//! English. + +#[cfg(test)] +const CAPABILITY_CLAIMS: &[&str] = &[ + "a non-2D tx class on a rectangular transform (never expected at this size)", + "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)", + "a nonzero angle delta (this encoder never writes one)", + "a partition below 16x16 other than a clean split (this encoder never writes one)", + "a partition below 8x8 (this encoder never writes one)", + "a tx_type symbol on a rectangular transform (never expected at this size)", +]; + +#[cfg(test)] +const REFUSALS: &[&str] = &[ + "GLOBALMV (round 3)", + "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", + "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", + "a 32x32 partition type this decoder does not code (value={part32})", + "a Golomb tail longer than this decoder reads", + "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 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", + "a block that actually uses a palette (Y) -- reconstruction is out of scope", + "a block that actually uses a palette (Y) -- the index map decodes but the reconstructed pixels do not match libaom yet (lane-palette r3/r4)", + "a block that actually uses intrabc (this decoder never reconstructs one)", + "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 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 row (only tile columns are proven pixel-exact so far)", + "a frame with more than two tile columns (a non-last column's right-edge reach bound past column 0 is unimplemented)", + "a multi-tile frame with loop filtering enabled (deblocking crosses tile boundaries by spec default; PlaneBuf's tile origin does not clip a non-last column's right-edge reach)", + "an inter frame with more than one tile (the inter tile-decode path has no per-tile loop, only key frames do)", + "a frame with no mode-info grid", + "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)", + "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", + "a palette block with a split luma transform (round 1)", + "a reference frame other than LAST_FRAME (round 2)", + "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it", + "a reference picture that is not this frame's own true size", + "a show_existing_frame header naming an empty reference slot", + "an 8x8 leaf that coded WARPED_CAUSAL (motion_mode == 2): av1_find_projection/the affine warp filter are not ported, only motion_mode_allowed's alphabet choice is", + "an inter frame using TxMode::Select (this decoder's inter path never reads a tx_depth symbol, so it desyncs after the first block's mode)", + "an inter frame whose global motion for a single-reference frame is AFFINE (unverified this round; ROTZOOM/TRANSLATION/IDENTITY are proven)", + "an inter frame with no key frame before it", + "an inter SB-level partition type other than SPLIT (this decoder's inter tile path only recurses a superblock as SPLIT)", + "an inter partition below 16x16 (8x8 and smaller inter blocks are not coded yet)", + "an intra mode this decoder does not code (round 2)", + "an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder does not code yet", + "filter intra on a HORZ/VERT strip (this decoder predicts square-only)", +]; + +/// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than +/// a test failure. +/// +/// A gate named `..._decodes_pixel_exact` that cannot decode has failed, and +/// swallowing the error keeps the suite green while the gate proves nothing -- +/// the same vacuum as a gate whose feature never fires, arrived at from the +/// other side. These four predate the attempt-loop pattern the newer gates use +/// (encode several fixtures, require at least one to decode, hard-assert the +/// firing count). They are pinned here so the set cannot grow while they are +/// converted one at a time. +#[cfg(test)] +const GATES_THAT_SKIP_ON_A_DECODE_ERROR: &[&str] = &[ + "a_real_aomenc_filter_intra_stream_decodes_pixel_exact", + "a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact", + "a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact", + "a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact", +]; + +#[cfg(test)] +mod tests { + use super::{CAPABILITY_CLAIMS, GATES_THAT_SKIP_ON_A_DECODE_ERROR, REFUSALS}; + use std::collections::BTreeSet; + + /// Every distinct `unsupported(...)` reason on the decode path. + /// + /// Both sources use the same shape -- `stream.rs` calls + /// `Error::unsupported(context, reason)` and `decode.rs` a local + /// `unsupported(reason)` helper -- so the reason is always the LAST string + /// literal of the call, and Rust's `\` line continuations inside it are + /// joined the way rustc joins them. + fn decode_path_refusals() -> BTreeSet { + let mut found = BTreeSet::new(); + for src in [include_str!("decode.rs"), include_str!("stream.rs")] { + let bytes = src.as_bytes(); + for (start, _) in src.match_indices("unsupported(") { + // `Error::unsupported(` and the bare helper both end here. + let mut i = start + "unsupported(".len(); + // `unsupported(format!("..."))` is the same refusal, one layer in. + if src[i..].starts_with("format!(") { + i += "format!(".len(); + } + let mut last: Option = None; + loop { + while i < bytes.len() && (bytes[i] as char).is_whitespace() { + i += 1; + } + if i >= bytes.len() || bytes[i] != b'"' { + break; + } + i += 1; + let mut lit = String::new(); + while i < bytes.len() && bytes[i] != b'"' { + if bytes[i] == b'\\' { + // A backslash-newline continuation drops the newline + // and the indentation that follows it. + if bytes.get(i + 1) == Some(&b'\n') { + i += 2; + while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') { + i += 1; + } + continue; + } + lit.push(bytes[i] as char); + lit.push(bytes[i + 1] as char); + i += 2; + continue; + } + lit.push(bytes[i] as char); + i += 1; + } + i += 1; + last = Some(lit); + while i < bytes.len() && (bytes[i] as char).is_whitespace() { + i += 1; + } + if i < bytes.len() && bytes[i] == b',' { + i += 1; + continue; + } + break; + } + if let Some(reason) = last { + // `Error::unsupported`'s first argument is the context + // ("AV1 tile"), which is not a reason. + if reason != "AV1 tile" { + found.insert(reason); + } + } + } + } + found + } + + #[test] + fn the_decode_path_refuses_exactly_the_listed_cases() { + let found = decode_path_refusals(); + let listed: BTreeSet = CAPABILITY_CLAIMS + .iter() + .chain(REFUSALS) + .map(|&s| s.to_owned()) + .collect(); + assert!(found.len() >= 30, "the refusal scan found only {} reasons -- it is broken, not the decoder", found.len()); + + let added: Vec<&String> = found.difference(&listed).collect(); + assert!( + added.is_empty(), + "new decode-path refusals are not in the inventory: {added:#?}\n\ + Add each to REFUSALS -- or, if it claims something about what an ENCODER can \ + emit, to CAPABILITY_CLAIMS, which requires evidence that the case is genuinely \ + unreachable rather than merely unseen." + ); + let removed: Vec<&String> = listed.difference(&found).collect(); + assert!( + removed.is_empty(), + "these refusals are listed but no longer in the decode path: {removed:#?}\n\ + Delete them from the inventory -- the capability landed, which is the good case." + ); + } + + /// A refusal may say what THIS DECODER does not do. Saying what an encoder + /// never emits is a claim about the world, and this repository has already + /// shipped one that was false. + #[test] + fn capability_claims_are_declared_not_scattered() { + let claimy: Vec = decode_path_refusals() + .into_iter() + .filter(|r| r.contains("never writes") || r.contains("never expected")) + .collect(); + let declared: BTreeSet<&str> = CAPABILITY_CLAIMS.iter().copied().collect(); + for reason in &claimy { + assert!( + declared.contains(reason.as_str()), + "{reason:?} claims an encoder never emits this case but is not in \ + CAPABILITY_CLAIMS. Such a claim needs a gate that proves the case is \ + unreachable; until it has one, phrase the refusal as what this decoder \ + does not decode." + ); + } + } + + /// No NEW gate may quietly turn a decode error into a skip. + #[test] + fn gates_that_swallow_a_decode_error_are_declared() { + let src = include_str!("stream.rs"); + let mut found: BTreeSet = BTreeSet::new(); + for (i, _) in src.match_indices("\"SKIP ") { + let rest = &src[i + "\"SKIP ".len()..]; + let Some(colon) = rest.find(':') else { continue }; + let name = &rest[..colon]; + if !name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') { + continue; + } + // The tail of the message says what was skipped. Only "{e}" -- the + // decode error itself -- is the shape this test is about; "no + // ffmpeg"/"no aomenc" are tool absence, governed by + // EC_AV1_REQUIRE_AOMENC instead. + let Some(end) = rest.find("\"") else { continue }; + if rest[colon..end].contains("{e}") { + found.insert(name.to_owned()); + } + } + let listed: BTreeSet<&str> = GATES_THAT_SKIP_ON_A_DECODE_ERROR.iter().copied().collect(); + let added: Vec<&String> = found.iter().filter(|n| !listed.contains(n.as_str())).collect(); + assert!( + added.is_empty(), + "these gates turn a decode error into a printed SKIP and are not declared: \ + {added:#?}\nA gate that cannot decode has failed -- assert on the error, or use \ + the attempt-loop pattern (several fixtures, at least one must decode, firing count \ + hard-asserted)." + ); + let stale: Vec<&&str> = listed.iter().filter(|n| !found.contains(**n)).collect(); + assert!( + stale.is_empty(), + "{stale:#?} no longer swallow a decode error -- delete them from the list." + ); + } +} diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 718dbade..92137166 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`/ @@ -286,13 +278,58 @@ pub fn decode_stream(data: &[u8]) -> Result> { // `skip_mode_present` refusal is gone. // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names // which tile's end-of-tile adapted CDFs become the frame's own; this - // decoder only ever decodes tile 0 (`tiles.first()` above), so a - // multi-tile frame is refused rather than silently forwarding the - // wrong tile's table (or leaving the rest of the picture undecoded). - if header.tile_info.cols > 1 || header.tile_info.rows > 1 { + // decoder still only ever *keeps* tile 0's adapted table (see the + // `context_update_tile_id != 0` refusal further down), so any frame + // naming a different tile there is refused rather than silently + // forwarding the wrong tile's table. + // + // lane-tiles r4: the multi-tile refusal itself is now scoped, not + // blanket. `decode_key_frame_tile_with_cdfs` genuinely loops every + // tile (r2/r3), proven pixel-exact by + // `a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact` + // (2 tile columns, `--loopfilter-control=0`) -- but that gate's own + // doc comment names two gaps it deliberately sidesteps, so this + // refusal keeps refusing exactly those: + // - `decode_inter_frame_tile_with_cdfs` takes one `&[u8]` tile + // payload, not a `tiles: &[&[u8]]` list -- it has no per-tile + // loop at all, so an inter frame with >1 tile is still refused + // unconditionally. + // - Deblocking crosses tile boundaries by spec default (AV1 has + // no `loop_filter_across_tiles_enabled`-style flag at all -- + // confirmed absent from `ec-av1-syntax`'s `loop_filter_params` + // read, spec 5.9.11 has no such field either), but `PlaneBuf`'s + // `tile_x0`/`tile_y0` origin only ever clips a tile's own + // left/top reach, not a non-last column's right-edge reach -- + // so a key frame with `loop_filter.level` non-zero (deblocking + // actually on) still refuses. + // - The proven gate is 2 tile *columns*, 1 tile *row*; a + // non-last column's right-edge reach bound past column 0 is + // unimplemented for 3+ columns (r3's own known gap), so `cols` + // is capped at 2. Tile rows are untested this round, so `rows` + // stays capped at 1. + let loop_filter_on = header.loop_filter.level.iter().any(|&l| l != 0); + if header.frame_type != FrameType::Key && header.tile_info.cols > 1 { + return Err(Error::unsupported( + "AV1 decode_stream", + "an inter frame with more than one tile (the inter tile-decode path has no per-tile loop, only key frames do)", + )); + } + if header.tile_info.rows > 1 { + return Err(Error::unsupported( + "AV1 decode_stream", + "a frame with more than one tile row (only tile columns are proven pixel-exact so far)", + )); + } + if header.tile_info.cols > 2 { + return Err(Error::unsupported( + "AV1 decode_stream", + "a frame with more than two tile columns (a non-last column's right-edge reach bound past column 0 is unimplemented)", + )); + } + if header.tile_info.cols > 1 && loop_filter_on { return Err(Error::unsupported( "AV1 decode_stream", - "a frame with more than one tile (this decoder only ever decodes tile 0)", + "a multi-tile frame with loop filtering enabled (deblocking crosses tile boundaries by spec default; PlaneBuf's tile origin does not clip a non-last column's right-edge reach)", )); } // `Tile::offset` is relative to the buffer `parse_obu` was handed @@ -300,6 +337,13 @@ pub fn decode_stream(data: &[u8]) -> Result> { // to `obu_offset`, not to `data` as a whole. let start = obu_offset + tile.offset; let tile_bytes = data.get(start..start + tile.size).ok_or(Error::NeedMore)?; + let tile_bufs: Vec<&[u8]> = tiles + .iter() + .map(|t| { + data.get(obu_offset + t.offset..obu_offset + t.offset + t.size) + .ok_or(Error::NeedMore) + }) + .collect::>()?; let enable_filter_intra = parser .sequence_header() .is_some_and(|seq| seq.enable_filter_intra); @@ -360,7 +404,8 @@ pub fn decode_stream(data: &[u8]) -> Result> { let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key { let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs( - tile_bytes, + &tile_bufs, + &header.tile_info, header.mi_cols, header.mi_rows, header.quantization.base_q_idx, @@ -1855,6 +1900,272 @@ mod tests { ); } + /// lane-chroma r2 stage 1: a real aomenc key frame with + /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`) + /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still- + /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never + /// fires; smooth *luma* neighbours are exactly what this gate wants to + /// exercise, proving [`decode::smooth_luma_hits`] actually landed a + /// directional block next to a smooth-predicted one and decoded + /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix). + #[test] + fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() { + if !have_ffmpeg() { + eprintln!( + "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg" + ); + return; + } + if !have_aomenc() { + eprintln!( + "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}", + aomenc_path().display() + ); + return; + } + let (width, height) = (64usize, 64usize); + let mut refusals = Vec::new(); + let mut fired_runs = 0u32; + for attempt in 0..40u32 { + let seed = 42 + attempt; + let source = format!( + "mandelbrot=size=64x64:start_scale={}:rate=25", + 5.0 - f64::from(attempt) * 0.06 + ); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-t", + "0.04", + "-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", + "--cq-level=45", + "--cpu-used=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=1", + // Smooth/paeth chroma is a still-refused, separate + // round-2 gap -- off so no attempt trips it while this + // gate is purely about luma's edge-filter fix. + "--enable-paeth-intra=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--enable-intra-edge-filter=1", + "--max-partition-size=32", + "--min-partition-size=16", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--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: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let smooth_before = decode::smooth_luma_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + refusals.push(format!("seed {seed}: {e}")); + continue; + } + }; + if decode::smooth_luma_hits() == smooth_before { + refusals.push(format!( + "seed {seed}: decoded, but no smooth-luma-neighbour block fired" + )); + continue; + } + fired_runs += 1; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!( + frames[0].y, ffmpeg_frames[0].y, + "luma vs ffmpeg (seed {seed})" + ); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); + if fired_runs >= 4 { + return; + } + } + assert!( + fired_runs > 0, + "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}", + refusals.join("\n") + ); + } + + /// The smooth/paeth-chroma gate (lane-chroma r1/r3): a real aomenc key + /// frame with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the + /// opposite of the directional-chroma gate below, which turns these OFF + /// to keep this gap from firing while directional chroma is under test). + /// Some seeds won't pick smooth/paeth for chroma at all -- retry like + /// every other real-encoder gate here, but the first attempt that + /// actually fires [`decode::smooth_uv_hits`] must decode pixel-exact. + #[test] + fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() { + if !have_ffmpeg() { + eprintln!( + "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg" + ); + return; + } + if !have_aomenc() { + eprintln!( + "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}", + aomenc_path().display() + ); + return; + } + let (width, height) = (64usize, 64usize); + let mut refusals = Vec::new(); + let mut fired_runs = 0u32; + for attempt in 0..40u32 { + let seed = 42 + attempt; + let source = format!( + "mandelbrot=size=64x64:start_scale={}:rate=25", + 5.0 - f64::from(attempt) * 0.06 + ); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-t", + "0.04", "-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", + "--cq-level=45", + "--cpu-used=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=1", + "--enable-paeth-intra=1", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--enable-intra-edge-filter=1", + "--max-partition-size=32", + // 8x8/leaf8 splits are a separate, already-named refusal. + "--min-partition-size=16", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--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: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let smooth_before = decode::smooth_uv_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + refusals.push(format!("seed {seed}: {e}")); + continue; + } + }; + if decode::smooth_uv_hits() == smooth_before { + refusals.push(format!( + "seed {seed}: decoded, but no smooth/paeth uv_mode fired" + )); + continue; + } + fired_runs += 1; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!( + frames[0].y, ffmpeg_frames[0].y, + "luma vs ffmpeg (seed {seed})" + ); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); + if fired_runs >= 4 { + return; + } + } + assert!( + fired_runs > 0, + "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}", + refusals.join("\n") + ); + } + /// The directional-chroma/angle-delta gate: a real aomenc key frame with /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the /// opposite of every sibling recipe's `=0`, which existed specifically to @@ -4813,14 +5124,211 @@ mod tests { ); } - /// 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: - /// the WARPED_CAUSAL interp-read suppression; warp-flake-7: the same - /// suppression for skip_mode blocks; warp-flake-5: mvstack entry - /// clamping; ii-flake-1..8: interintra neighbours excluded from - /// warp-sample gathering, ref_frame[1] == INTRA_FRAME in the mi grid). - /// `EC_AV1_GATE_DUMP_PIN` overrides to a single stream. + /// 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: + /// the WARPED_CAUSAL interp-read suppression; warp-flake-7: the same + /// suppression for skip_mode blocks; warp-flake-5: mvstack entry + /// clamping; ii-flake-1..8: interintra neighbours excluded from + /// warp-sample gathering, ref_frame[1] == INTRA_FRAME in the mi grid). + /// `EC_AV1_GATE_DUMP_PIN` overrides to a single stream. /// Deterministic and static -- `#[ignore]`d because the gitignored /// fixtures dir may be absent; run manually. #[test] @@ -5629,4 +6137,373 @@ mod tests { } } } + + /// lane-tiles r3: a real two-tile-column aomenc key frame, decoded + /// through [`decode_key_frame_tile_with_cdfs`] directly with the whole + /// `tiles: &[&[u8]]` list -- `decode_stream`'s `cols > 1 || rows > 1` + /// refusal (this file, ~line 292) still fires for any stream this wide, + /// so this gate bypasses it on purpose to prove the per-tile loop r2 + /// landed (fresh `SymbolDecoder`/CDF copy per tile, `Neighbours::start_tile`, + /// `PlaneBuf::set_tile_origin`) actually decodes both tiles pixel-exact + /// before that refusal is lifted. 128x64 is exactly two 64x64 + /// superblocks wide with `--tile-columns=1` (`TileCols=2`), so tile 1 is + /// also the frame's own right edge -- the known gap (`PlaneBuf`'s + /// tile_x0/tile_y0 only clip left/top reach, not a non-last column's + /// right-edge reach) does not apply to this fixture; it would to a + /// 3+-column one. Tile count itself is a structural aomenc param, not + /// RD-dependent content, but this decoder's chroma smooth/paeth gap + /// (`decode.rs` "a smooth or paeth chroma mode (round 2)", unrelated to + /// tiles, pre-dating this lane) is content-dependent -- no aomenc flag + /// disables UV-only smooth/paeth search, so a small seed sweep is + /// needed the same way the sibling `a_real_aomenc_stream_with_*` gates + /// retry past unrelated named refusals (every refusal in this crate is + /// prefixed `"AV1 tile"` regardless of category, so unlike the sibling + /// gates' `warp`/`obmc`/`interintra` banned lists there is no + /// tile-specific substring to forbid here -- `matched > 0` plus the + /// hard `tile_hits > 1`/pixel-exact asserts on any actual decode are + /// the real proof). + #[test] + fn a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact"; + 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) = (128usize, 64usize); + let mut matched = 0u32; + let mut named_refusals = 0u32; + for attempt in 0..20u32 { + let seed = 42 + attempt; + let source = gradients_source(seed, width, height, "duration=0.04: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 mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--limit=1", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--tile-columns=1", + "--tile-rows=0", + // This decoder hardcodes SB_MI=16 (64px) superblocks + // everywhere (`decode.rs`'s sb128 dead-end, ledger + // `av1-superblock-contexts`) -- without this, aomenc's + // own default 128x128 superblock makes 128x64 exactly + // ONE superblock wide, so `--tile-columns=1` has nothing + // to split and `cols` comes back 1. + "--sb-size=64", + // Deblocking crosses tile boundaries by default (spec + // `loop_filter_across_tiles_enabled`); `PlaneBuf`'s + // tile_x0/tile_y0 origin only ever clips a tile's own + // left/top reach (r2/r3's documented known gap), so a + // non-last tile column's right-edge deblock would read + // into the next tile's still-undecoded/differently- + // origined samples. Off here since deblocking itself is + // not what this gate is proving. + "--loopfilter-control=0", + "--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=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--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: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + + // Parse the stream ourselves (rather than `decode_stream`, whose + // multi-tile refusal is exactly what this gate exists to run + // ahead of) to reach the real `Frame` OBU's `tile_info` and its + // full `Vec` -- `Av1Parser::parse_obu` already locates + // every tile in a multi-tile tile group (`parse_tile_group`), it + // is only `decode_stream` that ever narrows this to + // `tiles.first()`. + let mut parser = Av1Parser::new(); + let mut pos = 0usize; + let mut frame = None; + while pos < stream.len() { + let obu_offset = pos; + let obu = parser.parse_obu(&stream[pos..]).unwrap(); + pos += obu.total_size; + if let ObuKind::Frame(header, tiles) = obu.kind { + frame = Some((header, tiles, obu_offset)); + break; + } + } + let (header, tiles, obu_offset) = frame.expect("stream has a Frame OBU"); + assert!( + header.tile_info.cols > 1, + "{NAME}: aomenc did not actually split into >1 tile column (cols={}, seed {seed})", + header.tile_info.cols + ); + assert_eq!( + tiles.len(), + header.tile_info.cols as usize, + "{NAME}: expected one tile per column (seed {seed})" + ); + // `Tile::offset` is relative to the buffer `parse_obu` was + // handed (`&stream[pos..]` at the time this OBU was parsed), so + // it needs `obu_offset` added back -- the same adjustment + // `decode_stream` makes for its own single-tile slice above. + let tile_bufs: Vec<&[u8]> = tiles + .iter() + .map(|t| &stream[obu_offset + t.offset..obu_offset + t.offset + t.size]) + .collect(); + + let enable_filter_intra = parser + .sequence_header() + .is_some_and(|seq| seq.enable_filter_intra); + let enable_edge_filter = parser + .sequence_header() + .is_some_and(|seq| seq.enable_intra_edge_filter); + + let before = crate::decode::tile_hits(); + let picture = match decode_key_frame_tile_with_cdfs( + &tile_bufs, + &header.tile_info, + header.mi_cols, + header.mi_rows, + header.quantization.base_q_idx, + header.frame_width, + header.frame_height, + enable_filter_intra, + enable_edge_filter, + &header.cdef, + &header.loop_filter, + None, + header.tx_mode == TxMode::Select, + header.reduced_tx_set, + header.allow_screen_content_tools, + header.allow_intrabc, + ) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" + ); + named_refusals += 1; + eprintln!("seed {seed} refusal: {msg}"); + continue; + } + Ok((picture, _end_cdfs)) => picture, + }; + let hits = crate::decode::tile_hits() - before; + assert!( + hits > 1, + "{NAME}: tile_hits delta was {hits}, expected >1 -- both tiles must actually \ + decode, not just tile 0 (seed {seed})" + ); + + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!(picture.y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})"); + assert_eq!(picture.u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})"); + assert_eq!(picture.v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})"); + matched += 1; + } + assert!( + matched > 0, + "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \ + a two-tile-column stream" + ); + eprintln!( + "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20" + ); + } + + /// lane-tiles r4: the same real two-tile-column stream as the gate + /// above, this time run through `decode_stream` itself -- the entry + /// point real callers use, not the `decode_key_frame_tile_with_cdfs` + /// bypass. Proves the `cols > 1` refusal is actually lifted (not just + /// that the underlying per-tile loop works) for the scoped case this + /// round proved safe: 2 tile columns, 1 tile row, key frame, loop + /// filtering off (`--loopfilter-control=0` stays -- deblocking crosses + /// tile boundaries by spec default and `PlaneBuf` cannot bound a + /// non-last column's right-edge reach yet, see the refusal's own doc + /// comment above `decode_stream`). + #[test] + fn a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream() { + const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream"; + 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) = (128usize, 64usize); + let mut matched = 0u32; + let mut named_refusals = 0u32; + for attempt in 0..20u32 { + let seed = 42 + attempt; + let source = gradients_source(seed, width, height, "duration=0.04: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 mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--limit=1", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--tile-columns=1", + "--tile-rows=0", + "--sb-size=64", + "--loopfilter-control=0", + "--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=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--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: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + + let before = crate::decode::tile_hits(); + let pictures = 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}" + ); + named_refusals += 1; + eprintln!("seed {seed} refusal: {msg}"); + continue; + } + Ok(pictures) => pictures, + }; + let hits = crate::decode::tile_hits() - before; + assert!( + hits > 1, + "{NAME}: tile_hits delta was {hits}, expected >1 -- both tiles must actually \ + decode, not just tile 0 (seed {seed})" + ); + assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})"); + + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})"); + assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})"); + assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})"); + matched += 1; + } + assert!( + matched > 0, + "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \ + decoded a two-tile-column stream" + ); + eprintln!( + "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20" + ); + } } diff --git a/lanes/chroma-r1-attempt.diff b/lanes/chroma-r1-attempt.diff new file mode 100644 index 00000000..b1d5b9c7 --- /dev/null +++ b/lanes/chroma-r1-attempt.diff @@ -0,0 +1,254 @@ +diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs +index fc53c53..9abc050 100644 +--- a/crates/ec-av1/src/decode.rs ++++ b/crates/ec-av1/src/decode.rs +@@ -126,6 +126,20 @@ pub(crate) fn directional_uv_hits() -> usize { + DIRECTIONAL_UV_HITS.with(|c| c.get()) + } + ++/// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12), ++/// across every call in the process -- lane-chroma r1's own before/after ++/// counter, proving a stream actually exercised chroma's smooth/paeth ++/// predictor rather than every block landing on DC/CFL/directional. ++thread_local! { ++ static SMOOTH_UV_HITS: std::cell::Cell = ++ const { std::cell::Cell::new(0) }; ++} ++ ++/// Current value of [`SMOOTH_UV_HITS`]. ++pub(crate) fn smooth_uv_hits() -> usize { ++ SMOOTH_UV_HITS.with(|c| c.get()) ++} ++ + /// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as + /// something other than [`ANGLE_DELTA_ZERO`], across every call in the + /// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`], +@@ -1967,7 +1981,7 @@ fn read_intra_mode_rect( + None + }; + if (9..=12).contains(&uv_mode) { +- return Err(unsupported("a smooth or paeth chroma mode (round 2)")); ++ SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1)); + } + let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { + DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1)); +@@ -2447,15 +2461,15 @@ fn read_intra_mode( + } else { + None + }; +- // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap +- // from this lane's directional chroma: a corner block with neither +- // `above` nor `left` (both `Edges::build`'s no-neighbour fallback, +- // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta +- // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched +- // bug in that fallback this lane's own scope does not cover. Keep it +- // refused here rather than ship a silently-wrong decode. ++ // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma: lane-chroma r1 lands this -- ++ // the predictor itself (`intra::predict`) is already shared with luma and ++ // already spec-correct for the no-neighbour corner case (127/129/128 is ++ // the spec's own default, `Edges::build`). The earlier round's "worst ++ // delta 78" trace was `smooth_neighbor` hardcoded `false` interacting ++ // with a DIFFERENT bug that has since been fixed elsewhere; re-verified ++ // clean under `a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact`. + if (9..=12).contains(&uv_mode) { +- return Err(unsupported("a smooth or paeth chroma mode (round 2)")); ++ SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1)); + } + // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the + // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads +diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs +index 20ff033..31479d2 100644 +--- a/crates/ec-av1/src/stream.rs ++++ b/crates/ec-av1/src/stream.rs +@@ -1861,6 +1861,191 @@ mod tests { + ); + } + ++ /// The smooth/paeth-chroma gate (lane-chroma r1): a real aomenc key frame ++ /// with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the opposite of ++ /// the directional-chroma gate above, which turned these OFF to keep this ++ /// round-2 gap from firing while directional chroma was under test) and ++ /// directional intra left on aomenc's own default too, so the RD search ++ /// is free to land on any `uv_mode`. Some seeds won't pick smooth/paeth ++ /// for chroma at all -- retry like every other real-encoder gate here, ++ /// but the first attempt that actually fires [`decode::smooth_uv_hits`] ++ /// must decode pixel-exact. ++ #[test] ++ fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() { ++ if !have_ffmpeg() { ++ eprintln!( ++ "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg" ++ ); ++ return; ++ } ++ if !have_aomenc() { ++ eprintln!( ++ "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}", ++ aomenc_path().display() ++ ); ++ return; ++ } ++ let (width, height) = (64usize, 64usize); ++ let mut refusals = Vec::new(); ++ let mut fired_runs = 0u32; ++ for attempt in 0..40u32 { ++ let seed = 42 + attempt; ++ let source = format!( ++ "mandelbrot=size=64x64:start_scale={}:rate=25", ++ 5.0 - f64::from(attempt) * 0.06 ++ ); ++ let y4m = Command::new("ffmpeg") ++ .args([ ++ "-v", ++ "error", ++ "-f", ++ "lavfi", ++ "-i", ++ &source, ++ "-pix_fmt", ++ "yuv420p", ++ "-t", ++ "0.04", ++ "-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", ++ "--cq-level=45", ++ "--cpu-used=0", ++ "--enable-rect-partitions=0", ++ "--enable-ab-partitions=0", ++ "--enable-1to4-partitions=0", ++ "--enable-filter-intra=0", ++ "--enable-smooth-intra=1", ++ "--enable-paeth-intra=1", ++ "--enable-tx-size-search=0", ++ "--enable-cdef=0", ++ "--enable-restoration=0", ++ "--enable-intra-edge-filter=1", ++ "--max-partition-size=32", ++ // Same reason as the tx-select gate above: 8x8 and other ++ // sub-16x16 splits are a separate, already-named refusal. ++ "--min-partition-size=16", ++ "--enable-palette=0", ++ "--enable-intrabc=0", ++ "--enable-cfl-intra=0", ++ // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack; ++ // leaving it on silently desyncs symbols on inter frames (grainfix lesson). ++ "--enable-ref-frame-mvs=0", ++ "--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: {}", ++ String::from_utf8_lossy(&out.stderr) ++ ); ++ let stream = out.stdout; ++ let smooth_before = decode::smooth_uv_hits(); ++ let frames = match decode_stream(&stream) { ++ Ok(frames) => frames, ++ Err(e) => { ++ refusals.push(format!("seed {seed}: {e}")); ++ continue; ++ } ++ }; ++ if decode::smooth_uv_hits() == smooth_before { ++ refusals.push(format!( ++ "seed {seed}: decoded, but no smooth/paeth uv_mode fired" ++ )); ++ continue; ++ } ++ fired_runs += 1; ++ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); ++ let mismatched = frames[0].y != ffmpeg_frames[0].y ++ || frames[0].u != ffmpeg_frames[0].u ++ || frames[0].v != ffmpeg_frames[0].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}"); ++ } ++ assert_eq!( ++ frames[0].y, ffmpeg_frames[0].y, ++ "luma vs ffmpeg (seed {seed})" ++ ); ++ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})"); ++ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})"); ++ if fired_runs >= 4 { ++ return; ++ } ++ } ++ assert!( ++ fired_runs > 0, ++ "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}", ++ refusals.join("\n") ++ ); ++ } ++ ++ #[test] ++ #[ignore] ++ fn zzz_smooth_pin_diag() { ++ let path = std::env::var("EC_ZZZ_PATH").unwrap_or_else(|_| { ++ "/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/baaa03f8-c4ff-4469-8ebb-83100429b150/scratchpad/smooth-pin.obu" ++ .to_string() ++ }); ++ let stream = std::fs::read(&path).unwrap(); ++ let frames = decode_stream(&stream).unwrap(); ++ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1); ++ for (row, (a, b)) in frames[0] ++ .y ++ .chunks(64) ++ .zip(ffmpeg_frames[0].y.chunks(64)) ++ .enumerate() ++ { ++ for (col, (x, y)) in a.iter().zip(b).enumerate() { ++ if x != y { ++ eprintln!("Y mismatch row={row} col={col} ours={x} ffmpeg={y}"); ++ } ++ } ++ } ++ for (row, (a, b)) in frames[0] ++ .u ++ .chunks(32) ++ .zip(ffmpeg_frames[0].u.chunks(32)) ++ .enumerate() ++ { ++ for (col, (x, y)) in a.iter().zip(b).enumerate() { ++ if x != y { ++ eprintln!("U mismatch row={row} col={col} ours={x} ffmpeg={y}"); ++ } ++ } ++ } ++ } ++ + /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0 + /// --auto-alt-ref=0` keep every non-key frame a simple forward + /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this diff --git a/lanes/chroma-r1.charter.md b/lanes/chroma-r1.charter.md new file mode 100644 index 00000000..3aaeb658 --- /dev/null +++ b/lanes/chroma-r1.charter.md @@ -0,0 +1,65 @@ +# lane-chroma r1 charter — the chroma intra modes this decoder still refuses + +## Where you are +Worktree /home/user/Documents/Code/Rust/edith_codecs-chroma, branch +lane-chroma @ main. +Build/test ONLY: + `env CARGO_TARGET_DIR=$HOME/.cache/cargo-target-chroma 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 -realworld worktree. WIP COMMIT after every green step. + +## The measurement +Walking a DEFAULT-settings stream through its blockers, this is number 5 in the +chain — reached as soon as CDEF, delta-q and palette are out of the way: + + unsupported: AV1 tile (a smooth or paeth chroma mode (round 2)) + +at `decode.rs`: + + if (9..=12).contains(&uv_mode) { + return Err(unsupported("a smooth or paeth chroma mode (round 2)")); + } + +There is a sibling refusal, "a directional chroma mode (round 2)", to check +alongside it. + +## Why this may be much smaller than it looks — verify before assuming +`crates/ec-av1/src/intra.rs` ALREADY implements SMOOTH_PRED, SMOOTH_V, SMOOTH_H +and PAETH_PRED, and they are exercised for LUMA today. The chroma path may +simply be refusing modes whose predictor is already present and correct. + +Do NOT assume that. Establish it: +1. Read the luma call path and the chroma call path side by side and list every + difference — edge construction, availability, the `Reach`, subsampling, the + CfL interaction (`UV_CFL_PRED` is mode 13 and is handled separately today). +2. Check against libaom what a chroma block of these modes actually needs that + a luma block does not. `av1_predict_intra_block` is shared in libaom, which + is evidence the predictor is shared, but the EDGE setup differs for a + subsampled plane. +3. If it really is just the refusal, removing it is a two-line change and the + whole value of the round is the PROOF — a gate with a hard-asserted firing + count showing real aomenc streams decode those modes pixel-exact. + +The "(round 2)" suffix means an earlier round deliberately deferred these. Find +out whether it deferred them because they were hard or merely because they were +out of that round's scope — `git log -S "smooth or paeth chroma"` will say. + +## Method +Refuse-by-name first, decode second. On a pixel mismatch, self-pin with +`EC_AV1_GATE_DUMP` and compare the msac RANGE (never `tell()`) against the +instrumented oracle: `EC_TRACE=1`, `EC_TRACE_MODE=1` (covers intra key-frame +mode info too), `EC_TRACE_COEFF=1`. If the oracle's range is UNCHANGED where +ours moves, we read a symbol it never wrote — check that before suspecting a +predictor. + +Note these modes affect PIXELS, not symbol flow, if the mode symbol is already +being read correctly today — so a mismatch here is most likely a prediction +defect, and the recon dump (`EC_AV1_PREFILT_DUMP` on both sides) is the faster +instrument than the range ladder. + +## Done criteria +Full lib suite stays green (232 passed / 0 failed on main today). Smooth and +Paeth chroma decode pixel-exact under a gate that HARD-ASSERTS its firing count, +or the report explains precisely what a chroma block needs that is missing. +Report on the directional-chroma sibling too, even if you do not land it. +REPORT `lanes/chroma-r1.report.md`, VERDICT on the FIRST line. diff --git a/lanes/chroma-r1.report.md b/lanes/chroma-r1.report.md new file mode 100644 index 00000000..f3187ac6 --- /dev/null +++ b/lanes/chroma-r1.report.md @@ -0,0 +1,126 @@ +# lane-chroma r1 report — smooth/paeth chroma refusal + +VERDICT: NOT LANDED — root cause found and localized, refusal kept (reverted +to HEAD). This is the charter's documented fallback outcome: "the report +explains precisely what a chroma block needs that is missing." + +## What was established (charter step 1-2) + +The predictor itself (`crate::intra::predict`, `SMOOTH_PRED`/`SMOOTH_V_PRED`/ +`SMOOTH_H_PRED`/`PAETH_PRED` branches) IS shared between luma and chroma, +and its formula matches spec 7.11.2.6 / libaom `intrapred.c` exactly (weight +tables, `round2` shifts, no-neighbour `Edges::build` fallback of 127/129/128 +which is the spec's own default for a corner block). The chroma call path +(`PlaneBuf::reconstruct`) is the SAME function luma uses — there is no +missing chroma-specific machinery for the predictor math itself. + +`git log -S "smooth or paeth chroma"` shows the refusal was added in the SAME +commit (4f93fb2, "chroma tx_type derivation…") that landed the predictor +plumbing — its own comment already named the reason: a corner block with no +above/left neighbour, fed `SMOOTH_PRED`, produced a wrong pixel (worst delta +78 vs ffmpeg), traced 2026-08-27. So the earlier round deferred this because +it was HARD (a real bug found), not because it was merely out of scope. + +## What this round found (charter step 3, attempted, then reverted) + +Removed both refusals (`decode.rs` ~1970 and ~2458, the two `read_intra_mode` +variants), added a `SMOOTH_UV_HITS` counter, and wrote +`a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact` (same +structure as the existing `..._with_directional_chroma_...` gate, but +`--enable-smooth-intra=1 --enable-paeth-intra=1`). First attempt (seed 42) +FAILED: luma mismatched ffmpeg, not chroma. + +Grepped every other real-aomenc gate in `stream.rs` (23 call sites): every +single one passes `--enable-smooth-intra=0 --enable-paeth-intra=0`. So +smooth/paeth has NEVER been exercised end-to-end against a real encoder +stream before this lane, for EITHER plane — the charter's premise "already +exercises them for LUMA" holds only in `intra.rs`'s own unit tests, not +against a real bitstream. This is a real, previously-unverified defect, not +a chroma-specific gap. + +Root-caused with `EC_AV1_TRACE=1` (mode dump) + a throwaway pixel-diff test +against the pinned stream, with and without the loop filter +(`--loopfilter-control=0` reproduces it too, ruling out deblocking): + +- First mismatch (no-LF stream): `row=16 col=48`, inside luma block + `px=48 py=16 side=16 mode=5` (`D113_PRED`, a directional mode). +- Its ABOVE neighbour is `px=48 py=0 side=16 mode=11` (`SMOOTH_H_PRED`). + +This is exactly the corner-cut already named in the code, verbatim, at the +`reconstruct()` call site's own doc comment: + +> `smooth_neighbor` (spec `get_intra_edge_filter_type`) is left `false`: +> exact for chroma here (a smooth `uv_mode` is refused before decode reaches +> this call) and a corner-cut for LUMA -- ceiling is one wrong filter-strength +> bucket on a block whose real neighbour predicted smooth; upgrade path is +> threading `Neighbours::above_mode`/`left_mode`'s `SMOOTH_PRED..=SMOOTH_H_PRED` +> membership down instead of `false`. + +Enabling `--enable-smooth-intra=1` makes the RD search reachable to actually +land SMOOTH_H on a block, which is exactly the case the corner-cut's own +comment predicted would break: `intra_edge_filter_strength`'s +`smooth_neighbor` threshold bucket is picked wrong for the directional +neighbour below it, producing the observed off-by-one-ish deltas +(`intra_edge_filter_strength` returns the wrong strength index -> different +filter kernel -> pixels shift by 1-2). + +## Why it wasn't landed this round + +The fix is well-scoped (`Neighbours::above_mode`/`left_mode` already track +per-16x16-cell LUMA mode; threading `SMOOTH_PRED..=SMOOTH_H_PRED.contains()` +into every `reconstruct`/`reconstruct_rect` call site's `smooth_neighbor` +argument is mechanical) but touches ~9 call sites across 3 planes x 3 partition +shapes (`decode.rs:2161,2174,2186,2279,2317,2354,2928,3038,3050,3061,3337, +3349,3360,7850,7862,7873,8923,8934,8945`), and the CHROMA side of the same +question needs a NEW piece of state this decoder does not track at all: a +per-cell UV-mode neighbour array (today's `Neighbours` only has `above_mode`/ +`left_mode` for LUMA). Landing chroma smooth/paeth correctly needs BOTH the +luma-side threading (fixes the observed defect) AND new UV-mode tracking +(so a chroma block's own `smooth_neighbor` reflects its chroma neighbour, not +its luma one) — verified but not measured against a gate this round, out of +budget. Shipping only the luma-side half and leaving chroma's `smooth_neighbor` +hardcoded `false` would silently reintroduce the same bug on the chroma side +the moment two chroma smooth/directional blocks sit adjacent, which is exactly +the kind of silently-wrong decode this lane's own rules forbid landing. + +Given the choice between (a) landing a two-line refusal removal with a KNOWN, +now-quantified pixel defect gated by a passing test that happened not to +exercise the bad case, and (b) reverting to the safe refusal with the root +cause fully documented, this round takes (b). The attempted diff (refusal +removal + counter + gate + throwaway diagnostic test) is saved at +`/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/baaa03f8-c4ff-4469-8ebb-83100429b150/scratchpad/chroma-r1-attempt.diff` +for whichever round lands the `smooth_neighbor` threading. + +## Gate firing count + +None — the gate (`a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact`) +was written and fired real smooth/paeth chroma symbols on its very first +attempt (seed 42), but FAILED on luma pixel mismatch before reaching a +chroma pixel-exact assertion; it was reverted along with the refusal removal +rather than left in the tree failing or disabled. `smooth_uv_hits` counter: +1 firing observed (chroma `uv_mode=11` on block `px=32 py=16`), never +verified pixel-exact. + +## The directional-chroma sibling ("a directional chroma mode (round 2)") + +Not touched this round; it lives at a DIFFERENT, unrelated code path +(`decode.rs:7786`, inside the intra-block-within-an-inter-frame reader) than +the two smooth/paeth refusals (`~1970`/`~2458`, the key-frame `read_intra_mode` +variants). That inter-frame intra-block path never computes `angle_delta_uv` +at all and refuses ANY non-DC/non-CFL `uv_mode` outright — i.e. directional +chroma is refused there unconditionally, unlike the key-frame path (`~2458`), +which ALREADY decodes directional chroma correctly today (see the existing, +passing `a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact` +gate). Landing the `~7786` sibling needs angle-delta-for-chroma support added +to that separate reader, plus its own gate; not attempted this round — +smaller in shape than the smooth/paeth work (no known predictor bug blocking +it, just missing plumbing) but independent scope, deferred to a future round. + +## Disposition + +deferred: thread `smooth_neighbor` through luma + add chroma UV-mode +neighbour tracking, then re-attempt this refusal removal — unblocks on +someone picking up the saved attempt diff and the ~9 call-site list above. +deferred: the `~7786` "directional chroma mode (round 2)" sibling in the +inter-frame intra-block path — unblocks independently, no known bug, just +unwritten angle-delta-for-chroma plumbing in that reader. diff --git a/lanes/chroma-r2.charter.md b/lanes/chroma-r2.charter.md new file mode 100644 index 00000000..da633285 --- /dev/null +++ b/lanes/chroma-r2.charter.md @@ -0,0 +1,80 @@ +# lane-chroma r2 — smooth-neighbour edge filter, then smooth/paeth chroma + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-chroma`, branch +`lane-chroma`, at 3ca2455 (r1's report; r1 landed NO code — it reverted). + +## What r1 established (read `lanes/chroma-r1.report.md` first — it is short) +- The `SMOOTH_PRED`/`PAETH_PRED` predictor math in `intra.rs` is already + spec-correct and shared between luma and chroma. Removing the chroma refusal + (`decode.rs` uv_mode 9..=12, around lines 1970 and 2458) is NOT the work. +- The real defect is on LUMA: `reconstruct()` hardcodes `smooth_neighbor = false` + — its own comment calls this "a corner-cut for luma" and names the upgrade + path. `intra_edge_filter_strength` therefore picks the wrong bucket whenever a + directional block's neighbour used a SMOOTH mode. r1 reproduced it exactly: + seed 42, directional block px=48 py=16 mode=5, neighbour px=48 py=0 with + SMOOTH_H_PRED, off by 1-2 in the filtered edge. +- **Nothing in this repo had ever exercised it**: all 23 real-aomenc gates in + `stream.rs` pass `--enable-smooth-intra=0 --enable-paeth-intra=0`. That is a + fleet-wide gate-recipe blindness, not a one-gate miss. +- r1's attempted diff (refusal removal + the new gate + the counter) is + preserved at `lanes/chroma-r1-attempt.diff` in this worktree. Start from it. + +## Goal, in order +1. **Fix the luma bug first, on its own, with its own gate.** Thread the + neighbour's intra mode into `reconstruct()` / `reconstruct_rect()` so + `smooth_neighbor` is `above_mode` (or `left_mode`, per the spec's + directionality) being in `SMOOTH_PRED..=SMOOTH_H_PRED`. r1's report lists + the ~9 call sites. `Neighbours` already tracks per-block state — add the + luma mode alongside whatever it already stores; follow the shape of the + existing `skip_at` / `skip_txfm_ctx` accessors in `decode.rs`. + Spec anchor: 7.11.2.9 `intra edge filter strength` — the `filt_type` + argument is 1 when the relevant neighbour used a smooth mode. libaom: + `av1/common/reconintra.c` `get_filt_type()` / `av1_filter_intra_edge` and + `intra_edge_filter_strength`; `get_filt_type` reads + `av1_is_directional_mode` and `is_smooth(above_mbmi)`/`is_smooth(left_mbmi)`. + Gate it with a real-aomenc stream that enables smooth intra for LUMA while + the chroma refusal is still in place (chroma can still refuse at this + stage — that keeps the two changes separable). COMMIT. +2. **Then** add chroma UV-mode neighbour tracking and remove the smooth/paeth + chroma refusal, with the gate from the attempt diff + (`a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact`) + passing pixel-exact on luma AND chroma. COMMIT. +3. **Then** the directional-chroma sibling if turns remain: `decode.rs:7786`, + the inter-frame intra-block reader, which refuses any non-DC/CFL uv_mode + unconditionally and never computes `angle_delta_uv`. r1 found no bug there, + only unwritten plumbing. COMMIT. + +## Gate rules (mandatory) +- Run tests with `EC_AV1_REQUIRE_AOMENC=1` — a missing oracle must FAIL, not SKIP. +- Bound every ffmpeg `generate` with `-t `. +- Build fixtures through the existing `gradients_source(seed, w, h, tail)` + helper; ffmpeg's `gradients` source ignores its own seed. +- aomenc `--threads=1 --row-mt=0`, and of course `--enable-smooth-intra=1` + (and `--enable-paeth-intra=1` for stage 2). +- Hard-assert a firing count with a thread-local `Cell` counter in + decode.rs matching the existing `*_HITS` (thread-local now, NOT atomics): + for stage 1, count the blocks where `smooth_neighbor` came out TRUE — a gate + that runs with smooth intra enabled but never hits the new branch proves + nothing (class `gate-blind-to-feature`). +- Refusals inside a gate are FORBIDDEN once the stage removing them lands. + +## Method +CLASS `compare-range-not-tell`: compare the msac RANGE against the oracle, never +`tell()`. Oracle at `~/.cache/aom-oracle`, rungs `EC_TRACE=1` (partitions), +`EC_TRACE_COEFF=1`, `EC_TRACE_MODE=1` (inter + intra mode info), +`EC_AV1_PREFILT_DUMP=` (per-frame pre-filter recon — the right rung for +a predictor bug, since it isolates prediction from the loop filters). +Add a rung via `scripts/instrument-aom-oracle.sh` + `scripts/build-aom-oracle.sh` +in the existing shape (env-gated, silent when unset, idempotent) if you need one. + +## Hard rules +- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-chroma`. Foreground builds, + `nice -n 19 cargo ... -j4`. Sibling worktrees (edith_codecs, -realworld, -lr, + -superres, -tiles) have live agents — never build in or edit them. +- Suite: `nice -n 19 cargo test -p ec-av1 --lib`, baseline 232 passed / 0 failed. +- NEVER push, never merge, never touch `main`. Commit on `lane-chroma` only. +- 75-turn cap: COMMIT AFTER EVERY GREEN MILESTONE. r1 spent its whole budget and + landed zero code because it held everything in the working tree; a commit that + compiles beats a perfect uncommitted tree. Do not re-derive what r1's report + already tells you (class `worker-cap-spent-reading`). +- End with `lanes/chroma-r2.report.md`, VERDICT on the first line. diff --git a/lanes/chroma-r3.charter.md b/lanes/chroma-r3.charter.md new file mode 100644 index 00000000..d2bc06b3 --- /dev/null +++ b/lanes/chroma-r3.charter.md @@ -0,0 +1,60 @@ +# lane-chroma r3 — run the smooth-intra gate, then the chroma refusal + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-chroma`, branch +`lane-chroma`. + +## State +- `8bca1d6` — **the luma fix landed**: `smooth_neighbor` is threaded into the + intra edge filter strength instead of being hardcoded `false`. This is r1's + root cause (a directional block neighbouring a smooth-mode one picked the + wrong filter bucket). Committed, compiles. +- The next commit is the orchestrator's cap-rescue of r2's gate: ~140 new lines + in `crates/ec-av1/src/stream.rs`, a smooth-intra gate that **compiles but has + never been run once**. That is your first job. +- `lanes/chroma-r2.charter.md` — still binding for everything below. +- `lanes/chroma-r1.report.md` + `lanes/chroma-r1-attempt.diff` — r1's root-cause + writeup and its reverted attempt (the chroma-side gate lives there). + +## Order — COMMIT AFTER EVERY GREEN STEP +1. Run the new gate: + `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-chroma` then + `EC_AV1_REQUIRE_AOMENC=1 nice -n 19 cargo test -p ec-av1 --lib -j4 -- --nocapture` + with a timeout of at least 600000 ms. Make it pass pixel-exact on luma with a + HARD-asserted firing count proving `smooth_neighbor` actually came out TRUE + somewhere — a gate that enables smooth intra but never hits the new branch + proves nothing (class `gate-blind-to-feature`). Then the full suite + (baseline 232/0 on this tree; main is at 234 with two new guard tests). + COMMIT. +2. Chroma: add UV-mode neighbour tracking to `Neighbours` and remove the + smooth/paeth chroma refusals (decode.rs uv_mode 9..=12, around 1970 and + 2458), with r1's gate + `a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact` from the + attempt diff green on luma AND chroma. COMMIT. +3. Once a gate really enables smooth-intra and paeth-intra, main's + `crates/ec-av1/src/gate_coverage.rs` guard will FAIL by design: its + `NEVER_EXERCISED` list still names `enable-smooth-intra` and + `enable-paeth-intra` as tools no gate exercises. Deleting those two entries + is part of landing this work — that guard exists precisely so closing the + hole is noticed. (The guard is on main, so you will meet it at merge if not + before; if `gate_coverage.rs` is not in your tree yet, note it in the report + for the merge instead.) +4. If turns remain: the directional-chroma sibling at `decode.rs:7786`, the + inter-frame intra-block reader, which refuses any non-DC/CFL uv_mode + unconditionally and never computes `angle_delta_uv`. No known bug there, + just unwritten plumbing. COMMIT. + +## Gate rules (mandatory) +`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 --enable-smooth-intra=1` (and `--enable-paeth-intra=1` +for stage 2); firing counts are HARD asserts via thread-local `Cell` +counters like the existing `*_HITS`. + +## Hard rules +- Own `CARGO_TARGET_DIR` as above; foreground builds, `nice -n 19 cargo ... -j4`; + every `cargo test` gets a timeout of at least 600000 ms. +- Sibling worktrees (edith_codecs, -realworld, -lr, -superres, -tiles) have live + agents. Never build in or edit them. +- NEVER push, never merge, never touch `main`. Commit on `lane-chroma` only. +- 75-turn cap and it does NOT reset on resume: commit at every green step. +- End with `lanes/chroma-r3.report.md`, VERDICT on the first line. diff --git a/lanes/chroma-r4.charter.md b/lanes/chroma-r4.charter.md new file mode 100644 index 00000000..f39d43d9 --- /dev/null +++ b/lanes/chroma-r4.charter.md @@ -0,0 +1,49 @@ +# lane-chroma r4 — finish the chroma refusal removal + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-chroma`, branch +`lane-chroma`. Read `lanes/chroma-r3.charter.md` (still binding) and, briefly, +`lanes/chroma-r1.report.md` for the root cause. Do not re-derive them. + +## State +- `8bca1d6` — the real luma fix: `smooth_neighbor` threaded into the intra edge + filter strength instead of hardcoded `false`. +- `bafda07` — r2's smooth-intra gate, cap-rescued, compiles. +- HEAD — r3's work, cap-rescued by the orchestrator: `decode.rs` +99, + `stream.rs` +126. r3's last words before the cap were "now let's add the r1 + gate for smooth/paeth chroma (charter step 2), then run the full lib test + suite" — so the luma gate is believed to have gone green in r3's hands, but + **no suite run has ever been seen on this tree**. Verify, do not assume. + +## Order +1. `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-chroma` then + `EC_AV1_REQUIRE_AOMENC=1 nice -n 19 cargo test -p ec-av1 --lib -j4` + (timeout >= 600000 ms). Report the count against 232/0 for this tree. + If red, fixing HEAD is the whole job until it is green. COMMIT once green. +2. Chroma: UV-mode neighbour tracking in `Neighbours`, remove the smooth/paeth + chroma refusals (decode.rs uv_mode 9..=12, around 1970 and 2458), with r1's + gate `a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact` + (in `lanes/chroma-r1-attempt.diff`) green on luma AND chroma. COMMIT. +3. Note for the merge: main carries `crates/ec-av1/src/gate_coverage.rs`, whose + `NEVER_EXERCISED` list still names `enable-smooth-intra` and + `enable-paeth-intra` as tools no gate exercises. Once your gates enable them, + those two entries must be deleted — that guard exists so closing the hole is + noticed. If `gate_coverage.rs` is not in your tree, say so in the report so + the merge does it. +4. If turns remain: the directional-chroma sibling at `decode.rs:7786` (the + inter-frame intra-block reader refuses any non-DC/CFL uv_mode and never + computes `angle_delta_uv`). 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 --enable-smooth-intra=1 --enable-paeth-intra=1`; +firing counts are HARD asserts via thread-local `Cell` counters. + +## Hard rules +Own `CARGO_TARGET_DIR` as above; foreground builds `nice -n 19 cargo ... -j4`; +every `cargo test` a timeout >= 600000 ms. Sibling worktrees (edith_codecs, +-realworld, -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 — three rounds in a row on this lane have +ended with the work uncommitted. End with `lanes/chroma-r4.report.md`, VERDICT +on line 1. diff --git a/lanes/chroma-r4.report.md b/lanes/chroma-r4.report.md new file mode 100644 index 00000000..8f49ef06 --- /dev/null +++ b/lanes/chroma-r4.report.md @@ -0,0 +1,66 @@ +VERDICT: GREEN + +## Step 1 -- verify HEAD +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4`: **234 passed; 0 failed; 17 +ignored** (vs the charter's 232/0 baseline -- 2 extra tests are r3's own new +smooth-intra/smooth-paeth-chroma gates, already in HEAD). Tree was clean at +start (nothing to commit for this step); r3's cap-rescued work is genuinely +green, contrary to the "no suite run has ever been seen" warning. + +## Step 2 -- chroma UV-mode neighbour tracking + smooth/paeth chroma refusal +Already done in HEAD (r3's commit `47da0be`): `Neighbours::above_uv_mode`/ +`left_uv_mode` exist, `decode.rs`'s two `read_intra_mode`/`read_intra_mode_rect` +sites (keyframe callers) removed the `9..=12` uv_mode refusal, and +`lanes/chroma-r1-attempt.diff`'s gate +(`a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact`) is +present in `stream.rs` and passes on its own +(`cargo test ... smooth_paeth_chroma` -- 1 passed). No new commit needed. + +## Step 3 -- gate_coverage.rs +`crates/ec-av1/src/gate_coverage.rs` **does not exist in this tree** +(confirmed via `find`). Per the charter, the merge must delete the +`enable-smooth-intra`/`enable-paeth-intra` entries from `NEVER_EXERCISED` +on `main`'s copy. + +## Step 4 -- directional-chroma sibling (turns remained) +Charter's line number (`decode.rs:7786`) had drifted from r3's +99 lines; +the real sibling was `decode_inter_block`'s intra-in-inter branch (the +`else` arm handling an intra block coded inside an inter frame), which read +`uv_mode` and refused outright with `"a directional chroma mode (round 2)"` +for anything past DC/CFL, and never read `angle_delta_uv` at all. + +Fixed by mirroring `read_intra_mode`'s already-proven pattern in that one +function (`crates/ec-av1/src/decode.rs`, `decode_inter_block`): +- `uv_predict_mode` (CFL predicts as DC for the reconstruct call, same as + the keyframe path) threaded through both `u`/`v.reconstruct` calls (skip + path) and both chroma `read_plane` calls (non-skip path), replacing the + hardcoded `DC_PRED`. +- `angle_delta_uv` computed via `read_angle_delta` when `uv_mode` is + directional (`V_PRED..=D67_PRED`), replacing the hardcoded `0`. +- `smooth_neighbor_uv` computed from the chroma neighbour's own `uv_mode` + (`is_smooth_mode(above_uv_mode/left_uv_mode)`), replacing the hardcoded + `false`, threaded into the same reconstruct/read_plane calls. +- `SMOOTH_UV_HITS`/`DIRECTIONAL_UV_HITS` counted here too (shared + thread-locals with the keyframe path). +- `neighbours.record_rect`'s uv-mode arg (previously hardcoded `DC_PRED`) + now carries the real `uv_predict_mode` so a following block's own + smooth-neighbour check sees it. +- The luma-mode side of this branch (`mode`, its own angle_delta refusal at + the top) is **untouched** -- out of this charter step's chroma-only scope. + +`cargo check -p ec-av1 --lib`: clean (no new warnings/errors). Full lib +suite re-run after the change: still **234 passed; 0 failed; 17 ignored** -- +no regression. + +**Gap, disclosed per "refusal strings are claims":** no dedicated gate +proves a real aomenc stream ever actually exercises this specific path (an +intra block, directional/smooth/paeth `uv_mode`, coded *inside an inter +frame*) end to end against ffmpeg. The change is a direct structural mirror +of the already-gated keyframe fix (identical CDF tables, identical +`get_uv_mode`/angle-delta semantics per spec 9.3), and the full suite stays +green, but it is **code-verified by mirroring, not gate-verified by firing**. +`deferred: dedicated a_real_aomenc_stream_with_directional_chroma_in_inter_frame_intra gate -- next round, no seat left this round -- unblocks by writing a stream.rs gate that forces an inter-frame key/delta pair whose delta frame codes an intra 8x8+ leaf with directional/smooth/paeth uv_mode (drop --enable-tx-size-search=0 constraint if it starves the recipe) and asserts on decode::smooth_uv_hits()/directional_uv_hits() firing plus pixel-exact vs ffmpeg`. + +## Commit +`c806bd6` -- directional/smooth/paeth chroma in inter-frame intra blocks. +Nothing else uncommitted; `git status` clean. 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. diff --git a/lanes/realworld-r3.report.md b/lanes/realworld-r3.report.md new file mode 100644 index 00000000..f6344fb5 --- /dev/null +++ b/lanes/realworld-r3.report.md @@ -0,0 +1,158 @@ +# lane-realworld r3 report + +VERDICT: Job 1 (part64 silent desync) FIXED, tested, committed (879999d). +Job 2 (delta_q/delta_lf) UNSTARTED but fully scoped below — turn budget ran +out during the design phase, before any code was written, so there is +nothing half-done to unwind for the next agent. + +## Job 1 -- part64 silent desync (committed 879999d) +`decode_inter_frame_tile_with_cdfs` (decode.rs, the `(true, true)` arm around +what was line 9397) read `part64` then `let _ = part64;`, always recursing +the quadrant loop as if SPLIT. Fixed: the value is now kept (still inferred +as `PARTITION_SPLIT` for the three straddle/forced-half cases, matching the +intra tile's own three-way write), and if a real read comes back anything +other than `PARTITION_SPLIT` the function returns +`Err(unsupported("an inter SB-level partition type other than SPLIT (this +decoder's inter tile path only recurses a superblock as SPLIT)"))` before +the quadrant recursion runs. + +**New refusal string** (verbatim, for the merge's `refusal_inventory.rs`): +`"an inter SB-level partition type other than SPLIT (this decoder's inter +tile path only recurses a superblock as SPLIT)"` + +Test: `decode::tests::a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing` +hand-writes a single `PARTITION_HORZ` `part64` symbol with `SymbolEncoder` +and asserts `decode_inter_frame_tile` returns that named error rather than +decoding garbage. `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4`: +**234 passed, 0 failed, 17 ignored** (was 232/0/17 before this lane; +1 this +test, +1 from r2's CDEF work already on the branch). + +No gate needed for this one (charter: "make it refuse by name... and prove +the refusal with a test" -- minimum rung taken deliberately, not the +"handle it" rung, since real non-SPLIT part64 content requires the same +multi-SB, non-`--cpu-used=0` recipe r2 already flagged as its own separate +lane, not this desync fix). + +## Job 2 -- delta_q/delta_lf: scoped, not started + +Ran the libaom source at `~/.cache/aom-oracle/src/av1/decoder/decodemv.c` +and `av1/common/entropymode.c` directly (real oracle, not memory) before +running out of budget. Concrete plan for the next agent: + +### Default CDFs (verified against entropymode.c:840-852) +Both are 4-symbol alphabets (`DELTA_Q_PROBS`/`DELTA_LF_PROBS` = 3), and this +crate's CDF convention already matches libaom's `AOM_CDF4` arguments +directly (confirmed against `cdf.rs`'s existing `SKIP` table, which is +`AOM_CDF2(31671)` verbatim) -- no inversion needed: +```rust +pub const DELTA_Q: [u16; 5] = [28160, 32120, 32677, 32768, 0]; +pub const DELTA_LF: [u16; 5] = [28160, 32120, 32677, 32768, 0]; +pub const DELTA_LF_MULTI: [[u16; 5]; 4] = [DELTA_Q; 4]; // same value x FRAME_LF_COUNT +``` +(`FRAME_LF_COUNT = 4`, `MAX_LOOP_FILTER = 63`, `DELTA_Q_SMALL = DELTA_LF_SMALL = 3`.) + +### Read logic (decodemv.c:85-146, `read_delta_qindex`/`read_delta_lflevel`, +called from `read_delta_q_params` at :732) +Both follow the same shape: a 4-symbol CDF read; if the result is 3 +(`DELTA_*_SMALL`), extend with `L(3)`-then-`1+that`-many literal bits +(`rem_bits = literal(3)+1; thr = (1<` reset exactly like +`CDEF_TRANSMITTED` (decode.rs ~82, reset alongside it at the top of both +tile loops' `sb_c` loop bodies) replaces the position check with no +behavioural difference. The remaining condition, "skip the read entirely +(state carries over unchanged)", fires only when this first block **is +itself the whole superblock** (`bsize == sb_size`) **and** `skip == true`. + +### Call sites -- only 4, not the dozen it looks like +`maybe_read_cdef_idx` (decode.rs:115) is called from exactly 4 places, +right after each one's own `skip` read, and delta_q/delta_lf's spec order +is `skip -> cdef -> delta_q -> delta_lf` (already commented at decode.rs +~2474: "spec order... `cdef` lands right here" -- delta lands right after +that same line, one function per call site): +- `read_intra_mode_rect` (decode.rs:1987, feeds `decode_block_rect`) -- + `bw`/`bh` never both 64 here (SB-level partition never recurses to a rect + strip directly), so `is_whole_sb` is always `false`. +- `read_intra_mode` (decode.rs:2447, feeds `decode_block`/`decode_leaf8`) -- + has a `side: usize` param; `is_whole_sb = side == 64`. +- `decode_inter_block` (decode.rs:6344) -- has `side: usize`; same rule. +- `decode_inter_block8` (decode.rs:8215) -- always sub-8x8, `is_whole_sb` + always `false`. + +### Threading `CurrentQIndex` into dequant -- narrower than it looks +`base_q_idx: u8` is already threaded as a plain pass-through parameter +through every one of these functions down to exactly 2 real use sites +(confirmed by grep -- `base_q_idx` appears 92x in decode.rs but is *read*, +not just passed, only at decode.rs:2986 and :5397, both +`dequant_and_inverse_typed(..., i32::from(base_q_idx), ...)`). This means +the running quantizer state does **not** need a new parameter threaded +through every block/leaf/rect function signature: a `thread_local! +static CURRENT_Q_IDX: Cell`, reset to `base_q_idx as i32` at the top +of both `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs` +(same place `CDEF_BITS`/`CDEF_SB_COLS` already get set per tile), mutated +only inside the new `maybe_read_delta_q_lf` helper, and read back at the 2 +dequant call sites instead of `i32::from(base_q_idx)`, reproduces the exact +running-state semantics with no signature changes to the block readers. +`DeltaLF` needs the same `Cell<[i32; 4]>` treatment, but **does** need a +consumer: `lf_level`/`edge_params` (decode.rs:3991/4020) currently read +only the frame-level `LoopFilterParams.level` array -- applying `DeltaLF` +there needs `MiGrid`/`fill_lf_grid` (decode.rs:1444) to carry a per-block +delta value forward to the deblocker, which is genuinely new state, not a +narrow substitution like q_idx. This is the part of Job 2 that needs a +real design pass, not just wiring -- flag it to whoever picks this up next. + +### Header threading + refusal removal +`header.delta.{q_present,q_res,lf_present,lf_res,lf_multi}` +(`ec_av1_syntax::frame::DeltaParams`, already parsed) need to become new +parameters on `decode_key_frame_tile_with_cdfs`/`_inter_..._with_cdfs` (and +their public non-`_with_cdfs` wrappers, and `stream.rs`'s 2 call sites), +mirroring how `CdefParams`/`LoopFilterParams` are already threaded. Then +delete the `stream.rs:170-174` refusal +(`"a frame with delta_q_present or delta_lf_present set..."`). + +### Gate +Reproducible refusal fixture already on file (r2's note): `--aq-mode=1` or +default `cpu-used>=1` at 128x64+. Same shape as the CDEF gate (128x64, +2 SBs, `--threads=1 --row-mt=0`), with a hard-asserted firing counter +(`DELTA_Q_HITS`/`DELTA_LF_HITS`, same `Cell` pattern as +`CDEF_IDX_HITS`). + +## Remaining refusal strings verbatim (all pre-existing, untouched by this +lane except the one new one above) +- `"a partition type this encoder never writes"` (decode.rs, intra SB + level, key frame catchall) -- pre-existing, real, out of scope. +- `"a partition type this encoder never writes (value={part32})"` -- pre-existing. +- `"an INTER 32x32 partition type this encoder never writes (value={part32})"` -- pre-existing. +- `"a frame with delta_q_present or delta_lf_present set (this decoder + never reads the per-superblock delta symbols)"` -- Job 2's target, + **still present, still refuses correctly** (not touched this round). +- `"an inter SB-level partition type other than SPLIT (this decoder's + inter tile path only recurses a superblock as SPLIT)"` -- **new this + lane**, Job 1. + +## Merge note +`gate_coverage.rs`/`refusal_inventory.rs` (main-only guards this worktree +doesn't have) need the one new refusal string above added at merge; nothing +to delete from `gate_coverage.rs` this round since no gate closed a tool +entry (Job 1 has no gate by design, see above). + +## Next lever +Job 2 exactly as scoped above. The `DeltaLF`-into-deblocker sub-problem +(new `MiGrid` state, not a narrow substitution) is the one piece that needs +design before code -- everything else (CDFs, read logic, call sites, +`CURRENT_Q_IDX` substitution, header threading, refusal removal, gate +recipe) is now a direct port, not an investigation. diff --git a/lanes/tiles-r2.charter.md b/lanes/tiles-r2.charter.md new file mode 100644 index 00000000..e5d27602 --- /dev/null +++ b/lanes/tiles-r2.charter.md @@ -0,0 +1,61 @@ +# lane-tiles r2 — actually decode the tiles + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-tiles`, branch +`lane-tiles`, at 23f412f. + +## Read first, then write code +- `lanes/tiles.report.md` — r1's report. Its "next lever" section names exact + line ranges and the staging order. Do NOT redo r1's recon (class + `worker-cap-spent-reading`). +- `lanes/tiles.charter.md` — the original charter: the three hard parts + (entropy reset per tile, tile-clipped neighbour availability, + `context_update_tile_id`), the gate rules, the hard rules. Still binding. + +## What r1 landed (1231cd5, suite green 232/0, currently a no-op) +`Neighbours` gained `tile_row0_mi` / `tile_col0_mi` and `start_tile()`, and every +literal-`0` availability check — `skip_txfm_ctx`, `tx_size_context`, +`tx_size_context_rect`, and the has_above / has_left in `decode_inter_block` and +`decode_inter_block8` — now compares against the tile origin instead of 0. +Nothing calls `start_tile()` yet, so the origin stays 0 and behaviour is +unchanged. + +## Still missing (r1's list, verbatim) +- entropy-per-tile restructuring in `decode_key_frame_tile_with_cdfs` / + `decode_inter_frame_tile_with_cdfs` +- `PlaneBuf` tile-pixel-origin clipping — not started +- `mvstack.rs` neighbour scan still frame-relative +- multi-OBU tile-group collection — not started +- the refusal at `stream.rs:294-296` is unchanged and still fires + +## Order — COMMIT AFTER EVERY GREEN STEP +1. Restructure `decode_key_frame_tile_with_cdfs` to loop tiles: fresh msac over + each tile's byte range, fresh copy of the frame's initial CDFs per tile, and + only `context_update_tile_id`'s end-of-tile CDFs kept. Wire `start_tile()` + and the new `PlaneBuf` tile-pixel-origin fields. Prove it on an intra-only + two-tile column split, pixel-exact. COMMIT. +2. Tile rows, then non-uniform spacing. COMMIT. +3. Inter frames — thread the tile origin into `mvstack.rs`'s neighbour scan. + This is where it will break. COMMIT. +4. Several tile-group OBUs per frame. COMMIT. +5. `context_update_tile_id` proven with a stream where it is not tile 0, the + FOLLOWING frame decoding pixel-exact off those inherited CDFs. COMMIT. + +## Gate (mandatory) +Same rules as r1's charter: `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` plus tile-columns/tile-rows log2, a frame large +enough to be splittable, and a HARD-asserted thread-local `Cell` counter +proving more than one tile was decoded. + +## Hard rules +- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tiles`. Foreground builds, + `nice -n 19 cargo ... -j4`; give every `cargo test` a timeout of at least + 600000 ms (the suite runs ~3-4 min; a 120 s default kills it mid-run). +- Sibling worktrees (edith_codecs, -chroma, -realworld, -lr, -superres) have + live agents. Never build in or edit them. +- Baseline 232 passed / 0 failed on this tree; main is at 234 with two new + guard tests you inherit at merge. +- NEVER push, never merge, never touch `main`. Commit on `lane-tiles` only. +- 75-turn cap: commit at every green step. Stage 1 alone committed and green is + a good outcome; a perfect uncommitted tree is not. +- End with `lanes/tiles-r2.report.md`, VERDICT on the first line. diff --git a/lanes/tiles-r3.charter.md b/lanes/tiles-r3.charter.md new file mode 100644 index 00000000..8e699e41 --- /dev/null +++ b/lanes/tiles-r3.charter.md @@ -0,0 +1,48 @@ +# lane-tiles r3 — verify r2's per-tile loop, then finish it + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-tiles`, branch +`lane-tiles`, at d1c2071. + +## State +- `1231cd5` (r1) — tile-origin groundwork in `Neighbours` (`tile_row0_mi`, + `tile_col0_mi`, `start_tile()`), every literal-`0` availability check keyed on + the tile origin. A no-op until something calls `start_tile`. +- `d1c2071` (r2, cap-rescued by the orchestrator) — `decode.rs` +159, + `stream.rs` +3, staged but never committed by r2 and **never seen to compile + or pass anything**. That is your first job: find out what it is. +- `lanes/tiles-r2.charter.md` and `lanes/tiles.charter.md` still govern the + staging, the three hard parts and the gate rules. `lanes/tiles.report.md` has + r1's exact line ranges. + +## Order +1. `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tiles`, then + `cargo check -p ec-av1 --lib` and, if it compiles, + `EC_AV1_REQUIRE_AOMENC=1 nice -n 19 cargo test -p ec-av1 --lib -j4` + (timeout >= 600000 ms). Report the count against 232/0 for this tree. Getting + d1c2071 green is the whole job until it is green. COMMIT once green. +2. Stage 1 from the r2 charter: the key-frame tile decode as a per-tile loop — + fresh msac over each tile's byte range, a fresh copy of the frame's initial + CDFs per tile, only `context_update_tile_id`'s end-of-tile CDFs kept, and + `start_tile()` wired along with the `PlaneBuf` tile-pixel-origin fields. + Proven on an intra-only two-tile column split, pixel-exact, with a + hard-asserted thread-local count of tiles decoded `> 1`. COMMIT. +3. Then tile rows and non-uniform spacing; then inter frames (thread the tile + origin into `mvstack.rs`'s neighbour scan — this is where it will break); + then several tile-group OBUs per frame; then `context_update_tile_id` proven + with a stream where it is not tile 0. One commit each. + +## Note for the merge +Main carries two guards you do not have: `gate_coverage.rs` (pins the aomenc +tools no gate exercises) and `refusal_inventory.rs` (pins every decode-path +refusal string, so adding, renaming or removing one — including the multi-tile +refusal you are here to delete — fails until the list is updated). Report the +refusal strings you change, verbatim. + +## Hard rules +Foreground builds `nice -n 19 cargo ... -j4`, own `CARGO_TARGET_DIR` as above, +every `cargo test` a timeout >= 600000 ms. Sibling worktrees (edith_codecs, +-chroma, -realworld, -lr, -superres, -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 — both rounds on this lane so far ended with +work uncommitted. Stage 1 committed and green is a good round on its own. End +with `lanes/tiles-r3.report.md`, VERDICT on line 1. diff --git a/lanes/tiles-r3.report.md b/lanes/tiles-r3.report.md new file mode 100644 index 00000000..be040582 --- /dev/null +++ b/lanes/tiles-r3.report.md @@ -0,0 +1,67 @@ +VERDICT: PARTIAL -- step 1 (confirm) and step 2 (prove) done and committed; step 3 +(lift the refusal) not attempted, out of turn budget. + +## Step 1: confirmation run +`cargo check -p ec-av1 --tests` clean. `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 +--lib -j4`: 232 passed, 0 failed, 17 ignored, 207.55s -- matches the corrected charter +note exactly. Nothing to commit (tree was already clean at d1c2071). + +## Step 2: prove the per-tile loop on a real two-tile-column stream +Added `a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact` to +`crates/ec-av1/src/stream.rs` (committed 1648317). It: +- builds a 128x64 aomenc key frame with `--tile-columns=1 --tile-rows=0 + --sb-size=64 --loopfilter-control=0`, 20-seed sweep (structural tile split + isn't content-dependent, but this decoder's pre-existing chroma + smooth/paeth refusal is -- accepted as a named refusal like every sibling + gate does for unrelated capabilities); +- parses the stream itself (not `decode_stream`, whose `cols > 1 || rows > 1` + refusal is exactly what this gate runs ahead of) to get the real `Vec` + `Av1Parser::parse_obu` already produces; +- calls `decode_key_frame_tile_with_cdfs(&[tile0, tile1], &header.tile_info, + ...)` directly; +- hard-asserts `tile_hits()` delta `> 1` and pixel-exactness against ffmpeg. + +Result: 20/20 pixel-exact matches, 0 refusals, tile_hits > 1 every time. +`cargo check -p ec-av1 --tests` clean after. + +Two things needed beyond the charter's one-liner: +- `--sb-size=64`: this decoder hardcodes 64px superblocks everywhere + (SB_MI=16); aomenc's own default is 128px SBs, which makes 128x64 exactly + one superblock -- nothing for `--tile-columns=1` to split, `cols` came back + 1 without this. +- `--loopfilter-control=0`: deblocking crosses tile boundaries by spec + default, and `PlaneBuf`'s `tile_x0`/`tile_y0` only ever clip a tile's own + left/top reach (the exact known gap r2 flagged) -- a non-last column's + right-edge deblock read into the next tile wrong without this. Sidestepped + on purpose; not fixed, deblocking is not what this gate proves. + +Also caught and fixed a real bug in my own first draft while wiring the test: +`Tile::offset` is relative to the buffer `parse_obu` was handed, not absolute +in `stream` -- forgetting to add `obu_offset` back (the way `decode_stream` +already does at its own tile-extraction site) fed the decoder garbage-offset +bytes, which silently decoded as an all-skip flat DC block per tile (128/127 +uniform) instead of erroring -- a quiet false negative, not a crash. Fixed +before committing; the committed test carries a comment on this. + +## Step 3: not attempted +Lifting the `cols > 1 || rows > 1` refusal in `decode_stream` needs more than +deleting the `if`: the call site currently hardcodes `&[tile_bytes]` (single +tile, `tiles.first()`), so it needs building the full `tile_bufs: Vec<&[u8]>` +the same way this gate's test code now does (including the `obu_offset` fix), +threaded through for BOTH `decode_key_frame_tile_with_cdfs` and +`decode_inter_frame_tile_with_cdfs`. More importantly, real streams +`decode_stream` sees do NOT get `--loopfilter-control=0` for free -- lifting +the refusal for general (non-test-controlled) multi-tile streams would need +either the right-edge reach gap actually fixed in `PlaneBuf`, or deblocking +proven to not cross tile boundaries in the streams under test +(`loop_filter_across_tiles_enabled` -- unread, not checked this round). +Doing this without checking would very likely reintroduce the exact luma +mismatch this round diagnosed (uncaught first-draft bug notwithstanding) for +any real multi-tile stream with loop filtering on. Left for the next round; +the intra-only case specifically (per charter step 3) still needs the deblock +question answered first. + +## Refusal strings +None added, renamed or removed this round -- the multi-tile refusal in +`stream.rs` is untouched. (Step 3, when attempted, will need to report this +line verbatim before deleting it, per the charter's merge note.) diff --git a/lanes/tiles-r4.charter.md b/lanes/tiles-r4.charter.md new file mode 100644 index 00000000..b3f29b14 --- /dev/null +++ b/lanes/tiles-r4.charter.md @@ -0,0 +1,47 @@ +# lane-tiles r4 — lift the multi-tile refusal + +At 477f972. Read `lanes/tiles-r3.report.md`. + +## State +The per-tile loop works and is proven: gate +`a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact` (stream.rs +~5484) decodes 20/20 pixel-exact with `tile_hits()` hard-asserted `> 1`, by +calling `decode_key_frame_tile_with_cdfs(&[tile0, tile1], ...)` directly and +bypassing the still-live refusal in `decode_stream`. + +Facts r3 paid for: `--sb-size=64` is required (this decoder hardcodes 64px +superblocks; aomenc's default 128px makes a 128x64 frame a single superblock +with nothing to split). `--loopfilter-control=0` is required *for now* because +deblocking crosses tile boundaries by spec default while `PlaneBuf`'s +`tile_x0`/`tile_y0` clip left/top reach only. And a trap that produced a FALSE +PASS: `Tile::offset` is relative to the slice handed to `parse_obu`, not +absolute — forgetting to add `obu_offset` back decoded flat all-skip DC garbage +that compared "equal" instead of erroring. + +## Your job +1. Read `loop_filter_across_tiles_enabled` in `ec-av1-syntax`'s header parse — + grep it first, it may not be parsed at all. Real multi-tile streams reaching + `decode_stream` get no `--loopfilter-control=0` escape hatch, so this + question has to be answered before the refusal comes off. +2. Thread a real `tile_bufs: Vec<&[u8]>` through `decode_stream`'s key-frame AND + inter-frame tile-decode call sites (both currently hardcode + `&[tile_bytes]`), mirroring r3's `obu_offset`-corrected extraction. +3. Lift the `cols > 1 || rows > 1` refusal for the cases you can prove, and + refuse the rest BY NAME with an accurate string. Re-run r3's gate through + `decode_stream` itself, and drop `--loopfilter-control=0` from it once the + crossing question is resolved to see whether it still holds. COMMIT. +4. Then tile rows, non-uniform spacing, inter frames (tile origin into + `mvstack.rs`), several tile-group OBUs, and `context_update_tile_id != 0`. + Also still open: a non-last tile column's right-edge reach bound is + unimplemented (fine for 2 columns, wrong for 3+). + +Merge note: main is at 06d29ee with `gate_coverage.rs` and `refusal_inventory.rs`, +which pin the aomenc tools no gate exercises and every decode-path refusal +string — including the multi-tile refusal you are here to remove. Report every +refusal string you add, rename or remove, verbatim. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tiles`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling +worktrees 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/tiles-r4.report.md`, VERDICT on line 1. diff --git a/lanes/tiles-r4.report.md b/lanes/tiles-r4.report.md new file mode 100644 index 00000000..4179491a --- /dev/null +++ b/lanes/tiles-r4.report.md @@ -0,0 +1,80 @@ +VERDICT: PARTIAL -- steps 1-3 done and committed (9962fb1); step 4 (tile rows, +non-uniform spacing, inter frames, several tile-group OBUs, +context_update_tile_id != 0) not attempted, out of scope this round. + +## Step 1: `loop_filter_across_tiles_enabled` +Grepped `crates/ec-av1-syntax/src/frame.rs`'s `read_loop_filter_params` (spec +5.9.11) end to end: the field does not exist, and it isn't a gap in this +crate's parser -- AV1's spec `loop_filter_params()` has no such syntax +element at all (unlike HEVC's `loop_filter_across_tiles_enabled` PPS flag, +which the charter's naming echoes but AV1 has no equivalent of). Deblocking +crosses tile boundaries unconditionally whenever `loop_filter.level` is +non-zero; there is no per-stream bit that turns it off. That answers the +charter's question: the refusal cannot be conditioned on a header field, +only on whether loop filtering is on at all (`level.iter().any(|&l| l != 0)`) +combined with the already-known `PlaneBuf` gap (tile origin clips a tile's +own left/top reach, never a non-last column's right-edge reach). + +## Step 2: thread real `tile_bufs` through `decode_stream` +`crates/ec-av1/src/stream.rs`'s key-frame call site now builds +`tile_bufs: Vec<&[u8]>` from every element of the OBU's own `tiles: Vec` +(the same `obu_offset + t.offset` correction r3's gate proved necessary) and +passes `&tile_bufs` to `decode_key_frame_tile_with_cdfs` instead of the old +`&[tile_bytes]` (tile 0 only). The inter-frame call site still passes the +single `tile_bytes` it always did -- `decode_inter_frame_tile_with_cdfs` +takes one `&[u8]`, not a tile list, and has no per-tile loop at all; widening +that signature is real work left for step 4 ("inter frames (tile origin into +mvstack.rs)"), not attempted this round. + +## Step 3: lift the refusal, scoped; re-run r3's gate through `decode_stream` +The blanket `cols > 1 || rows > 1` refusal is now four scoped refusals, only +firing for what is genuinely still unproven: +- inter frame with `cols > 1` (no per-tile loop on that path at all) +- `rows > 1` (tile rows never tested) +- `cols > 2` (non-last column's right-edge reach bound past column 0 is + unimplemented -- r3's own documented gap, matters starting at 3 columns) +- multi-tile frame with `loop_filter.level` non-zero anywhere (deblocking + crossing gap from step 1) + +A key frame with exactly 2 tile columns, 1 tile row, and loop filtering off +now decodes through `decode_stream` itself. New test +`a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream` +(`stream.rs`, next to r3's gate) runs the identical aomenc recipe through +`decode_stream(&stream)` instead of the hand-parsed bypass: 20/20 pixel-exact, +`tile_hits()` delta `> 1` every attempt, `pictures.len() == 1`. + +Did not drop `--loopfilter-control=0` from either gate -- step 1 established +that would hit the still-unfixed `PlaneBuf` cross-tile-column reach gap +(the new refusal explicitly names this and blocks it before it can silently +miscode), not something worth testing-then-reverting this round. + +## Full suite +`cargo check -p ec-av1 --tests`: clean (only pre-existing doc-lint warnings). +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4`: 234 passed, 0 +failed, 17 ignored, 146.97s -- both tile gates included, nothing else moved. + +## Refusal strings + +Removed (verbatim, was the single blanket refusal): +> a frame with more than one tile (this decoder only ever decodes tile 0) + +Added, four in its place (all in `stream.rs`, all `Error::unsupported("AV1 +decode_stream", ...)`): +> an inter frame with more than one tile (the inter tile-decode path has no per-tile loop, only key frames do) + +> a frame with more than one tile row (only tile columns are proven pixel-exact so far) + +> a frame with more than two tile columns (a non-last column's right-edge reach bound past column 0 is unimplemented) + +> a multi-tile frame with loop filtering enabled (deblocking crosses tile boundaries by spec default; PlaneBuf's tile origin does not clip a non-last column's right-edge reach) + +## Still open (per charter step 4, unattempted) +Tile rows, non-uniform tile spacing, inter-frame multi-tile decode (needs +`decode_inter_frame_tile_with_cdfs` to grow the same per-tile loop +`decode_key_frame_tile_with_cdfs` already has, plus tile origin threaded into +`mvstack.rs` for inter prediction/MV candidates that reach across a tile +boundary), several tile-group OBUs per frame, `context_update_tile_id != 0` +(this decoder still only ever keeps tile 0's adapted CDF table as the frame's +output regardless of what the header names), and the 3+-column right-edge +reach bound in `PlaneBuf` itself (currently hard-refused via the `cols > 2` +check above rather than silently miscoding). diff --git a/lanes/tiles.charter.md b/lanes/tiles.charter.md new file mode 100644 index 00000000..3f1b0acf --- /dev/null +++ b/lanes/tiles.charter.md @@ -0,0 +1,96 @@ +# lane-tiles — multi-tile decode + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-tiles`, branch +`lane-tiles`, off main (48a6e29 or later). + +## Goal +Remove the refusal at `crates/ec-av1/src/stream.rs:293-298` +("a frame with more than one tile (this decoder only ever decodes tile 0)") +by decoding every tile of every tile group, in order, into one picture. + +## What is already there +- `crates/ec-av1-syntax/src/frame.rs:115` `TileInfo` already carries everything + the walk needs: `cols`, `rows`, `cols_log2`, `rows_log2`, `mi_col_starts` + (`TileCols + 1` entries, 4x4 units), `mi_row_starts`, `context_update_tile_id`, + `tile_size_bytes`. The uniform/non-uniform spacing derivation is at + `frame.rs:1292` onward and is already implemented — READ it, do not re-derive. +- The tile-group OBU parse already produces per-tile `offset`/`size`; today + `stream.rs` takes `tiles.first()` and drops the rest. `Tile::offset` is + relative to the OBU buffer, not to `data` — see the comment at stream.rs:298. +- The superblock walk lives in `crates/ec-av1/src/decode.rs` (two sites, around + lines 4547 and 9275: `for sb_r in 0..sb_rows { for sb_c ... }`). Today those + bounds are the whole frame; per tile they become the tile's own sb range + derived from `mi_row_starts[t]..mi_row_starts[t+1]`. + +## The three things that make tiles more than a loop +1. **Entropy reset per tile.** Each tile starts a FRESH msac decoder over its + own byte range AND a fresh copy of the frame's initial CDFs (spec 5.11.2 + `decode_tile`: `init_symbol` + `clear_above_context`). Only the tile named by + `context_update_tile_id` has its END-of-tile adapted CDFs saved as the + frame's output tables (spec `exit_symbol`) — every other tile's adaptation is + discarded. This is exactly what the current refusal comment warns about. +2. **Context reset at tile boundaries.** Above-context arrays are cleared at the + start of each tile ROW of superblocks within the tile; left-context at each + superblock row. Neighbour availability MUST be clipped to the tile: a block + at the tile's left edge has NO left neighbour even though a decoded block + sits there in the picture. Same for above. Grep libaom + `av1/decoder/decodeframe.c` `av1_tile_init`/`av1_tile_set_col`/ + `av1_tile_set_row` and `av1/common/tile_common.c`; the availability + predicates are `xd->left_available` / `xd->up_available`, set in + `set_mi_row_col` (av1/common/blockd.h). Deblocking and CDEF, by contrast, + run ACROSS tile boundaries unless `loop_filter_across_tiles` says otherwise — + check the actual v3.13.3 source, AV1 has no such flag in the final spec but + verify rather than assume. + Also check the mv-stack / ref-mv scan (`crates/ec-av1/src/mvstack.rs`) and + the CDEF/deblock neighbour reads for the same tile clipping. +3. **Tile ordering across tile groups.** A frame may carry several tile-group + OBUs; tiles are numbered `tg_start..tg_end` globally. + +## Method +CLASS `compare-range-not-tell`: compare the msac RANGE against the oracle after +each element, never `tell()`. The instrumented oracle is at `~/.cache/aom-oracle` +with env-gated rungs (`EC_TRACE=1` partitions, `EC_TRACE_COEFF=1`, +`EC_TRACE_MODE=1`); `scripts/instrument-aom-oracle.sh` + `scripts/build-aom-oracle.sh` +add and rebuild rungs. If you need a per-tile rung (tile index at each +`decode_tile` entry), add one in the existing shape: env-gated, silent when +unset, idempotent, wrapper-around-impl. +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. + +## Staging — COMMIT AFTER EVERY GREEN MILESTONE (75-turn cap; builders have lost whole implementations here) +1. Two tiles, one column split, all-intra key frame. COMMIT. +2. Tile rows as well as columns; non-uniform spacing. COMMIT. +3. Inter frames (mv-stack + neighbour clipping is where this will break). COMMIT. +4. Several tile-group OBUs per frame. COMMIT. +5. `context_update_tile_id` proven: a stream where it is NOT tile 0, decoding + pixel-exact across the following frame (which inherits those CDFs). COMMIT. + +## Gate (mandatory, in `crates/ec-av1/src/stream.rs` beside the existing gates) +- Copy the existing gate shape. Tests must be run with `EC_AV1_REQUIRE_AOMENC=1` + so a missing oracle FAILS instead of SKIPping. +- Bound every ffmpeg `generate` with `-t ` (an unbounded source once + hung a gate for an hour). +- Build fixtures through the existing `gradients_source(seed, w, h, tail)` + helper — ffmpeg's `gradients` ignores its own seed, so a hand-written + `gradients=size=` string makes the gate non-reproducible. +- aomenc: `--threads=1 --row-mt=0` plus `--tile-columns=1 --tile-rows=1` + (log2 values in aomenc) on a frame large enough that the tiles are legal — + a 64x64 frame cannot be split, so size the fixture accordingly. +- Hard-assert a firing count: a thread-local `Cell` counter in decode.rs + matching the existing `*_HITS` (thread-local, NOT atomics), incremented per + tile decoded, asserted `> 1`. CLASS `gate-blind-to-feature`: a gate that + cannot prove its feature fired is vacuous. +- Refusals inside the gate are FORBIDDEN once the stage removing them lands. + +## Hard rules +- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tiles`. Foreground builds + only, `nice -n 19 cargo ... -j4`. Never build in or edit another worktree: + edith_codecs, -chroma, -realworld, -lr, -superres all have agents in them NOW. +- Suite: `nice -n 19 cargo test -p ec-av1 --lib`, baseline 232 passed / 0 failed + (~67 s). It stays green. +- NEVER push, never merge, never touch `main`. Commit on `lane-tiles` only. +- Refuse-by-name rather than desync; never write a refusal string claiming the + encoder cannot emit a case unless you proved it (class + `refusal-claim-disproved-by-its-own-gate`). +- End with `lanes/tiles.report.md`: what landed, gate name + firing count, + remaining refusal strings verbatim, next lever. diff --git a/lanes/tiles.report.md b/lanes/tiles.report.md new file mode 100644 index 00000000..acd77e16 --- /dev/null +++ b/lanes/tiles.report.md @@ -0,0 +1,116 @@ +# lane-tiles report + +## What landed +Groundwork only, commit `1231cd5` on branch `lane-tiles`: +`crates/ec-av1/src/decode.rs` +- `Neighbours` gained `tile_row0_mi`/`tile_col0_mi` (spec `MiRowStart`/ + `MiColStart`), default `0`, and `start_tile(row0_mi, col0_mi, col1_mi)` + (spec `decode_tile`'s `clear_above_context` over the tile's own column + span; left-context reset per SB row was already unconditional and needed + no change). +- Every availability check that compared a raw mi position against literal + `0` now compares against the tile origin instead: `skip_txfm_ctx`, + `tx_size_context`, `tx_size_context_rect`, and `decode_inter_block`/ + `decode_inter_block8`'s `has_above`/`has_left`. +- Behaviourally a no-op today: nothing calls `start_tile`, so the origin + stays `(0, 0)` everywhere and every existing test is bit-identical. + +The refusal at `crates/ec-av1/src/stream.rs:292-297` ("a frame with more +than one tile") is **unchanged and still fires** — it was not removed. + +## Why it stops here (turn budget) +Recon (charter + call-site tracing across `decode.rs`, `mvstack.rs`, +`ec-av1-syntax/frame.rs`'s `TileInfo`/`parse_tile_group`) took the first +~35 tool calls to establish the real shape of the three hard parts. What +full removal of the refusal needs, none of which is done: +1. **Entropy per tile.** `decode_key_frame_tile_with_cdfs` / + `decode_inter_frame_tile_with_cdfs` each take one `data: &[u8]` and run + one `SymbolDecoder`/`cdfs` over the whole `for sb_r in 0..sb_rows { for + sb_c in 0..sb_cols }` walk. This needs restructuring into a `for tile in + &tiles` outer loop: fresh `SymbolDecoder` per tile's own byte range + (`Tile::offset` is relative to the OBU, already handled correctly in + stream.rs for tile 0 today), fresh `cdfs = initial_cdfs.clone()` per + tile, sb range narrowed to `mi_row_starts[t]/SB_MI..mi_row_starts[t+1]/ + SB_MI` (same for cols), and only `context_update_tile_id`'s own + end-of-tile `cdfs` returned as the frame's adapted table. `TileInfo` + already carries everything this needs (`frame.rs:115`); the derivation + at `frame.rs:1292` confirms `mi_col_starts`/`mi_row_starts` are always + fully populated by the real parser, including the `cols==rows==1` case. +2. **Context clipping — partially wired, NOT complete.** This commit's + `Neighbours` change covers the context-symbol reads it touched. Two + things it does **not** cover: + - `PlaneBuf::edges`/`edges_rect` (`decode.rs` ~2653-2696) still gate + intra-prediction pixel reach on `x > 0`/`y > 0` — a block at a tile's + own left/top edge would read real reconstructed pixels from the + PREVIOUS tile (decoded earlier, sitting right there in the shared + buffer) instead of treating them as unavailable, which is a real + pixel-value bug per spec (AV1 tiles are independently decodable; + intra prediction does not cross tile boundaries). Needs a + `tile_x0`/`tile_y0` pair on `PlaneBuf` (luma-pixel and chroma-pixel + scaled, i.e. `mi_col0*4`/`mi_col0*2`), set before each tile, checked + in `edges`/`edges_rect` in place of `0`. + - `mvstack.rs`'s `find_mv_stack_with_sign_bias` (the actual MV + neighbour scan for every inter block) still hardcodes + `mi_row > 0`/`mi_col > 0` for `max_row_offset`/`max_col_offset` and + `found_above`/`found_left` (its own doc comment at line ~690 already + flags this: *"clamped to the tile's near edge (single-tile-per-frame + here, so that's just the frame edge at 0)"*). `find_samples`/ + `num_proj_ref` (`decode.rs` ~5488/5617, warp-sample gathering for + `WARPED_CAUSAL`) have the same gap. Neither was touched this round. + - Deblock/CDEF were confirmed (not just assumed) to run across the + whole picture after all tiles decode (`apply_deblock`/`apply_cdef` + calls sit after the SB loop, once, over the full `y`/`u`/`v`) — + these need **no** tile clipping, matching the charter's note. +3. **Tile-group ordering.** Not started. `ObuKind::Frame(header, tiles)`'s + `tiles: Vec` already spans every tile in `tg_start..tg_end` for a + *single* OBU (`parse_tile_group`, `ec-av1-syntax/src/frame.rs:1992`), + which covers the common `--tile-columns`/`--tile-rows` aomenc case (one + `OBU_FRAME` carries every tile). The separate multi-OBU case + (`ObuKind::FrameHeader` followed by one or more standalone + `ObuKind::TileGroup(Vec)` OBUs) is not collected at all today — + `decode_stream`'s `while pos < data.len()` loop only matches + `ObuKind::Frame`/`FrameHeader` (for `show_existing_frame`) and silently + `continue`s past everything else, including a bare `TileGroup` OBU. + +No gate was added — the charter's mandatory gate asserts a tile-firing +counter `> 1` on real decoded output, which requires part 1 (entropy per +tile) to exist first; writing the gate against the untouched refusal would +either be vacuous or fail immediately. + +## Remaining refusal strings (verbatim, unchanged) +- `"a frame with more than one tile (this decoder only ever decodes tile 0)"` + — `stream.rs:294-296`, still fires for every `tile_info.cols > 1 || + tile_info.rows > 1` frame, intra or inter. + +## Verification +`cargo test -p ec-av1 --lib` (`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tiles`, +`EC_AV1_REQUIRE_AOMENC=1`): 232 passed, 0 failed, 17 ignored, 174.28s — +baseline unchanged, no regression from the groundwork commit. + +## Next lever (for whoever picks this up) +Land in the charter's own staged order, each its own commit: +1. Restructure `decode_key_frame_tile_with_cdfs` to accept + `tiles: &[(u32 /* tile_num */, &[u8])]` + `&TileInfo` in place of a + single `data: &[u8]`, wrap the existing SB double loop (currently + `decode.rs` lines ~4547 header `for sb_r in 0..sb_rows` through its + matching close ~4947) in `for &(tile_num, bytes) in tiles`, call + `neighbours.start_tile(...)` (already written, unused) and set + `PlaneBuf` tile pixel origins (not yet added) at each tile's start, + narrow the sb range, and capture `cdfs` as the returned table only when + `tile_num == tile_info.context_update_tile_id`. Update the one caller + (`decode_key_frame_tile`, `decode.rs:4478`) and `stream.rs`'s key-frame + branch to build the tile list instead of `tiles.first()`. Prove stage 1 + (two tiles, column split, all-intra) before touching anything else. +2. Same restructuring for `decode_inter_frame_tile_with_cdfs`, PLUS + threading `tile_row0_mi`/`tile_col0_mi` into `find_mv_stack_with_sign_bias` + and `find_samples`/`num_proj_ref` (both currently frame-relative-only). +3. Multi-tile-group OBU collection in `decode_stream`'s main loop + (`ObuKind::FrameHeader` + trailing `ObuKind::TileGroup` accumulation + before dispatch, mirroring the existing `pending: Option` + field already on `Av1Parser` internally, though that field is private — + check whether it's exposed or the collection has to happen in + `decode_stream` itself against raw OBU events). +4. `context_update_tile_id != 0` pin test once tables save correctly. +5. The mandatory gate: `--tile-columns=1 --tile-rows=1` aomenc recipe + (log2 values), thread-local `TILE_HITS` counter (not yet added) + incremented once per tile actually decoded, hard-asserted `> 1`.