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 85f2ccd4..d23f9d7a 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1384,6 +1384,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 @@ -2029,6 +2056,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 @@ -2415,12 +2461,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, @@ -2433,6 +2481,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(); @@ -2444,17 +2493,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(); @@ -2509,6 +2576,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(); @@ -2524,6 +2595,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 @@ -3507,6 +3582,25 @@ impl Neighbours { 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), @@ -3716,6 +3810,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, } @@ -4492,12 +4593,13 @@ 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 (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) = read_intra_mode_rect( dec, cdfs, - neighbours.above_mode[c], - neighbours.left_mode[r], + nb_above_mode, + nb_left_mode, true, bw, bh, @@ -4507,8 +4609,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)); } @@ -4849,9 +4950,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, @@ -4869,8 +4971,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]; @@ -4882,6 +4991,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 { @@ -4902,6 +5021,9 @@ fn decode_leaf_rect( leaf_mi.0, leaf_mi.1, )?; + 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)", @@ -4920,73 +5042,105 @@ 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], - ], - ); - // lane-sub8 r6: the caller patches only the coarse `above_mode`/ - // `left_mode` slot (one value for the whole 16x16), so record this - // strip's own span mi-exactly like every square leaf does. - neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode); - neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode); + 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); + // 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) } @@ -5026,12 +5180,13 @@ 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 (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) = 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 @@ -5048,8 +5203,7 @@ fn decode_block_rect64( 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)); } @@ -6260,12 +6414,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, @@ -6295,8 +6450,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)); } @@ -6686,6 +6840,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, @@ -9305,6 +9470,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, @@ -9322,6 +9488,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; @@ -9351,6 +9518,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, @@ -9368,6 +9536,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; @@ -9401,7 +9570,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // 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]; + 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); @@ -17298,6 +17467,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 5d982dca..96889135 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1131,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`. @@ -1160,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 @@ -3169,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/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 74e544e0..56ee1562 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -28,13 +28,11 @@ 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 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)", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 5df8c004..b6fdeb1d 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -7924,6 +7924,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 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.