diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index b76ea5b2..d0ac55e0 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1583,6 +1583,21 @@ pub(crate) fn angle_delta_hits() -> usize { pub(crate) fn tx_class1_hits() -> usize { TX_CLASS1_HITS.with(|c| c.get()) } + +// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent +// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion +// bottom) this thread's decode actually reconstructed -- the same +// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream +// genuinely exercised the sub-8x8 leaf path rather than every attempt +// coincidentally landing on `PARTITION_NONE`. +thread_local! { + static SUB8_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`SUB8_SPLIT_HITS`]. +pub(crate) fn sub8_split_hits() -> usize { + SUB8_SPLIT_HITS.with(|c| c.get()) +} const SUB_MI: u32 = 4; const MI: usize = 4; const SB: usize = 64; @@ -2486,6 +2501,26 @@ struct Neighbours { /// one was coded at 8x8. above_side_mi: Vec, left_side_mi: Vec, + /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column + /// / row, with the mi position it was written at + /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on + /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an + /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode + /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8 + /// leaf whose neighbour is another split group needs that group's leaf 3 + /// (bottom-right), not the leaf the coarse slot happens to hold. Written + /// and read only by [`decode_leaf_split4`]; the position guard makes it + /// fall back to the coarse slot whenever the real neighbour was a block + /// of 8x8 or larger (whose one mode is correct for every row it spans). + sub8_mode_col: Vec<(usize, usize)>, + sub8_mode_row: Vec<(usize, usize)>, + /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5): + /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode` + /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse + /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves -- + /// the leaf above writes the same row slot the block to the left owns. + uv_mode_col: Vec<(usize, usize)>, + uv_mode_row: Vec<(usize, usize)>, /// Whether the block above/left of this column/row was coded `skip` -- /// an inter frame's own `skip` context (spec `SkipContext`), which the /// key-frame writer never tracks (its skip context is always zero); a @@ -2633,6 +2668,10 @@ impl Neighbours { left_side: vec![SB; rows], above_side_mi: vec![SB; cols * (SUB / MI)], left_side_mi: vec![SB; rows * (SUB / MI)], + sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)], + sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)], + uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)], + uv_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)], above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)], // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an @@ -2716,6 +2755,14 @@ impl Neighbours { self.above_compound_idx[i] = 0; self.above_filter[i] = [3u8; 2]; } + // lane-sub8 r6: the mi-granular column maps are per tile too -- a + // stale `(row, mode)` from the tile to the LEFT names an mi row this + // tile's first block would read as its own above neighbour. + let mcol_end = col1_mi.min(self.sub8_mode_col.len()); + for i in col0_mi.min(mcol_end)..mcol_end { + self.sub8_mode_col[i] = (usize::MAX, 0); + self.uv_mode_col[i] = (usize::MAX, 0); + } } /// Writes a just-decoded block's own palette-Y size/colours (`size == 0` @@ -2984,6 +3031,10 @@ impl Neighbours { self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0); self.left_compound_idx.iter_mut().for_each(|r| *r = 0); self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]); + // lane-sub8 r6: mi-granular row maps reset with the rest of the left + // context (a tile/SB-row boundary has no left neighbour). + self.sub8_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0)); + self.uv_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0)); } /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next @@ -3272,6 +3323,85 @@ impl Neighbours { /// [`Self::partition_ctx`]) are the neighbour's own width/height per the /// spec's per-edge partition-context rule, so a true rectangular block /// naturally wants two different values here rather than one. + /// Writes this block's luma `mode` into the mi-granular + /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi + /// position a *later* neighbour would read it from: the block's LAST mi + /// row for every column it spans (what the block below reads via + /// `mi(row-1, col)`) and its LAST mi column for every row (what the + /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves + /// read these back, and only when the recorded position is exactly their + /// own neighbour -- see [`Self::sub8_mode_col`]'s doc. + fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) { + let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1); + for cell in 0..mi_w { + if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) { + *slot = (last_r, mode); + } + } + for cell in 0..mi_h { + if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) { + *slot = (last_c, mode); + } + } + } + + /// The mi-exact above/left neighbour luma mode for a block whose top-left + /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact + /// mi position (then the coarse [`SUB`]-grid slot is right by + /// construction). See [`Self::record_mode_mi`]. + fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option { + match self.sub8_mode_col.get(mi_c) { + Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => Some(m), + _ => None, + } + } + + fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option { + match self.sub8_mode_row.get(mi_r) { + Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => Some(m), + _ => None, + } + } + + /// [`Self::record_mode_mi`] for the block's `uv_mode`, into + /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`]. + fn record_uv_mode_mi( + &mut self, + mi_r: usize, + mi_c: usize, + mi_w: usize, + mi_h: usize, + uv_mode: usize, + ) { + let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1); + for cell in 0..mi_w { + if let Some(slot) = self.uv_mode_col.get_mut(mi_c + cell) { + *slot = (last_r, uv_mode); + } + } + for cell in 0..mi_h { + if let Some(slot) = self.uv_mode_row.get_mut(mi_r + cell) { + *slot = (last_c, uv_mode); + } + } + } + + /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)` + /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for + /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no + /// block has recorded the exact neighbouring mi. + fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool { + let above = match self.uv_mode_col.get(mi_c) { + Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => m, + _ => self.above_uv_mode[c], + }; + let left = match self.uv_mode_row.get(mi_r) { + Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => m, + _ => self.left_uv_mode[r], + }; + is_smooth_mode(above) || is_smooth_mode(left) + } + fn record_rect( &mut self, at: (usize, usize), @@ -3292,6 +3422,8 @@ impl Neighbours { self.left_uv_mode[r + cell] = uv_mode; self.left_side[r + cell] = h; } + self.record_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, mode); + self.record_uv_mode_mi(r * (SUB / MI), c * (SUB / MI), w / MI, h / MI, uv_mode); self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids); } @@ -3421,6 +3553,8 @@ impl Neighbours { } let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); let (w_mi, h_mi) = (w / MI, h / MI); + self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode); + self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode); for cell in 0..h_mi { self.left_side_mi[mi_r + cell] = h; } @@ -4734,6 +4868,11 @@ fn decode_leaf_rect( vec![0i32; chroma_w * chroma_h], ], ); + // lane-sub8 r6: the caller patches only the coarse `above_mode`/ + // `left_mode` slot (one value for the whole 16x16), so record this + // strip's own span mi-exactly like every square leaf does. + neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode); + neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode); neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip); neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0); Ok(mode) @@ -5182,7 +5321,7 @@ fn read_intra_mode( } let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; if trace { - eprintln!("TRACE skip value={}", skip as i32); + eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0); } istep!("skip", skip as i32); if !seg_id_pre_skip() { @@ -5228,7 +5367,7 @@ fn read_intra_mode( let left_ctx = INTRA_MODE_CTX[left_mode]; let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]); if trace { - eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}"); + eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0); } istep!("mode", mode as i32); let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { @@ -5250,7 +5389,7 @@ fn read_intra_mode( dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; if trace { - eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}"); + eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0); } istep!("uv_mode", uv_mode as i32); let alpha = if cfl && uv_mode == UV_CFL_PRED { @@ -5369,7 +5508,7 @@ fn read_intra_mode( let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0; if trace { eprintln!( - "TRACE use_filter_intra side={side} value={}", + "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0, use_filter_intra as i32 ); } @@ -6400,9 +6539,26 @@ 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. + // The mi-exact neighbour wins over both the coarse 16x16 slot and + // `prev_leaf`: one 16x16 slot cannot hold the two different modes its + // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left + // neighbour sits in a split cell read the wrong `kf_y_mode` row. + if let Some(m) = neighbours.mode_above_mi(leaf_mi.0, leaf_mi.1) { + above_mode = m; + } + if let Some(m) = neighbours.mode_left_mi(leaf_mi.0, leaf_mi.1) { + left_mode = m; + } let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); + // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode` + // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode + // this leaf's `smooth_neighbor` is built from -- passing `false` here + // filtered a directional chroma block's edge at the wrong strength + // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3). + // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`), + // with the coarse [`SUB`] slot as the fallback when no block recorded + // that exact mi cell. + let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c); if smooth_neighbor { SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); } @@ -6431,6 +6587,9 @@ fn decode_leaf8( } else { uv_mode }; + neighbours.above_uv_mode[c] = uv_predict_mode; + neighbours.left_uv_mode[r] = uv_predict_mode; + neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode); // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1, // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4 @@ -6469,7 +6628,7 @@ fn decode_leaf8( &vec![0i32; 16], alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, - false, + smooth_neighbor_uv, ); v.reconstruct( cpx, @@ -6481,7 +6640,7 @@ fn decode_leaf8( &vec![0i32; 16], alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, - false, + smooth_neighbor_uv, ); luma_grid = vec![0i32; 64]; u_grid = vec![0i32; 16]; @@ -6535,7 +6694,7 @@ fn decode_leaf8( alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, - false, + smooth_neighbor_uv, )?; v_grid = read_plane( dec, @@ -6557,7 +6716,7 @@ fn decode_leaf8( alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, - false, + smooth_neighbor_uv, )?; } else { // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order @@ -6633,7 +6792,7 @@ fn decode_leaf8( alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, - false, + smooth_neighbor_uv, )?; v_grid = read_plane( dec, @@ -6655,7 +6814,7 @@ fn decode_leaf8( alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, - false, + smooth_neighbor_uv, )?; // `record_split_luma` expects a `record`-style `(r, c)` position in // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is @@ -6687,14 +6846,290 @@ fn decode_leaf8( } neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid(leaf_mi, 2, 4, 0); + neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode); return Ok(mode); } neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]); neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid(leaf_mi, 2, 8, 0); + neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode); Ok(mode) } +/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf +/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8` +/// bottom, where no partition symbol is read at all -- `decode_block` runs +/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec +/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always +/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference` +/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf +/// of the 2x2 4x4 group carries chroma syntax at all. +#[allow(clippy::too_many_arguments)] +fn read_intra_mode_sub8( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + above_mode: usize, + left_mode: usize, + has_chroma: bool, + enable_filter_intra: bool, + skip_ctx: usize, + allow_intrabc: bool, + mi_r: usize, + mi_c: usize, +) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option)> { + let trace = std::env::var_os("EC_AV1_TRACE").is_some(); + let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; + if trace { + eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0); + } + maybe_read_cdef_idx(dec, mi_r, mi_c, skip); + maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip); + maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip); + if allow_intrabc { + let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; + if use_intrabc { + return Err(unsupported( + "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)", + )); + } + } + 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]); + if trace { + eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0); + } + // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/ + // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`, + // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta + // symbol. Reading one consumed a symbol the encoder never wrote and + // desynced the tile at the very next element. + let angle_delta_y = 0; + let chroma = if has_chroma { + let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]); + if trace { + eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0); + } + if (9..=12).contains(&uv_mode) { + SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1)); + } + let alpha = if uv_mode == UV_CFL_PRED { + Some(read_cfl_alphas(dec, cdfs)) + } else { + None + }; + if (V_PRED..=D67_PRED).contains(&uv_mode) { + DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1)); + } + // See the luma comment above: no angle delta below 8x8. + let angle_delta_uv = 0; + Some((uv_mode, angle_delta_uv, alpha)) + } else { + None + }; + let mut filter_intra = None; + if mode == DC_PRED && enable_filter_intra { + // `BLOCK_4X4`'s own row (class 0, `filter_intra_size_class(4)`) -- + // every sub-8x8 leaf here is a `BLOCK_4X4`. + let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[0]) != 0; + if trace { + eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32); + } + if use_filter_intra { + FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1)); + let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode); + filter_intra = Some(fi_mode); + } + } + Ok((skip, mode, angle_delta_y, chroma, filter_intra)) +} + +/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves +/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s +/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode` +/// bookkeeping needs no change. Each leaf reads its own luma mode info, +/// neighboured off the *previously decoded leaf in this same group* on +/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf` +/// pattern, one level deeper); chroma is read and reconstructed exactly +/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4 +/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference` +/// derivation. +#[allow(clippy::too_many_arguments)] +fn decode_leaf_split4( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + outer_at: (usize, usize), + leaf_mi: (usize, usize), + scan4: &[u16], + prev_leaf: Option<((usize, usize), usize)>, + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + base_q_idx: u8, + enable_filter_intra: bool, + allow_intrabc: bool, + reduced_tx_set: bool, + // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8 + // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the + // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1)). +) -> Result<(usize, usize)> { + SUB8_SPLIT_HITS.with(|c| c.set(c.get() + 1)); + let (r, c) = outer_at; + let mut above_mode = neighbours.above_mode[c]; + let mut left_mode = neighbours.left_mode[r]; + if let Some(((pr, pc), pmode)) = prev_leaf { + if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 { + above_mode = pmode; + } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 { + left_mode = pmode; + } + } + // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter + // type is the chroma neighbours' `uv_mode`, mi-exact where recorded. + let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c); + let mut leaf_modes = [0usize; 4]; + let mut leaf_skips = [false; 4]; + let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None; + for i in 0..4usize { + let (dr, dc) = (i / 2, i % 2); + let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc); + // Neighbour modes at real mi granularity: inside the group the + // sibling leaf, outside it the split-leaf map when the adjacent mi + // was itself a 4x4 leaf, else the coarse 16x16 slot (see + // `sub8_mode_col`'s doc). + let leaf_above = if dr == 0 { + neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode) + } else { + leaf_modes[i - 2] + }; + let leaf_left = if dc == 0 { + neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode) + } else { + leaf_modes[i - 1] + }; + let has_chroma = i == 3; + let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1); + let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8( + dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra, skip_ctx, + allow_intrabc, lmi.0, lmi.1, + )?; + leaf_modes[i] = mode; + leaf_skips[i] = skip; + neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode); + let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left); + if smooth_neighbor { + SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); + } + let (px, py) = (lmi.1 * MI, lmi.0 * MI); + let reach = Reach::of(4, px, py, y.width, y.height); + if skip { + y.reconstruct(px, py, 4, mode, angle_delta_y, reach, &vec![0i32; 16], None, filter_intra, smooth_neighbor); + neighbours.record_mi_luma(lmi, 4, &vec![0i32; 16]); + } else { + let tu_around = neighbours.around_mi(lmi, 4)[0]; + // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's + // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]` + // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table + // (`txb_common.h:400`). Reading the table here decoded `all_zero` + // off the wrong CDF on the very first leaf and desynced the tile. + let tu_grid = read_plane( + dec, + cdfs, + if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 }, + scan4, + 0, + tu_around, + mode, + mode, + angle_delta_y, + reach, + y, + px, + py, + 4, + 4, + base_q_idx, + None, + filter_intra, + None, + smooth_neighbor, + )?; + neighbours.record_mi_luma(lmi, 4, &tu_grid); + } + neighbours.fill_skip_grid(lmi, 1, skip); + neighbours.fill_lf_grid(lmi, 1, 4, 0); + if has_chroma { + last_uv = chroma; + } + } + let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI); + let (cpx, cpy) = (gpx / 2, gpy / 2); + let group_reach = Reach::of(8, gpx, gpy, y.width, y.height); + let (uv_mode, angle_delta_uv, alpha) = + last_uv.expect("i==3 always sets has_chroma, so chroma is always Some"); + let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; + neighbours.above_uv_mode[c] = uv_predict_mode; + neighbours.left_uv_mode[r] = uv_predict_mode; + neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode); + let (u_grid, v_grid): (Vec, Vec) = if leaf_skips[3] { + u.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv); + v.reconstruct(cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], None, None, smooth_neighbor_uv); + (vec![0i32; 16], vec![0i32; 16]) + } else { + let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8)); + let chroma_around = neighbours.around_mi(leaf_mi, 8); + let ug = read_plane( + dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode, + angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx, + alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, + )?; + let vg = read_plane( + dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode, + angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx, + alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, + )?; + (ug, vg) + }; + // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors + // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s + // rescaling is wrong for an already-mi-unit position, so this inlines + // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition + // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one + // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is + // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8 + // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion + // bottom). libaom's `update_ext_partition_context` writes + // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for + // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via + // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and + // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs + // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this + // round's bug) makes the very next sibling 8x8's `partition_w8` read + // with the wrong context and desync immediately. + let side_mi = 2; + for cell in 0..side_mi { + neighbours.left_side_mi[leaf_mi.0 + cell] = 4; + neighbours.above_side_mi[leaf_mi.1 + cell] = 4; + } + let round_up_even = |n: usize| n.div_ceil(2) * 2; + let bound_h = round_up_even(neighbours.mi_rows); + let bound_w = round_up_even(neighbours.mi_cols); + let u_state = neighbour_state(&u_grid); + let v_state = neighbour_state(&v_grid); + for cell in 0..side_mi { + if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) { + neighbours.left[leaf_mi.0 + cell][1] = u_state; + neighbours.left[leaf_mi.0 + cell][2] = v_state; + } + if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) { + neighbours.above[leaf_mi.1 + cell][1] = u_state; + neighbours.above[leaf_mi.1 + cell][2] = v_state; + } + } + Ok((leaf_modes[2], leaf_modes[1])) +} + /// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary /// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2` /// (mod 8) reuse the same table. @@ -8777,11 +9212,38 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // the one or two the edge leaves. let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); - let mut prev_leaf: Option<((usize, usize), usize)> = None; + // Each 8x8 leaf's intra-mode context + // must see its own siblings: the + // bottom-left leaf's ABOVE neighbour + // is leaf 0, not the previously + // decoded leaf 1 (and the bottom-right + // leaf's above is leaf 1, while + // `prev_leaf` only ever carried the + // immediately preceding one). The + // coarse `above_mode`/`left_mode` + // arrays hold one slot per 16x16, so + // the sibling modes are swapped in + // around each leaf call and restored + // after; the loop tail writes the last + // leaf's mode as before. + let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4]; for i in 0..4 { let (mr, mc) = (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2); let leaf_mi = (mr as usize, mc as usize); + let li = i as usize; + let saved_modes = + (neighbours.above_mode[sc], neighbours.left_mode[sr]); + if li >= 2 { + if let Some((below, _)) = sib_modes[li - 2] { + neighbours.above_mode[sc] = below; + } + } + if li % 2 == 1 { + if let Some((_, right)) = sib_modes[li - 1] { + neighbours.left_mode[sr] = right; + } + } let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); @@ -8790,34 +9252,56 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}" ); } - if part8 != PARTITION_NONE { + let leaf_mode = if part8 == PARTITION_NONE { + decode_leaf8( + &mut dec, + &mut cdfs, + &mut neighbours, + at16, + leaf_mi, + (&scan8, &scan4), + None, + &mut y, + &mut u, + &mut v, + base_q_idx, + enable_filter_intra, + allow_screen_content_tools, + allow_intrabc, + tx_select, + reduced_tx_set, + ).map(|m| (m, m))? + } else if part8 == PARTITION_SPLIT { + decode_leaf_split4( + &mut dec, + &mut cdfs, + &mut neighbours, + at16, + leaf_mi, + &scan4, + None, + &mut y, + &mut u, + &mut v, + base_q_idx, + enable_filter_intra, + allow_intrabc, + reduced_tx_set, + )? + } else { return Err(unsupported( - "a partition below 8x8 (this decoder codes no leaf smaller than 8x8)", + "a HORZ/VERT partition below 8x8 (this decoder's transform primitive is square-only; 4x8/8x4 need a real rectangular transform)", )); - } - let leaf_mode = decode_leaf8( - &mut dec, - &mut cdfs, - &mut neighbours, - at16, - leaf_mi, - (&scan8, &scan4), - prev_leaf, - &mut y, - &mut u, - &mut v, - base_q_idx, - enable_filter_intra, - allow_screen_content_tools, - allow_intrabc, - tx_select, - reduced_tx_set, - )?; - prev_leaf = Some((leaf_mi, leaf_mode)); + }; + neighbours.above_mode[sc] = saved_modes.0; + neighbours.left_mode[sr] = saved_modes.1; + sib_modes[li] = Some(leaf_mode); } - if let Some((_, mode)) = prev_leaf { - neighbours.above_mode[sc] = mode; - neighbours.left_mode[sr] = mode; + if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) { + neighbours.above_mode[sc] = below; + } + if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) { + neighbours.left_mode[sr] = right; } continue; } @@ -8851,9 +9335,25 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2)) .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols) .collect(); - let mut prev_leaf: Option<((usize, usize), usize)> = None; + // See the sibling-mode note in the clean + // SPLIT path above. + let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4]; for (mr, mc) in leaf_positions { let leaf_mi = (mr as usize, mc as usize); + let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2) + as usize; + let saved_modes = + (neighbours.above_mode[sc], neighbours.left_mode[sr]); + if li >= 2 { + if let Some((below, _)) = sib_modes[li - 2] { + neighbours.above_mode[sc] = below; + } + } + if li % 2 == 1 { + if let Some((_, right)) = sib_modes[li - 1] { + neighbours.left_mode[sr] = right; + } + } let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); if std::env::var_os("EC_AV1_TRACE").is_some() { @@ -8861,30 +9361,50 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}" ); } - if part8 != PARTITION_NONE { + let leaf_mode = if part8 == PARTITION_NONE { + decode_leaf8( + &mut dec, + &mut cdfs, + &mut neighbours, + at16, + leaf_mi, + (&scan8, &scan4), + None, + &mut y, + &mut u, + &mut v, + base_q_idx, + enable_filter_intra, + allow_screen_content_tools, + allow_intrabc, + tx_select, + reduced_tx_set, + ).map(|m| (m, m))? + } else if part8 == PARTITION_SPLIT { + decode_leaf_split4( + &mut dec, + &mut cdfs, + &mut neighbours, + at16, + leaf_mi, + &scan4, + None, + &mut y, + &mut u, + &mut v, + base_q_idx, + enable_filter_intra, + allow_intrabc, + reduced_tx_set, + )? + } else { return Err(unsupported( - "a partition below 8x8 (this decoder codes no leaf smaller than 8x8)", + "a HORZ/VERT partition below 8x8 (this decoder's transform primitive is square-only; 4x8/8x4 need a real rectangular transform)", )); - } - let leaf_mode = decode_leaf8( - &mut dec, - &mut cdfs, - &mut neighbours, - at16, - leaf_mi, - (&scan8, &scan4), - prev_leaf, - &mut y, - &mut u, - &mut v, - base_q_idx, - enable_filter_intra, - allow_screen_content_tools, - allow_intrabc, - tx_select, - reduced_tx_set, - )?; - prev_leaf = Some((leaf_mi, leaf_mode)); + }; + neighbours.above_mode[sc] = saved_modes.0; + neighbours.left_mode[sr] = saved_modes.1; + sib_modes[li] = Some(leaf_mode); } // `record()`'s `above_mode`/`left_mode` // write is a no-op at an 8x8 leaf's own @@ -8892,9 +9412,11 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // 16x16 slot's leaves are done, from the // last leaf (mirrors the writer's r15 // fix). - if let Some((_, mode)) = prev_leaf { - neighbours.above_mode[sc] = mode; - neighbours.left_mode[sr] = mode; + if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) { + neighbours.above_mode[sc] = below; + } + if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) { + neighbours.left_mode[sr] = right; } } } @@ -15212,7 +15734,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); if part8 != PARTITION_NONE { return Err(unsupported( - "a partition below 8x8 (this decoder codes no leaf smaller than 8x8)", + "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)", )); } let (skip, is_inter, skip_mode_leaf, compound_ctx8, leaf_refs) = diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 65f44ae3..23609a7f 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1020,7 +1020,7 @@ pub(crate) struct Reach { /// it. Indexed by the block's position in the superblock, in blocks of its own /// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's /// 128, not this crate's 64 superblock -- bit by bit from the low end. -const HAS_TOP_RIGHT: [&[u8]; 3] = [ +const HAS_TOP_RIGHT: [&[u8]; 4] = [ &[255, 85, 119, 85, 127, 85, 119, 85], &[95, 87], // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16 @@ -1029,11 +1029,28 @@ const HAS_TOP_RIGHT: [&[u8]; 3] = [ 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, ], + + // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) -- + // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128 + // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here + // with side 4 outside a TX4 split; without their own row they clamped + // into the 8x8 table and read above-right samples the decoder has not + // written yet (all-zero pixels in the bottom-right triangle of a + // directional 4x4 leaf). + &[ + 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, + 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85, + 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, + 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, + 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, + 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, + 119, 119, 119, 119, 85, 85, 85, 85, + ], ]; /// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the /// left. -const HAS_BOTTOM_LEFT: [&[u8]; 3] = [ +const HAS_BOTTOM_LEFT: [&[u8]; 4] = [ &[84, 16, 84, 0, 84, 16, 84, 0], &[4, 4], // has_bl_8x8 (libaom av1/common/reconintra.c) @@ -1041,6 +1058,16 @@ const HAS_BOTTOM_LEFT: [&[u8]; 3] = [ 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, ], + + // has_bl_4x4 (same source, same order). + &[ + 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, + 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, + 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, + 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, + 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, + 85, 85, 0, 0, 0, 0, + ], ]; /// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by @@ -1196,21 +1223,19 @@ impl Reach { if col + 1 == per_side { return false; } - // corner-cut: `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` only carry dedicated - // rows for side 8/16/32/64 (libaom's own `has_tr_8x8`/`has_tr_16x16` - // families); a `TxMode::Select` TX4 transform unit reaches here with - // side 4, whose real table (`has_tr_4x4`, 128 bytes) was never - // transcribed. Clamping into the 16/32 table's own bit range keeps - // this in-bounds and correct at every position that table already - // covers periodically -- wrong only at the small remainder past its - // length, a reach over-/under-estimate (extra or missing above-right - // reference pixels), never a stream desync (Reach never gates a - // symbol read). Ceiling: transcribe `has_tr_4x4`/`has_bl_4x4` - // verbatim and give TX4 its own `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` row. - let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) { - HAS_TOP_RIGHT_VERT[Self::table(side)] + // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row + // (the clamp corner-cut that used to live here is gone); sides + // 16/32/64 share row 0 exactly as libaom's tables repeat. + // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block + // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table + // -- a reach over-estimate (extra above-right reference pixels), + // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` / + // `has_bl_vert_4x4` and extend the VERT tables to four rows. + let row = Self::table(side); + let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && row < HAS_TOP_RIGHT_VERT.len() { + HAS_TOP_RIGHT_VERT[row] } else { - HAS_TOP_RIGHT[Self::table(side)] + HAS_TOP_RIGHT[row] }; Self::bit( table, @@ -1230,11 +1255,19 @@ impl Reach { if row + 1 == per_side { return false; } - // corner-cut: see `top_right`'s note -- same clamp, same ceiling. - let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) { - HAS_BOTTOM_LEFT_VERT[Self::table(side)] + // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row + // (the clamp corner-cut that used to live here is gone); sides + // 16/32/64 share row 0 exactly as libaom's tables repeat. + // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block + // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table + // -- a reach over-estimate (extra above-right reference pixels), + // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` / + // `has_bl_vert_4x4` and extend the VERT tables to four rows. + let row = Self::table(side); + let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && row < HAS_BOTTOM_LEFT_VERT.len() { + HAS_BOTTOM_LEFT_VERT[row] } else { - HAS_BOTTOM_LEFT[Self::table(side)] + HAS_BOTTOM_LEFT[row] }; Self::bit( table, @@ -1270,6 +1303,8 @@ impl Reach { 1 } else if side == 8 { 2 + } else if side == 4 { + 3 } else { 0 } diff --git a/crates/ec-av1/src/gate_coverage.rs b/crates/ec-av1/src/gate_coverage.rs index 49f3a6c3..e913ef75 100644 --- a/crates/ec-av1/src/gate_coverage.rs +++ b/crates/ec-av1/src/gate_coverage.rs @@ -139,10 +139,6 @@ const ALIASES: &[(&str, &str)] = &[("superres-mode", "enable-superres")]; /// depth retires the entry, and this test fails until it is deleted. #[cfg(test)] const NEVER_EXERCISED_8BIT: &[(&str, &str)] = &[ - ( - "enable-1to4-partitions", - "off in 42 gates, on in none: PARTITION_HORZ_4/VERT_4 at 64x64 needs TX_64X16 luma plus 32x8 chroma scans (lane-part32 r5)", - ), ( "enable-angle-delta", "off in 36 gates, on in none: the directional-intra gates pin it off to isolate the base modes", @@ -203,7 +199,7 @@ const NEVER_EXERCISED_10BIT: &[(&str, &str)] = &[ // gate passes `=1` for both. ( "enable-1to4-partitions", - "hole at both depths, see the 8-bit list", + "on in an 8-bit gate (lane-sub8) but no 10-bit gate passes `=1`", ), ( "enable-angle-delta", diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 82bc3b66..35ed94a4 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -28,7 +28,6 @@ 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 8x8 (this decoder codes no leaf smaller than 8x8)", "a tx_type symbol on a rectangular transform (never expected at this size)", ]; @@ -40,6 +39,8 @@ const REFUSALS: &[&str] = &[ "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect prediction is not ported)", "a HORZ_A/HORZ_B/VERT_A partition below 16x16 (this decoder codes only the square arms, HORZ, VERT, VERT_B, and a clean split below 16x16)", + "a HORZ/VERT partition below 8x8 (this decoder's transform primitive is square-only; 4x8/8x4 need a real rectangular transform)", + "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)", "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})", @@ -51,6 +52,7 @@ const REFUSALS: &[&str] = &[ "a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed for square blocks only)", "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 sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)", "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)", "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)", "a frame OBU with no tile group", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 4a5b1519..7ddabbc3 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -9528,6 +9528,206 @@ mod tests { ); } + /// lane-sub8 r1: `--min-partition-size=4` on fine-detail noisy gradients + /// at low cq reliably makes aomenc split an 8x8 block all the way to + /// four `BLOCK_4X4` leaves (`PARTITION_SPLIT` below 8x8, spec + /// `decode_partition`'s recursion bottom) -- confirmed with + /// `EC_AV1_TRACE=1` against `examples/decode_probe` before this gate was + /// written (`partition_w8 ... value=3` at mi=(0,0) on the very first + /// block). [`decode::sub8_split_hits`] hard-asserts the path actually + /// ran rather than every attempt landing on `PARTITION_NONE`. + #[test] + fn a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact() { + if !have_ffmpeg() { + eprintln!("SKIP a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact: no ffmpeg"); + return; + } + if !have_aomenc() { + let msg = format!( + "no aomenc at {}", + aomenc_path().display() + ); + assert!( + std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), + "EC_AV1_REQUIRE_AOMENC is set but {msg}" + ); + eprintln!("SKIP a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact: {msg}"); + return; + } + // round 2: `--enable-rect-partitions=0` was added below to keep + // aomenc off HORZ/VERT-below-8x8 elsewhere in the same tile, but it + // is NOT sufficient alone -- see the round-2 report + // (lanes/sub8-r1.report.md) for the live finding: 0/160 attempts + // across both 64x64 and a spatially-isolated single-16x16-leaf + // fixture passed, and every SPLIT that fires is immediately + // followed by a spurious HORZ/VERT read on the very next sibling + // 8x8 leaf, which reads as a real desync left behind by + // `decode_leaf_split4`/`read_intra_mode_sub8`, not an encoder + // choice this recipe can dodge. Tried and rejected: shrinking the + // frame to 16x16 (single 16x16 leaf, at most 4 candidate 8x8s) -- + // that surfaces an UNRELATED pre-existing tiny-frame edge-straddle + // defect (reproduces with zero sub8 code involved, `--min-partition + // -size`/`--max-partition-size` absent entirely), so it is not a + // safe way to isolate the leaf count. Left red; do not "fix" this + // gate by picking fixture parameters that dodge the desync without + // finding it. + // lane-sub8 r6: three arms. The mi-granular mode maps + // (`sub8_mode_col`/`uv_mode_col` and their row twins) are per TILE -- + // the verifier's repro was a 128x64 `--tile-columns=1` stream (seeds + // 207/228) whose every mismatching luma pixel sat at x>=64, the tile + // boundary -- so one arm per tile axis is part of this gate. + for (width, height, tile_args) in [ + (64usize, 64usize, &[][..]), + (128usize, 64usize, &["--tile-columns=1"][..]), + (64usize, 128usize, &["--tile-rows=1"][..]), + ] { + let mut refusals = Vec::new(); + let mut fired_runs = 0u32; + for attempt in 0..40u32 { + let seed = 100 + attempt; + let cq = 6 + (attempt % 4) * 2; + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &gradients_source(seed, width, height, "rate=25"), + "-vf", + // `noise` without `all_seed` re-renders differently on + // every run (seeded-fixture-not-reproducible); pinning it + // makes (seed, cq) name one exact stream. + &format!("noise=alls=40:allf=t:all_seed={seed},format=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", + &format!("--cq-level={cq}"), + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--min-partition-size=4", + "--max-partition-size=8", + // Below 8x8 only PARTITION_NONE/SPLIT are decodable (HORZ/VERT + // need a real rectangular transform, see the module doc above); + // disabling rect partitions entirely -- not just AB -- keeps + // aomenc from picking the still-refused HORZ/VERT arms almost + // every attempt (round 2 measured ~90% HORZ/VERT-below-8x8 + // refusals with --enable-ab-partitions=0 alone). + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=1", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-restoration=0", + "--enable-cdef=0", + "--loopfilter-control=0", + // use_ref_frame_mvs (temporal MV projection) is unimplemented in + // mvstack; this is a key-frame-only fixture, but keep it off for + // safety against a run that emits a second frame. + "--enable-ref-frame-mvs=0", + "--limit=1", + "--obu", + "-o", + "-", + "-", + ]) + .args(tile_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"); + if !out.status.success() { + refusals.push(format!( + "seed={seed} cq={cq}: aomenc itself refused the fixture" + )); + continue; + } + let stream = out.stdout; + let before = decode::sub8_split_hits(); + let tiles_before = decode::tile_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + // Only a named refusal ("unsupported: ...") is a skip + // reason; any other decode error is this decoder failing. + let msg = e.to_string(); + assert!( + msg.starts_with("unsupported: "), + "decode error that is not a named refusal \ + (seed={seed} cq={cq} tiles={tile_args:?}): {msg}" + ); + refusals.push(format!("seed={seed} cq={cq}: {msg}")); + continue; + } + }; + // gate-blind-to-feature: a tile arm must actually decode more + // than one tile, not merely carry `tile_info.cols > 1`. + assert!( + tile_args.is_empty() || decode::tile_hits() - tiles_before >= 2, + "tiles={tile_args:?} decoded only {} tile(s) (seed={seed} cq={cq})", + decode::tile_hits() - tiles_before + ); + if decode::sub8_split_hits() == before { + refusals.push(format!( + "seed={seed} cq={cq}: decoded, but no block read a real PARTITION_SPLIT below 8x8" + )); + continue; + } + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!( + frames[0].y, ffmpeg_frames[0].y, + "luma vs ffmpeg (seed={seed} cq={cq})" + ); + assert_eq!( + frames[0].u, ffmpeg_frames[0].u, + "U vs ffmpeg (seed={seed} cq={cq})" + ); + assert_eq!( + frames[0].v, ffmpeg_frames[0].v, + "V vs ffmpeg (seed={seed} cq={cq})" + ); + fired_runs += 1; + if fired_runs >= 4 { + break; + } + } + assert!( + fired_runs >= 4, + "fewer than 4 firing+pixel-exact runs out of 40 attempts \ + ({width}x{height} tiles={tile_args:?}):\n{}", + refusals.join("\n") + ); + } + } + /// lane-av1golden7 r9's decisive fixture: a real aomenc stream (seed 59, /// `--tune-content=film`, GOLDEN_FRAME firing downstream) whose frame-0 /// *intra keyframe* mismatched ffmpeg on 3855/4096 luma pixels -- traced diff --git a/lanes/COMMON-20260901.md b/lanes/COMMON-20260901.md new file mode 100644 index 00000000..f788cd90 --- /dev/null +++ b/lanes/COMMON-20260901.md @@ -0,0 +1,76 @@ +# COMMON CHARTER PREAMBLE — batch 2026-09-01 (ec-av1 decode, his real films) + +GOAL (why): ec-av1 must decode the user's two real AV1 films bit-exact +(`/home/user/Videos/Films/reelc.mkv`, +`/home/user/Downloads/reelb.mkv`, +both yuv420p10le). 47 refusal strings remain in crates/ec-av1/src/refusal_inventory.rs. +Each lane lifts its cluster of refusals WITH a real-aomenc gate proving it. + +WORKING RULES (binding): +- Work ONLY in your worktree; branch named in your charter. Never touch main, never + merge into main, never `git checkout ` to revert (copy to scratch first). +- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-` (named in charter) for EVERY cargo + command. sccache is the global rustc wrapper. Use `nice -n 10 cargo ... -j3` — 10 lanes + run concurrently on 12 cores / 30G RAM. Long/lavfi runs under + `systemd-run --user --scope -p MemoryMax=8G` and bound ffmpeg with `-t`. +- Test scope: `cargo test -p ec-av1 --lib` only (plus `cargo check -p ec-av1`). Never the + workspace suite. Set `EC_AV1_REQUIRE_AOMENC=1` so an absent oracle FAILS, never SKIPs. +- Oracle: `~/.cache/aom-oracle/build/aomenc` and instrumented `aomdec` (scripts/build-aom-oracle.sh, + scripts/instrument-aom-oracle.sh; rungs EC_TRACE=1 / EC_TRACE_COEFF=1 / EC_TRACE_MODE=1 / + EC_AV1_PREFILT_DUMP). Ours: EC_TRACE_COEFF / EC_TRACE_MODE / EC_TRACE_MODE_STEP in decode.rs. + Cross-decoder bisection compares msac RANGE element by element, never tell(). + The reference is at the oracle source tree (find via scripts/build-aom-oracle.sh). +- FIRST STEP, always: `git log --oneline -8 main` and rebase your branch onto main + (`git rebase main`; resolve conflicts, keeping main's fixes). Then RE-MEASURE your lane's + premise before building — charters may carry stale premises. Cite the command that + produced every premise you act on. +- Fixtures: `fixtures` is a symlink to main's fixtures dir (shared). Pin any new stream + fixture under crates/ec-av1/fixtures/ or fixtures/ with a hash; hash an aomenc output + TWICE before trusting a seed (lavfi gradients ignores its seed). +- A refusal is lifted ONLY together with a gate: a real-aomenc stream (tool explicitly + enabled on the aomenc command line) decoded pixel-exact vs ffmpeg/aomdec, that + HARD-ASSERTS a hit counter proving the feature fired, and never turns a decode error or + pixel mismatch into SKIP. Update refusal_inventory.rs + gate_coverage.rs in the same + commit. `refusal_inventory` and `gate_coverage` tests must stay green. +- Defect classes to check first (memory-proven, each cost rounds): CDF row indexed by a + field that moves; table indexed by RAW vs adjusted tx_size; scan/ctx tables transposed + vs spec (libaom layout is not the spec's — gate on asymmetric behaviour); neighbour ctx + read from one cell instead of gathered over the span; a symbol we read that the + reference never wrote (reference range unchanged = unread); a header field parsed then + never consumed; counter-reset list missing a table; call-site arg order; a probe loop + reusing last run's output file (rm -f first, check exit status). +- Tool-call ceiling ~70. If you hit it: commit everything on your branch, write + `lanes/-r.handoff.md` with exact facts (ranges, stream, element) so a fresh + agent continues without re-reading. +- DONE = commit(s) on your branch + `lanes/-r.report.md` in your worktree with: + what changed (path:line), gate name + command + result, refusals lifted, test totals + (`cargo test -p ec-av1 --lib` passed/failed/ignored), and EVIDENCE lines of the form + `EVIDENCE: | | `. State open residue with + fix-now | deferred() | accepted. Never claim "done" beyond what you ran. +- Film check, when your lane targets a film blocker: extract 0.4s with + `ffmpeg -t 0.4 -i -c:v copy -f obu .obu` (bounded), run + `cargo run -p ec-av1 --example decode_probe -- .obu` before and after; report + the refusal string each film now stops at. + +VERIFIERS (added 2026-09-01 22:40 after a verifier left a lane worktree on a detached HEAD +while its builder was mid-round): a verifier NEVER runs `git checkout`, `git switch`, +`git stash` or any tree-changing git command inside a lane worktree. To test a specific +commit, `git worktree add --detach /tmp/claude-1000/.../scratchpad/verify- ` with its +own CARGO_TARGET_DIR, and remove it when done. + +NEIGHBOUR MAPS (added 2026-09-02 00:50, class new-map-ignores-tile-edge): any per-mi side band +you add or inherit (mode, uv_mode, skip, ref, filter, txfm ctx, palette) MUST (1) guard +availability with `mi_r > tile_row0_mi` / `mi_c > tile_col0_mi`, never `> 0`; (2) be reset in +start_tile AND start_row; (3) have a `--tile-columns=1` arm in the lane's gate. Gate Err arms +tolerate ONLY messages containing "unsupported"; lavfi sources carry an explicit seed +(noise=all_seed=N) and the report shows two identical hashes. + +SIBLING GATES (added 2026-09-02 03:00, rectsplit r3): a root-cause fix that turns YOUR gate green +is not done until every gate that exercises the same tables/paths (grep the table name and the +function in stream.rs) is re-run — rectsplit r2 shipped a transposition that fixed its gate and +broke the merged SB HORZ/VERT gate at seed 43. Run the siblings before writing "root cause". + +FORMAT + LOGS (added 2026-09-02 03:30): never run a repo-wide `cargo fmt` in a lane (txselect +carried 5000 lines of churn that the merge had to strip; format only files you touched, or +not at all). Suite logs go to a PRIVATE path (`$CARGO_TARGET_DIR/../-suite.log`), never +a shared scratchpad name — another session overwrote a verifier's log mid-run. diff --git a/lanes/sub8-r1.report.md b/lanes/sub8-r1.report.md new file mode 100644 index 00000000..fa21da3a --- /dev/null +++ b/lanes/sub8-r1.report.md @@ -0,0 +1,206 @@ +# lane-sub8 report (rounds 1-2) + +## Round 1 (2f35dec, a564705) +Implemented `read_intra_mode_sub8` + `decode_leaf_split4` in +`crates/ec-av1/src/decode.rs` (~5140-5370): decodes `PARTITION_SPLIT` of an +8x8 intra block into four `BLOCK_4X4` leaves (spec `decode_partition`'s +recursion bottom). Both intra call sites (the straddle path and the clean +16x16-SPLIT path) branch on the new `part8` read; `PARTITION_HORZ`/`VERT` +below 8x8 and all inter sub-8x8 stay refused by name. + +**is_chroma_reference derivation** (spec/libaom `av1_common_int.h:1454`): +for 4:2:0 subsampling, only the *last* (bottom-right, index 3) of the four +4x4 leaves in a split 8x8 group carries chroma syntax at all -- the whole +8x8 group's one 4x4 chroma unit is read and reconstructed once, on that +leaf. `decode_leaf_split4` implements this via `has_chroma = i == 3`. + +**Filter-intra CDF row**: `BLOCK_4X4`'s own row (`cdf.rs FILTER_INTRA[0] = +4621`) is already present and is what every sub-8x8 leaf here uses +(`filter_intra_size_class(4)` in libaom is class 0 for all sub-8x8 sizes). +If 4x8/8x4 (HORZ/VERT below 8x8) were ever implemented, they would need two +*more* rows: `BLOCK_4X8 = 6743`, `BLOCK_8X4 = 5893` (libaom +`BLOCK_SIZES_ALL` order, values from `entropymode.c:821`) -- not present +in this table yet. + +**Why HORZ/VERT below 8x8 stays refused**: this decoder's transform +primitive is square-only. A real 4x8/8x4 leaf needs an actual rectangular +TX_4X8/TX_8X4 transform (scan order, EOB context, coefficient CDF set all +differ from the square 4x4 case); faking it as two 4x4 squares would desync +against a real encoder immediately. This is a scope cut, not a bug -- +tracked by refusal name in `refusal_inventory.rs`. + +## Round 2 (6703411) +Round 1 left the gate (`a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact`, +`stream.rs` ~6604) uncompiled. It now compiles clean +(`cargo check -p ec-av1 --lib`, zero errors). **The gate is still RED.** + +### What was tried +1. `--enable-rect-partitions=0` added to the aomenc recipe: necessary but + not sufficient. Without it, aomenc picks a real `PARTITION_HORZ`/`VERT` + at 8x8 (still refused by name) in ~63% of the original 40 attempts + (25/40). With it, that specific refusal drops but the gate still hits + 0/160 total passing attempts across two fixture shapes (see below). +2. Shrinking the fixture to a single-16x16-leaf frame (16x16 pixels, so at + most four 8x8 candidates exist in the whole frame) to structurally rule + out a second, still-refused HORZ/VERT leaf sharing the tile. This + surfaced an **unrelated, pre-existing tiny-frame defect**: a plain + 16x16 aomenc stream with NO `--min-partition-size`/`--max-partition-size` + override and no sub8 code involved at all (`decode_leaf_split4` never + called) still decodes with wrong pixels for most seeds (2/3 sampled). + `EC_AV1_TRACE=1` shows the bitstream parses cleanly (no refusal, no + panic, valid-looking symbol values throughout) but the picture desyncs + silently partway through -- consistent with the frame-edge/"true edge + straddle" logic (`decode.rs` ~6864-6957, the `has_cols16`/`has_rows16` + branch) being exercised at a degenerate case (frame == exactly one + 16x16 block, most of the SB out of frame) that larger sub-SB frames + (32x32, 64x64, used successfully elsewhere in this file) don't reach. + **Out of scope for this lane** -- not touched, not fixed, flagged here + for whichever lane owns edge-straddle handling next. +3. Widening the seed/cq sweep for the 64x64 fixture (with + `--enable-rect-partitions=0`) to 160 total attempts across two batches: + still 0 passes. + +### The actual finding +`EC_AV1_TRACE=1` on failing 64x64 attempts shows the pattern directly: +`partition_w8 mi=(0,0) ... value=3` (a real, clean `PARTITION_SPLIT`, +`decode_leaf_split4` fires, `SUB8_SPLIT_HITS` increments) is immediately +followed by `partition_w8 mi=(0,2) ... value=2` (`PARTITION_VERT`) on the +very next sibling 8x8 leaf in the same 16x16 parent -- and that leaf hits +the (correct, by-design) HORZ/VERT-below-8x8 refusal. This happened on +every single attempt that reached a SPLIT at all, which is not consistent +with random encoder choice given `--enable-rect-partitions=0` is set (per +libaom `partition_search.c`'s `do_rectangular_split` gating, that flag +should make `PARTITION_HORZ`/`VERT` unreachable via RD at 8x8 too). The +more consistent read: `decode_leaf_split4`/`read_intra_mode_sub8` leaves +some piece of decoder, CDF, or neighbour-context state wrong on return, and +the very next `partition_w8` symbol read (on the sibling leaf) decodes a +value the real bitstream did not write -- i.e. a real desync introduced by +this round's own new code, immediately after it runs. + +**This was not chased down further this round** -- turn budget spent +finding and narrowing it. Next round should NOT try more fixture-shape +workarounds; instead: trace `dec`'s range/tell before and after +`decode_leaf_split4` against a byte-identical aomdec run (mirror the +`av1-mvstack-refmv-corner`/`cdf-counter-not-reset` class method: exact +range ladder up to the read, compare the step) to find which of +`read_intra_mode_sub8`'s reads or which piece of `Neighbours`/CDF +bookkeeping in `decode_leaf_split4`'s tail (the chroma-neighbour section, +lines ~5346-5369) is wrong. + +### Suite / build state at HEAD (6703411) +- `cargo check -p ec-av1 --lib`: clean, 0 errors. +- Gate `a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact`: FAILS + (0/40 in-suite attempts pass; `sub8_split_hits()` DOES go nonzero during + the run -- the SPLIT path fires -- but no attempt completes pixel-exact). +- Full `cargo test -p ec-av1 --lib` and ReelB extract probe: not run + this round (turn budget spent on the above investigation). Deferred to + round 3. + +## Round 3 (05b20f9) + +### Fixed: the partition-context bug the round-2 finding pointed at +libaom's `update_ext_partition_context` (`av1_common_int.h:1500`) only +writes anything when `bsize >= BLOCK_8X8`; the four recursive +`decode_partition(BLOCK_4X4)` calls a real `PARTITION_SPLIT` at 8x8 +produces are no-ops for context purposes. The *one* write that happens is +at the 8x8 level itself, with `subsize = BLOCK_4X4`: +`partition_context_lookup[BLOCK_4X4] = {31, 31}` (bit0 = 1), vs +`partition_context_lookup[BLOCK_8X8] = {30, 30}` (bit0 = 0) for a plain +`PARTITION_NONE` 8x8. `decode_leaf_split4`'s chroma-tail (the block that +sets `left_side_mi`/`above_side_mi` for the whole 8x8 group, `decode.rs` +~5350-5354) had copied `decode_leaf8`'s own TX4-branch value (`8`, +correct there -- that block is still one whole `BLOCK_8X8`, just with a +split *transform*) instead of the value that makes +`partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` bit read as 1, which +needs `<= 4`. Changed both writes to `4`. Verified directly against the +libaom source at `~/.cache/aom-oracle/src/av1/common/av1_common_int.h:1441-1552` +(`update_partition_context`/`update_ext_partition_context`/ +`partition_plane_context`), not by re-deriving it by hand. + +**Effect measured**: before the fix, every attempt that hit a real SPLIT +crashed the very next sibling 8x8's `partition_w8` read (round 2's +finding). After the fix, `EC_AV1_TRACE=1` on the dumped stream that +previously crashed shows the sibling reads land on the *correct* context +(cross-checked bit-for-bit against instrumented aomdec's `EC_PART` trace +at the equivalent block, ctx encodes the same left/above bits both sides) +and the whole stream decodes to completion with `Ok`, no error, no panic. +This is real, but not sufficient -- see below. + +### Range-ladder result: gate still RED, and the divergence is UPSTREAM of any sub8 code +Ran the decisive check the charter asked for: rebuilt +`~/.cache/aom-oracle` (rungs 2/5/10 already present in the source, +`EC_PART`/`EC_PART_VAL`/`EC_ISTEP` per-symbol range ladder), decoded the +one dumped failing stream (seed=139, cq=12, 64x64, +`--enable-rect-partitions=0 --min-partition-size=4 --max-partition-size=8`) +through instrumented `aomdec` and compared trace order against our own +`EC_AV1_TRACE` output block by block. + +**First divergence**: the 16x16-level partition read at SUB-unit +`at16=(0,1)` (mi=(0,4)), the *second* 16x16 quadrant of the first 32x32 +block -- i.e. it fires before our decoder has executed one single line of +`decode_leaf_split4`/`read_intra_mode_sub8` (the actual sub8x8-SPLIT in +this stream is at mi=(2,6), inside quadrant (0,1)'s own subtree, per +aomdec's `EC_PART_VAL mi_row=2 mi_col=6 bsize=3 value=3`). aomdec reads +`PARTITION_SPLIT` (value=3) there; ours reads `PARTITION_NONE` (value=0). +The context bits agree (both decode to left=1, above=0, aomdec's combined +`ctx=6` and ours `ctx=2` are the same left/above pair under different +context-array encodings) -- so this is not a context bug, it is either a +CDF-adaptation drift carried in from the *first* 16x16 quadrant's own +four 8x8 leaves (all plain `decode_leaf8`, zero sub8 code touched) or a +genuine range/probability desync from something even earlier that this +round did not get to trace symbol-by-symbol (no per-symbol trace exists +in our decoder for `decode_leaf8`'s own mode-info reads, only for the +`read_intra_mode_sub8` leaves added in round 1 -- that instrumentation +gap is why the ladder stops here this round). + +**This changes the round-2 hypothesis**: the failure is very likely NOT +inside `decode_leaf_split4`/`read_intra_mode_sub8` at all. It reproduces +on this stream before any of that code has run. Whatever the true root +cause is, it sits in code shared by every 8x8/16x16 intra block in this +recipe (`decode_leaf8`, `partition_w16`/`partition_w32` context, or CDF +adaptation for `kf_y_mode`/`uv_mode`/`skip`), and `--min-partition-size=4` +is what surfaces it (this exact recipe may not be exercised by any other +gate). Round 4 should NOT keep assuming the bug is sub8-owned code -- +start by adding the same per-symbol trace (`skip`/`mode`/`uv_mode`/ +`angle_delta`) to `decode_leaf8` itself and ladder the *first* 16x16 +quadrant's four 8x8 leaves symbol-by-symbol against aomdec's `EC_ISTEP` +trace before looking at sub8 code again. + +### Suite / build state at HEAD (05b20f9) +- `cargo check --workspace --all-targets`: clean. +- Gate `a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact`: + still FAILS, now for a different, better-localized reason (see above). + Only 1/40 attempts this round both fired a real SPLIT and reached the + pixel comparison at all (39/40 either fired no SPLIT -- most now decode + clean with `PARTITION_NONE` chosen throughout the min-partition-size=4 + region, itself now consistent with correct decoding since they don't + panic -- or the run's own aomenc/decode plumbing skipped). The one that + did fire failed pixel-exact per the finding above. +- `cargo test -p ec-av1 --lib`: not completed this round (turn budget + spent on the range-ladder trace above); deferred to round 4, run it + first thing. +- Debug-only instrumentation (`EC_AV1_DUMP_SUB8` stream dump in + `stream.rs`, temp `dec.rng()` trace print attempt in `decode.rs`) was + added, used, and **reverted** this round -- not left in the tree. + +## Open (round 4 charter should start here) +- fix-now candidate: root cause is upstream of sub8's own code (see + "changes the round-2 hypothesis" above) -- add per-symbol trace to + `decode_leaf8` and ladder against aomdec `EC_ISTEP` on the first 16x16 + quadrant before touching `decode_leaf_split4` again. +- `cargo test -p ec-av1 --lib` full run: not done this round, do it first. +- ReelB extract probe (charter step 4): not reached this round -- + the gate is still red and the 10-bit wall in this branch (main merged + 10-bit at 5636fd2, this branch has not) makes it low-value until the + above is fixed. + +## Open (carried from round 2, unchanged) +- fix-now candidate: the desync in `decode_leaf_split4`/ + `read_intra_mode_sub8` (see "the actual finding" above) -- root cause, + not yet found. +- deferred: tiny-frame (exactly-16x16) edge-straddle defect, unrelated to + sub8, found as a side effect of workaround #2 above -- needs its own + charter, not this lane's. +- deferred: ReelB extract probe (charter step 4) and the ledger + append for round 1's findings (charter step 5) -- partially done here + (this file), full ledger append below. diff --git a/lanes/sub8-r4.report.md b/lanes/sub8-r4.report.md new file mode 100644 index 00000000..4f422fa9 --- /dev/null +++ b/lanes/sub8-r4.report.md @@ -0,0 +1,74 @@ +# lane-sub8 report (round 4) + +## Premise correction (this is the round's main result) +Round 2/3 assumed aomenc was really choosing `PARTITION_HORZ`/`VERT` below 8x8 +and AB partitions in this gate's recipe. **It is not.** Instrumented aomdec on +the gate's own stream (seed=117 cq=8, `--enable-rect-partitions=0`) reads only +`value=0` (NONE) and `value=3` (SPLIT) at every level: + +``` +EC_TRACE=1 ~/.cache/aom-oracle/build/aomdec --rawvideo -o /dev/null s117.obu \ + | grep EC_PART_VAL | awk '{print $4,$5}' | sort | uniq -c + 42 bsize=3 value=0 22 bsize=3 value=3 16 bsize=6 value=3 + 4 bsize=9 value=3 1 bsize=12 value=3 +``` + +So all 40 of the gate's "refusals" (`HORZ/VERT below 8x8`, `HORZ_A/B/VERT_A +below 16x16`, `a 32x32 partition type value=4/8/9`) were **hallucinated symbols +from our own desync**, not encoder choices. `--enable-rect-partitions=0` IS +honoured. Every refusal-shaped conclusion in rounds 2-3 was measuring the +desync. + +## Root causes found and fixed (commit "mi-exact intra mode neighbours ...") +1. **Coarse mode neighbours (`context-read-from-one-cell` class).** + `above_mode`/`left_mode` are one slot per 16x16; a split cell leaves two + (8x8) or four (4x4) different modes behind, and a leaf whose above/left + neighbour sits in such a cell read the wrong `kf_y_mode` CDF row -> desync. + `Neighbours` now keeps a mi-granular map (`sub8_mode_col`/`sub8_mode_row`, + `record_mode_mi`), written by `record_rect`, `record_split_luma`, + `decode_leaf8` and every 4x4 leaf, read back with an exact-position guard + (`mode_above_mi`/`mode_left_mi`) that falls back to the coarse slot. +2. **`has_tr_4x4`/`has_bl_4x4` never transcribed** (`encode.rs`, the + `corner-cut` comment that named this exact ceiling). Side-4 blocks clamped + into the 8x8 table, so a directional 4x4 leaf predicted from above-right + samples the decoder has not written yet -- all-zero pixels in the leaf's + bottom-right triangle. Both tables transcribed verbatim from + `~/.cache/aom-oracle/src/av1/common/reconintra.c:65,254`; `Reach::table` + maps side 4 to the new row. +3. Cherry-picked lane-tiny `9b1297a` (deblocker chroma tx size from the block + span) per the charter -- it does not change this lane's residue but keeps + the branch aligned with main's fix. + +## Gate result +`a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact` -- **still RED**, +but for a 4-pixel chroma residue instead of a desync: +- symbol ladder vs instrumented aomdec is now **exact** on both sampled + streams (324/324 elements seed=117, 318/318 seed=100), no refusal, decode + completes; +- luma is **bit-exact** on seed=100; +- chroma differs on 4 pixels: U/V (row 20, cols 18-19), deltas 1..3. + +EVIDENCE: /tmp/.../scratchpad/{ref100.yuv,ours100.yuv} | aomenc seed=100 cq=6 recipe from the gate, decoded by ec-av1 and by ffmpeg | 4096/4096 luma bytes equal, 4/2048 chroma bytes differ (max |delta| 3); before this round the same stream refused at a hallucinated partition symbol +EVIDENCE: /tmp/.../scratchpad/{ref.txt,ours.txt} + ladder.py | EC_TRACE/EC_TRACE_MODE_STEP ladder, ours vs instrumented aomdec, seed=117 | 324 elements, no divergence (was: first divergence at element 62) + +## Suite +`cargo test -p ec-av1 --lib` (EC_AV1_REQUIRE_AOMENC=1): **267 passed, 2 failed, +22 ignored**, 1124 s. +- `stream::a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact` -- the + 4-pixel chroma residue above. +- `refusal_inventory::the_decode_path_refuses_exactly_the_listed_cases` -- + NOT investigated this round (budget). Expected shape: a refusal the + inventory expects to fire no longer fires now that the desync is gone + (that is what the fix was for), but it is a RED test and no refusal string + was lifted this round. + +## Open +- fix-now: the 4-pixel chroma residue (U/V row 20, cols 18-19 of the 64x64 + seed=100 frame; block = chroma 4x4 at (20,16), luma 8x8 group mi(10,8)). + Tried and REVERTED (no effect on these pixels): OR-ing the subsampling scale + into the chroma edge's mi (`set_lpf_parameters`' `scale_vert | ...`) in + `edge_params`. Next step: dump post-reconstruction vs `EC_AV1_PREFILT_DUMP` + to separate recon from deblock before touching either. +- fix-now: `refusal_inventory` red (see above). +- deferred(gate green): lifting any refusal string -- nothing lifted, none + proven. diff --git a/lanes/sub8-r5.report.md b/lanes/sub8-r5.report.md new file mode 100644 index 00000000..9835b2ee --- /dev/null +++ b/lanes/sub8-r5.report.md @@ -0,0 +1,93 @@ +# lane-sub8 report (round 5) + +## Root cause of the 4-pixel chroma residue + +Recon vs filtering was separated FIRST (charter step 1): the gate's own aomenc +recipe carries `--enable-cdef=0 --loopfilter-control=0`, and our +`EC_AV1_PREFILT_DUMP` / `EC_AV1_POSTDEBLOCK_DUMP` dumps are byte-identical to +the final planes -- so every filter stage is inert on this stream and the +residue was pure reconstruction. (r4's `edge_params` experiment could not have +moved it: there is no deblocking in this stream at all.) + +The mismatching block is NOT a sub-8x8 group: `EC_AV1_TRACE` shows +`partition_w8 mi=(10,8) value=0` -- a plain `PARTITION_NONE` 8x8 leaf with +`tx_depth=1` (four 4x4 luma TUs), luma mode H_PRED, `uv_mode=6` (D157_PRED), +chroma 4x4 at (16,20). Subtracting the (bit-exact) residual from both recons +isolates it to the *prediction*: ours and libaom's differ only at row 0, +columns 2-3. + +**`get_intra_edge_filter_type` (reconintra.c:974) reads the CHROMA neighbours' +`uv_mode` for planes 1/2**, never the luma mode. `decode_leaf8` and +`decode_leaf_split4` passed a hardcoded `false` on every chroma +`reconstruct`/`read_plane`, so a directional chroma block whose chroma +neighbour is smooth filtered its above edge at `intra_edge_filter_strength` +type 0 (kernel `{0,4,8,4,0}`, strength 1 at d=67) instead of type 1 +(`{0,5,6,5,0}`, strength 2) -- deltas of 1..3 on the two pixels the kernel +difference reaches. + +Second half of the cause: the coarse `SUB`-grid `above_uv_mode`/`left_uv_mode` +slots cannot name that neighbour. Adding the leaf's own write to them makes +the top-left 8x8 leaf of a 16x16 clobber the row slot that the block to the +LEFT owns, and the block at mi(10,8) then still read `false` (measured: the +frame stayed 4 pixels off). So this round adds the `uv_mode` twin of the +existing mi-granular `sub8_mode_col`/`sub8_mode_row` machinery. + +## What changed +- `crates/ec-av1/src/decode.rs:1784` -- new `uv_mode_col`/`uv_mode_row` mi-granular + maps on `Neighbours` (+ init). +- `crates/ec-av1/src/decode.rs:2548` `record_uv_mode_mi`, `:2573` + `smooth_uv_neighbour` (mi-exact above/left `uv_mode`, coarse `SUB` slot as + fallback), written from `record_rect` (:2606), `record_split_luma` (:2718), + `decode_leaf8` (:5362) and `decode_leaf_split4` (:5845). +- `crates/ec-av1/src/decode.rs:5331,5758` -- `smooth_neighbor_uv` replaces the + hardcoded `false` at all 10 chroma reconstruct/read_plane arguments in those + two functions. +- `crates/ec-av1/src/refusal_inventory.rs:31` -- deleted the stale capability + claim `"a partition below 8x8 (this decoder codes no leaf smaller than + 8x8)"` (corrected in r6: the string named here originally was wrong); r4's fixes + removed that string from the decode path, which is exactly what made + `the_decode_path_refuses_exactly_the_listed_cases` RED (charter step 2). + It was the only entry the test named. + +## Gate +`a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact` -- **GREEN** +(4 firing + pixel-exact runs; `sub8_split_hits` hard-asserted, no SKIP). + +``` +EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib sub8 + test stream::tests::a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact ... ok +``` + +EVIDENCE: /sub8r5/{mine.yuv,ref.yuv} | seed=100 cq=6 gate recipe re-run standalone (sha256 64f6f74e... 3994 B), decoded by `examples/decode_probe` and by ffmpeg | 6144/6144 bytes equal (was 4 chroma bytes off, |delta| <= 3) +EVIDENCE: /sub8r5/prefilt+postdeblock dumps | EC_AV1_PREFILT_DUMP / EC_AV1_POSTDEBLOCK_DUMP on the same stream | both byte-identical to the final planes -> filters inert, residue is reconstruction +EVIDENCE: /sub8r5/hg.obu | `ffmpeg -t 0.4 -c:v copy -f obu` from the ReelB film, `decode_probe` after the fix | REFUSED at "a HORZ/VERT partition below 8x8" (was: "a partition below 8x8") + +## Refusals +Nothing lifted, nothing to lift: the PARTITION_SPLIT-to-4x4 shape the charter +names has had **no refusal string** since `decode_leaf_split4` landed (r2) -- +the gate is what was missing, and it is now green, so the capability is +proven rather than assumed. The two below-8x8 strings that remain are both +out of this lane by the standing constraint: +- `"a HORZ/VERT partition below 8x8 (... 4x8/8x4 need a real rectangular + transform)"` -- deferred(a real TX_4X8/TX_8X4 primitive). This is now the + ReelB blocker. +- `"an inter partition below 8x8 ..."` -- deferred(an inter lane; lane-sub8 is + intra-scoped). + +## Suite +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib`: **269 passed, 0 failed, 22 +ignored**, 476 s (r4 was 267 passed, 2 failed -- both now green). + +## Open / disposition +- deferred(an inter-frame gate whose chroma neighbour codes a smooth `uv_mode`) + -- same-shape sweep: `decode.rs:12084,12096` (`decode_inter_block8`'s + intra-in-inter chroma reconstruct) still pass a hardcoded `false` for the + chroma edge-filter type. Every other chroma site now takes a `uv_mode`-derived + flag; `decode_block`/`decode_inter_block` (:3251,:3765,:4893,:10929) take it + from the coarse `SUB` slots, which is exact for >=16x16 neighbours and + approximate when the neighbour is an 8x8 leaf -- upgrade path is to route + those four through `smooth_uv_neighbour` too. +- accepted: `smooth_uv_neighbour` falls back to the coarse slot when no block + recorded the exact neighbouring mi (documented at the field). +- Film: ReelB now stops at the HORZ/VERT-below-8x8 refusal above; the + film is also yuv420p10le, so a 10-bit refusal waits behind it. diff --git a/lanes/sub8-r6.report.md b/lanes/sub8-r6.report.md new file mode 100644 index 00000000..9772445f --- /dev/null +++ b/lanes/sub8-r6.report.md @@ -0,0 +1,77 @@ +# lane-sub8 report (round 6) -- verifier FAIL closed + +## The defect the verifier found (root cause) + +The mi-granular mode maps added in r2/r5 (`sub8_mode_col`/`sub8_mode_row`, +`uv_mode_col`/`uv_mode_row`) are FRAME-wide arrays read with a FRAME-relative +availability guard (`mi_r > 0` / `mi_c > 0`) and never reset per tile. Every +other neighbour site in `decode.rs` guards tile-relatively +(`mi_r > self.tile_row0_mi`, e.g. :2240, :3222, :6152). With more than one +tile, the first block of tile N read a `(row, mode)` entry left by the tile to +its LEFT (or above) as if it were its own neighbour -- wrong intra-mode +context / wrong chroma edge-filter type, and from there wrong pixels. + +## What changed (all in the lane worktree, branch `lane-sub8`) +- `crates/ec-av1/src/decode.rs:2533,2540,2574,2578` -- the four reads now guard + with `self.tile_row0_mi` / `self.tile_col0_mi`. +- `crates/ec-av1/src/decode.rs:2000` (`start_tile`) -- clears + `sub8_mode_col`/`uv_mode_col` over the tile's own mi column span + (`col0_mi..col1_mi`), alongside the existing `above_*` reset. +- `crates/ec-av1/src/decode.rs:2286` (`start_row`) -- clears + `sub8_mode_row`/`uv_mode_row` with the rest of the left context. +- `crates/ec-av1/src/decode.rs:3763` -- `decode_leaf_rect` (the 16x8/8x16 + strips) now calls `record_mode_mi`/`record_uv_mode_mi` over its real span; + before, the caller patched only the coarse 16x16 `above_mode`/`left_mode` + slot, so a neighbour of the TOP strip read the BOTTOM strip's mode. + (Sweep item 1 of the verifier's list.) +- `crates/ec-av1/src/decode.rs:5326` -- deleted the stale `corner-cut` comment + claiming the uv neighbours are coarse; they are mi-exact since r5. +- `crates/ec-av1/src/stream.rs:7259..` -- gate rewritten: three arms + (single tile / `--tile-columns=1` at 128x64 / `--tile-rows=1` at 64x128), + each needing 4 firing + pixel-exact runs; `tile_hits()` delta >= 2 asserted + on the tile arms (gate-blind-to-feature); the `Err` arm now ASSERTS the + message starts with `unsupported: ` -- any other decode error panics + instead of counting as a tolerated refusal; the fixture's `noise` filter + carries `all_seed={seed}`. +- `lanes/sub8-r5.report.md:45` -- the deleted refusal string named correctly + ("a partition below 8x8 ..."). + +## Gate + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib sub8` -> **ok, 1 passed** +(3 arms x 4 firing+pixel-exact runs). + +Regression value proved by reverting only the guard+reset hunks: the same gate +FAILS (`U vs ffmpeg (seed=139 cq=12)`, stream.rs:7394) -- so this gate catches +the defect, it is not a pass-by-construction arm. + +EVIDENCE: /bad207.obu (sha256 0f78db8b...), bad228.obu (sha256 6a73db99...) | `decode_probe out.yuv` + `ffmpeg -i -f rawvideo -pix_fmt yuv420p` on this branch | both 12288/12288 bytes equal (verifier's pre-fix .mine.yuv: 221 and 158 differing bytes, all at x>=64) +EVIDENCE: gate run above | 3-arm gate incl. --tile-columns=1 / --tile-rows=1, tile_hits delta >= 2 asserted | ok; with the guard+reset hunks reverted the same gate FAILS at seed=139 cq=12 (U plane) +EVIDENCE: /reelb_r6.obu | `ffmpeg -t 0.4 -c:v copy -f obu` from the ReelB film, `decode_probe` on this branch | REFUSED at "a HORZ/VERT partition below 8x8 (... 4x8/8x4 need a real rectangular transform)" -- unchanged from r5, and past main's "a partition below 8x8" +EVIDENCE: fixture reproducibility | the gate's lavfi source (seed 207, 128x64) rendered twice with and without `all_seed=207` | with: d3c4b3e3... both runs; without: 5619b3ee... both runs -- ffmpeg's `noise` was in fact deterministic in this pair of runs, `all_seed` pins it explicitly rather than relying on that + +## Refusals +None lifted, none added this round; `refusal_inventory` and `gate_coverage` +stay green (totals below). + +## Suite +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib`: **269 passed, 0 failed, 22 ignored**, 933 s (r5: 269/0/22). + +An earlier run of the same command on the same tree reported `error: test +failed` with the failing test's name swallowed by my own grep filter; the +full rerun above (log `/suite_r6.log`) is clean. Flagged as a +possible flake under 10 concurrent lanes rather than claimed benign -- +open, unblocked by a rerun that captures the whole log. + +## Open / disposition +- deferred(an inter lane) -- `decode.rs:8547-8548` (`up_available`/ + `left_available` in the inter path) and `mvstack.rs:727,733,742,756,1486, + 1492,1501,1515` still use frame-relative `mi_row > 0` / `mi_col > 0` where + libaom uses `tile->mi_row_start`/`mi_col_start`. Same shape as this round's + defect but in code this lane never touched and no intra gate reaches; + unblocked by a multi-tile INTER gate. +- deferred(an inter-frame gate whose chroma neighbour codes a smooth + `uv_mode`) -- carried from r5: `decode.rs:12084,12096` still pass a + hardcoded `false` chroma edge-filter type. +- accepted: `smooth_uv_neighbour` falls back to the coarse `SUB` slot when no + block recorded the exact neighbouring mi.