diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index fda4e1ae..1967c2a6 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -293,6 +293,42 @@ pub const EOB_PT_128_CHROMA_Q3: [u16; 9] = [ 24313, 26062, 28385, 30107, 31217, 31898, 32345, 32768, 0, ]; +/// `av1_default_eob_multi128_cdfs[2][0][0]` (`token_cdfs.h:830-849`, +/// lane-rectx): the end-of-block group of a LUMA transform with 128 coded +/// positions -- what a true 16x8/8x16 rectangular transform has +/// (`decode_leaf_rect`'s own leaf, one level below [`EOB_PT_512_LUMA`]'s +/// 32x16/16x32), distinct from [`EOB_PT_256_LUMA`]'s 256-position group a +/// *square* 16x16 reads. Read straight from the plane-0 half of the same +/// `token_cdfs.h` table [`EOB_PT_128_CHROMA`] reads its plane-1 half from. +pub const EOB_PT_128_LUMA: [u16; 9] = [ + 1366, 1738, 2527, 5016, 9355, 15797, 24643, 32768, 0, +]; +/// [`EOB_PT_128_LUMA`], q-context 0. +pub const EOB_PT_128_LUMA_Q0: [u16; 9] = [ + 219, 482, 1140, 2091, 3680, 6028, 12586, 32768, 0, +]; +/// [`EOB_PT_128_LUMA`], q-context 1. +pub const EOB_PT_128_LUMA_Q1: [u16; 9] = [ + 685, 933, 1488, 2714, 4766, 8562, 19254, 32768, 0, +]; +/// [`EOB_PT_128_LUMA`], q-context 3. +pub const EOB_PT_128_LUMA_Q3: [u16; 9] = [ + 3472, 4885, 7489, 12481, 18517, 24536, 29635, 32768, 0, +]; + +/// `av1_default_eob_multi32_cdfs[2][1][0]` (`token_cdfs.h:792-808`, +/// lane-rectx): the end-of-block group of a CHROMA transform with 32 coded +/// positions -- what a true 8x4/4x8 rectangular transform has (the chroma +/// plane of a [`decode_leaf_rect`] 16x8/8x16 luma strip), distinct from +/// [`EOB_PT_16_CHROMA`]'s 16-position group a *square* 4x4 reads. +pub const EOB_PT_32_CHROMA: [u16; 7] = [13468, 16303, 20361, 25105, 29281, 32768, 0]; +/// [`EOB_PT_32_CHROMA`], q-context 0. +pub const EOB_PT_32_CHROMA_Q0: [u16; 7] = [2636, 4273, 7588, 11794, 20401, 32768, 0]; +/// [`EOB_PT_32_CHROMA`], q-context 1. +pub const EOB_PT_32_CHROMA_Q1: [u16; 7] = [8394, 10352, 13932, 18855, 26014, 32768, 0]; +/// [`EOB_PT_32_CHROMA`], q-context 3. +pub const EOB_PT_32_CHROMA_Q3: [u16; 7] = [22086, 24282, 27010, 29770, 31743, 32768, 0]; + /// `av1_default_eob_multi512_cdfs[2][1][0]` (`token_cdfs.h:874-901`, /// lane-part32 r4): the end-of-block group of a CHROMA transform with 512 /// coded positions -- what a 32x16/16x32 chroma transform has (the chroma @@ -421,13 +457,21 @@ pub const CFL_SIGN: [u16; 9] = [1418, 2123, 13340, 18405, 26972, 28343, 32294, 3 /// (12756/14301, `default_filter_intra_cdfs` index 8/7) -- the two rect /// strips `PARTITION_HORZ`/`PARTITION_VERT` decode, each with its own /// distinct default probability from every square class above. -pub const FILTER_INTRA: [[u16; 3]; 6] = [ +/// `[6]`/`[7]` (lane-rectx r3) add `BLOCK_16X8`/`BLOCK_8X16`'s own rows +/// (9394/12551, `default_filter_intra_cdfs` index 5/4) -- the 16x8/8x16 +/// strips [`crate::decode`]'s `decode_leaf_rect` codes. Missing them meant +/// the flag was never read at that size at all (libaom reads it for every +/// DC_PRED block whose sides are both <= 32), so every DC_PRED 16x8 strip +/// dropped one symbol and desynced the tile from that block on. +pub const FILTER_INTRA: [[u16; 3]; 8] = [ [4621, 32768, 0], [7866, 32768, 0], [12408, 32768, 0], [22343, 32768, 0], [12756, 32768, 0], [14301, 32768, 0], + [9394, 32768, 0], + [12551, 32768, 0], ]; /// `default_filter_intra_mode_cdf` (entropymode.c): which of the five /// `FILTER_INTRA_MODES` a `use_filter_intra` block picks. diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index c03486cb..97407756 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -127,6 +127,41 @@ pub(crate) enum TxbSet { /// different existing sets is why this variant exists at all rather than /// reusing [`LumaRect32x16`](TxbSet::LumaRect32x16)'s chroma sibling. ChromaRect32x16, + /// The luma 16x8/8x16 transform of a `PARTITION_HORZ`/`VERT` intra strip + /// below 16x16 (lane-rectx, `decode_leaf_rect`'s own leaf, one level + /// under [`LumaRect32x16`](TxbSet::LumaRect32x16)): `get_txsize_entropy_ctx` + /// reduces this 2:1 rect size to `TX_16X16` too, so this shares every + /// table [`Luma16`](TxbSet::Luma16) does except two: its mode-indexed + /// `tx_type` CDF, which is the *8x8* row's (see + /// [`LumaRect16x8Set1`](TxbSet::LumaRect16x8Set1)), and `eob_pt`, which + /// reads the true 128-position [`crate::cdf::EOB_PT_128_LUMA`] rather + /// than `Luma16`'s 256-position one. Unlike + /// [`LumaRect32x16`](TxbSet::LumaRect32x16), this size DOES carry a + /// `tx_type` symbol: `av1_get_ext_tx_set_type` (`av1/common/blockd.h`) + /// sees `tx_size_sqr_up == TX_16X16`, so intra reads + /// `EXT_TX_SET_DTT4_IDTX` under `reduced_tx_set` and + /// `EXT_TX_SET_DTT4_IDTX_1DDCT` without it (`tx_size_sqr` is `TX_8X8` + /// here, not `TX_16X16`) -- this variant is the reduced arm, its + /// `Set1` sibling the other. + LumaRect16x8, + /// [`LumaRect16x8`](TxbSet::LumaRect16x8)'s `reduced_tx_set: false` + /// counterpart (lane-rectx r3), the same split + /// [`Luma8Set1`](TxbSet::Luma8Set1) has to [`Luma8`](TxbSet::Luma8) -- + /// and it is deliberately those two tables, not the 16x16 row: libaom's + /// `read_tx_type` indexes `intra_ext_tx_cdf[eset][square_tx_size]` with + /// `square_tx_size = txsize_sqr_map[tx_size]`, which for `TX_16X8`/ + /// `TX_8X16` is `TX_8X8`, NOT the `txsize_sqr_up_map` `TX_16X16` the + /// txb-skip/base/br tables use (`get_txsize_entropy_ctx`). r2 read the + /// 16x16 row's five-symbol reduced CDF here and desynced on the very + /// first coded rect leaf. + LumaRect16x8Set1, + /// The chroma 8x4/4x8 transform under the same leaf (lane-rectx): + /// [`Chroma8`](TxbSet::Chroma8)'s tables except `eob_pt`, which reads the + /// true 32-position [`crate::cdf::EOB_PT_32_CHROMA`] instead of + /// `Chroma8`'s 64-position one -- the same square-up relationship + /// [`ChromaRect16x8`](TxbSet::ChromaRect16x8) has to `Chroma16`, one size + /// class down. + ChromaRect8x4, } /// The tables one transform block is coded with, borrowed from the state for @@ -301,6 +336,12 @@ pub(crate) struct Cdfs { /// The end-of-block group of a true 32x16/16x32 rect CHROMA transform /// (lane-sbpart), see [`TxbSet::ChromaRect32x16`]. pub eob_pt_512_chroma: [u16; 11], + /// The end-of-block group of a true 16x8/8x16 rect LUMA transform + /// (lane-rectx), see [`TxbSet::LumaRect16x8`]. + pub eob_pt_128_luma: [u16; 9], + /// The end-of-block group of a true 8x4/4x8 rect CHROMA transform + /// (lane-rectx), see [`TxbSet::ChromaRect8x4`]. + pub eob_pt_32_chroma: [u16; 7], /// The end-of-block offset bit, per table set. pub eob_extra_luma_32: [[u16; 3]; 9], /// The same, for a 64x64 luma transform. @@ -464,9 +505,10 @@ pub(crate) struct Cdfs { /// [`Self::dv_joint`]'s per-component half. pub dv_comp: [MvComponentCdfs; 2], /// The `use_filter_intra` flag, indexed by block-size class (`[0]`=4x4, - /// `[1]`=8x8, `[2]`=16x16, `[3]`=32x32, `[4]`=32x16, `[5]`=16x32) -- + /// `[1]`=8x8, `[2]`=16x16, `[3]`=32x32, `[4]`=32x16, `[5]`=16x32, + /// `[6]`=16x8, `[7]`=8x16) -- /// see [`cdf::FILTER_INTRA`]. - pub filter_intra: [[u16; 3]; 6], + pub filter_intra: [[u16; 3]; 8], /// Which `FILTER_INTRA_MODES` entry a `use_filter_intra` block picks. pub filter_intra_mode: [u16; 6], /// `TxMode::Select`'s `tx_depth` flag at an 8x8 block, by `tx_size_context` @@ -681,6 +723,8 @@ impl Cdfs { reset1(&mut self.eob_pt_512_luma); reset1(&mut self.eob_pt_128_chroma); reset1(&mut self.eob_pt_512_chroma); + reset1(&mut self.eob_pt_128_luma); + reset1(&mut self.eob_pt_32_chroma); reset2(&mut self.eob_extra_luma_32); reset2(&mut self.eob_extra_luma_64); reset2(&mut self.eob_extra_chroma_16); @@ -1138,6 +1182,20 @@ impl Cdfs { cdf::EOB_PT_128_CHROMA, cdf::EOB_PT_128_CHROMA_Q3, ), + eob_pt_128_luma: pick( + q_ctx, + cdf::EOB_PT_128_LUMA_Q0, + cdf::EOB_PT_128_LUMA_Q1, + cdf::EOB_PT_128_LUMA, + cdf::EOB_PT_128_LUMA_Q3, + ), + eob_pt_32_chroma: pick( + q_ctx, + cdf::EOB_PT_32_CHROMA_Q0, + cdf::EOB_PT_32_CHROMA_Q1, + cdf::EOB_PT_32_CHROMA, + cdf::EOB_PT_32_CHROMA_Q3, + ), eob_pt_512_chroma: pick( q_ctx, cdf::EOB_PT_512_CHROMA_Q0, @@ -1584,6 +1642,42 @@ impl Cdfs { tx_type: None, eob_pt_class1: Some(&mut self.eob_pt_512_chroma_class1), }, + TxbSet::LumaRect16x8 => TxbTables { + side: 16, + txb_skip: &mut self.txb_skip_luma_16, + eob_pt: &mut self.eob_pt_128_luma, + eob_extra: &mut self.eob_extra_luma_16, + base: &mut self.base_luma_16, + base_eob: &mut self.base_eob_luma_16, + br: &mut self.br_luma_16, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.intra_tx_type_8[mode].as_mut_slice()), + eob_pt_class1: None, + }, + TxbSet::LumaRect16x8Set1 => TxbTables { + side: 16, + txb_skip: &mut self.txb_skip_luma_16, + eob_pt: &mut self.eob_pt_128_luma, + eob_extra: &mut self.eob_extra_luma_16, + base: &mut self.base_luma_16, + base_eob: &mut self.base_eob_luma_16, + br: &mut self.br_luma_16, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.intra_tx_type_8_set1[mode].as_mut_slice()), + eob_pt_class1: None, + }, + TxbSet::ChromaRect8x4 => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_chroma_8, + eob_pt: &mut self.eob_pt_32_chroma, + eob_extra: &mut self.eob_extra_chroma_8, + base: &mut self.base_chroma_8, + base_eob: &mut self.base_eob_chroma_8, + br: &mut self.br_chroma_8, + dc_sign: &mut self.dc_sign_chroma, + tx_type: None, + eob_pt_class1: None, + }, } } } diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index dd464593..86192b4c 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1437,6 +1437,33 @@ pub(crate) fn rect_coeff_hits() -> usize { RECT_COEFF_HITS.with(|c| c.get()) } +// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`]) +// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the +// charter's real-aomenc gate hard-asserts. +thread_local! { + static RECT_LEAF_COEFF_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`RECT_LEAF_COEFF_HITS`]. +pub(crate) fn rect_leaf_coeff_hits() -> usize { + RECT_LEAF_COEFF_HITS.with(|c| c.get()) +} + +// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader +// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an +// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16 +// slot -- i.e. how often the r5 defect would have picked the wrong CDF row. +thread_local! { + static MODE_MI_OVERRIDE_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`MODE_MI_OVERRIDE_HITS`]. +pub(crate) fn mode_mi_override_hits() -> usize { + MODE_MI_OVERRIDE_HITS.with(|c| c.get()) +} + // lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT` // blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the // gate's proof this round's arms actually reached a real block, not just @@ -1694,6 +1721,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; @@ -2067,6 +2109,25 @@ const SCAN_8X32: [u16; 256] = [ 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252, 239, 246, 253, 247, 254, 255, ]; +/// `Default_Scan_8x4` (lane-rectx, see [`SCAN_32X16`]'s doc comment for the +/// transposition rule this repo's `SCAN_WxH` names follow): this repo's +/// `(w=8, h=4)` reads libaom's own `default_scan_4x8` verbatim -- the same +/// axis swap [`SCAN_16X8`]/[`SCAN_8X16`] already carry one size class up +/// (repo `SCAN_16X8` == libaom `default_scan_8x16`, repo `SCAN_8X16` == +/// libaom `default_scan_16x8`), checked against `scan.c` before landing +/// rather than re-deriving the zigzag formula. +const SCAN_8X4: [u16; 32] = [ + 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21, 14, 7, + 29, 22, 15, 30, 23, 31, +]; + +/// `Default_Scan_4x8` (lane-rectx): this repo's `(w=4, h=8)` reads libaom's +/// own `default_scan_8x4` verbatim, the same transposition [`SCAN_8X4`]'s +/// doc comment explains. +const SCAN_4X8: [u16; 32] = [ + 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28, + 23, 26, 29, 27, 30, 31, +]; /// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents /// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s @@ -2453,12 +2514,14 @@ fn read_coeffs( Ok((grid, tx_type)) } -/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire), restricted to -/// `TxClass::TwoD` -- the only class either rect size pair this decoder codes -/// can ever produce (see [`decode_block_rect`]'s doc comment): refuses by -/// name rather than guess-decode if a `tx_type` symbol or non-2D class ever -/// shows up here, since neither `base_ctx_rect`/`br_ctx_rect` nor -/// [`class_scan_table`] have a rect form for those. +/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the +/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to +/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes +/// can ever produce, since every `tx_type` this decoder's rect sets can read +/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name +/// rather than guess-decode if a non-2D class ever shows up here, since +/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect +/// form for those. fn read_coeffs_rect( dec: &mut SymbolDecoder, coding: &mut TxbTables, @@ -2471,6 +2534,7 @@ fn read_coeffs_rect( ) -> Result<(Vec, TxType)> { let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some(); let mut grid = vec![0i32; w * h]; + let entry_rng = dec.debug_state().0; let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; if ec_trace_coeff { let (rng, _) = dec.debug_state(); @@ -2482,17 +2546,35 @@ fn read_coeffs_rect( if all_zero { return Ok((grid, TxType::DctDct)); } - if coding.tx_type.is_some() { - return Err(unsupported( - "a tx_type symbol on a rectangular transform (never expected at this size)", - )); + let trace = std::env::var_os("EC_TRACE_COEFF").is_some(); + if trace { + let (rng, _) = dec.debug_state(); + eprintln!("EC_COEFF_STEP tag=all_zero ctx={skip_ctx} all_zero=0 rng={rng}"); + } + let mut tx_type = default_tx_type; + if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() { + // Mirrors [`read_coeffs`]'s own `tx_type` read: the CDF row's width + // names its set (lane-rectx, `TxbSet::LumaRect16x8` -- the one rect + // set here that carries a `tx_type` symbol at all). + let len = tx_type_cdf.len(); + let t = dec.symbol(tx_type_cdf); + tx_type = match len { + 17 => TxType::from_symbol_all16(t), + 13 => TxType::from_symbol_set2_12(t), + 8 => TxType::from_symbol_set1(t), + _ => TxType::from_symbol(t), + } + .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?; } - let tx_type = default_tx_type; if TxClass::of(tx_type) != TxClass::TwoD { return Err(unsupported( "a non-2D tx class on a rectangular transform (never expected at this size)", )); } + if trace { + let (rng, _) = dec.debug_state(); + eprintln!("EC_COEFF_STEP tag=tx_type rng={rng}"); + } let eob = read_eob(dec, coding, TxClass::TwoD); if ec_trace_coeff { let (rng, _) = dec.debug_state(); @@ -2547,6 +2629,10 @@ fn read_coeffs_rect( level }; levels[pos] = level; + if trace { + let (rng, _) = dec.debug_state(); + eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}"); + } } if ec_trace_coeff { let (rng, _) = dec.debug_state(); @@ -2562,6 +2648,10 @@ fn read_coeffs_rect( } else { dec.literal(1) == 1 }; + if trace { + let (rng, _) = dec.debug_state(); + eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} rng={rng}", u8::from(negative)); + } let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL { let g = read_golomb(dec)?; level + g as i32 @@ -2644,6 +2734,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 @@ -2791,6 +2901,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 @@ -2874,6 +2988,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` @@ -3192,6 +3314,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 @@ -3480,6 +3606,104 @@ 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) + } + + /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a + /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse + /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a + /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them + /// holding an OLDER, larger block's mode -- it only ever recorded into the + /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the + /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip + /// whose left neighbour was a 16x8 leaf still read the stale row and picked + /// a different CDF for the same mode value). + fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) { + let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); + let above = self.mode_above_mi(mi_r, mi_c).unwrap_or(self.above_mode[c]); + let left = self.mode_left_mi(mi_r, mi_c).unwrap_or(self.left_mode[r]); + if above != self.above_mode[c] || left != self.left_mode[r] { + MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1)); + } + (above, left) + } + fn record_rect( &mut self, at: (usize, usize), @@ -3500,6 +3724,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); } @@ -3629,6 +3855,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; } @@ -3685,6 +3913,13 @@ fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option { match (bw, bh) { (32, 16) => Some(4), (16, 32) => Some(5), + // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <= + // 32", so a 16x8/8x16 strip reads the flag too -- returning `None` + // here dropped that symbol on every DC_PRED strip of that size and + // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder: + // identical mode/uv_mode values, range 34808 vs the oracle's 40668). + (16, 8) => Some(6), + (8, 16) => Some(7), _ if bw == bh => filter_intra_size_class(bw), _ => None, } @@ -4562,14 +4797,15 @@ fn decode_block_rect( ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); + let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); let palette_uv_cache = neighbours.palette_uv_cache(at); let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode_rect( dec, cdfs, - neighbours.above_mode[c], - neighbours.left_mode[r], + nb_above_mode, + nb_left_mode, true, bw, bh, @@ -4581,8 +4817,7 @@ fn decode_block_rect( r * (SUB / MI), c * (SUB / MI), )?; - let smooth_neighbor = - is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]); + let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); if smooth_neighbor { SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); } @@ -4977,9 +5212,10 @@ fn decode_block_rect( /// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at /// this strip's real position, never the coarse `record_rect` (which the /// caller uses once, after both strips, exactly like the `VERT_B` arm next -/// to it). Only the skip case is ported -- see [`decode_block_rect`]'s own -/// doc for why a coded rect strip below 16x16 has no coefficient tables here -/// yet. +/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16` +/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8` +/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level +/// under [`decode_block_rect`]'s own 32x16/16x32 strip. #[allow(clippy::too_many_arguments)] fn decode_leaf_rect( dec: &mut SymbolDecoder, @@ -4997,8 +5233,15 @@ fn decode_leaf_rect( allow_screen_content_tools: bool, base_q_idx: u8, tx_select: bool, + reduced_tx_set: bool, ) -> Result { let _ = base_q_idx; + if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() { + eprintln!( + "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}", + dec.debug_state().0 + ); + } let (r, c) = outer_at; let mut above_mode = neighbours.above_mode[c]; let mut left_mode = neighbours.left_mode[r]; @@ -5010,6 +5253,16 @@ fn decode_leaf_rect( left_mode = pmode; } } + // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot + // cannot hold the modes a split (or a pair of strips) leaves behind, so + // when the map holds the block at exactly this strip's above/left mi it + // is the neighbour libaom's `above_mi`/`left_mi` reads. + 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); if smooth_neighbor { @@ -5049,6 +5302,9 @@ fn decode_leaf_rect( "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)", )); } + if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() { + eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}"); + } if filter_intra.is_some() { return Err(unsupported( "filter intra on a HORZ/VERT strip (this decoder predicts square-only)", @@ -5067,66 +5323,99 @@ fn decode_leaf_rect( prediction is not ported)", )); } - if !skip { - return Err(unsupported( - "a coded (non-skip) HORZ/VERT rect strip below 16x16 (this decoder ports only \ - the skip case at this size)", - )); - } let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height); let (cpx, cpy) = (px / 2, py / 2); let (chroma_w, chroma_h) = (bw / 2, bh / 2); - y.reconstruct_rect( - px, - py, - bw, - bh, - mode, - angle_delta_y, - reach, - &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( - cpx, - cpy, - chroma_w, - chroma_h, - uv_predict_mode, - angle_delta_uv, - reach, - &vec![0i32; chroma_w * chroma_h], - alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), - None, - false, - ); - v.reconstruct_rect( - cpx, - cpy, - chroma_w, - chroma_h, - uv_predict_mode, - angle_delta_uv, - reach, - &vec![0i32; chroma_w * chroma_h], - alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), - None, - false, - ); - neighbours.record_mi_rect( - leaf_mi, - bw, - bh, - &[ - vec![0i32; bw * bh], - vec![0i32; chroma_w * chroma_h], - vec![0i32; chroma_w * chroma_h], - ], - ); + let (luma_levels, u_levels, v_levels); + if skip { + luma_levels = vec![0i32; bw * bh]; + u_levels = vec![0i32; chroma_w * chroma_h]; + v_levels = vec![0i32; chroma_w * chroma_h]; + y.reconstruct_rect( + px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra, + smooth_neighbor, + ); + let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh)); + u.reconstruct_rect( + cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels, + alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, false, + ); + v.reconstruct_rect( + cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels, + alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, false, + ); + } else { + // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`, + // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type` + // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s + // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at + // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square + // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`). + let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 { + (&SCAN_16X8, &SCAN_8X4) + } else { + (&SCAN_8X16, &SCAN_4X8) + }; + let around = neighbours.around_mi_rect(leaf_mi, bw, bh); + let luma_set = if reduced_tx_set { + TxbSet::LumaRect16x8 + } else { + TxbSet::LumaRect16x8Set1 + }; + let mut luma_coding = cdfs.txb(luma_set, mode); + let (l_levels, luma_tx_type) = read_coeffs_rect( + dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct, + )?; + if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() { + let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect(); + eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}"); + } + luma_levels = l_levels; + let luma_residual = dequant_and_inverse_typed_wh( + &luma_levels, bw, bh, crate::decode::bit_depth(), + CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type, + ); + y.reconstruct_rect( + px, py, bw, bh, mode, angle_delta_y, reach, &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); + let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); + let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); + let (u_l, u_tx_type) = read_coeffs_rect( + dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx, + dc_sign_ctx(around[1].2), u_default_tx, + )?; + u_levels = u_l; + let u_residual = dequant_and_inverse_typed_wh( + &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(), + CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type, + ); + u.reconstruct_rect( + cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual, + alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, false, + ); + 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); + let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); + let (v_l, v_tx_type) = read_coeffs_rect( + dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx, + dc_sign_ctx(around[2].2), v_default_tx, + )?; + v_levels = v_l; + let v_residual = dequant_and_inverse_typed_wh( + &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(), + CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type, + ); + v.reconstruct_rect( + cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual, + alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, false, + ); + RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1)); + } + neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]); 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); // This leaf is necessarily non-palette (a palette one refused above), so @@ -5135,6 +5424,10 @@ fn decode_leaf_rect( // off whatever block last covered the cell (lane-palette2 r8). neighbours.record_palette_y_rect(pal_at, bw, bh, 0, [0u16; 8]); neighbours.record_palette_uv_rect(pal_at, bw, bh, 0, [0u16; 8]); + // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and + // rows -- record the whole span, not one cell. + 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); Ok(mode) } @@ -5174,14 +5467,15 @@ fn decode_block_rect64( ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); + let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); let palette_uv_cache = neighbours.palette_uv_cache(at); let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode_rect( dec, cdfs, - neighbours.above_mode[c], - neighbours.left_mode[r], + nb_above_mode, + nb_left_mode, // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is @@ -5212,8 +5506,7 @@ fn decode_block_rect64( strip (corner-cropped luma coefficients not ported for palette)", )); } - let smooth_neighbor = - is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]); + let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); if smooth_neighbor { SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); } @@ -5702,7 +5995,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() { @@ -5748,7 +6041,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) { @@ -5770,7 +6063,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 { @@ -5895,7 +6188,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 ); } @@ -6480,12 +6773,13 @@ fn decode_block( let (px, py) = (c * SUB, r * SUB); let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); let palette_uv_cache = neighbours.palette_uv_cache(at); + let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode( dec, cdfs, - neighbours.above_mode[c], - neighbours.left_mode[r], + nb_above_mode, + nb_left_mode, cfl, side, enable_filter_intra, @@ -6515,8 +6809,7 @@ fn decode_block( } else { uv_mode }; - let smooth_neighbor = - is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]); + let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); if smooth_neighbor { SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); } @@ -6919,6 +7212,17 @@ fn decode_block( /// at. Returns the mode this leaf decoded, for the caller's own /// `prev_leaf`/final mode-writeback bookkeeping. #[allow(clippy::too_many_arguments)] +/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one +/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads +/// `above_mode[col]`, and its true above neighbour is the mi directly above +/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one +/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left +/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf +/// (bottom-right) into both, as this path did, is right only when all four +/// leaves happen to share a mode. `done` may be short at the true frame edge +/// (the straddle caller filters positions off the frame), so each side falls +/// back to the last leaf actually decoded. + fn decode_leaf8( dec: &mut SymbolDecoder, cdfs: &mut Cdfs, @@ -6947,9 +7251,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)); } @@ -6978,6 +7299,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 @@ -7016,7 +7340,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, @@ -7028,7 +7352,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]; @@ -7082,7 +7406,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, @@ -7104,7 +7428,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 @@ -7180,7 +7504,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, @@ -7202,7 +7526,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 @@ -7242,6 +7566,7 @@ 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]); @@ -7255,9 +7580,284 @@ fn decode_leaf8( } 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. @@ -9258,6 +9858,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; let mode_bot = decode_leaf_rect( &mut dec, @@ -9275,6 +9876,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; neighbours.above_mode[sc] = mode_bot; neighbours.left_mode[sr] = mode_bot; @@ -9304,6 +9906,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; let mode_right = decode_leaf_rect( &mut dec, @@ -9321,6 +9924,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; neighbours.above_mode[sc] = mode_right; neighbours.left_mode[sr] = mode_right; @@ -9340,11 +9944,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]); @@ -9353,34 +9984,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((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) { + neighbours.above_mode[sc] = below; } - if let Some((_, mode)) = prev_leaf { - neighbours.above_mode[sc] = mode; - neighbours.left_mode[sr] = mode; + if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) { + neighbours.left_mode[sr] = right; } continue; } @@ -9414,9 +10067,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() { @@ -9424,30 +10093,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 @@ -9455,9 +10144,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; } } } @@ -16036,7 +16727,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 ( @@ -17164,6 +17855,72 @@ mod tests { // this decoder's one target, and the round-trip test below is against // that path with real quantised residual, not a synthetic all-DC frame. + /// [`SCAN_8X4`]/[`SCAN_4X8`] (lane-rectx r2): a bijection check alone + /// cannot catch a transposed pair -- a swap of two orientation tables is + /// still a bijection over the same 32 positions. This pins BOTH arrays + /// at once, element-for-element, against literal transcriptions of + /// libaom's real `default_scan_4x8`/`default_scan_8x4` in + /// `av1/common/scan.c` (`~/.cache/aom-oracle/src`, read directly for + /// this test, not re-derived from the zigzag formula). The two source + /// sequences are themselves different in their own right (not equal to + /// each other), so this is asymmetric in the two axes: if the repo's + /// `SCAN_8X4`/`SCAN_4X8` were swapped with each other, one side of this + /// assert pair would fail even though each individual array would still + /// pass a same-orientation bijection test. + #[test] + fn scan_8x4_and_4x8_are_not_transposed_against_each_other() { + // libaom `default_scan_4x8` verbatim (scan.c:29-32) -- this repo + // names it `SCAN_8X4` under the established w/h axis swap (see + // `SCAN_8X4`'s own doc comment). + const LIBAOM_DEFAULT_SCAN_4X8: [u16; 32] = [ + 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21, + 14, 7, 29, 22, 15, 30, 23, 31, + ]; + // libaom `default_scan_8x4` verbatim (scan.c:44-47) -- this repo's + // `SCAN_4X8`. + const LIBAOM_DEFAULT_SCAN_8X4: [u16; 32] = [ + 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, + 25, 28, 23, 26, 29, 27, 30, 31, + ]; + assert_ne!( + LIBAOM_DEFAULT_SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4, + "the two libaom source sequences must differ, or this pin would \ + pass regardless of a swap" + ); + assert_eq!(SCAN_8X4, LIBAOM_DEFAULT_SCAN_4X8, "SCAN_8X4 vs libaom default_scan_4x8"); + assert_eq!(SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4, "SCAN_4X8 vs libaom default_scan_8x4"); + } + + /// lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <= 32", + /// so a DC_PRED 16x8/8x16 strip reads a `use_filter_intra` flag exactly + /// like a square 16x16 does. [`filter_intra_size_class_rect`] returned + /// `None` at those two sizes, so the symbol was never read and the tile + /// desynced from that block on (root-caused against an instrumented + /// aomdec `EC_TRACE_COEFF` ladder on a real stream: identical `mode=0`/ + /// `uv_mode=9` values, our range 34808 vs the oracle's 40668 at the very + /// next transform block). + /// + /// The two rows are ASYMMETRIC (9394 for 16x8, 12551 for 8x16), so this + /// pin fails if the pair is ever transposed -- the shape the repo's + /// scan tables already carry (`SCAN_8X4` == libaom `default_scan_4x8`). + #[test] + fn a_rect_strip_below_16x16_reads_its_own_filter_intra_cdf_row() { + // `default_filter_intra_cdfs` (entropymode.c), indexed by BLOCK_SIZES_ALL: + // [4] = BLOCK_8X16, [5] = BLOCK_16X8, [7] = BLOCK_16X32, [8] = BLOCK_32X16. + const LIBAOM_8X16: u16 = 12551; + const LIBAOM_16X8: u16 = 9394; + let c16x8 = filter_intra_size_class_rect(16, 8).expect("16x8 reads use_filter_intra"); + let c8x16 = filter_intra_size_class_rect(8, 16).expect("8x16 reads use_filter_intra"); + assert_ne!(c16x8, c8x16, "the two orientations must not share a CDF row"); + assert_eq!(cdf::FILTER_INTRA[c16x8][0], LIBAOM_16X8, "16x8 filter_intra row"); + assert_eq!(cdf::FILTER_INTRA[c8x16][0], LIBAOM_8X16, "8x16 filter_intra row"); + // The sizes one class up keep their own distinct rows (lane-intradisp). + assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(32, 16).unwrap()][0], 12756); + assert_eq!(cdf::FILTER_INTRA[filter_intra_size_class_rect(16, 32).unwrap()][0], 14301); + // A size with a side over 32 is genuinely not allowed the flag. + assert_eq!(filter_intra_size_class_rect(64, 32), None); + } + /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly /// when both references sit on the same temporal side -- the three /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 65f44ae3..96889135 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 @@ -1104,6 +1131,38 @@ const HAS_TOP_RIGHT_RECT: [&[u8]; 2] = [&[15, 5, 7, 5], &[255, 119, 127, 119]]; /// `has_bl_32x16`/`has_bl_16x32`, same source, same order. const HAS_BOTTOM_LEFT_RECT: [&[u8]; 2] = [&[78, 14, 78, 14], &[16, 0, 16, 0]]; +/// libaom `reconintra.c`'s `has_tr_*`/`has_bl_*` for the four rectangular +/// block sizes this decoder codes, transcribed verbatim (lane-rectx r4). +/// The 16x8/8x16 rows are what the 32x16/16x32 pair above cannot stand in +/// for: they are 16 bytes, not 4, and their bit pattern is a different +/// coding order entirely -- reading the 16x32 table for a 16x8 block gave +/// the wrong bottom-left availability and a directional (D203) strip whose +/// prediction diverged exactly where it starts reading below its own height. +/// `has_tr_vert_tables`/`has_bl_vert_tables` hold the SAME pointers as these +/// for every WH (no VERT_A/B ever produces one), +/// so the partition type does not select a different table at these sizes. +fn has_tr_rect_table(bw: usize, bh: usize) -> &'static [u8] { + match (bw, bh) { + (16, 8) => &[255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0], + (8, 16) => &[255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119], + (32, 16) => &[15, 5, 7, 5], + (16, 32) => &[255, 119, 127, 119], + (64, 32) => &[19], + _ => &[127], + } +} + +fn has_bl_rect_table(bw: usize, bh: usize) -> &'static [u8] { + match (bw, bh) { + (16, 8) => &[254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0], + (8, 16) => &[16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0], + (32, 16) => &[78, 14, 78, 14], + (16, 32) => &[16, 0, 16, 0], + (64, 32) => &[34], + _ => &[0], + } +} + impl Reach { /// What a block of `side` samples at `(x, y)` may read past its own edges, /// in a frame of `width` by `height`. @@ -1133,37 +1192,61 @@ impl Reach { } } - fn position_rect(bw: usize, bh: usize, x: usize, y: usize) -> (usize, usize, usize, usize) { - ( - (y % SUPERBLOCK) / bh, - (x % SUPERBLOCK) / bw, - SUPERBLOCK / bh, - SUPERBLOCK / bw, - ) - } - + /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0, + /// the transform covering the whole block, luma): everything before the + /// table lookup is that function's own early-exit ladder. fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool { - let (row, col, _per_row, per_col) = Self::position_rect(bw, bh, x, y); - if row == 0 { + const SB_MI: usize = SUPERBLOCK / 4; + let (mi_row, mi_col) = (y / 4, x / 4); + let bw_log2 = (bw / 4).trailing_zeros() as usize; + let bh_log2 = (bh / 4).trailing_zeros() as usize; + let blk_row = (mi_row & (SB_MI - 1)) >> bh_log2; + let blk_col = (mi_col & (SB_MI - 1)) >> bw_log2; + // Top row of the superblock: the top-right pixels are in the (already + // decoded) superblock above. + if blk_row == 0 { return true; } - if col + 1 == per_col { + // Rightmost column: they fall in the superblock to the right. + if ((blk_col + 1) << bw_log2) >= SB_MI { return false; } - let table = HAS_TOP_RIGHT_RECT[usize::from(bw == 16)]; - Self::bit(table, (row * Self::table_stride(bw) + col) % (table.len() * 8)) + let table = has_tr_rect_table(bw, bh); + Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) + } + + /// libaom `has_top_right`'s own index arithmetic: + /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and + /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a + /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5: + /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but + /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a + /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main). + /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it. + fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize { + (blk_row << (5 - bw_log2)) + blk_col } + /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`]. fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool { - let (row, col, per_row, _per_col) = Self::position_rect(bw, bh, x, y); - if col == 0 { - return row * bh + bh < SUPERBLOCK; + const SB_MI: usize = SUPERBLOCK / 4; + let (mi_row, mi_col) = (y / 4, x / 4); + let bw_log2 = (bw / 4).trailing_zeros() as usize; + let bh_log2 = (bh / 4).trailing_zeros() as usize; + let blk_row = (mi_row & (SB_MI - 1)) >> bh_log2; + let blk_col = (mi_col & (SB_MI - 1)) >> bw_log2; + // Leftmost column of the superblock: the bottom-left pixels are in + // the left superblock iff they stay inside its height. + if blk_col == 0 { + return (blk_row << bh_log2) + (bh / 4) < SB_MI; } - if row + 1 == per_row { + // Bottom row (and not the leftmost column): they fall in the + // superblock below, which is not decoded yet. + if ((blk_row + 1) << bh_log2) >= SB_MI { return false; } - let table = HAS_BOTTOM_LEFT_RECT[usize::from(bw == 16)]; - Self::bit(table, (row * Self::table_stride(bw) + col) % (table.len() * 8)) + let table = has_bl_rect_table(bw, bh); + Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) } /// Marks every [`Reach::of`] made until the returned guard drops as being @@ -1196,21 +1279,22 @@ 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. + // NB: named `table_row`, not `row` -- `row` above is the block's + // position inside the superblock and is what the bit index below + // steps by (a merge that shadowed it desynced every block size). + let table_row = Self::table(side); + let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() { + HAS_TOP_RIGHT_VERT[table_row] } else { - HAS_TOP_RIGHT[Self::table(side)] + HAS_TOP_RIGHT[table_row] }; Self::bit( table, @@ -1230,11 +1314,22 @@ 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. + // NB: named `table_row`, not `row` -- `row` above is the block's + // position inside the superblock and is what the bit index below + // steps by (a merge that shadowed it desynced every block size). + let table_row = Self::table(side); + let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() { + HAS_BOTTOM_LEFT_VERT[table_row] } else { - HAS_BOTTOM_LEFT[Self::table(side)] + HAS_BOTTOM_LEFT[table_row] }; Self::bit( table, @@ -1270,6 +1365,8 @@ impl Reach { 1 } else if side == 8 { 2 + } else if side == 4 { + 3 } else { 0 } @@ -3128,6 +3225,49 @@ pub fn encode_sequence( #[cfg(test)] mod tests { + + /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a + /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a + /// row holds `32 >> bw_in_mi_log2` bits and the table holds + /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that + /// superblock must therefore hit every bit of the table EXACTLY ONCE. + /// r4's `4 - bw_log2` index halved the row stride: the walk then covered + /// only a quarter of the 16x8 table and read the wrong byte for every + /// block row but the first (silently wrong above-right/below-left + /// availability -- wrong pixels, no error). + #[test] + fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() { + for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { + let (bw_log2, bh_log2) = + ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize); + let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2); + for (name, table) in + [("has_tr", has_tr_rect_table(bw, bh)), ("has_bl", has_bl_rect_table(bw, bh))] + { + assert_eq!( + table.len() * 8, + rows * cols, + "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits" + ); + let mut seen = vec![0u32; table.len() * 8]; + for blk_row in 0..rows { + for blk_col in 0..cols { + let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col); + assert!( + idx < seen.len(), + "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})" + ); + seen[idx] += 1; + } + } + assert!( + seen.iter().all(|&n| n == 1), + "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \ + (row stride is not {cols})" + ); + } + } + } use super::*; use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED}; use std::io::Write; diff --git a/crates/ec-av1/src/gate_coverage.rs b/crates/ec-av1/src/gate_coverage.rs index ee711e35..d1e73e92 100644 --- a/crates/ec-av1/src/gate_coverage.rs +++ b/crates/ec-av1/src/gate_coverage.rs @@ -199,7 +199,7 @@ const NEVER_EXERCISED_10BIT: &[(&str, &str)] = &[ // gate passes `=1` for both. ( "enable-1to4-partitions", - "10-bit hole only: lane-tx64x16's 8-bit SB-level 1:4 gate passes `=1` and asserts both arms, but no 10-bit gate does", + "10-bit hole only: 8-bit gates (lane-tx64x16 SB-level 1:4, lane-sub8) pass `=1` and assert their arms, but no 10-bit gate does", ), ( "enable-angle-delta", diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index fb536901..097cb5e9 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -28,17 +28,16 @@ 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)", ]; #[cfg(test)] const REFUSALS: &[&str] = &[ "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only the skip case at this size)", - "a coded (non-skip) HORZ/VERT rect strip below 16x16 (this decoder ports only the skip case at this size)", "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})", @@ -50,6 +49,7 @@ const REFUSALS: &[&str] = &[ "a palette block with a real transform on a superblock-level HORZ/VERT strip (corner-cropped luma coefficients not ported for palette)", "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 69eee982..02ec635f 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -8268,6 +8268,330 @@ mod tests { result.as_ref().map(|f| f.len()).map_err(|e| e.to_string()) ); } + /// lane-rectx r3: a real `aomenc` stream whose 16x16-level + /// `PARTITION_HORZ`/`PARTITION_VERT` strips are CODED (non-skip), i.e. + /// carry genuine `TX_16X8`/`TX_8X16` luma coefficients and their + /// `TX_8X4`/`TX_4X8` chroma halves through [`decode_leaf_rect`]'s + /// lane-rectx arm -- the refusal "a coded (non-skip) HORZ/VERT rect strip + /// below 16x16" this round lifts. `--min-partition-size=8 + /// --max-partition-size=32 --enable-rect-partitions=1` is what makes + /// aomenc reach for a 16x8 leaf at all; mandelbrot at `cq-level=24` is + /// what makes those leaves non-skip (a gradient fixture codes them all + /// away). `--reduced-tx-type-set=1` pins the five-symbol + /// `EXT_TX_SET_DTT4_IDTX` alphabet: without it aomenc also writes + /// `V_DCT`/`H_DCT`, whose 1D tx classes [`read_coeffs_rect`] still + /// refuses by name (see the r3 report's open residue), so a `=0` run + /// would prove nothing about the 2D path it does support. + /// + /// r2 shipped this path unproven; it was wrong. `TxbSet::LumaRect16x8` + /// read its `tx_type` symbol from the 16x16 row, but libaom's + /// `read_tx_type` indexes `intra_ext_tx_cdf[eset][txsize_sqr_map[tx_size]]` + /// and `txsize_sqr_map[TX_16X8] == TX_8X8` -- a five-symbol CDF where a + /// seven-symbol one belonged, desyncing at the FIRST coded rect leaf + /// (whole frame wrong from pixel (0,0)). + #[test] + fn a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (64usize, 64usize); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &format!("mandelbrot=size={width}x{height}:start_x=-0.6"), + "-pix_fmt", + "yuv420p", + "-t", + "1", + "-vframes", + "1", + "-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 encode = || { + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=16", + "--cpu-used=4", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--kf-max-dist=0", + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-tx-size-search=0", + // Filter intra on a strip is a separate, still-refused + // predictor (`filter intra on a HORZ/VERT strip`); this + // gate is about the rect RESIDUAL path, so it is off here + // and covered by the square filter-intra gate instead. + "--enable-filter-intra=0", + "--reduced-tx-type-set=1", + "--min-partition-size=8", + "--max-partition-size=32", + "--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) + ); + out.stdout + }; + // The fixture rule: an encoder output is only a pin if it reproduces. + let stream = encode(); + assert_eq!(stream, encode(), "{NAME}: aomenc output is not reproducible for this recipe"); + let before = crate::decode::rect_leaf_coeff_hits(); + let frames = decode_stream(&stream) + .unwrap_or_else(|e| panic!("{NAME}: decode failed, not a pixel mismatch: {e}")); + let fired = crate::decode::rect_leaf_coeff_hits() - before; + assert!( + fired > 0, + "{NAME}: the stream decoded but no coded (non-skip) rect leaf fired -- \ + the gate proves nothing" + ); + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len()); + assert_eq!(frames.len(), 1, "{NAME}: expected one key frame"); + assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count"); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg ({fired} coded rect leaves)"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg"); + } + eprintln!("{NAME}: pixel-exact, rect_leaf_coeff_hits={fired}"); + } + + /// lane-rectx r5: the same 16x8/8x16 rect leaves, but this time proving + /// what a LATER, non-strip block reads from them. `decode_leaf_rect` took + /// the mi-exact intra mode map in r4; `decode_block`/`decode_block_rect`/ + /// `decode_block_rect64` did not, so a 32x16 strip whose left neighbour was + /// a 16x8 leaf still read the coarse per-16x16 `left_mode` slot -- which no + /// sub-16x16 block ever writes -- and picked a DIFFERENT `kf_y_mode` CDF row + /// for the same decoded mode value. The stream stayed in sync through mode + /// info (`EC_TRACE_MODE_STEP` ranges match up to that symbol) and then + /// diverged inside the block's own coefficients: the whole bottom-right + /// 32x32 quadrant of this fixture decoded wrong (1650 bytes) while the + /// three earlier quadrants were exact -- wrong pixels returned as success. + /// `mode_mi_override_hits` counts exactly the reads where the mi-exact + /// neighbour disagrees with the coarse slot, so a regression that drops the + /// override again fails the counter as well as the pixels. + #[test] + fn a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (64usize, 64usize); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", + &format!("rgbtestsrc=size={width}x{height}"), + "-pix_fmt", "yuv420p", "-t", "1", "-vframes", "1", "-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)); + // Two swept cells of the r4 sweep that decoded to completion with + // WRONG pixels (1714 and 1650 bytes): `--reduced-tx-type-set` and + // `--enable-filter-intra` are the two axes that move which block sizes + // aomenc reaches for here; both arms are pinned. + let mut total_overrides = 0usize; + for (rtx, filter_intra) in [("1", "0"), ("0", "1")] { + let encode = || { + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32", + "--cpu-used=4", "--threads=1", "--row-mt=0", "--sb-size=64", + "--kf-max-dist=0", "--enable-rect-partitions=1", + "--enable-ab-partitions=0", "--enable-1to4-partitions=0", + "--enable-tx-size-search=0", "--enable-cdef=0", + "--enable-restoration=0", + &format!("--enable-filter-intra={filter_intra}"), + &format!("--reduced-tx-type-set={rtx}"), + "--min-partition-size=8", "--max-partition-size=32", + "--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) + ); + out.stdout + }; + let stream = encode(); + assert_eq!( + stream, + encode(), + "{NAME}: aomenc output is not reproducible (rtx={rtx} filter_intra={filter_intra})" + ); + let before = crate::decode::mode_mi_override_hits(); + let frames = decode_stream(&stream).unwrap_or_else(|e| { + panic!("{NAME}: decode failed (rtx={rtx} filter_intra={filter_intra}): {e}") + }); + // Counted only on an attempt that actually decoded AND is compared + // below -- a refusal never contributes to the firing assert. + let overrides = crate::decode::mode_mi_override_hits() - before; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len()); + assert_eq!(frames.len(), 1, "{NAME}: expected one key frame"); + assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count"); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!( + got.y, want.y, + "{NAME} frame {i} luma vs ffmpeg (rtx={rtx} filter_intra={filter_intra}, \ + {overrides} mi-exact mode overrides)" + ); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (rtx={rtx})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (rtx={rtx})"); + } + total_overrides += overrides; + } + assert!( + total_overrides > 0, + "{NAME}: no non-strip block ever read a mi-exact neighbour that disagreed with its \ + coarse slot -- the gate proves nothing" + ); + eprintln!("{NAME}: pixel-exact, mode_mi_override_hits={total_overrides}"); + } + + #[test] + #[ignore = "lane-rectx r3 scratch sweep"] + fn sweep_rectx_recipes() { + let _gate_lock = lock_gate_counters(); + let srcs: Vec = vec![ + "mandelbrot=size=64x64:start_x=0.4".into(), + "mandelbrot=size=64x64:start_x=-0.6".into(), + "mandelbrot=size=64x64:start_x=0.1".into(), + "mandelbrot=size=128x128:start_x=0.4".into(), + "mandelbrot=size=128x128:start_x=-0.6".into(), + "testsrc2=size=64x64".into(), + "testsrc2=size=128x128".into(), + "rgbtestsrc=size=64x64".into(), + "smptebars=size=128x128".into(), + ]; + for start_x in srcs { + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", + &start_x, + "-pix_fmt", "yuv420p", "-t", "1", "-vframes", "1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()) + .output().expect("ffmpeg"); + assert!(y4m.status.success()); + let (width, height) = if start_x.contains("128x128") { (128usize, 128usize) } else { (64usize, 64usize) }; + for cq in [16u32, 20, 24, 28, 32, 40, 50] { + for rtx in ["0", "1"] { + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", "--passes=1", "--end-usage=q", + &format!("--cq-level={cq}"), "--cpu-used=4", "--threads=1", + "--row-mt=0", "--sb-size=64", "--kf-max-dist=0", + "--enable-rect-partitions=1", "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", "--enable-tx-size-search=0", + "--enable-cdef=0", "--enable-restoration=0", + &format!("--reduced-tx-type-set={rtx}"), + "--min-partition-size=8", "--max-partition-size=32", + "--obu", "-o", "-", "-", + ]) + .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()) + .spawn().expect("aomenc"); + child.stdin.take().unwrap().write_all(&y4m.stdout).unwrap(); + let out = child.wait_with_output().unwrap(); + assert!(out.status.success()); + let stream = out.stdout; + let before = crate::decode::rect_leaf_coeff_hits(); + let res = decode_stream(&stream); + let fired = crate::decode::rect_leaf_coeff_hits() - before; + match res { + Err(e) => eprintln!("x={start_x} cq={cq} rtx={rtx} fired={fired} REFUSED {e}"), + Ok(frames) => { + let want = ffmpeg_decode_sequence(&stream, width, height, frames.len()); + let bad = frames.iter().zip(&want) + .filter(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v).count(); + eprintln!("x={start_x} cq={cq} rtx={rtx} fired={fired} frames={} mismatched={bad}", frames.len()); + if bad == 0 { continue; } + let (g, w) = (&frames[0], &want[0]); + for br in 0..height / 8 { + let mut line = String::new(); + for bc in 0..width / 8 { + let mut n = 0; + for row in br * 8..br * 8 + 8 { + for col in bc * 8..bc * 8 + 8 { + if g.y[row * width + col] != w.y[row * width + col] { + n += 1; + } + } + } + line.push_str(&format!("{n:4}")); + } + eprintln!(" blk8 row{br}: {line}"); + } + } + } + } + } + } + } + /// lane-rectgate r1: every prior gate pins `--enable-rect-partitions=0 /// --enable-ab-partitions=0 --min/max-partition-size=32` so aomenc never /// gets to choose a real rect/ab split. This charter's premise ("rect @@ -10457,6 +10781,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/rectx-r3.handoff.md b/lanes/rectx-r3.handoff.md new file mode 100644 index 00000000..61a97ccc --- /dev/null +++ b/lanes/rectx-r3.handoff.md @@ -0,0 +1,54 @@ +# lane-rectx r3 handoff — one defect fixed, one precisely located + +TOTALS `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` (CARGO_TARGET_DIR=~/.cache/cargo-target-rectx): +**269 passed, 1 failed, 24 ignored** (1042s). The single failure is this lane's own gate, +`stream::tests::a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact`; +it now stops on an unrelated third blocker ("a 32x32 partition type this decoder does not code +(value=7)" = PARTITION_VERT_B at 32x32) with the recipe as written. No other test regressed +(268 -> 269 passed is this round's new pin). + +## Do next, in this order + +1. **Per-mi y-mode neighbour grid.** `Neighbours::above_mode` (decode.rs:1806) / `left_mode` + are per-16x16 cell; libaom reads `above_mi`/`left_mi` off the real mi grid. Reproduce in + one command: + - stream: `ffmpeg -v error -f lavfi -i rgbtestsrc=size=64x64 -pix_fmt yuv420p -t 1 -vframes 1 + -f yuv4mpegpipe g.y4m` then `aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=50 + --cpu-used=4 --threads=1 --row-mt=0 --sb-size=64 --kf-max-dist=0 --enable-rect-partitions=1 + --enable-ab-partitions=0 --enable-1to4-partitions=0 --enable-tx-size-search=0 + --enable-cdef=0 --enable-restoration=0 --reduced-tx-type-set=1 --min-partition-size=8 + --max-partition-size=32 --obu -o t.obu g.y4m` + - ours: `EC_TRACE_COEFF=1 EC_AV1_RECTX_TRACE=1 EC_TRACE_MODE_STEP=1 + target/debug/examples/decode_probe t.obu` + - oracle: `EC_TRACE_COEFF=1 EC_TRACE_MODE=1 ~/.cache/aom-oracle/build/aomdec --rawvideo + -o /dev/null t.obu` + - THE ELEMENT: leaf `mi=(4,12)`, bw=16 bh=8, outer_at=(1,3). Both enter at range **59792**. + Oracle `EC_IMODE_VAL mode=2 uv_mode=2 skip=0 -> rng=49036`; ours `mode=0 uv_mode=13 -> + rng=47236`. First 15 transform blocks of the frame are bit-exact before it. + - Fix shape: a per-mi mode grid written wherever `fill_skip_grid`/`fill_skip_grid_rect` + (13 sites) is written, read by `read_intra_mode*`'s `above_ctx`/`left_ctx`. +2. **Then re-pick the gate recipe.** `stream::tests::sweep_rectx_recipes` (`#[ignore]`, + `--nocapture`) sweeps 9 lavfi sources x 7 cq x reduced-tx-type-set 0/1 and prints + `fired=`/refusal/`mismatched=` per cell plus an 8x8 mismatch map. After the filter_intra fix + exactly one cell decodes to completion (rgbtestsrc cq=50 rtx=1, fired=4) and it mismatches + on defect (1). Every other cell refuses; the dominant refusal is + "a HORZ_A/HORZ_B/VERT_A partition below 16x16" — this aomenc build writes AB partitions + below 16x16 even with `--enable-ab-partitions=0` (126/126 cells swept; same quirk the ledger + records at SB level). Wiring HORZ_A/HORZ_B/VERT_A below 16x16 may be the cheaper route to a + green gate than recipe hunting. +3. Only then lift "a coded (non-skip) HORZ/VERT rect strip below 16x16" and "a non-skip + rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding" in + `refusal_inventory.rs` + `gate_coverage.rs`. NOT lifted this round. + +## Do NOT re-do + +- The r2 coefficient path (scans, `EOB_PT_128_LUMA`/`EOB_PT_32_CHROMA`, txb sets, nz-map/br + ctx, DC-sign ctx) is range-exact against aomdec for a real non-skip TX_16X8 leaf + both + TX_8X4 chroma halves. Don't re-derive it. +- `base_ctx_rect`'s 11/16 rect nz-map offsets are CORRECT as written (display-orientation + convention: our (row,col) are display row/col, libaom's flat `av1_nz_map_ctx_offset` tables + are column-major so their INDEX packing, not their rule, is what differs). Swapping the two + constants was tried this round: the 126-cell sweep went from 2 full decodes to 0 (every cell + refused). Dead end. +- `SCAN_8X4`/`SCAN_4X8` were re-checked verbatim against + `~/.cache/aom-oracle/src/av1/common/scan.c` this round. They are right. diff --git a/lanes/rectx-r3.report.md b/lanes/rectx-r3.report.md new file mode 100644 index 00000000..c3c83a5f --- /dev/null +++ b/lanes/rectx-r3.report.md @@ -0,0 +1,88 @@ +# lane-rectx r3 — the rect leaf was bit-exact; the block AFTER it was not + +Branch `lane-rectx`, on top of `main` 3808cf8 (`git merge-base --is-ancestor main HEAD` = OK, +no rebase needed). Prior state: r1/r2 landed non-skip TX_16X8/TX_8X16 rect-leaf coefficient +decode (`decode_leaf_rect`'s lane-rectx arm, `read_coeffs_rect`, `TxbSet::LumaRect16x8{,Set1}` +/`ChromaRect8x4`, `EOB_PT_128_LUMA`/`EOB_PT_32_CHROMA`, `SCAN_8X4`/`SCAN_4X8`) UNPROVEN, with +the lane's own gate red. + +## What this round proved + +1. **The r2 coefficient path is right.** Against the instrumented oracle + (`~/.cache/aom-oracle/build/aomdec`, `EC_TRACE_COEFF=1`) on a real aomenc stream, a + non-skip `TX_16X8` luma leaf plus both its `TX_8X4` chroma halves decode with an + IDENTICAL msac range at every element (`all_zero` 37445, `tx_type` 55512, `eob`=1 41024, + `base_eob` pos 0 level 1 64544, DC sign 37072, chroma `all_zero`=1 40760 / 47390). + Scans, eob CDF alphabet, txb sets, nz-map/br contexts and the DC-sign context at this size + are all confirmed by that ladder, not by argument. +2. **`SCAN_8X4`/`SCAN_4X8` re-checked against the real `scan.c`** (not a memory of it): + `~/.cache/aom-oracle/src/av1/common/scan.c` `default_scan_4x8` == our `SCAN_8X4` and + `default_scan_8x4` == our `SCAN_4X8`, verbatim, which is what + `decode.rs::tests::the_rect_scan_tables_match_libaom...` already pins (asymmetric pair, a + swap fails it). +3. **Root cause of the desync (FIXED): the `use_filter_intra` flag was never read at + 16x8/8x16.** `av1_filter_intra_allowed_bsize` is "both sides <= 32", so libaom reads the + flag for every DC_PRED 16x8/8x16 block; `filter_intra_size_class_rect` returned `None` + there, so we dropped one symbol per DC_PRED strip and desynced the tile from that block on + — silently, with a full-frame pixel mismatch and no error. Ladder evidence: leaf mi=(2,4), + we and the oracle both decode `mode=0 uv_mode=9 skip=0`, but our post-mode range is 34808 + where the oracle's is 40668 (value-equal narrowing drift). After the fix our range at that + point is 40668 and the next transform block's `all_zero` reads 40269 — bit-identical to the + oracle. + +## Files changed + +- `crates/ec-av1/src/cdf.rs:415` — `FILTER_INTRA` 6 -> 8 rows, adding `default_filter_intra_cdfs` + index 5 (BLOCK_16X8, 9394) and 4 (BLOCK_8X16, 12551). +- `crates/ec-av1/src/cdf_state.rs:467` — the field's type/doc follow. +- `crates/ec-av1/src/decode.rs` `filter_intra_size_class_rect` — `(16,8) => Some(6)`, + `(8,16) => Some(7)`; the actual fix. +- `crates/ec-av1/src/decode.rs` `read_coeffs_rect` — three env-gated trace prints + (`tag=all_zero_rect` with the pre-symbol range, `tag=sign_rect`) under the existing + `EC_TRACE_COEFF`, plus the entry range on the `EC_AV1_RECTX_TRACE` line; these are what made + the cross-decoder bisection possible and are kept for the successor. +- `crates/ec-av1/src/decode.rs` tests — new + `a_rect_strip_below_16x16_reads_its_own_filter_intra_cdf_row`. +- `crates/ec-av1/src/stream.rs` `sweep_rectx_recipes` (scratch, `#[ignore]`) — also sweeps + `--reduced-tx-type-set=1`, and only dumps the 8x8 mismatch map when there IS a mismatch. + +## Checks + +- `cargo test -p ec-av1 --lib -- filter_intra scan_` -> 8 passed, 0 failed (includes the new pin + and the existing `a_real_aomenc_filter_intra_stream_decodes_pixel_exact`). +- `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` -> see TOTALS below. +- EVIDENCE: /tmp/claude-1000/.../scratchpad/{s.obu,aom.log,ours.log} | ffmpeg mandelbrot 64x64 + start_x=-0.6 -> aomenc cq16 --enable-rect-partitions=1 --min-partition-size=8 + --max-partition-size=32; instrumented aomdec `EC_TRACE_COEFF=1` vs + `examples/decode_probe` `EC_TRACE_COEFF=1` | first divergence moved from the transform block + after leaf mi=(2,4) (ours 34467 vs oracle 40269) to none at that point (both 40269) after the + fix. + +## Open residue + +- **fix-now (next round, out of this round's tool budget): the rect leaf's `kf_y_mode` + context is read from the coarse 16x16 neighbour grid.** Second, independent defect, found + by the same ladder on `rgbtestsrc=size=64x64` cq=50 `--reduced-tx-type-set=1`: at leaf + mi=(4,12) (`decode_leaf_rect`, bw=16 bh=8, outer_at=(1,3)) we and the oracle ENTER the block + at the same range 59792, and then we decode `mode=0` where the oracle decodes `mode=2` + (H_PRED) — a wrong CDF row, not a wrong value. `Neighbours::above_mode`/`left_mode` + (decode.rs:1806) are per-16x16-cell; libaom takes `above_mi`/`left_mi` from the real mi grid, + so when the cell above was split into 8x8 leaves our slot holds the last-written leaf's mode + (bottom-RIGHT) instead of the true above neighbour (bottom-LEFT at mi col 12). Known class: + "context read from one cell". The fix is a per-mi mode grid alongside the existing per-mi + `skip_grid`/`lf_grid` — 13 `fill_skip_grid*` call sites would gain a mode write. It affects + every intra path, not just rect leaves. +- **deferred(the mode-grid fix above): the lane gate + `a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact` is still RED**, + and its two refusals are NOT lifted. Its current recipe fails on a third, unrelated blocker + ("a HORZ_A/HORZ_B/VERT_A partition below 16x16"): a 126-cell sweep (9 lavfi sources x 7 + cq x reduced-tx-type-set 0/1, `sweep_rectx_recipes`) found aomenc writes AB partitions below + 16x16 despite `--enable-ab-partitions=0` in most cells — same aomenc quirk the ledger already + records one level up. After the filter_intra fix the sweep has exactly ONE cell that decodes + to completion (rgbtestsrc cq=50 rtx=1, 4 rect leaves fired) and it mismatches on the mode-ctx + defect above. So there is currently no recipe that can turn the gate green; a green gate + needs the mode-grid fix first. +- accepted: `read_coeffs_rect` still refuses `V_DCT`/`H_DCT` ("a non-2D tx class on a + rectangular transform"), which is why the gate recipe pins `--reduced-tx-type-set=1`. + +TOTALS: see lanes/rectx-r3.handoff.md. diff --git a/lanes/rectx-r4.report.md b/lanes/rectx-r4.report.md new file mode 100644 index 00000000..402ebdca --- /dev/null +++ b/lanes/rectx-r4.report.md @@ -0,0 +1,89 @@ +# lane-rectx r4 — the gate is GREEN: two defects, one cherry-picked, one found here + +Branch `lane-rectx`, commits on top of `main` 3808cf8. Round 3 left the lane's own gate red +with the mode-neighbour defect precisely located; this round fixed it and one more. + +## What changed + +1. **Cherry-picked lane-sub8 `1841406`** (mi-exact intra mode neighbours + `has_tr_4x4`/ + `has_bl_4x4`): `Neighbours::sub8_mode_col/row`, `record_mode_mi`, `mode_above_mi`/ + `mode_left_mi` (`crates/ec-av1/src/decode.rs` ~1830, ~2533-2570), written by `record_rect` + and `record_split_luma`/`decode_leaf8`, plus `crates/ec-av1/src/encode.rs`'s reach rows. + The commit's `decode_leaf_split4`/`read_intra_mode_sub8` hunks were dropped — those + functions exist only on lane-sub8. +2. **`decode_leaf_rect` joins that map** (`decode.rs` ~3644 read, ~3786 write): it now reads + `mode_above_mi`/`mode_left_mi` after the `prev_leaf` override and records its own + `mi_w x mi_h` span, not one cell. This is r3's located defect (leaf mi=(4,12) read + `kf_y_mode` from the coarse 16x16 slot, decoding `mode=0` where the oracle decodes + `mode=2`). +3. **ROOT CAUSE FOUND THIS ROUND — the rect reach tables were the wrong block size.** + `Reach::of_rect` (`encode.rs` ~1096) indexed `HAS_TOP_RIGHT_RECT`/`HAS_BOTTOM_LEFT_RECT` + by `bw == 16`; both arrays only ever held the 32x16/16x32 rows (lane-intradisp's sizes). + A 16x8 block read `has_tr_16x32`/`has_bl_16x32` (4 bytes) where libaom reads + `has_tr_16x8`/`has_bl_16x8` (16 bytes), an 8x16 read the 32x16 rows, and the index + arithmetic (`table_stride = 128/side`, `% (len*8)`) was not libaom's either. + `top_right_rect`/`bottom_left_rect` are now libaom `has_top_right`/`has_bottom_left` + verbatim at block granularity (`row_off`/`col_off` 0, luma), with `has_tr_rect_table`/ + `has_bl_rect_table` carrying 16x8, 8x16, 32x16, 16x32, 64x32 and 32x64 transcribed from + `~/.cache/aom-oracle/src/av1/common/reconintra.c`. (`has_tr_vert_tables`/`has_bl_vert_tables` + hold the SAME pointers for every WH, so the partition type selects + no different table at these sizes.) +4. Gate recipe (`stream.rs` ~5366): mandelbrot `start_x=-0.6`, `--cq-level=16`, and + `--enable-filter-intra=0` added (filter intra ON a strip is a separate, still-refused + predictor). +5. `examples/decode_probe.rs`: lane-sub8's optional second arg dumping raw yuv420p, which is + what made the ffmpeg pixel diff a one-liner outside the test harness. + +## Evidence + +EVIDENCE: /tmp/claude-1000/.../scratchpad/{x.obu,pre_a.yuv.f0,pre_o.yuv.f0} | ffmpeg lavfi +rgbtestsrc 64x64 -> aomenc cq50 --enable-rect-partitions=1 --enable-ab-partitions=0 +--enable-filter-intra=0 --reduced-tx-type-set=1 --min-partition-size=8 --max-partition-size=32; +`EC_AV1_PREFILT_DUMP` on instrumented aomdec vs `examples/decode_probe` | pre-loop-filter luma +diffs 1440 -> 0, final vs `ffmpeg -f rawvideo` 1567 -> 0 bytes. The 1440 luma diffs were a +D203 (`mode=7`) 16x8 strip at mi=(4,8): exact for the first rows, first mismatch at pixel +(44,18) with a diagonal wavefront — the signature of a ray that has started reading BELOW the +block's own height, i.e. wrong bottom-left availability. + +EVIDENCE: gate `a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact` | +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -- a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16 --nocapture` | +`pixel-exact, rect_leaf_coeff_hits=8`; the stream's own symbol trace shows 6 non-skip TX_16X8 +luma leaves + 1 non-skip TX_8X16 (both orientations), 9 non-skip TX_8X4 and 3 non-skip TX_4X8 +chroma halves. + +## Refusals + +- `a coded (non-skip) HORZ/VERT rect strip below 16x16` — the string was already removed from + `decode.rs` in r2 (never in `refusal_inventory::REFUSALS`); this round is what finally PROVES + it, with the gate above. Nothing to delete, the inventory test stays green. +- `a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding` + (`decode.rs:9138`) — **NOT lifted.** It sits in the INTER square-block path + (`reject_residual`, lane-warp r5), which this key-frame gate never reaches. Lifting it needs + an inter gate. +- `a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16` — **NOT lifted**, HORZ_B/VERT_B + never fired in the gate stream. + +## Open residue + +- accepted: `read_coeffs_rect` still refuses `V_DCT`/`H_DCT` (`a non-2D tx class on a + rectangular transform`), hence `--reduced-tx-type-set=1` in the gate. +- deferred(a lane for AB partitions below 16x16): the dominant refusal across the recipe sweep + is still `a HORZ_A/HORZ_B/VERT_A partition below 16x16`. NOTE: unlike r3's premise, this + survives the mode-grid fix, so at THIS size it is not (only) our own desync — 8 of 24 swept + cells still refuse on it after both fixes. +- fix-now(next round): two swept cells decode to completion but are NOT pixel-exact + (rgbtestsrc cq24 3540 bytes, cq32 1714; mandelbrot start_x=-0.6 cq16 with + `--enable-filter-intra=1` 126). Same ladder applies; the gate's own cell is exact. + +## Totals + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` (CARGO_TARGET_DIR=~/.cache/cargo-target-rectx): +**270 passed, 0 failed, 24 ignored** (738.88s) — r3's single failure (this lane's own gate) is +gone and nothing regressed (269 -> 270 passed is exactly this gate). + +That full run was built BEFORE the last hunk (the explicit 64x32/32x64 rows in +`has_tr_rect_table`/`has_bl_rect_table`, which previously fell through to the 16x32 row). +On the final build the four gates that can see those sizes were re-run: +`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`, +`..._with_mandelbrot_fires_the_vert_b_partition_arm`, `..._with_directional_chroma_...` and +this lane's own gate — 4 passed, 0 failed, 1 ignored (21.26s). diff --git a/lanes/rectx-r5.report.md b/lanes/rectx-r5.report.md new file mode 100644 index 00000000..1a1c567b --- /dev/null +++ b/lanes/rectx-r5.report.md @@ -0,0 +1,116 @@ +# lane-rectx r5 -- three "decodes fine, wrong pixels" cells: one root cause, luma now exact in all three + +Branch `lane-rectx`, on top of r4's `fad4d5a`. r4 left three swept cells decoding to +completion with WRONG pixels (the worst class). All three had the SAME root cause; after the +fix two are byte-exact and all three are LUMA-exact, with a chroma-only residue below. + +## Root cause (found this round) + +`decode_leaf_rect` took the mi-exact intra-mode neighbour map in r4 (`mode_above_mi` / +`mode_left_mi`). The three OTHER `kf_y_mode` readers did not: +`decode_block` (square, `decode.rs` ~4960), `decode_block_rect` (32x16/16x32, ~3274) and +`decode_block_rect64` (64x32/32x64, ~3850) each read the COARSE per-16x16 `above_mode[c]` / +`left_mode[r]` slots -- which no sub-16x16 block ever writes (`record_rect` loops +`w / SUB` = 0 cells for a 16x8). So a 32x16 strip whose left neighbour was a 16x8 rect leaf +read an older, larger block's mode, indexed a DIFFERENT `kf_y_mode` CDF row, decoded the same +mode VALUE off a different distribution, and desynced from that block's first coefficient on. +This is the memory class "context read from one cell" / "CDF row held constant", one level up +from r4's own instance. + +Fix (`decode.rs`): one `Neighbours::modes_above_left(r, c)` helper (mi-exact if the map holds +exactly this block's above/left mi, else the coarse slot) used by all three readers, for the +mode CDF row AND for `smooth_neighbor` (libaom's `get_filt_type` reads the same `above_mi`/ +`left_mi`). New `MODE_MI_OVERRIDE_HITS` counter (`decode.rs` ~760) counts the reads where the +two disagree. + +Also applied here, per the coordinator's mid-round correction (defect found by lane-sub8's +verifier in the code r4 cherry-picked from that lane): `mode_above_mi`/`mode_left_mi` guarded +availability with `mi_r > 0`/`mi_c > 0` instead of the tile-relative +`mi_r > tile_row0_mi`/`mi_c > tile_col0_mi`, and the maps were never reset -- `start_tile` now +clears `sub8_mode_col` over the tile's mi columns and `start_row` clears `sub8_mode_row`, +exactly like every other neighbour array beside them. (This lane's sweep is single-tile, so +that half is code-verified here, not gate-proven; lane-sub8 r6 owns the multi-tile gate.) + +## Evidence + +EVIDENCE: /tmp/.../scratchpad/rx/{rgb240.obu,pre_a.f0,pre_o.f0,o.step.txt,a.step.txt} | +ffmpeg lavfi `rgbtestsrc=size=64x64` -> aomenc `--cq-level=24 --reduced-tx-type-set=0 +--enable-rect-partitions=1 --min-partition-size=8 --max-partition-size=32 +--enable-filter-intra=0 --enable-cdef=0 --enable-restoration=0` (sha256 +22113636b7ab950b5d1a175a60b9e01251dcead819f99a9ef14dcd1378ccfad6, reproducible across two +encodes); `EC_TRACE_MODE_STEP` ladder ours vs instrumented aomdec, `EC_AV1_PREFILT_DUMP` both | +first divergent element = `mi_row=8 mi_col=8 name=mode val=2` at range 53452 (oracle) vs 33402 +(ours) -- same value, different CDF row, entry ranges equal (56121) so it is the ROW not the +symbol; that block's left neighbour is the 16x8 leaf at mi(8,4) mode=12. Pre-filter luma diff +1006 -> 0, total 1650 -> 12 bytes (all chroma). + +EVIDENCE: gate `a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact` +(`stream.rs` ~5460) | `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -- a_real_aomenc_stream_whose_square_block_reads_a_sub16 --nocapture` | +`pixel-exact, mode_mi_override_hits=2`, two pinned arms (`rgbtestsrc` 64x64 cq32 with +`--reduced-tx-type-set=1 --enable-filter-intra=0` and with `=0 --enable-filter-intra=1`), each +encoded twice and byte-compared before decode; the counter is read only on an attempt that +decoded AND is pixel-compared. + +EVIDENCE: /tmp/.../scratchpad/rx/{rgb240,rgb241,rgb321,mandfi161}.{obu,ours.yuv,ref.yuv} | +`examples/decode_probe ` vs `ffmpeg -i -f rawvideo`, per-plane byte diff | +per cell, before -> after this round: rgbtestsrc cq24 rtx=0 1650 -> 12 (luma 1118 -> 0); +rgbtestsrc cq24 rtx=1 3461 -> 14 (luma 2304 -> 0); rgbtestsrc cq32 rtx=1 1622 -> 0; +rgbtestsrc cq32 `--enable-filter-intra=1` rtx=0 -> 0; mandelbrot start_x=-0.6 cq16 +`--enable-filter-intra=1` rtx=1 126 -> 123 (luma 0, U 40, V 83). + +## Second defect this round (coordinator-reported, verified and fixed) + +`Reach::top_right_rect`/`bottom_left_rect` (`encode.rs` ~1162/~1196) indexed the rect +`has_tr_*`/`has_bl_*` tables with `(blk_row << (4 - bw_log2)) + blk_col`. libaom's +`has_top_right` uses `MAX_MIB_SIZE_LOG2` = **5** (`enums.h`; its tables are laid out for a +128x128 = 32-mi superblock), so r4 halved the row stride and every table row but the first +read the wrong byte -- 16x8 wrong at 80 mi positions in a 64-wide SB, 8x16 at 16, 32x16 at 64 +(a regression against `main`). Fixed via a named `Reach::rect_table_index` used by both. + +EVIDENCE: `cargo test -p ec-av1 --lib -- rect_reach_tables_are_indexed --nocapture` | +new `encode::tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride` walks every block +position of a 32-mi superblock for all six rect sizes and asserts the index set is a BIJECTION +onto the table's bits (plus `len * 8 == rows * cols`) | passes with the shift at 5; with r4's +`4 - bw_log2` the walk covers a quarter of the 16x8 table and the assert fails. No pixel change +in the five swept cells (they are all luma-exact either way), so this fix is table-verified, +not gate-differentiated. + +## Open residue + +- fix-now(next round, needs its own lane -- it is a CHROMA PREDICTION defect, not a rect one): + every remaining mismatch is chroma-only with luma byte-exact and the entropy ladder + IDENTICAL end to end (`diff` of the two `EC_ISTEP` traces on mandfi161 is empty apart from + two `use_filter_intra` lines the oracle prints and we do not -- ranges match, so the symbol + is consumed). Localised per 4x4 chroma block on mandelbrot cq16 fi=1: the three FULLY wrong + blocks (16/16 samples) are mi(10,4) V, mi(10,6) V, mi(12,12) U -- all three `uv_mode=13` + (`UV_CFL_PRED`), one plane wrong while the other is exact, i.e. the per-plane CFL alpha, not + the shared luma AC. The partially wrong blocks (1-13 samples, max delta 9) are all + directional chroma with a NON-ZERO `angle_uv` (mi(8,12) uv=4 delta -3, mi(10,2) uv=4 delta 3, + mi(12,8) uv=6 delta -3, ...), i.e. the chroma intra-edge filter/upsample path. Ruled out this + round by experiment: `smooth_neighbor_uv` is NOT the cause -- forcing it true and false + globally leaves the diff at 123 bytes either way (rgb240: 12/13/12). +- deferred(a lane for AB partitions below 16x16): unchanged from r4, `a HORZ_A/HORZ_B/VERT_A + partition below 16x16` still dominates the refusals in the sweep. +- accepted: `read_coeffs_rect` still refuses `V_DCT`/`H_DCT` on a rect transform + (`--reduced-tx-type-set=0` cells can hit it: rgbtestsrc cq32 rtx=0 fi=0 refuses by name). +- accepted: `filter intra on a HORZ/VERT strip` still refuses (4 of the 6 filter-intra cells + swept above stop there, non-silently). +- deferred(the rect `predict_filter_intra` predictor): the coordinator asked for a gate arm + asserting a counter of `use_filter_intra` reads on 16x8/8x16 leaves. It cannot exist yet -- + every recipe where aomenc puts filter intra ON a rect leaf hits exactly that refusal + (`filter intra on a HORZ/VERT strip`, 4 of 6 cells), and the two `--enable-filter-intra=1` + recipes that DO decode (`rgbtestsrc` cq32 rtx=0, now a pinned arm of the new gate) contain no + such leaf, so the counter would assert 0. A gate for those CDF rows unblocks when + `predict_filter_intra` grows a rectangular arm; the r4 refusal is what holds the line + meanwhile. + +## Refusals + +None lifted or added this round; `refusal_inventory` and `gate_coverage` unchanged and green. + +## Totals + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` (CARGO_TARGET_DIR=~/.cache/cargo-target-rectx, +final commit): **272 passed, 0 failed, 24 ignored** (825.42s) -- r4's 270 plus the two tests +added this round (`a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact`, +`rect_reach_tables_are_indexed_with_a_32_mi_row_stride`); nothing regressed. 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. diff --git a/lanes/sub8merge-r1.report.md b/lanes/sub8merge-r1.report.md new file mode 100644 index 00000000..ca148369 --- /dev/null +++ b/lanes/sub8merge-r1.report.md @@ -0,0 +1,67 @@ +# lane-sub8merge report (round 1) -- merge cross-product defect closed + +## Root cause (one line, one variable) + +The merge resolution of `Reach::top_right` / `Reach::bottom_left` +(`crates/ec-av1/src/encode.rs:1237,1272`) introduced + +```rust +let row = Self::table(side); // 0..=3, the TABLE row +``` + +which SHADOWS the block's position row bound eight lines above +(`let (row, col, per_side) = Self::position(side, x, y);`) and is then used by +the bit index `(row * Self::table_stride(side) + col)`. Main computed the table +index inline (`HAS_TOP_RIGHT[Self::table(side)]`) and kept `row` = position. +So on the merged tree EVERY block size read `has_top_right`/`has_bottom_left` +at the wrong bit: the reach (above-right / below-left reference availability) +was wrong for ordinary square blocks, not just sub-8x8 -- which is exactly why +each side was green alone and the merged tree failed a gate whose stream +contains zero sub8 splits and zero split-tx strips (seed 55 printed +"split-tx strips this stream: 0"). + +Fix: rename to `table_row` in both functions, restoring `row` as the position +row, plus a NB comment naming the shadowing hazard. +`crates/ec-av1/src/encode.rs:1234-1241,1269-1276`. + +Class: `adjacent same-typed args` / shadowing sibling -- a merge that renames a +value into an identifier already live in scope. Sweep: `grep -n "let row = \|let col = " crates/ec-av1/src/encode.rs` +returns nothing else; the only two `Self::position*` consumers are these two. + +Also removed the previous agent's leftover ablation hook +`EC_ABLATE_SUB8` in `decode_leaf_split4` (`crates/ec-av1/src/decode.rs:6978`). + +The charter's untested suspects (the six `smooth_neighbor_uv` sites, the +per-tile mi-map resets, `Neighbours::new`, `record_split_luma_rect`) are all +INNOCENT: they are unchanged by this round and both gates are green. + +## Gates + +EVIDENCE: $HOME/.cache/sub8merge-suite.log | `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib split_transform_horz_vert` on the merged tree before and after the rename | before: FAILED, seed 55 first luma mismatch (191,76) ours=127 ffmpeg=128, 3080 samples, bbox x94..191 y76..127; after: ok, 1 passed (8.55 s) +EVIDENCE: same log | `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib sub8` after the rename | ok, 1 passed (5.10 s, 3 tile arms x 4 firing+pixel-exact runs) +EVIDENCE: $HOME/.cache/sub8merge-suite.log | full `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib` (1228 s) | 298 passed, 1 failed, 27 ignored -- every sibling gate named in the charter (sub8, tiny_frame_size_sweep, tx_select, an_8x8_leaf_split, split_transform_horz_vert, filter_intra_on_a_horz, superblock_level_*, refusal_inventory, gate_coverage) green + +## The one failure is INHERITED FROM MAIN, not this lane + +`decode::tests::nz_map_ctx_offset_tables_match_the_rect_rule` fails: +`32x64 nz_map offset at display (row 0, col 2): left 6, right 11` +(decode.rs:16837). `cdf.rs` is byte-identical between the merge base 61c6a5b, +this branch, and current main df5d630, and the test body is identical on +df5d630 (`git show df5d630:crates/ec-av1/src/decode.rs`, lines 16299-16321) -- +so main itself is red on this test. `NZ_MAP_CTX_OFFSET_32X64` row 2 is +`[6, 6, 21, 21, 21]`, i.e. under the column-major read the table gives 6 where +the rule (w