diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs index 92c83905..ce9a3d90 100644 --- a/crates/ec-av1/examples/decode_probe.rs +++ b/crates/ec-av1/examples/decode_probe.rs @@ -66,6 +66,18 @@ fn main() { } } println!("TILING: {frames_seen} frame headers parsed"); + // lane-sb128 r4: the superblock size decides the whole partition tree, so + // report it next to the tiling -- it is the first thing a film blocker + // triage needs. + if let Some(seq) = parser.sequence_header() { + println!( + "SEQ: use_128x128_superblock={} bit_depth={} max_frame={}x{}", + seq.use_128x128_superblock, + seq.color_config.bit_depth, + seq.max_frame_width, + seq.max_frame_height + ); + } for (cols, rows, uniform, ctx_id) in &seen { println!( "TILING: cols={cols} rows={rows} uniform_spacing={uniform} context_update_tile_id={ctx_id}" diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index 47f8df73..e3ecb30e 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -8,6 +8,17 @@ /// `Default_Partition_W64_Cdf` (spec 9.4): the ten partition types of a /// 64x64 block, indexed by the context the blocks above and left give. +/// `default_partition_cdf`'s last four contexts (entropymode.c:154, the +/// `AOM_CDF8` rows): the `BLOCK_128X128` root's alphabet is +/// `EXT_PARTITION_TYPES - 2 = 8` -- `PARTITION_HORZ_4`/`_VERT_4` do not exist +/// at 128 (spec `partition_cdf_length`). +pub const PARTITION_W128: [[u16; 9]; 4] = [ + [27899, 28219, 28529, 32484, 32539, 32619, 32639, 32768, 0], + [6607, 6990, 8268, 32060, 32219, 32338, 32371, 32768, 0], + [5429, 6676, 7122, 32027, 32227, 32531, 32582, 32768, 0], + [711, 966, 1172, 32448, 32538, 32617, 32664, 32768, 0], +]; + pub const PARTITION_W64: [[u16; 11]; 4] = [ [ 20137, 21547, 23078, 29566, 29837, 30261, 30524, 30892, 31724, 32768, 0, @@ -477,7 +488,7 @@ pub const CFL_SIGN: [u16; 9] = [1418, 2123, 13340, 18405, 26972, 28343, 32294, 3 /// `av1_filter_intra_allowed_bsize`'s "both sides <= 32" bound, so libaom /// reads `use_filter_intra` there too and the missing rows dropped the /// symbol on every DC_PRED 1:4 strip. -pub const FILTER_INTRA: [[u16; 3]; 12] = [ +pub const FILTER_INTRA: [[u16; 3]; 14] = [ [4621, 32768, 0], [7866, 32768, 0], [12408, 32768, 0], @@ -490,6 +501,12 @@ pub const FILTER_INTRA: [[u16; 3]; 12] = [ [5893, 32768, 0], [18101, 32768, 0], [20229, 32768, 0], + // lane-r14: the 16x16-level 1:4 pair (`default_filter_intra_cdfs` index + // 17/16 -- BLOCK_16X4/BLOCK_4X16, generated by + // `scripts/extract-filter-intra-cdfs.py`), classes 12/13. Both sides <= 32, + // so libaom writes `use_filter_intra` on every DC_PRED strip of this shape. + [10368, 32768, 0], + [12770, 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 90b8878c..7eef9418 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -214,6 +214,22 @@ pub(crate) enum TxbSet { /// `tx_size_sqr == TX_4X4`, intra returns `EXT_TX_SET_DTT4_IDTX_1DDCT`, /// the same seven-symbol set (and same `TX_4X4` row) `Luma4Set1` reads. LumaRect4x8Set1, + /// The luma 16x4/4x16 transform of a 16x16-level `PARTITION_HORZ_4`/ + /// `PARTITION_VERT_4` strip (lane-r14). `get_txsize_entropy_ctx` + /// ((`txsize_sqr_map` + `txsize_sqr_up_map` + 1) >> 1) resolves `TX_16X4` + /// to `TX_8X8`, and the transform has 64 coded positions, so EVERY table + /// here is [`Luma8`](TxbSet::Luma8)'s (`eob_pt_64` included) except + /// `tx_type`: `read_tx_type` indexes `intra_ext_tx_cdf[eset] + /// [txsize_sqr_map[TX_16X4]]` = the `TX_4X4` row, and + /// `av1_get_ext_tx_set_type` at `tx_size_sqr_up == TX_16X16` with + /// `tx_size_sqr == TX_4X4` returns `EXT_TX_SET_DTT4_IDTX` under + /// `reduced_tx_set` -- the same pair [`LumaRect4x8`](TxbSet::LumaRect4x8) + /// reads, which differs from this variant only in its 32-position `eob_pt`. + LumaRect16x4, + /// [`LumaRect16x4`](TxbSet::LumaRect16x4)'s `reduced_tx_set: false` + /// counterpart: `EXT_TX_SET_DTT4_IDTX_1DDCT`, the seven-symbol `TX_4X4` + /// row [`LumaRect4x8Set1`](TxbSet::LumaRect4x8Set1) reads. + LumaRect16x4Set1, } /// The tables one transform block is coded with, borrowed from the state for @@ -251,6 +267,8 @@ pub(crate) struct TxbTables<'a> { #[derive(Clone)] pub(crate) struct Cdfs { /// The partition symbol of a 64x64 superblock. + /// `partition_cdf`'s `BLOCK_128X128` rows (8 symbols). + pub partition_w128: [[u16; 9]; 4], pub partition_w64: [[u16; 11]; 4], /// The partition symbol of a 32x32 block. pub partition_w32: [[u16; 11]; 4], @@ -569,7 +587,7 @@ pub(crate) struct Cdfs { /// `[1]`=8x8, `[2]`=16x16, `[3]`=32x32, `[4]`=32x16, `[5]`=16x32, /// `[6]`=16x8, `[7]`=8x16, `[8]`=4x8, `[9]`=8x4, `[10]`=32x8, `[11]`=8x32) -- /// see [`cdf::FILTER_INTRA`]. - pub filter_intra: [[u16; 3]; 12], + pub filter_intra: [[u16; 3]; 14], /// 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` @@ -721,6 +739,7 @@ impl Cdfs { /// into a reference slot for cross-frame forwarding; never on a table /// still being read within the same tile. pub(crate) fn reset_counts(&mut self) { + reset2(&mut self.partition_w128); reset2(&mut self.partition_w64); reset2(&mut self.partition_w32); reset2(&mut self.txfm_partition); @@ -886,6 +905,7 @@ impl Cdfs { /// quantizer, so they are the same for every `q_ctx`. pub fn new(q_ctx: usize) -> Cdfs { Cdfs { + partition_w128: cdf::PARTITION_W128, partition_w64: cdf::PARTITION_W64, partition_w32: cdf::PARTITION_W32, skip: cdf::SKIP, @@ -1807,6 +1827,30 @@ impl Cdfs { tx_type: Some(self.intra_tx_type_8_set1[mode].as_mut_slice()), eob_pt_class1: Some(&mut self.eob_pt_128_luma_class1), }, + TxbSet::LumaRect16x4 => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_luma_8, + eob_pt: &mut self.eob_pt_64_luma, + eob_extra: &mut self.eob_extra_luma_8, + base: &mut self.base_luma_8, + base_eob: &mut self.base_eob_luma_8, + br: &mut self.br_luma_8, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.intra_tx_type_4[mode].as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_64_luma_class1), + }, + TxbSet::LumaRect16x4Set1 => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_luma_8, + eob_pt: &mut self.eob_pt_64_luma, + eob_extra: &mut self.eob_extra_luma_8, + base: &mut self.base_luma_8, + base_eob: &mut self.base_eob_luma_8, + br: &mut self.br_luma_8, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.intra_tx_type_4_set1[mode].as_mut_slice()), + eob_pt_class1: Some(&mut self.eob_pt_64_luma_class1), + }, TxbSet::LumaRect16x8Inter => TxbTables { side: 16, txb_skip: &mut self.txb_skip_luma_16, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 9983e8e0..897669cf 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -56,6 +56,71 @@ const PARTITION_VERT_4: usize = 9; const SB_MI: u32 = 16; const BLOCK_MI: u32 = 8; +// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1). +// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the +// superblock's own top-left mi?", the loop-restoration read's unit span, the +// partition tree's own root level) keys off it; `SB_MI` stays the 64x64 +// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF +// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64 +// inside a 128 superblock). +thread_local! { + static SB128: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`). +pub(crate) fn set_sb128(v: bool) { + SB128.with(|c| c.set(v)); + crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }); +} + +fn sb128() -> bool { + SB128.with(|c| c.get()) +} + +/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128). +pub(crate) fn sb_mi_cur() -> u32 { + if sb128() { SB_MI * 2 } else { SB_MI } +} + +/// How many real 128-level partition symbols this decoder has read, and how +/// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the +/// gate's proof a `--sb-size=128` stream exercised the 128 partition root. +thread_local! { + static PART128_SYMBOLS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static PART128_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static PART128_GATHERED_SYMBOLS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the +/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec +/// 5.11.4), which this decoder used to read and throw away. +pub(crate) fn part128_gathered_symbols() -> usize { + PART128_GATHERED_SYMBOLS.with(|c| c.get()) +} + +/// Current value of [`PART128_SYMBOLS`]. +pub(crate) fn part128_symbols() -> usize { + PART128_SYMBOLS.with(|c| c.get()) +} + +/// Current value of [`PART128_SPLIT_HITS`]. +pub(crate) fn part128_split_hits() -> usize { + PART128_SPLIT_HITS.with(|c| c.get()) +} + +/// [`gather`] over an alphabet of any length -- the 128-level partition CDF +/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec +/// `partition_cdf_length`), so its forced-split gather sums 5 elements where +/// the 64/32 levels sum 6. +fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] { + let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum(); + [32768 - split, 32768, 0] +} + +/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root. +const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7]; +const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6]; + // How many `use_filter_intra` symbols this decoder has read as `1`, across // every call on the current thread -- the cheap counter [`filter_intra_hits`] gate // tests read (before/after, not the absolute value) to prove a stream @@ -241,10 +306,14 @@ fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_ if !DELTA_Q_PRESENT.with(|c| c.get()) { return; } - if mi_r % SB_MI as usize != 0 || mi_c % SB_MI as usize != 0 { + let sb_mi = sb_mi_cur() as usize; + if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 { return; } - if is_whole_sb && skip { + // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, which + // it computes against the 64x64 root; under a 128 superblock no leaf this + // decoder codes can be the whole superblock (the root is always SPLIT). + if is_whole_sb && !sb128() && skip { return; } let mut abs = dec.symbol(&mut cdfs.delta_q) as i32; @@ -296,10 +365,14 @@ fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi if !DELTA_LF_PRESENT.with(|c| c.get()) { return; } - if mi_r % SB_MI as usize != 0 || mi_c % SB_MI as usize != 0 { + let sb_mi = sb_mi_cur() as usize; + if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 { return; } - if is_whole_sb && skip { + // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, which + // it computes against the 64x64 root; under a 128 superblock no leaf this + // decoder codes can be the whole superblock (the root is always SPLIT). + if is_whole_sb && !sb128() && skip { return; } let multi = DELTA_LF_MULTI.with(|c| c.get()); @@ -916,6 +989,10 @@ thread_local! { // their rect max transform into square sub-transforms. static RECT_INTER_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; static RECT_INTER_TXSPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + // lane-r14 r2: luma transform units of an inter strip with a 64-px axis + // (64x32/32x64/64x16/16x64), whose coefficients are coded as the + // truncated low-32 corner. + static RECT64_INTER_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter // frame -- 16x8 and 8x16 inter leaves. static INTER_LEAF16_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; @@ -963,6 +1040,11 @@ pub(crate) fn rect_inter_txsplit_hits() -> usize { RECT_INTER_TXSPLIT_HITS.with(|c| c.get()) } +/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2). +pub(crate) fn rect64_inter_tu_hits() -> usize { + RECT64_INTER_TU_HITS.with(|c| c.get()) +} + /// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/ /// [`ENABLE_FILTER_INTRA_INTER`]. pub(crate) fn set_inter_tx_mode( @@ -1374,6 +1456,24 @@ pub(crate) fn palette_split_tx_hits() -> usize { PALETTE_SPLIT_TX_HITS.with(|c| c.get()) } +// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform +// and which are therefore predicted one transform unit at a time (a skipped +// block codes no coefficients, so nothing else in the stream witnesses this +// path -- only the pixels do). +thread_local! { + static SKIP_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units). +pub fn skip_split_tx_hits() -> usize { + SKIP_SPLIT_TX_HITS.with(|c| c.get()) +} + +/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt. +pub fn reset_skip_split_tx_hits() { + SKIP_SPLIT_TX_HITS.with(|c| c.set(0)); +} + // lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth` // symbol split their luma transform, bucketed by block side (8, 16, 32, 64) -- // the gate's proof that the lifted path actually ran, per size. @@ -1848,6 +1948,22 @@ pub(crate) fn rect_leaf_coeff_hits() -> usize { RECT_LEAF_COEFF_HITS.with(|c| c.get()) } +// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the +// INTER block path ([`decode_intra_rect_in_inter`]), per shape class -- +// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16. +// Every one of them was the named refusal "an intra-coded HORZ/VERT strip +// needs rectangular intra prediction" before this round. +thread_local! { + static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> = + const { std::cell::Cell::new([0; 3]) }; +} + +/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class +/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16). +pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize { + INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class]) +} + // 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 @@ -1939,6 +2055,33 @@ thread_local! { } /// Current value of [`SB_RECT_HITS`]. +// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a +// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as +// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the +// non-SPLIT edge arm actually decoded (before this round the bit was read and +// thrown away, so that arm was unreachable). +thread_local! { + static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; +} + +/// Current value of [`EDGE_PART_HITS`]. +pub(crate) fn edge_part_hits() -> [usize; 4] { + EDGE_PART_HITS.with(|c| c.get()) +} + +/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time). +pub(crate) fn reset_edge_part_hits() { + EDGE_PART_HITS.with(|c| c.set([0; 4])); +} + +fn bump_edge_part(slot: usize) { + EDGE_PART_HITS.with(|c| { + let mut h = c.get(); + h[slot] += 1; + c.set(h); + }); +} + pub(crate) fn sb_rect_hits() -> usize { SB_RECT_HITS.with(|c| c.get()) } @@ -2079,6 +2222,30 @@ pub(crate) fn rect4_coeff_hits() -> usize { RECT4_COEFF_HITS.with(|c| c.get()) } +// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or +// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that +// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual. +thread_local! { + static RECT4_16_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT4_16_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT4_16_CHROMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT4_16_COEFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT4_16_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16 +/// strips, chroma-reference strips, strips with a coded residual, strips +/// whose luma transform is split)`. +pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) { + ( + RECT4_16_HORZ_HITS.with(|c| c.get()), + RECT4_16_VERT_HITS.with(|c| c.get()), + RECT4_16_CHROMA_HITS.with(|c| c.get()), + RECT4_16_COEFF_HITS.with(|c| c.get()), + RECT4_16_SPLIT_HITS.with(|c| c.get()), + ) +} + /// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded). pub(crate) fn rect4_32_horz_hits() -> usize { RECT4_32_HORZ_HITS.with(|c| c.get()) @@ -2452,6 +2619,18 @@ fn note_chroma_class1(plane_idx: usize, tx_type: TxType) { const SUB_MI: u32 = 4; const MI: usize = 4; const SB: usize = 64; +/// The `above_side`/`left_side` value a cell with no decoded neighbour holds +/// (tile start, superblock-row start). +/// +/// [`Neighbours::partition_ctx_mi`] reads it as libaom's +/// `av1_get_partition_plane_context` reads its own zero-initialised +/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at +/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB` +/// (64), which reads identically at every level up to 64x64 but sets the bit +/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition +/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec +/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`). +const NO_NEIGHBOUR_SIDE: usize = 128; const BLOCK: usize = 32; const SUB: usize = 16; const TX32: usize = 32; @@ -3316,7 +3495,7 @@ fn read_coeffs_rect( let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; if rect_trace { eprintln!( - "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} all_zero={} rng={}", + "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}", all_zero as i32, dec.debug_state().0 ); @@ -3679,10 +3858,10 @@ impl Neighbours { left_mode: vec![DC_PRED; rows], above_uv_mode: vec![DC_PRED; cols], left_uv_mode: vec![DC_PRED; rows], - above_side: vec![SB; cols], - left_side: vec![SB; rows], - above_side_mi: vec![SB; cols * (SUB / MI)], - left_side_mi: vec![SB; rows * (SUB / MI)], + above_side: vec![NO_NEIGHBOUR_SIDE; cols], + left_side: vec![NO_NEIGHBOUR_SIDE; rows], + above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)], + left_side_mi: vec![NO_NEIGHBOUR_SIDE; 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)], @@ -3747,7 +3926,7 @@ impl Neighbours { let end = col1_mi.min(self.above.len()); for i in col0_mi.min(end)..end { self.above[i] = Default::default(); - self.above_side_mi[i] = SB; + self.above_side_mi[i] = NO_NEIGHBOUR_SIDE; } let (sc0, sc1) = ( col0_mi / (SUB / MI), @@ -3755,7 +3934,7 @@ impl Neighbours { ); for i in sc0.min(sc1)..sc1 { self.above_mode[i] = DC_PRED; - self.above_side[i] = SB; + self.above_side[i] = NO_NEIGHBOUR_SIDE; } // lane-inter8 r2: the inter bands are mi-granular, so they reset over // the tile's own mi column span directly. @@ -4094,8 +4273,8 @@ impl Neighbours { self.left.iter_mut().for_each(|l| *l = Default::default()); self.left_mode.iter_mut().for_each(|m| *m = DC_PRED); self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED); - self.left_side.iter_mut().for_each(|s| *s = SB); - self.left_side_mi.iter_mut().for_each(|s| *s = SB); + self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE); + self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE); self.left_skip.iter_mut().for_each(|s| *s = false); self.left_skip_mode.iter_mut().for_each(|s| *s = false); self.left_inter.iter_mut().for_each(|i| *i = false); @@ -4907,6 +5086,10 @@ fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option { // tile (class symbol-consumption-gap). (32, 8) => Some(10), (8, 32) => Some(11), + // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16 + // strips), rows 17/16 of `default_filter_intra_cdfs`. + (16, 4) => Some(12), + (4, 16) => Some(13), _ if bw == bh => filter_intra_size_class(bw), _ => None, } @@ -4932,7 +5115,13 @@ fn palette_bsize_ctx(side: usize) -> Option { /// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own /// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`). fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option { - if !(8..=64).contains(&bw) || !(8..=64).contains(&bh) { + // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the + // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and + // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx` + // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as + // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped + // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame. + if bw > 64 || bh > 64 || bw * bh < 64 { return None; } Some(((bw * bh) as u32).trailing_zeros() as usize - 6) @@ -5254,6 +5443,12 @@ fn read_intra_mode_rect( above_mode: usize, left_mode: usize, cfl: bool, + // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall + // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads + // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's + // chroma is coded once, on the closing strip). Every other caller is a + // block big enough to own its chroma and passes `true`. + has_chroma: bool, bw: usize, bh: usize, enable_filter_intra: bool, @@ -5317,21 +5512,23 @@ fn read_intra_mode_rect( 0 }; istep!("angle_y", angle_delta_y); - let uv_mode = if cfl { + let uv_mode = if !has_chroma { + DC_PRED + } else if cfl { dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; istep!("uv_mode", uv_mode as i32); - let alpha = if cfl && uv_mode == UV_CFL_PRED { + let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { None }; - if (9..=12).contains(&uv_mode) { + if has_chroma && (9..=12).contains(&uv_mode) { SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1)); } - let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { + let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) { DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1)); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { @@ -5371,7 +5568,11 @@ fn read_intra_mode_rect( palette_y_pending = Some((n, colors)); } let palette_uv_mode_ctx = usize::from(use_palette_y); - if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 { + // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard. + if has_chroma + && uv_mode == DC_PRED + && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 + { let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache); palette_uv_pending = Some((n, u_colors, v_colors)); @@ -5661,12 +5862,13 @@ fn decode_rect_split( let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI)); let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h); let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h); - // lane-golomb r3: a frame-edge HORZ/VERT strip is the one block - // shape that hangs off the bottom (or right) of the frame, and - // libaom's `av1_foreach_transformed_block_in_plane` clips its - // loop bounds to `max_blocks_high/wide` (`mb_to_bottom_edge` / - // `mb_to_right_edge`, i.e. `mi_rows * 4` / `mi_cols * 4`): a unit - // whose TOP-LEFT sample is outside the frame is never coded. + // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged): + // libaom clips `av1_foreach_transformed_block_in_plane` to + // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`, + // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose + // TOP-LEFT sample falls outside the frame is never coded. We read + // coefficients for those phantom units and desynced the stream at + // the very next symbol. if tu_px >= y.true_width || tu_py >= y.true_height { continue; } @@ -5719,7 +5921,19 @@ fn decode_rect_split( // own (always DC_PRED) mode -- [`read_plane`] applies that // for the square arm, so this one must too. let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0]; - let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI); + // libaom `get_txb_ctx`: a LUMA transform that covers its whole + // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the + // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the + // neighbour-magnitude table is for a unit SMALLER than its + // block. [`decode_block_rect`]'s own unsplit read passes a + // literal 0 for the same reason; this arm applied the table + // unconditionally and desynced every depth-0 rect strip that + // reached it (lane-intrarect r2: ctx 5 where aomdec read 0). + let tu_skip_ctx = if tx_w == bw && tx_h == bh { + 0 + } else { + neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI) + }; let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra)); let (tu_grid, tu_tx_type) = read_coeffs_rect( dec, @@ -5897,6 +6111,211 @@ fn decode_rect_split( Ok(()) } +/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect +/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name +/// because it predicts squares only. Every pixel here goes through the rect +/// machinery the key-frame paths already prove: [`decode_rect_split`], which +/// at `depth == 0` is the unsplit strip as a single transform unit and +/// beyond it the per-unit walk of [`depth_to_tx_wh`]. +/// +/// What is genuinely different from [`decode_block_rect`] is the mode +/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and +/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never +/// the key frame's `kf_y_mode` above/left pair. This mirrors the square +/// intra-in-inter arm's own reads at the rect footprint, including its +/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe +/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the +/// square and this arm) and a nonzero luma angle delta refused by name. +/// +/// The strip's own neighbour records (luma per transform unit, chroma, skip +/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the +/// inter-side bands and the mi map. +#[allow(clippy::too_many_arguments)] +fn decode_intra_rect_in_inter( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + at: (usize, usize), + bw: usize, + bh: usize, + skip: bool, + allow_screen_content_tools: bool, + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + base_q_idx: u8, +) -> Result<()> { + // `at` is in MI units (the inter path's own unit since lane-inter4); + // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands + // below are still keyed by. + let (mi_r, mi_c) = at; + let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI)); + // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat` + // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 / + // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx + // finding -- the category is NOT the same for every strip size). + // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so + // it is refused by name rather than read from the wrong CDF row. + let (size_group, tx_cat) = match (bw.min(bh), bw.max(bh)) { + (8, 16) => (1usize, 1usize), + (16, 32) => (2, 2), + (32, 64) => (3, 3), + _ => { + return Err(unsupported( + "an intra-coded 1:4 (or other non-2:1) rect strip on the inter block path", + )) + } + }; + // [`read_intra_mode_rect`]'s own refusal: palette/intrabc syntax is + // consumed for square blocks only, so a strip in a screen-content frame + // would skip symbols the encoder wrote. + if allow_screen_content_tools { + return Err(unsupported( + "a HORZ/VERT intra strip in a screen-content frame (palette syntax \ + is consumed for square blocks only)", + )); + } + let mode = dec.symbol(&mut cdfs.y_mode[size_group]); + if mode >= 13 { + return Err(unsupported( + "an intra mode this decoder does not code (round 2)", + )); + } + // lane-angleinter (merged on main for the square intra-in-inter arm): + // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the + // directional predictor; this arm refused a nonzero one before the merge. + let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { + read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]) + } else { + 0 + }; + if angle_delta_y != 0 { + INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.set(c.get() + 1)); + } + // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the + // superblock-level strip reads the no-CFL alphabet -- the same split + // [`read_intra_mode_rect`] makes for [`decode_block_rect64`]. + let cfl_allowed = bw.max(bh) <= 32; + let uv_mode = if cfl_allowed { + dec.symbol(&mut cdfs.uv_mode_cfl[mode]) + } else { + dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) + }; + if (9..=12).contains(&uv_mode) { + SMOOTH_UV_HITS.with(|h| h.set(h.get() + 1)); + } + let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED { + Some(read_cfl_alphas(dec, cdfs)) + } else { + None + }; + let uv_predict_mode = if uv_mode == UV_CFL_PRED { + DC_PRED + } else { + uv_mode + }; + let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { + DIRECTIONAL_UV_HITS.with(|h| h.set(h.get() + 1)); + read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) + } else { + 0 + }; + if angle_delta_uv != 0 { + UV_ANGLE_DELTA_HITS.with(|h| h.set(h.get() + 1)); + INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|h| h.set(h.get() + 1)); + } + // lane-fiinter (merged on main for the square intra-in-inter arm): + // `read_filter_intra_mode_info` is the tail of + // `read_intra_block_mode_info`, after the palette syntax (refused whole + // above for this shape), and `av1_filter_intra_allowed_bsize` admits the + // 2:1 strips with both sides <= 32 -- their own CDF rows + // ([`filter_intra_size_class_rect`]). + let mut filter_intra = None; + if mode == DC_PRED + && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get) + && let Some(class) = filter_intra_size_class_rect(bw, bh) + && dec.symbol(&mut cdfs.filter_intra[class]) != 0 + { + FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1)); + INTRA_IN_INTER_FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1)); + filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode)); + } + // The intra-edge filter type is the NEIGHBOUR's mode (libaom + // `get_filt_type`), luma's off the luma neighbours and chroma's off the + // chroma ones -- [`decode_block_rect`]'s own pair. + let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); + let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); + if smooth_neighbor { + SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1)); + } + let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c); + let depth = if TX_SELECT_INTER.with(std::cell::Cell::get) { + let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh); + match tx_cat { + 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]), + 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]), + _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]), + } + } else { + 0 + }; + if depth != 0 { + TX_DEPTH_HITS.with(|h| h.set(h.get() + 1)); + // merge b51719f+lane-intrarect (class merge-cross-product-defect): + // main's 10-bit `split_transform_intra_block` gate reaches this arm + // with a nonzero tx depth, and the split rect-TU walk mis-decodes it + // (2340 luma samples off at seed 51; refusing here restores that gate + // while the depth-0 strip the lane proved keeps decoding). The lane's + // own gate never exercised a split strip. + return Err(unsupported( + "a split (nonzero tx_depth) transform on an intra HORZ/VERT strip in an inter frame", + )); + } + let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); + let modes = RectStripModes { + skip, + mode, + angle_delta_y, + uv_predict_mode, + angle_delta_uv, + alpha, + filter_intra, + smooth_neighbor, + smooth_neighbor_uv, + // screen-content frames are refused whole above, so this strip can + // carry no palette. + palette_y: None, + palette_uv: None, + }; + decode_rect_split( + dec, + cdfs, + neighbours, + (mi_r, mi_c), + bw, + bh, + tx_w, + tx_h, + &modes, + y, + u, + v, + base_q_idx, + REDUCED_TX_SET_INTER.with(std::cell::Cell::get), + )?; + let class = match bw.max(bh) { + 64 => 0, + 32 => 1, + _ => 2, + }; + INTRA_RECT_IN_INTER_HITS.with(|h| { + let mut v = h.get(); + v[class] += 1; + h.set(v); + }); + Ok(()) +} + /// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip /// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's /// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/ @@ -5936,6 +6355,7 @@ fn decode_block_rect( nb_above_mode, nb_left_mode, true, + true, bw, bh, enable_filter_intra, @@ -6410,6 +6830,7 @@ fn decode_leaf_rect( above_mode, left_mode, true, + true, bw, bh, enable_filter_intra, @@ -6689,6 +7110,7 @@ fn decode_block_rect4( above_mode, left_mode, true, + true, bw, bh, enable_filter_intra, @@ -6990,6 +7412,434 @@ fn decode_block_rect4( Ok((mode, uv_predict_mode)) } +/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` / +/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level +/// down, and the first shape here whose luma block is a single mi row (or +/// column). +/// +/// What is new at this size is CHROMA. `is_chroma_reference` +/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an +/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/ +/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close +/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair -- +/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) && +/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma +/// transform at the PAIR's origin, with CfL averaging over the pair's luma. +/// +/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context +/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is +/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row); +/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is +/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE +/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and +/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this +/// shape's own CDF row. +/// +/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`) +/// refuses by name rather than guess-decode. +#[allow(clippy::too_many_arguments)] +fn decode_rect4_16( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + at16: (usize, usize), + horz: bool, + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + enable_filter_intra: bool, + allow_screen_content_tools: bool, + base_q_idx: u8, + tx_select: bool, + reduced_tx_set: bool, +) -> Result<()> { + let (r, c) = at16; + let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI)); + let (bw, bh) = if horz { (16, 4) } else { (4, 16) }; + let (mi_w, mi_h) = (bw / MI, bh / MI); + let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 }; + let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 }; + let mut prev: Option<((usize, usize), usize)> = None; + let mut last_mode = DC_PRED; + let mut last_uv_mode = DC_PRED; + for i in 0..4usize { + let lmi = if horz { + (mi_row0 + i, mi_col0) + } else { + (mi_row0, mi_col0 + i) + }; + let has_chroma = i % 2 == 1; + // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell + // aliases all four strips onto one entry, so the mi-exact map wins and + // the previous strip stands in on the split axis. + let mut above_mode = neighbours.above_mode[c]; + let mut left_mode = neighbours.left_mode[r]; + if let Some(((pr, pc), pmode)) = prev { + if pc == lmi.1 && lmi.0 == pr + mi_h { + above_mode = pmode; + } else if pr == lmi.0 && lmi.1 == pc + mi_w { + left_mode = pmode; + } + } + let (above_mode, left_mode) = + neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode)); + let ( + skip, + mode, + angle_delta_y, + uv_mode, + angle_delta_uv, + alpha, + filter_intra, + palette_y, + palette_uv, + ) = read_intra_mode_rect( + dec, + cdfs, + above_mode, + left_mode, + true, + has_chroma, + bw, + bh, + enable_filter_intra, + neighbours.skip_txfm_ctx(lmi.0, lmi.1), + allow_screen_content_tools, + None, + &[], + lmi.0, + lmi.1, + )?; + if palette_y.is_some() || palette_uv.is_some() { + return Err(unsupported( + "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)", + )); + } + let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); + if smooth_neighbor { + SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1)); + } + if filter_intra.is_some() { + FILTER_INTRA_RECT_HITS.with(|h| h.set(h.get() + 1)); + } + // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is + // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the + // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol + // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does. + let depth = if tx_select { + let ctx = tx_size_context_rect(neighbours, lmi, bw, bh); + dec.symbol(&mut cdfs.tx_size_cat1[ctx]) + } else { + 0 + }; + if depth != 0 { + TX_DEPTH_HITS.with(|h| h.set(h.get() + 1)); + RECT4_16_SPLIT_HITS.with(|h| h.set(h.get() + 1)); + } + let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth); + let (px, py) = (lmi.1 * MI, lmi.0 * MI); + let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height); + neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode); + if depth != 0 { + // [`decode_rect_split`]'s per-unit walk, inlined because the + // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to + // the strip (that function codes one chroma transform per block). + // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8 + // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each + // unit predicts off the units before it in raster order. + let rect_unit = tx_w != tx_h; + let zero_tu = vec![0i32; tx_w * tx_h]; + for tu_row in 0..bh / tx_h { + for tu_col in 0..bw / tx_w { + let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI)); + let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h); + let tu_reach = Reach::of_tu( + bw, + bh, + tu_col * tx_w, + tu_row * tx_h, + tx_w, + tx_h, + reach, + ); + if skip { + y.reconstruct_rect( + tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu, + None, filter_intra, smooth_neighbor, + ); + neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu); + } else if rect_unit { + // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with + // 32 coded positions and the `TX_4X4` `tx_type` row: + // exactly [`TxbSet::LumaRect4x8`]. + let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0]; + let tu_skip_ctx = + neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI); + let set = if reduced_tx_set { + TxbSet::LumaRect4x8 + } else { + TxbSet::LumaRect4x8Set1 + }; + let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 }; + let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra)); + let (tu_grid, tu_tx_type) = read_coeffs_rect( + dec, + &mut coding, + tu_scan, + tx_w, + tx_h, + tu_skip_ctx, + dc_sign_ctx(tu_around.2), + TxType::DctDct, + )?; + let residual = dequant_and_inverse_typed_wh( + &tu_grid, + tx_w, + tx_h, + crate::decode::bit_depth(), + block_q_idx(), + plane_q_delta(0).0, + plane_q_delta(0).1, + tu_tx_type, + ); + y.reconstruct_rect( + tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual, + None, filter_intra, smooth_neighbor, + ); + if tu_grid.iter().any(|&l| l != 0) { + RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1)); + } + neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid); + } else { + let tu_around = neighbours.around_mi(tu_mi, tx_w)[0]; + let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI); + let tu_grid = read_plane( + dec, + cdfs, + txbset_for(tx_w, reduced_tx_set), + &default_scan(tx_w), + 0, + tu_around, + mode, + mode, + angle_delta_y, + tu_reach, + y, + tu_px, + tu_py, + tx_w, + tx_w, + base_q_idx, + None, + filter_intra, + Some(tu_skip_ctx), + smooth_neighbor, + )?; + if tu_grid.iter().any(|&l| l != 0) { + RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1)); + } + neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid); + } + } + } + } else { + let levels = if skip { + let zeros = vec![0i32; bw * bh]; + y.reconstruct_rect( + px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra, + smooth_neighbor, + ); + zeros + } else { + // The strip's luma TU *is* the strip (`plane_bsize == + // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes + // `txb_skip_ctx` at 0. + let around = neighbours.around_mi_rect(lmi, bw, bh)[0]; + let set = if reduced_tx_set { + TxbSet::LumaRect16x4 + } else { + TxbSet::LumaRect16x4Set1 + }; + let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra)); + let (levels, tx_type) = read_coeffs_rect( + dec, + &mut coding, + scan, + bw, + bh, + 0, + dc_sign_ctx(around.2), + TxType::DctDct, + )?; + let residual = dequant_and_inverse_typed_wh( + &levels, + bw, + bh, + crate::decode::bit_depth(), + block_q_idx(), + plane_q_delta(0).0, + plane_q_delta(0).1, + tx_type, + ); + y.reconstruct_rect( + px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra, + smooth_neighbor, + ); + RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1)); + levels + }; + neighbours.record_mi_luma_rect(lmi, bw, bh, &levels); + } + neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip); + neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0); + // `update_partition_context` writes `partition_context_lookup[ + // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on + // the left (mirrored under VERT_4). + for cell in 0..mi_w { + if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) { + *slot = bw; + } + } + for cell in 0..mi_h { + if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) { + *slot = bh; + } + } + if has_chroma { + RECT4_16_CHROMA_HITS.with(|h| h.set(h.get() + 1)); + let pair_mi = if horz { + (lmi.0 - 1, lmi.1) + } else { + (lmi.0, lmi.1 - 1) + }; + let (pw, ph) = if horz { (16, 8) } else { (8, 16) }; + let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI); + let (cpx, cpy) = (ppx / 2, ppy / 2); + let (cw, ch) = (pw / 2, ph / 2); + let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode }; + let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height); + let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c); + let (u_levels, v_levels) = if skip { + let zeros = vec![0i32; cw * ch]; + for (buf, _plane) in [(&mut *u, 1usize), (&mut *v, 2)] { + buf.reconstruct_rect( + cpx, + cpy, + cw, + ch, + uv_predict_mode, + angle_delta_uv, + pair_reach, + &zeros, + None, + None, + smooth_neighbor_uv, + ); + } + (zeros.clone(), zeros) + } else { + let around = neighbours.around_mi_rect(pair_mi, pw, ph); + let mut planes = Vec::with_capacity(2); + for plane in 1..3 { + let default_tx = default_intra_tx_type(uv_predict_mode as u8); + let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1); + let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode); + let (levels, tx_type) = read_coeffs_rect( + dec, + &mut coding, + chroma_scan, + cw, + ch, + skip_ctx, + dc_sign_ctx(around[plane].2), + default_tx, + )?; + planes.push((levels, tx_type)); + } + let (v_levels, v_tx_type) = planes.pop().expect("plane 2"); + let (u_levels, u_tx_type) = planes.pop().expect("plane 1"); + // CfL averages the luma of the WHOLE pair, the region this one + // chroma transform covers. + let ac = alpha.map(|_| cfl_ac_q3_rect(y, ppx, ppy, pw, ph)); + for (plane, buf, levels, tx_type) in [ + (1usize, &mut *u, &u_levels, u_tx_type), + (2, &mut *v, &v_levels, v_tx_type), + ] { + let residual = dequant_and_inverse_typed_wh( + levels, + cw, + ch, + crate::decode::bit_depth(), + block_q_idx(), + plane_q_delta(plane).0, + plane_q_delta(plane).1, + tx_type, + ); + buf.reconstruct_rect( + cpx, + cpy, + cw, + ch, + uv_predict_mode, + angle_delta_uv, + pair_reach, + &residual, + alpha + .zip(ac.as_deref()) + .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), + None, + smooth_neighbor_uv, + ); + } + (u_levels, v_levels) + }; + neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode); + // The chroma planes' coefficient context, over the PAIR's mi span + // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is + // the luma one rounded up to its 4x4 unit). + let u_state = neighbour_state(&u_levels); + let v_state = neighbour_state(&v_levels); + 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); + for cell in 0..(ph / MI) { + if pair_mi.0 + cell < bound_h + && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell) + { + slot[1] = u_state; + slot[2] = v_state; + } + } + for cell in 0..(pw / MI) { + if pair_mi.1 + cell < bound_w + && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell) + { + slot[1] = u_state; + slot[2] = v_state; + } + } + last_uv_mode = uv_predict_mode; + } + if horz { + RECT4_16_HORZ_HITS.with(|h| h.set(h.get() + 1)); + } else { + RECT4_16_VERT_HITS.with(|h| h.set(h.get() + 1)); + } + last_mode = mode; + prev = Some((lmi, mode)); + } + // The coarse 16-px cell holds one entry for the whole 16x16: the last + // strip is what a block below (right) sees through it, the mi-exact maps + // above answering everything finer. + neighbours.above_mode[c] = last_mode; + neighbours.left_mode[r] = last_mode; + neighbours.above_uv_mode[c] = last_uv_mode; + neighbours.left_uv_mode[r] = last_uv_mode; + neighbours.above_side[c] = bw; + neighbours.left_side[r] = bh; + Ok(()) +} + /// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/ /// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` / /// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike @@ -7043,6 +7893,7 @@ fn decode_block_rect64( // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile // from this block's very first symbol (lane-sbpart r3 bisect). false, + true, bw, bh, enable_filter_intra, @@ -7902,6 +8753,26 @@ fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone. /// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written /// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`. +/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of +/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) -- +/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE). +fn dump_stage16(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, fw: usize, fh: usize) { + use std::io::Write; + if let Ok(path) = std::env::var(var) + && let Ok(mut f) = std::fs::File::create(format!("{path}.f0")) + { + for (p, w, h) in [(y, fw, fh), (u, fw.div_ceil(2), fh.div_ceil(2)), (v, fw.div_ceil(2), fh.div_ceil(2))] { + for row in 0..h { + let mut bytes = Vec::with_capacity(w * 2); + for &s in &p.data[row * p.width..][..w] { + bytes.extend_from_slice(&s.to_le_bytes()); + } + let _ = f.write_all(&bytes); + } + } + } +} + fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) { use std::io::Write; if let Ok(path) = std::env::var(var) @@ -8047,6 +8918,7 @@ impl PlaneBuf { /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own /// already-rect-capable `(bw, bh)` pair. #[allow(clippy::too_many_arguments)] + #[track_caller] fn reconstruct_rect( &mut self, x: usize, @@ -8105,6 +8977,16 @@ impl PlaneBuf { } prediction }; + // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's + // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). + if std::env::var_os("EC_PRED").is_some() { + let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); + let row0: Vec = prediction[..bw.min(8)].to_vec(); + let col0: Vec = (0..bh.min(8)).map(|r| prediction[r * bw]).collect(); + eprintln!( + "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller() + ); + } for row in 0..bh { for col in 0..bw { let idx = row * bw + col; @@ -8124,6 +9006,7 @@ impl PlaneBuf { /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual /// order (cfl.c). + #[track_caller] fn reconstruct( &mut self, x: usize, @@ -8187,6 +9070,16 @@ impl PlaneBuf { } prediction }; + // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's + // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). + if std::env::var_os("EC_PRED").is_some() { + let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); + let row0: Vec = prediction[..side.min(8)].to_vec(); + let col0: Vec = (0..side.min(8)).map(|r| prediction[r * side]).collect(); + eprintln!( + "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller() + ); + } for row in 0..side { for col in 0..side { let idx = row * side + col; @@ -8518,18 +9411,69 @@ fn decode_block( if skip { // A skipped block codes no residual syntax at all (spec 5.11.34): // straight prediction, on every plane. - y.reconstruct( - px, - py, - side, - mode, - angle_delta_y, - reach, - &vec![0i32; side * side], - None, - filter_intra, - smooth_neighbor, - ); + // + // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it + // is skipped (only an INTER skip forces the largest transform), and + // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts + // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units + // already written left/above of it inside this same block. Predicting + // the whole `side`x`side` at once gives a different (uniformly off by + // ~1) answer, which is exactly the residue this lane was chasing. + // The palette/intrabc override path keeps the single-call shape (its + // per-TU windowing is the non-skip loop's own `palette_y_buf` slice, + // untested for skip and unreachable in these streams). + let split_tx_skip = + tx_select && logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none(); + if split_tx_skip { + SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + let n_axis = side / logical_tx; + for tu_row in 0..n_axis { + for tu_col in 0..n_axis { + let tu_px = px + tu_col * logical_tx; + let tu_py = py + tu_row * logical_tx; + if tu_px >= y.true_width || tu_py >= y.true_height { + continue; + } + let tu_reach = tu_reach( + side, + side, + tu_col * logical_tx, + tu_row * logical_tx, + logical_tx, + reach, + px, + py, + y.width, + y.height, + ); + y.reconstruct( + tu_px, + tu_py, + logical_tx, + mode, + angle_delta_y, + tu_reach, + &vec![0i32; logical_tx * logical_tx], + None, + filter_intra, + smooth_neighbor, + ); + } + } + } else { + y.reconstruct( + px, + py, + side, + mode, + angle_delta_y, + reach, + &vec![0i32; side * side], + None, + filter_intra, + smooth_neighbor, + ); + } let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone()); @@ -8666,12 +9610,9 @@ fn decode_block( ); let tu_px = px + tu_col * logical_tx; let tu_py = py + tu_row * logical_tx; - // lane-golomb r3, same-shape sweep of the strip fix below: - // libaom clips this loop to `max_blocks_wide/high` too. A + // Same libaom clip as `decode_rect_split`'s loop above; a // square block only hangs off the frame when the frame's mi - // dimensions are odd at the block's own level (lane-oddh - // territory), so no gate here reaches it -- it is the - // identical libaom rule, not a measured fix. + // dimensions are odd at the block's own level. if tu_px >= y.true_width || tu_py >= y.true_height { continue; } @@ -8950,18 +9891,59 @@ fn decode_leaf8( let (cpx, cpy) = (px / 2, py / 2); let (luma_grid, u_grid, v_grid); if skip { - y.reconstruct( - px, - py, - 8, - mode, - angle_delta_y, - reach, - &vec![0i32; 64], - None, - filter_intra, - smooth_neighbor, - ); + // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an + // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4 + // transform units, each off the units already written left/above of + // it inside this same leaf -- an intra block's transform size is read + // whether or not it is skipped, and spec 7.11.2 predicts per unit. + if resolved == 4 { + SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + for tu_row in 0..2 { + for tu_col in 0..2 { + let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4); + if tu_px >= y.true_width || tu_py >= y.true_height { + continue; + } + let tu_reach = tu_reach( + 8, + 8, + tu_col * 4, + tu_row * 4, + 4, + reach, + px, + py, + y.width, + y.height, + ); + y.reconstruct( + tu_px, + tu_py, + 4, + mode, + angle_delta_y, + tu_reach, + &vec![0i32; 16], + None, + filter_intra, + smooth_neighbor, + ); + } + } + } else { + y.reconstruct( + px, + py, + 8, + mode, + angle_delta_y, + reach, + &vec![0i32; 64], + None, + filter_intra, + smooth_neighbor, + ); + } let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8)); u.reconstruct( cpx, @@ -10482,7 +11464,19 @@ fn read_block_tx_size( /// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a /// rect transform), neither of which exists yet -- both stay refused by name. fn rect_inter_residual_supported(w: usize, h: usize) -> bool { - matches!((w, h), (32, 16) | (16, 32) | (16, 8) | (8, 16)) + matches!( + (w, h), + // 2:1 strips whose transform is coded in full (lane-inter4). + (32, 16) | (16, 32) | (16, 8) | (8, 16) + // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes + // only the low 32 coefficients of a 64-length axis, so these read + // exactly the truncated corner the INTRA superblock-strip path + // already reads (`read_intra_mode_rect`), through + // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is + // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no + // `tx_type` symbol is coded at all. + | (64, 32) | (32, 64) | (64, 16) | (16, 64) + ) } /// The luma coefficient/`tx_type` table set of a whole-block rectangular @@ -10503,6 +11497,13 @@ fn rect_inter_luma_set(w: usize, h: usize) -> TxbSet { TxbSet::LumaRect16x8InterSet1 } } + // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to + // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and + // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the + // adjusted size, so the existing sets are bit-exact. Neither carries a + // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot. + (64, 32) | (32, 64) => TxbSet::Luma64, + (64, 16) | (16, 64) => TxbSet::LumaRect32x16, _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), } } @@ -10515,6 +11516,13 @@ fn rect_inter_chroma_set(w: usize, h: usize) -> TxbSet { match (w, h) { (16, 8) | (8, 16) => TxbSet::ChromaRect16x8, (8, 4) | (4, 8) => TxbSet::ChromaRect8x4, + // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a + // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma + // unit has a 64-px axis, so both are coded in full; `Chroma16` is the + // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16, + // `txsize_log2_minus4` = 4), same as the intra strip path uses. + (32, 16) | (16, 32) => TxbSet::ChromaRect32x16, + (32, 8) | (8, 32) => TxbSet::Chroma16, _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), } } @@ -10560,6 +11568,8 @@ fn rect_scan(w: usize, h: usize) -> &'static [u16] { (8, 16) => &SCAN_8X16, (8, 4) => &SCAN_8X4, (4, 8) => &SCAN_4X8, + (32, 8) => &SCAN_32X8, + (8, 32) => &SCAN_8X32, _ => unreachable!("rect_inter_residual_supported gates every shape that reaches here"), } } @@ -10626,6 +11636,16 @@ fn read_block_tx_size_rect( } TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1)); RECT_INTER_TXSPLIT_HITS.with(|c| c.set(c.get() + 1)); + // lane-r14 r2: `sub_tx_size_map` is square for every shape this decoder + // splits (TX_32X16 -> TX_16X16, TX_64X32 -> TX_32X32) EXCEPT the 1:4 + // strips with a 64-px axis, where it stays rectangular + // (TX_64X16 -> TX_32X16, TX_16X64 -> TX_16X32) and the square recursion + // below would code the wrong tree. + if tx_w.max(tx_h) == 64 && tx_w.min(tx_h) == 16 { + return Err(unsupported( + "a split transform on a 1:4 inter strip with a 64-px axis", + )); + } let sub = tx_w.min(tx_h); let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1)); let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0)); @@ -10689,16 +11709,50 @@ fn read_inter_plane_rect( Some(t) if w.max(h) < 32 => t, _ => TxType::DctDct, }; - let (grid, tx_type) = read_coeffs_rect( - dec, - &mut coding, - rect_scan(w, h), - w, - h, - skip_ctx, - dc_sign_ctx(around.2), - default_tx_type, - )?; + // lane-r14 r2: a 64-length axis codes only its low 32 coefficients + // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)` + // corner, zero-extended into the true `w x h` grid before the inverse + // transform -- exactly what the intra superblock-strip path does. A + // corner that comes out square (32x32, under a 64x32/32x64 strip) reads + // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`, + // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted + // rectangular shape (lane-sbpart r8). + let (cw, ch) = (w.min(32), h.min(32)); + if plane_idx == 0 && w.max(h) == 64 { + RECT64_INTER_TU_HITS.with(|c| c.set(c.get() + 1)); + } + let (corner, tx_type) = if (cw, ch) == (32, 32) { + let scan32 = default_scan(TX32); + read_coeffs( + dec, + &mut coding, + &scan32, + skip_ctx, + dc_sign_ctx(around.2), + default_tx_type, + Some((w, h)), + )? + } else { + read_coeffs_rect( + dec, + &mut coding, + rect_scan(cw, ch), + cw, + ch, + skip_ctx, + dc_sign_ctx(around.2), + default_tx_type, + )? + }; + let grid = if (cw, ch) == (w, h) { + corner + } else { + let mut full = vec![0i32; w * h]; + for row in 0..ch { + full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]); + } + full + }; let (dc_delta, ac_delta) = plane_q_delta(plane_idx); let residual = dequant_and_inverse_typed_wh( &grid, @@ -11669,6 +12723,131 @@ pub(crate) fn take_last_frame_wide_margin() -> Option { /// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table /// alongside the picture, for the caller to save into whichever reference /// slots this frame's `refresh_frame_flags` names. +/// The order the 64x64 superblock quadrants of a tile are decoded in. +/// +/// At `sb_size == 64` this is plain raster order over the tile's own +/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses +/// each 128x128 superblock in raster order and visits its four 64x64 +/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the +/// 64-level bodies must run in that nested order. `row_start` marks the first +/// item of each *superblock* row (where the left neighbour context resets), +/// `sb_start` the first item of each superblock (where the 128 root's own +/// loop-restoration units and partition symbol are read). +fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> { + let mut out = Vec::new(); + if !sb128 { + for r in r0..r1 { + for c in c0..c1 { + out.push((r, c, c == c0, true)); + } + } + return out; + } + let mut r = r0; + while r < r1 { + let mut first_in_row = true; + let mut c = c0; + while c < c1 { + let mut first_in_sb = true; + for qr in 0..2 { + for qc in 0..2 { + let (rr, cc) = (r + qr, c + qc); + if rr >= r1 || cc >= c1 { + continue; + } + out.push((rr, cc, first_in_row, first_in_sb)); + first_in_row = false; + first_in_sb = false; + } + } + c += 2; + } + r += 2; + } + out +} + +/// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and +/// the inter tile loop. Its loop-restoration units are read once for the whole +/// 128x128 (spec 5.11.57 is called with the superblock's own size), then one +/// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4) +/// decides the root -- only SPLIT recurses into the four 64x64 quadrants this +/// decoder codes, the other seven arms refuse by name. +#[allow(clippy::too_many_arguments)] +fn read_sb128_root( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &Neighbours, + lr: &LoopRestorationParams, + lr_grid: &mut crate::restoration::RestorationGrid, + lr_reference: &mut [( + crate::restoration::WienerInfo, + crate::restoration::SgrprojInfo, + ); 3], + sb_r: u32, + sb_c: u32, + mi_cols: u32, + mi_rows: u32, +) -> Result<()> { + let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI); + crate::restoration::read_lr( + dec, + cdfs, + lr, + lr_grid, + lr_reference, + mi_r128, + mi_c128, + SB_MI * 2, + ); + let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize); + let ctx128 = neighbours.partition_ctx(at128, 128); + let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows); + let part128 = if has_cols128 && has_rows128 { + PART128_SYMBOLS.with(|c| c.set(c.get() + 1)); + let p = dec.symbol(&mut cdfs.partition_w128[ctx128]); + if std::env::var_os("EC_AV1_TRACE").is_some() { + eprintln!("TRACE partition_w128 ctx={ctx128} value={p}"); + } + p + } else { + // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the + // partition, they are not a forced split -- exactly the discarded-bit + // defect the 64 root carries a comment about at `partition_w64`'s + // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or + // VERT (cols out of frame), which the refusal below then names + // instead of silently reconstructing a split. + PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() + 1)); + match (has_cols128, has_rows128) { + (true, false) => { + if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_HORZ + } + } + (false, true) => { + if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_VERT + } + } + _ => { + PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1)); + PARTITION_SPLIT + } + } + }; + if part128 != PARTITION_SPLIT { + return Err(unsupported( + "a 128x128 superblock partition other than SPLIT (NONE/HORZ/VERT and the four AB arms at the 128 root are not decoded)", + )); + } + PART128_SPLIT_HITS.with(|c| c.set(c.get() + 1)); + Ok(()) +} + pub(crate) fn decode_key_frame_tile_with_cdfs( tiles: &[&[u8]], tile_info: &TileInfo, @@ -11701,6 +12880,12 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( return Err(unsupported("a frame with no mode-info grid")); } ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter)); + let sb128 = sb128(); + if sb128 && allow_intrabc { + return Err(unsupported( + "intrabc under a 128x128 superblock (libaom's av1_is_dv_valid derives the block-vector delay from sb_size, which this decoder hardcodes to 64)", + )); + } let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI)); INTRABC_MI_GRID.with(|g| { *g.borrow_mut() = allow_intrabc.then(|| { @@ -11838,19 +13023,42 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( ); TILE_HITS.with(|c| c.set(c.get() + 1)); - for sb_r in sb_r0..sb_r1 { - neighbours.start_row(); - for sb_c in sb_c0..sb_c1 { - crate::restoration::read_lr( - &mut dec, - &mut cdfs, - lr, - &mut lr_grid, - &mut lr_reference, - sb_r * SB_MI, - sb_c * SB_MI, - SB_MI, - ); + for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) { + if row_start { + neighbours.start_row(); + } + { + // lane-sb128 r1: the 128 root. Its loop-restoration units are read + // once for the whole 128x128 (spec 5.11.57 is called with the + // superblock's own size), then one partition symbol off the + // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT + // recurses into the four 64x64 quadrants this decoder codes. + if sb128 && sb_start { + read_sb128_root( + &mut dec, + &mut cdfs, + &neighbours, + lr, + &mut lr_grid, + &mut lr_reference, + sb_r, + sb_c, + mi_cols, + mi_rows, + )?; + } + if !sb128 { + crate::restoration::read_lr( + &mut dec, + &mut cdfs, + lr, + &mut lr_grid, + &mut lr_reference, + sb_r * SB_MI, + sb_c * SB_MI, + SB_MI, + ); + } CDEF_TRANSMITTED.with(|c| c.set(false)); let at = (sb_r as usize * 4, sb_c as usize * 4); let ctx = neighbours.partition_ctx(at, SB); @@ -11872,23 +13080,24 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } p } else { - // lane-golomb r1 (class `parsed-then-discarded`): the gathered - // bit is the answer, not a formality -- libaom's - // `ec_read_partition_impl` returns `PARTITION_HORZ` (resp. - // `PARTITION_VERT`) when it reads 0, and only `PARTITION_SPLIT` - // when it reads 1. Forcing SPLIT here desynced the last - // superblock row of every frame whose height is not a multiple - // of 64 -- the ReelB head (3840x1608) diverges at - // mi_row=400 mi_col=0, the first block of that row. + // lane-hgkf r1 (class `parsed-then-discarded`, same finding as + // the unmerged lane-golomb r1): the gathered bit IS the + // partition -- libaom `ec_read_partition_impl` returns + // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1. + // Forcing SPLIT desynced the last superblock row of every + // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0, + // the first block of that row. match (has_cols, has_rows) { (true, false) => { let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE)); bump_edge32(4 + b.min(1) as usize); + bump_edge_part(b.min(1) as usize); if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ } } (false, true) => { let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE)); bump_edge32(4 + b.min(1) as usize); + bump_edge_part(b.min(1) as usize); if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } _ => PARTITION_SPLIT, @@ -11947,34 +13156,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } p } else { + // lane-hgkf r1: the 32-level frame-edge bit is the + // partition too (same libaom reader as the + // superblock level above). match (has_cols32, has_rows32) { (true, false) => { - // lane-golomb r1 (class `parsed-then-discarded`): the gathered - // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT - // (libaom `ec_read_partition_impl`). - if { - let b = dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE)); - bump_edge32(b.min(1) as usize); - b - } == 1 { - PARTITION_SPLIT - } else { - PARTITION_HORZ - } + let b = dec.symbol_fixed(&gather( + &cdfs.partition_w32[ctx32], + VERT_ALIKE, + )); + bump_edge32(b.min(1) as usize); + bump_edge_part(2 + b.min(1) as usize); + if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ } } (false, true) => { - // lane-golomb r1 (class `parsed-then-discarded`): the gathered - // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT - // (libaom `ec_read_partition_impl`). - if { - let b = dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE)); - bump_edge32(b.min(1) as usize); - b - } == 1 { - PARTITION_SPLIT - } else { - PARTITION_VERT - } + let b = dec.symbol_fixed(&gather( + &cdfs.partition_w32[ctx32], + HORZ_ALIKE, + )); + bump_edge32(b.min(1) as usize); + bump_edge_part(2 + b.min(1) as usize); + if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } _ => PARTITION_SPLIT, } @@ -12278,11 +13480,34 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( neighbours.left_mode[sr] = mode_right; continue; } - if part16 != PARTITION_SPLIT { - return Err(unsupported( - "a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 strips -- this decoder codes NONE, HORZ, VERT, the four AB arms and a clean split at 16x16)", - )); + if part16 == PARTITION_HORZ_4 + || part16 == PARTITION_VERT_4 + { + decode_rect4_16( + &mut dec, + &mut cdfs, + &mut neighbours, + at16, + part16 == PARTITION_HORZ_4, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + reduced_tx_set, + )?; + continue; } + // lane-r14 r2 (verifier note): every + // one of the 10 symbols this CDF can + // produce is handled above, so SPLIT + // is the only value that reaches + // here -- the refusal that used to + // stand here was unreachable and is + // gone from `refusal_inventory`. + debug_assert_eq!(part16, PARTITION_SPLIT); // A real (non-straddle) SPLIT of a // whole 16x16 into four 8x8 leaves -- // the same recursion the straddle @@ -12435,6 +13660,10 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( HORZ_ALIKE, )) }; + // lane-hgkf r1: slots 2/3 of + // [`EDGE_PART_HITS`], the gate's proof the + // non-SPLIT edge arm actually decoded. + bump_edge_part(if edge_split == 1 { 3 } else { 2 }); if edge_split == 0 { // lane-oddh r1: the strip IS decodable // -- libaom's `decode_partition` codes @@ -12604,9 +13833,9 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( if !has_rows32 { bump_edge32(2); } - // lane-golomb r2: at the frame edge only the first half of the - // strip is coded (libaom `decode_partition` guards the second - // with the same has_rows test that made this partition non-square). + // lane-hgkf r1: at the frame edge only the first half of the strip is + // coded (libaom `decode_partition` guards the second half with the same + // test that made this partition non-square). if has_rows32 { decode_block_rect( &mut dec, @@ -12648,9 +13877,9 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( if !has_cols32 { bump_edge32(3); } - // lane-golomb r2: at the frame edge only the first half of the - // strip is coded (libaom `decode_partition` guards the second - // with the same has_cols test that made this partition non-square). + // lane-hgkf r1: at the frame edge only the first half of the strip is + // coded (libaom `decode_partition` guards the second half with the same + // test that made this partition non-square). if has_cols32 { decode_block_rect( &mut dec, @@ -13259,6 +14488,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // that isolate whether a decode-order frame's mismatch already exists // in reconstruction (this dump) vs is introduced by the loop filter // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). + dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -13302,8 +14532,10 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter // dump above these bisect WHICH filter stage introduced a mismatch. dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); + dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); + dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid); let (fw, fh) = (frame_width as usize, frame_height as usize); @@ -13905,34 +15137,16 @@ fn overlappable_left( out } -/// `has_top_right` (`av1/common/mvref_common.c`), reduced to the -/// square-block, fixed-64px-superblock case this decoder ever reaches: no -/// rectangular partition (`VERT`/`HORZ`/`_4`/`VERT_A`) ever produces an -/// inter leaf here (`xd->width == xd->height` always), so libaom's own -/// rect-partition branches (`xd->width < xd->height`, `xd->width > -/// xd->height`, `PARTITION_VERT_A`) never fire and are dropped. `bs` is the -/// block's own side in 4x4 (`mi`) units. +/// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples` +/// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2: +/// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128` +/// libaom's mask loop runs one level further and strips the top-right sample +/// off blocks whose neighbour IS decoded, so a warped 128-superblock frame +/// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates +/// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is +/// the block's own side in 4x4 (`mi`) units (square inter leaves only here). fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool { - let sb_mi_size = SB_MI as usize; - let mask_row = mi_row & (sb_mi_size - 1); - let mask_col = mi_col & (sb_mi_size - 1); - if bs > sb_mi_size { - return false; - } - let mut has_tr = !((mask_row & bs != 0) && (mask_col & bs != 0)); - let mut b = bs; - while b < sb_mi_size { - if mask_col & b != 0 { - if (mask_col & (2 * b) != 0) && (mask_row & (2 * b) != 0) { - has_tr = false; - break; - } - } else { - break; - } - b <<= 1; - } - has_tr + crate::mvstack::has_top_right(mi_row, mi_col, bs, bs) } /// `av1_findSamples` (`mvref_common.c`), full port: the up to @@ -14961,18 +16175,6 @@ fn decode_inter_block( let whole_sb = side == 64 && write_w == 64 && write_h == 64; maybe_read_delta_q(dec, cdfs, rmi, cmi, whole_sb, skip); maybe_read_delta_lf(dec, cdfs, rmi, cmi, whole_sb, skip); - // lane-warp r5: see `reject_residual` -- a square-block decode of a - // HORZ_B strip is symbol-exact only for `skip` (no residual, no - // motion_mode/warp symbol), so gate here before any further read. - if reject_residual && !skip && !rect_inter_residual_supported(write_w, write_h) { - if std::env::var_os("EC_AV1_RECT_DUMP").is_some() { - eprintln!("EC_RECT_REFUSE mi_row={rmi} mi_col={cmi} w={write_w} h={write_h} side={side}"); - } - return Err(unsupported( - "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", - )); - } - let (has_above, has_left) = ( rmi > neighbours.tile_row0_mi, cmi > neighbours.tile_col0_mi, @@ -14988,6 +16190,29 @@ fn decode_inter_block( dec.debug_state().0 ); } + // lane-warp r5: see `reject_residual` -- a square-block decode of a + // HORZ_B strip is symbol-exact only for `skip` (no residual, no + // motion_mode/warp symbol). lane-intrarect r1 MOVED this gate from just + // after the `skip` read to here, past `is_inter` (class + // [[refusal-short-circuits-its-own-code]]: at the old place it refused + // 24/24 attempts of this lane's own gate before the intra arm below + // could run). An INTRA strip with its true `write_w`x`write_h` footprint + // now codes its residual rectangularly ([`decode_intra_rect_in_inter`]); + // an INTER one, and a strip decoded with square dimensions anyway, still + // cannot. + // merge b51719f+lane-intrarect: main's `rect_inter_residual_supported` + // term stays -- lane-inter4's 16x8/8x16 inter leaves DO code a + // rectangular residual, and the lane's condition (written before that + // landed) refused every one of them. + if reject_residual + && !skip + && !rect_inter_residual_supported(write_w, write_h) + && (is_inter || (write_w == side && write_h == side)) + { + return Err(unsupported( + "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", + )); + } if std::env::var_os("EC_AV1_TELL").is_some() { eprintln!( "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}", @@ -15113,6 +16338,22 @@ fn decode_inter_block( force_integer_mv, (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]), ); + if std::env::var_os("EC_TRACE_MODE").is_some() { + eprintln!( + "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={} ref0={ref0} ref1={ref1} mv0=({},{}) stack={} rng={}", + compound_mode + 17, + mv0.0, + mv0.1, + comp_stack.entries.len(), + dec.debug_state().0 + ); + for (i, e) in comp_stack.entries.iter().enumerate() { + eprintln!( + "EC_STACK mi_row={mi_row} mi_col={mi_col} i={i} this=({},{}) comp=({},{}) w={}", + e.mv0.0, e.mv0.1, e.mv1.0, e.mv1.1, e.weight + ); + } + } let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV // spec `is_nontrans_global_motion`: ALL active refs' models must // be non-TRANSLATION (IDENTITY counts) for the compound block's @@ -16999,10 +18240,64 @@ fn decode_inter_block( // already-square-predicted buffer). Named refusal instead of a // silently wrong square-shaped intra prediction. if write_w != side || write_h != side { - return Err(unsupported( - "an intra-coded HORZ/VERT strip needs rectangular intra prediction \ - this decoder does not code yet", - )); + // lane-intrarect r1: the strip decodes through its own rect + // machinery ([`decode_intra_rect_in_inter`] -> the key-frame + // paths' [`decode_rect_split`]) instead of refusing. That call + // already writes everything the shared tail below would for a + // square block EXCEPT the inter-side bands and the mi map, so + // this arm returns rather than falling through (a second + // `record_rect`/`fill_lf_grid_rect` at block granularity would + // overwrite the per-transform-unit records it just made). + decode_intra_rect_in_inter( + dec, + cdfs, + neighbours, + at, + write_w, + write_h, + skip, + allow_screen_content_tools, + y, + u, + v, + base_q_idx, + )?; + // merge b51719f+lane-intrarect: `at` is in MI units on this path + // (lane-inter4), so the strip's mi origin is `at` itself -- the + // lane's `r * SUB_MI` re-derivation would snap a sub-SUB strip to + // its enclosing 16-px cell. + let (mi_r0, mi_c0) = (rmi, cmi); + for dr in 0..write_h / MI { + for dc in 0..write_w / MI { + grid.set( + mi_r0 + dr, + mi_c0 + dc, + MiInfo { + is_inter: false, + ref_frame: -1, + ref_frame1: None, + mv1: None, + mv: (0, 0), + is_new_mv: false, + size: write_w / MI, + size_h: write_h / MI, + is_global_mv0: false, + is_global_mv1: false, + }, + ); + } + } + neighbours.record_inter_rect_mi( + at, + write_w / MI, + write_h / MI, + skip, + false, + 0, + [3, 3], + skip_mode, + ); + return Ok(()); } let mode = dec.symbol(&mut cdfs.y_mode[size_group_wh(write_w, write_h)]); if mode >= 13 { @@ -19128,6 +20423,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( )); } let (cols, rows) = block_grid(mi_cols, mi_rows); + let sb128 = sb128(); let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); CDEF_BITS.with(|c| c.set(cdef.bits)); CDEF_SB_COLS.with(|c| c.set(sb_cols as usize)); @@ -19349,19 +20645,44 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( ); TILE_HITS.with(|c| c.set(c.get() + 1)); - for sb_r in sb_r0..sb_r1 { - neighbours.start_row(); - for sb_c in sb_c0..sb_c1 { - crate::restoration::read_lr( - &mut dec, - &mut cdfs, - lr, - &mut lr_grid, - &mut lr_reference, - sb_r * SB_MI, - sb_c * SB_MI, - SB_MI, - ); + // lane-sb128 r2: at `sb_size == 128` the tile walks each 128x128 + // superblock's four 64x64 quadrants in libaom `decode_partition` order + // (TL, TR, BL, BR) and reads the 128 root's own loop-restoration units and + // partition symbol once per superblock -- exactly what the key-frame tile + // loop does; the 64-level body below is unchanged, `read_cdef`'s + // per-64x64-quadrant reset (`CDEF_TRANSMITTED`) already matches libaom's + // `cdef_idx[(mi_row & 16) >> 4 * 2 + (mi_col & 16) >> 4]` slot per quadrant. + for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) { + if row_start { + neighbours.start_row(); + } + { + if sb128 && sb_start { + read_sb128_root( + &mut dec, + &mut cdfs, + &neighbours, + lr, + &mut lr_grid, + &mut lr_reference, + sb_r, + sb_c, + mi_cols, + mi_rows, + )?; + } + if !sb128 { + crate::restoration::read_lr( + &mut dec, + &mut cdfs, + lr, + &mut lr_grid, + &mut lr_reference, + sb_r * SB_MI, + sb_c * SB_MI, + SB_MI, + ); + } CDEF_TRANSMITTED.with(|c| c.set(false)); let sb_at = (sb_r as usize * 4, sb_c as usize * 4); // lane-inter4 r1: every rect inter piece below is the same @@ -21007,6 +22328,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // that isolate whether a decode-order frame's mismatch already exists // in reconstruction (this dump) vs is introduced by the loop filter // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). + dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -21033,8 +22355,10 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter // dump above these bisect WHICH filter stage introduced a mismatch. dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); + dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); + dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid); let motion_field = build_motion_field( @@ -21131,8 +22455,6 @@ mod tests { // string that blocks the shape otherwise. Either way the row is // pinned HERE, so the round that lifts one of those refusals cannot // land a wrong CDF row for the shape it unlocks. - const PART16: &str = "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)"; let libaom: &[(usize, usize, u16, Option<&str>)] = &[ (4, 4, 4621, None), (4, 8, 6743, None), @@ -21147,8 +22469,10 @@ mod tests { // The 1:4 strips: a 16x16-level PARTITION_HORZ_4/VERT_4 gives // 4x16/16x4 (still refused by name before any leaf is coded), // a 32x32-level one 8x32/32x8. - (4, 16, 12770, Some(PART16)), - (16, 4, 10368, Some(PART16)), + // lane-r14: the 16-level pair is coded now (`decode_rect4_16`), + // owning classes 13/12. + (4, 16, 12770, None), + (16, 4, 10368, None), // lane-fi32x8 r1: the 32-level pair is coded (four 32x8/8x32 // strips per `PARTITION_HORZ_4`/`VERT_4`) and now owns classes // 10/11; only the 16-level pair is still refused before any leaf. @@ -21623,8 +22947,16 @@ mod tests { // non-skip, so the named refusal is the rectangular-inter-residual // one. Either string proves what the pin was written for: a non-SPLIT // superblock never silently decodes as SPLIT. + // lane-r14 r2: the rectangular-residual refusal is gone (a 64x32 strip + // now codes its truncated low-32 coefficient corner), so this + // hand-written fixture walks further still and stops on the limit of + // the FIXTURE rather than of the decoder: it names no reference + // pictures. All three strings prove the one thing this pin exists for + // -- a non-SPLIT superblock never silently decodes as SPLIT. assert!( - msg.contains("SPLIT") || msg.contains("rectangular residual coding"), + msg.contains("SPLIT") + || msg.contains("rectangular residual coding") + || msg.contains("no picture at this frame's own ref_frame_idx slot"), "expected the named inter-SB-partition refusal, got: {msg}" ); } diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 12121c4e..70125411 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -47,6 +47,26 @@ const SUB: usize = 16; /// The side of a superblock, which is what the partition tree starts from. pub(crate) const SUPERBLOCK: usize = 64; +// lane-sb128 r1: the superblock size in samples the intra-reach rules +// (`has_top_right`/`has_bottom_left`) are answered against. libaom masks the +// block's mi position with `mi_size_wide[cm->seq_params->sb_size] - 1` and +// tests the "top row"/"rightmost column" of THAT superblock, so a 128x128 +// superblock changes every answer inside it (the tables themselves are +// already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`] +// stays the encoder's own fixed 64. +thread_local! { + static REACH_SB_PX: std::cell::Cell = const { std::cell::Cell::new(SUPERBLOCK) }; +} + +/// Sets the superblock size [`Reach`] answers against (64 or 128). +pub(crate) fn set_reach_superblock_px(px: usize) { + REACH_SB_PX.with(|c| c.set(px)); +} + +fn reach_sb_px() -> usize { + REACH_SB_PX.with(|c| c.get()) +} + /// How heavily the mode search weighs rate against squared error, in units of /// the quantizer's reconstruction step squared per bit. /// @@ -1300,19 +1320,19 @@ impl Reach { /// 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 { - const SB_MI: usize = SUPERBLOCK / 4; + let sb_mi: usize = reach_sb_px() / 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; + 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; } // Rightmost column: they fall in the superblock to the right. - if ((blk_col + 1) << bw_log2) >= SB_MI { + if ((blk_col + 1) << bw_log2) >= sb_mi { return false; } let table = rect_reach_tables(bw, bh).0; @@ -1333,20 +1353,20 @@ impl Reach { /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`]. fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool { - const SB_MI: usize = SUPERBLOCK / 4; + let sb_mi: usize = reach_sb_px() / 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; + 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; + return (blk_row << bh_log2) + (bh / 4) < sb_mi; } // 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 { + if ((blk_row + 1) << bh_log2) >= sb_mi { return false; } let table = rect_reach_tables(bw, bh).1; @@ -1420,7 +1440,7 @@ impl Reach { fn bottom_left(side: usize, x: usize, y: usize) -> bool { let (row, col, per_side) = Self::position(side, x, y); if col == 0 { - return row * side + side < SUPERBLOCK; + return row * side + side < reach_sb_px(); } if row + 1 == per_side { return false; @@ -1451,11 +1471,8 @@ impl Reach { /// Where a block sits inside its superblock, in blocks of its own size, /// and how many of them a superblock is across. fn position(side: usize, x: usize, y: usize) -> (usize, usize, usize) { - ( - (y % SUPERBLOCK) / side, - (x % SUPERBLOCK) / side, - SUPERBLOCK / side, - ) + let sb = reach_sb_px(); + ((y % sb) / side, (x % sb) / side, sb / side) } /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index 5fe3ad33..300fa320 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -585,6 +585,43 @@ fn scan_col( found } +/// libaom `has_top_right` (mvref_common.c:264): whether the unit diagonally +/// above-right of this block has been decoded *by the superblock's own +/// recursion order*. The mask is `sb_size`-relative, so at a 128x128 +/// superblock the `while` loop runs one level further than at 64x64 and +/// strips the top-right neighbour off blocks that DO sit in already-decoded +/// memory -- an availability rule a plain "is the grid cell populated" probe +/// (what this module did before lane-sb128 r2) cannot see. It cost frame 6 of +/// the 128 inter gate 380 wrong luma bytes with the entropy stream in sync. +/// +/// corner-cut: libaom's three shape refinements (`is_last_vertical_rect`, +/// `is_first_horizontal_rect`, the `PARTITION_VERT_A` bottom-left square) are +/// not ported -- the ceiling is rectangular and AB-partitioned INTER leaves, +/// which this decoder refuses by name today; port them with the rect inter +/// leaf. +pub(crate) fn has_top_right(mi_row: usize, mi_col: usize, bw4: usize, bh4: usize) -> bool { + let sb_mi_size = crate::decode::sb_mi_cur() as usize; + let bs0 = bw4.max(bh4); + if bs0 > 16 { + return false; + } + let (mask_row, mask_col) = (mi_row & (sb_mi_size - 1), mi_col & (sb_mi_size - 1)); + let mut has_tr = !(mask_row & bs0 != 0 && mask_col & bs0 != 0); + let mut bs = bs0; + while bs < sb_mi_size { + if mask_col & bs != 0 { + if mask_col & (2 * bs) != 0 && mask_row & (2 * bs) != 0 { + has_tr = false; + break; + } + } else { + break; + } + bs <<= 1; + } + has_tr +} + /// The single top-right probe this reduction keeps of spec 7.10.2.4's extra /// scan positions, at the unit diagonally above-right of the block. Its /// vote is folded into the row scan's candidates (it sits on the same row @@ -780,15 +817,15 @@ pub fn find_mv_stack_with_sign_bias( &mut processed_cols, ); let found_top_right = scan_top_right( - grid, - mi_row, - mi_col, - bw4, - ref_frame, - gm, - &mut candidates, - &mut newmv_count, - ); + grid, + mi_row, + mi_col, + bw4, + ref_frame, + gm, + &mut candidates, + &mut newmv_count, + ); // libaom's `row_match_count`/`col_match_count` (mvref_common.c) fold the // top-right probe into the row side, so "found above" for context @@ -1539,15 +1576,15 @@ pub fn find_mv_stack_compound( &mut processed_cols, ); let found_top_right = scan_top_right_compound( - grid, - mi_row, - mi_col, - bw4, - ref_frame, - gm, - &mut candidates, - &mut newmv_count, - ); + grid, + mi_row, + mi_col, + bw4, + ref_frame, + gm, + &mut candidates, + &mut newmv_count, + ); let row_matched = found_above || found_top_right; let nearest_match = usize::from(row_matched) + usize::from(found_left); diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index bf3c9423..9581323a 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -34,7 +34,6 @@ const REFUSALS: &[&str] = &[ "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)", "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)", - "a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 strips -- this decoder codes NONE, HORZ, VERT, the four AB arms and a clean split at 16x16)", "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)", "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", @@ -43,6 +42,8 @@ const REFUSALS: &[&str] = &[ "a tx_type symbol outside its CDF's own set: {t}", "an INTER 32x32 partition type this decoder does not code (value={part32})", "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4", + "a 128x128 superblock partition other than SPLIT (NONE/HORZ/VERT and the four AB arms at the 128 root are not decoded)", + "intrabc under a 128x128 superblock (libaom's av1_is_dv_valid derives the block-vector delay from sb_size, which this decoder hardcodes to 64)", "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)", "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", @@ -50,7 +51,6 @@ const REFUSALS: &[&str] = &[ "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 sequence using 128x128 superblocks on a frame larger than 64x64 (this decoder's whole partition/CDEF/LR grid is 64x64-superblock only; aomenc picks 128x128 at --cpu-used=0)", "a frame OBU with no tile group", "a frame naming primary_ref_frame at a reference slot with no saved CDF state", "a frame with no mode-info grid", @@ -69,10 +69,22 @@ const REFUSALS: &[&str] = &[ "an inter SB-level AB partition (HORZ_A/HORZ_B/VERT_A/VERT_B; this decoder's inter tile path codes a superblock as NONE, SPLIT, HORZ, VERT, HORZ_4 or VERT_4)", "an inter 16x16-level AB or 1:4 partition (HORZ_A/HORZ_B/VERT_A/VERT_B/HORZ_4/VERT_4; this decoder's inter path codes a 16x16 as NONE, HORZ, VERT or SPLIT)", "an intra mode this decoder does not code (round 2)", - "an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder does not code yet", + // lane-intrarect r1 lifted the whole-shape refusal that stood here (the + // inter path's intra arm now routes 2:1 strips through `decode_rect_split`); + // what is left is the 1:4 shape, whose `bsize_to_tx_size_cat` breaks the + // size-group/category diagonal the 2:1 shapes share. + "an intra-coded 1:4 (or other non-2:1) rect strip on the inter block path", + "a split (nonzero tx_depth) transform on an intra HORZ/VERT strip in an inter frame", + // The same arm's screen-content gate: palette/intrabc syntax is consumed + // for square blocks only, so a strip in such a frame would skip symbols. + "a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed for square blocks only)", "warp prediction with a scaled reference (superres, unimplemented)", "an 8x8 partition leaf under a scaled reference (superres, unimplemented)", "a motion_mode symbol for a block shape with no CDF row here", + // lane-r14 r2: the whole-transform case of every 64-axis inter strip is + // coded; only the SPLIT of a 1:4 strip with a 64-px axis is left, whose + // `sub_tx_size_map` entry is rectangular (TX_64X16 -> TX_32X16). + "a split transform on a 1:4 inter strip with a 64-px axis", ]; /// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 04c9efa1..241a3b89 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -68,6 +68,12 @@ pub fn inter_rect_counters() -> (usize, usize, usize, usize, usize, usize) { ) } +/// lane-r14 r2: luma transform units of an inter strip with a 64-px axis, +/// coded as the truncated low-32 coefficient corner. +pub fn rect64_inter_tu_hits() -> usize { + crate::decode::rect64_inter_tu_hits() +} + pub fn rect4_32_counters() -> (usize, usize, usize) { ( crate::decode::rect4_32_horz_hits(), @@ -504,6 +510,18 @@ pub fn decode_stream(data: &[u8]) -> Result> { // inter frames are decoded on a thread that previously decoded a // different sequence would inherit that sequence's bit. crate::decode::set_enable_edge_filter(enable_edge_filter); + // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the + // key-frame and the inter tile path read the 128 partition root and + // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and + // libaom's quadrant visit order into the inter loop too). A frame at + // most 64x64 decodes identically either way (its 128 root reads no + // symbol -- neither half is in frame, so SPLIT is inferred), so the + // flag is only armed for frames bigger than one 64x64 superblock. + let use_sb128 = parser + .sequence_header() + .is_some_and(|seq| seq.use_128x128_superblock); + let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16); + crate::decode::set_sb128(sb128_active); // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`, // which every dequant/inverse-transform clamp reads -- set per frame, // not once per process, for the same cross-sequence-on-one-thread @@ -525,37 +543,6 @@ pub fn decode_stream(data: &[u8]) -> Result> { "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)", )); } - // lane-oddh r2: `use_128x128_superblock` reaches every level of the - // decode -- the partition tree starts at BLOCK_128X128, `SB_MI` is 32 - // mi units, and the CDEF/LR/deblock grids are per-128 -- and this - // decoder is written for 64x64 superblocks throughout (`SB_MI = 16`, - // no BLOCK_128X128 partition read at all). Until r1 that was SILENT: - // a 64x72 aomenc key frame at `--cpu-used=0` (libaom picks 128x128 - // whenever speed is 0, `av1_select_sb_size`) desynced at the very - // first symbol -- aomdec reads a gathered 2-symbol - // BLOCK_128X128 partition (has_cols false at mi_cols=16, - // has_rows true at mi_rows=18) where we read a 10-symbol - // BLOCK_64X64 one from the same byte, giving PARTITION_VERT_4 (9) - // against SPLIT (3). Refuse by name rather than decode wrong pixels. - // - // Scoped, not blanket (measured: a blanket refusal red-lined 29 - // previously pixel-exact gates): on a frame of at most 64x64 a - // 128x128 superblock decodes IDENTICALLY to a 64x64 one -- mi (0,0) - // has neither `has_rows` nor `has_cols`, so BLOCK_128X128 is a forced - // SPLIT that reads no symbol, and only one of its four 64x64 children - // is inside the frame. Every sibling inter gate at 64x64 and - // `--cpu-used=0` is exactly that case. The divergence starts the - // moment a superblock has a second child in frame. - if parser - .sequence_header() - .is_some_and(|seq| seq.use_128x128_superblock) - && (header.mi_cols > 16 || header.mi_rows > 16) - { - return Err(Error::unsupported( - "AV1 decode_stream", - "a sequence using 128x128 superblocks on a frame larger than 64x64 (this decoder's whole partition/CDEF/LR grid is 64x64-superblock only; aomenc picks 128x128 at --cpu-used=0)", - )); - } crate::decode::set_bit_depth(bit_depth); // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits. let enable_masked_compound = parser @@ -1097,22 +1084,18 @@ mod tests { eprintln!("{NAME}: {compared} attempts pixel-exact, edge_rect_strip_hits={strip_hits}, {refused} refusals"); } - /// lane-oddh r2 GATE: a REAL aomenc stream that uses 128x128 superblocks - /// is refused by name, not silently mis-decoded. This is the root cause of - /// r1's pinned 64x72 first-symbol desync: libaom's `av1_select_sb_size` - /// returns BLOCK_128X128 whenever speed is 0, so a tiny frame encoded at - /// `--cpu-used=0` carries 128x128 superblocks, and this 64x64-only - /// decoder read a 10-symbol BLOCK_64X64 partition (value 9, VERT_4) where - /// aomdec read a gathered 2-symbol BLOCK_128X128 one (value 3, SPLIT) from - /// the same byte -- the uncompressed header parse was byte-identical - /// (49 bits, tile data at file offset 20; hand-verified against spec - /// 5.9.2 field by field). + /// lane-sb128 r4 GATE (was lane-oddh r2's refusal gate): the SAME real + /// aomenc 64x72 `--cpu-used=0 --sb-size=128` stream that once desynced at + /// the very first symbol now decodes PIXEL-EXACT against aomdec. mi_rows + /// = 18 > 16, so the BLOCK_128X128 root reads a real gathered partition + /// symbol (2 symbols: has_cols false, has_rows true) -- exactly the case + /// r1 mis-read as a 10-symbol BLOCK_64X64 partition. /// /// The `use_128x128_superblock` assert is the "knob reached the tool" - /// half: without it, an aomenc that ignored `--sb-size=128` would leave - /// the gate asserting a refusal that never fires. + /// half: without it an aomenc that ignored `--sb-size=128` would leave + /// the gate proving nothing about 128 superblocks. #[test] - fn a_real_aomenc_128x128_superblock_stream_is_refused_by_name() { + fn a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact() { if !have_ffmpeg() || !have_aomenc() { eprintln!("SKIP: no ffmpeg/aomenc"); return; @@ -1133,7 +1116,8 @@ mod tests { let mut child = Command::new(aomenc_path()) .args([ "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32", - "--cpu-used=0", "--sb-size=128", "--kf-max-dist=0", "--limit=1", + "--cpu-used=0", "--sb-size=128", "--min-partition-size=16", + "--kf-max-dist=0", "--limit=1", "--threads=1", "--row-mt=0", "--obu", "-o", "-", "-", ]) .stdin(Stdio::piped()) @@ -1163,10 +1147,26 @@ mod tests { } assert!(sb128, "aomenc ignored --sb-size=128: this stream is 64x64-superblock"); - let err = decode_stream(&stream).unwrap_err().to_string(); + let _guard = lock_gate_counters(); + let before = crate::decode::part128_symbols() + + crate::decode::part128_gathered_symbols(); + let (frames, hidden) = + decode_all_frames_vs_oracle(&stream, "sb128-oddh-64x72"); + assert!(frames > 0, "no frames decoded for {width}x{height}"); + // The 128 root actually READ a partition symbol here: at mi_rows=18 + // `has_rows` is true, so BLOCK_128X128 is not a forced split. + let part128 = crate::decode::part128_symbols() + + crate::decode::part128_gathered_symbols() + - before; assert!( - err.contains("a sequence using 128x128 superblocks"), - "expected the 128x128-superblock refusal for {width}x{height}, got: {err}" + part128 > 0, + "{width}x{height} decoded without reading a single BLOCK_128X128 \ + partition symbol -- the gate proves nothing about the 128 root" + ); + eprintln!( + "a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact: \ + {frames} frames pixel-exact ({hidden} hidden) at {width}x{height}, \ + part128_symbols={part128}" ); } @@ -2749,6 +2749,7 @@ mod tests { "--error-resilient=1", "--aq-mode=0", "--deltaq-mode=0", + "--enable-cdef=0", "--enable-rect-partitions=0", "--enable-ab-partitions=0", "--enable-1to4-partitions=0", @@ -4245,6 +4246,331 @@ mod tests { tx_select_inter_gate(10); } + /// lane-intrarect r1's decisive gate: a real aomenc INTER sequence whose + /// hard mid-GOP content cut makes aomenc code INTRA blocks inside inter + /// frames, with rect partitions ON so those intra blocks land on + /// HORZ/VERT strip shapes. Every such block was the named refusal "an + /// intra-coded HORZ/VERT strip needs rectangular intra prediction this + /// decoder does not code yet" until this round; they now decode through + /// the same `decode_rect_split` machinery the key-frame rect paths use. + /// + /// Hard-asserts per-shape counters (`intra_rect_strip_in_inter_hits`: + /// 0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16) summed over the + /// attempts that were actually pixel-compared -- at least TWO of the + /// three shape classes must fire, so a green run cannot come from one + /// lucky size. A decode that succeeds is ALWAYS pixel-compared (class + /// [[gate-skips-on-its-own-failure]]); exhausting every attempt without + /// two shapes is a FAILURE, never a SKIP. + #[test] + fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact() { + intra_rect_in_inter_gate(8); + } + + /// The 10-bit arm (both of the user's films are `yuv420p10le`). + #[test] + fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact_10bit() { + intra_rect_in_inter_gate(10); + } + + fn intra_rect_in_inter_gate(bit_depth: u32) { + const NAME: &str = "a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (96usize, 96usize, 8usize); + let mut refusals: Vec = Vec::new(); + let mut uncounted_exact = 0u32; + let mut compared = 0u32; + let mut shapes = [0usize; 3]; + for attempt in 0..45u32 { + let seed = 42 + attempt; + // mandelbrot's fractal detail plus a HARD cut at frame 4: half + // the picture becomes a flat white box, which no motion vector + // can predict, so aomenc's RD codes those blocks INTRA inside an + // inter frame. The box's vertical edge at x=48 is what makes the + // partition search reach for HORZ/VERT strips there. + // A FAST ZOOM: `end_scale`/`end_pts` make mandelbrot rush + // through its own zoom, so consecutive frames share almost no + // content and aomenc's RD codes blocks INTRA inside INTER frames + // (`--kf-min-dist=1000` forbids a new key frame). That is the + // only way a real encoder reaches this decoder's intra-in-inter + // arm; a slowly-evolving source codes every rect strip inter. + let source = format!( + "mandelbrot=size={width}x{height}:start_scale={}:end_scale=0.004:end_pts=8:rate=25", + 5.0 - f64::from(attempt) * 0.06 + ); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-vf", + "hue=s=0", + "-pix_fmt", + if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }, + "-strict", + "-1", + "-t", + "0.32", + "-f", + "yuv4mpegpipe", + "-strict", + "-1", + "-", + ]) + .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 depth_args: &[&str] = if bit_depth == 10 { + &["-b", "10", "--input-bit-depth=10"] + } else { + &[] + }; + // MEASURED (r1): the speed preset gates the feature (class + // [[gate-preset-gates-the-feature]]) -- at `--cpu-used=4` this + // content produces no rect partition at all, at `--cpu-used=0` + // aomenc emits AB partitions the tile path refuses (it ignores + // `--enable-ab-partitions=0`, ledger). So the attempt sweep walks + // the preset as well as the seed. + let cpu = format!("--cpu-used={}", attempt % 5); + // The quantiser drives how finely the RD partitions: the sweep + // walks it too, so "no rect strip fired" cannot be an artefact of + // one cq. + let cq = format!("--cq-level={}", [30u32, 20, 12][(attempt / 5) as usize % 3]); + let mut child = Command::new(aomenc_path()) + .args(depth_args) + .arg(&cpu) + .arg(&cq) + .args([ + // class [[aomenc-first-flag-wins]]: every flag is spelled + // exactly ONCE in this recipe, so there is no override to + // order. These four are what this gate is about. + "--enable-rect-partitions=1", + // MEASURED (r1): the charter's `--min-partition-size=8` + // makes 24/24 attempts stop at a sub-16 AB-partition + // refusal ("a HORZ_A/HORZ_B/VERT_A partition below 16x16", + // "a coded (non-skip) HORZ_B/VERT_B rect strip below + // 16x16") before any intra rect strip is reached -- those + // are other lanes' surfaces. 16 keeps the 16x8/8x16 shape + // reachable (a 16x16 block's own HORZ/VERT children). + "--min-partition-size=16", + "--max-partition-size=64", + // MEASURED (r1): with tx-size search ON, 24/24 attempts stop at + // the SQUARE intra-in-inter arm's own refusal ("an intra + // block in an inter frame whose tx_depth splits its luma + // transform (round 1)", read_block_tx_size) long before a + // rect strip is reached -- that arm is another lane's + // surface. OFF, no tx-depth symbol is coded at all and + // every rect strip here is the unsplit single-transform + // case. The SPLIT rect arm (`depth_to_tx_wh` + + // decode_rect_split's per-unit walk) is wired but stays + // UNGATED on this path until that square refusal lifts. + "--enable-tx-size-search=0", + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--lag-in-frames=0", + "--auto-alt-ref=0", + // One key frame at the head: the frames after the cut must + // stay INTER frames carrying intra blocks, not become a + // new key frame. + "--kf-min-dist=1000", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--enable-order-hint=0", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-dist-wtd-comp=0", + "--enable-diff-wtd-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + // The intra-in-inter arm reads no `use_filter_intra` + // symbol (square OR rect) -- lane-fiinter owns that read. + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = [ + decode::intra_rect_strip_in_inter_hits(0), + decode::intra_rect_strip_in_inter_hits(1), + decode::intra_rect_strip_in_inter_hits(2), + ]; + let kf_rect_before = decode::rect_partition_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "intra-rect-in-inter decode failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed} {cpu} {cq}: {msg}")); + continue; + } + }; + let delta = [ + decode::intra_rect_strip_in_inter_hits(0) - before[0], + decode::intra_rect_strip_in_inter_hits(1) - before[1], + decode::intra_rect_strip_in_inter_hits(2) - before[2], + ]; + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + eprintln!( + "intrarect gate {bit_depth}-bit seed={seed} {cpu} {cq}: intra rect strips in inter frames \ + 64-level={} 32-level={} 16-level={}, key-frame rect strips this stream={}", + delta[0], delta[1], delta[2], + decode::rect_partition_hits() - kf_rect_before + ); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + for (plane, (g, w)) in [ + ("Y", (&got.y, &want.y)), + ("U", (&got.u, &want.u)), + ("V", (&got.v, &want.v)), + ] { + let stride = if plane == "Y" { width } else { width / 2 }; + if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) { + eprintln!( + "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} first \ + diff at ({}, {}) got {} want {} ({} samples differ)", + at % stride, + at / stride, + g[at], + w[at], + g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(), + ); + // Magnitude separates a deblock/prediction difference + // (all |d| == 1) from an entropy desync (large, + // arbitrary): the first thing r2 needs to know. + let maxd = g + .iter() + .zip(w.iter()) + .map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b))) + .max() + .unwrap_or(0); + let rows: std::collections::BTreeSet = g + .iter() + .zip(w.iter()) + .enumerate() + .filter(|(_, (a, b))| a != b) + .map(|(k, _)| k / stride) + .collect(); + eprintln!( + "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} max \ + |diff|={maxd}, rows {:?}..{:?}", + rows.iter().next(), + rows.iter().next_back() + ); + } + assert_eq!(g, w, "{plane} vs ffmpeg (seed {seed}, frame {i})"); + } + } + compared += 1; + if delta.iter().all(|d| *d == 0) { + uncounted_exact += 1; + refusals.push(format!( + "seed {seed} {cpu} {cq}: decoded and pixel-compared, but no intra rect strip on the \ + inter path" + )); + } + for k in 0..3 { + shapes[k] += delta[k]; + } + if shapes.iter().filter(|n| **n > 0).count() >= 2 { + break; + } + } + gate_buckets( + NAME, + compared - uncounted_exact, + uncounted_exact, + refusals.len() - uncounted_exact as usize, + ); + eprintln!( + "{NAME} ({bit_depth}-bit): compared {compared} streams, intra rect strips in inter \ + frames per shape: 64x32/32x64={} 32x16/16x32={} 16x8/8x16={}; refusals:\n{}", + shapes[0], + shapes[1], + shapes[2], + refusals.join("\n") + ); + assert!( + compared > 0, + "{NAME} ({bit_depth}-bit): every attempt hit a named refusal -- nothing was \ + pixel-compared:\n{}", + refusals.join("\n") + ); + // MEASURED (r1, 90 attempts; r2 re-ran the 45-attempt sweep at both + // depths): only the 32x16/16x32 class is REACHABLE on this branch -- + // the inter tile path refuses any SB-level partition other than + // NONE/SPLIT, so a 64x32/32x64 intra strip cannot be produced at all, + // and every 16x8/8x16 candidate stops at a sub-16 refusal owned by + // another lane. So the bar is that class, hard, not "two of three": + // a green run still cannot come from a stream that fired nothing. + assert!( + shapes[1] > 0, + "{NAME} ({bit_depth}-bit): no 32x16/16x32 intra rect strip fired over \ + {compared} compared streams (64-level={} 32-level={} 16-level={})", + shapes[0], + shapes[1], + shapes[2] + ); + } + fn tx_select_inter_gate(bit_depth: u32) { if !have_ffmpeg() { eprintln!( @@ -6233,10 +6559,21 @@ mod tests { // NON-skip, so it stops at "a non-skip rectangular (HORZ/VERT/HORZ_B) // strip needs rectangular residual coding". The 10-bit twin below is // `#[ignore]`d with that exact reason rather than deleted or weakened. + // lane-r14 r2 re-measured the 8-bit-only note above: the residual + // refusal it names is GONE (this round codes a 64-px transform axis as + // its truncated low-32 corner), and a 10-bit sweep of this exact + // recipe now reaches the arm -- 2 pixel-exact attempts, 2 64x32 and 2 + // 32x64 strips, 2 of them carrying a coded 64-axis residual. It stays + // 8-bit here for a DIFFERENT, newly exposed reason: 10-bit attempt 14 + // (cq 61, horizontal split, motion step 12) mismatches ffmpeg while + // decoding ZERO superblock-level rect strips and zero 64-axis + // residual units, i.e. a defect of some other shape that this gate + // must not absorb. See lanes/r14-r2.report.md. for bit_depth in [8u32] { let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) = (0u32, 0u32, 0u32, 0u32); let (mut horz_proved, mut vert_proved) = (0usize, 0usize); + let mut rect64_tus = 0usize; for attempt in 0..16u32 { // Two orientations (the transposed pair a one-sided gate could // never separate) x four quantisers x two motion steps: which @@ -6309,6 +6646,7 @@ mod tests { ); let stream = out.stdout; let before = crate::stream::inter_rect_counters(); + let rect64_before = crate::stream::rect64_inter_tu_hits(); let frames = match decode_stream(&stream) { Err(e) => { let msg = e.to_string(); @@ -6325,6 +6663,7 @@ mod tests { }; let after = crate::stream::inter_rect_counters(); let (horz, vert) = (after.2 - before.2, after.3 - before.3); + let rect64 = crate::stream::rect64_inter_tu_hits() - rect64_before; let ffmpeg_frames = if bit_depth == 10 { ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) } else { @@ -6353,11 +6692,13 @@ mod tests { } horz_proved += horz; vert_proved += vert; + rect64_tus += rect64; matched += 1; } eprintln!( "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \ attempts carrying the arm, 64x32 strips={horz_proved}, 32x64 strips={vert_proved}, \ + 64-axis residual TUs={rect64_tus}, \ {out_of_scope} attempts carried none ({oos_mismatch} of them mismatched)" ); assert_eq!( @@ -6365,6 +6706,15 @@ mod tests { "{NAME}: {oos_mismatch} attempt(s) with no superblock-level inter rect strip \ decoded but mismatched ffmpeg -- a defect of another shape, not a pass" ); + // lane-r14 r2: the residual half of the arm -- a strip that is not + // `skip` and codes a real 64-axis transform unit. Without this the + // gate proves only the partition symbol. + assert!( + rect64_tus > 0, + "{NAME} ({bit_depth}-bit): no superblock-level rect strip carried a coded \ + 64-axis residual transform unit inside a pixel-exact attempt \ + (horz={horz_proved}, vert={vert_proved}) -- the residual arm proved nothing" + ); assert!( horz_proved + vert_proved > 0, "{NAME} ({bit_depth}-bit): the superblock-level inter rect arm never fired \ @@ -13290,6 +13640,7 @@ mod tests { "--cpu-used=4", "--aq-mode=0", "--deltaq-mode=0", + "--enable-cdef=0", "--kf-max-dist=1000", "--threads=1", "--row-mt=0", @@ -16718,6 +17069,7 @@ mod tests { "--cpu-used=4", &aq, "--deltaq-mode=0", + "--enable-cdef=0", "--kf-max-dist=1000", "--threads=1", "--row-mt=0", @@ -17447,21 +17799,28 @@ mod tests { ); } - /// lane-sbpart r2: a real `aomenc` stream whose superblock-level - /// partition decision is genuinely HORZ/VERT (not NONE/SPLIT) must - /// decode pixel-exact through [`crate::decode::decode_block_rect64`] -- - /// `sb_rect_hits() > 0` is a HARD assert (this round's rule: a removed - /// refusal needs a firing gate in the same commit, not a green suite - /// that never took the new path). Recipe = the charter's own, verified - /// live by r1: `--min/max-partition-size=32/64` keeps the RD search - /// from ever recursing below 32x32, so every SB-level decision is - /// genuinely NONE/SPLIT/HORZ/VERT; a `gradients` source blended with - /// `testsrc2` (lavfi `blend=all_mode=average`) keeps the content from - /// being flat enough that the search stops at NONE every time. + /// lane-sb128 r1 gate: a real `aomenc --sb-size=128` stream (the size his + /// ReelC encode uses -- `EC_TRACE=1 aomdec reelc-head.obu` prints + /// `EC_PART mi_row=0 mi_col=0 bsize=15` = `BLOCK_128X128`) must decode + /// pixel-exact. `--max-partition-size=64` keeps the RD search from ever + /// choosing a 128-level NONE/HORZ/VERT/AB arm, so every 128 root here is + /// genuinely `PARTITION_SPLIT` -- the one arm + /// `decode_key_frame_tile_with_cdfs` codes; the other seven refuse by + /// name (`PART128_NON_SPLIT_REFUSAL`) and stay refused after this round. + /// + /// What the 128 root actually changes, and what this gate therefore + /// proves: the 8-symbol `partition_w128` CDF and its forced-split gather + /// at the frame edge, the quadrant VISIT ORDER (TL, TR, BL, BR inside one + /// superblock, not raster over 64x64 superblocks), one loop-restoration + /// read per 128x128 instead of per 64x64, `delta_q`/`delta_lf` once per + /// 128x128, and the per-64x64 `cdef_idx` read inside the 128 superblock. + /// 256x192 gives a 2x2 grid of 128 superblocks whose bottom row is a + /// partial superblock (the gathered forced-split read); 384x384 gives a + /// 3x3 grid of whole ones. 8-bit sweep plus one 10-bit stream (his films + /// are `yuv420p10le`). Only a missing tool SKIPs. #[test] - fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact() { - const NAME: &str = - "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact"; + fn a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact"; let _gate_lock = lock_gate_counters(); if !have_ffmpeg() { eprintln!("SKIP {NAME}: no ffmpeg"); @@ -17471,35 +17830,439 @@ mod tests { eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); return; } - let (width, height, frame_count) = (192usize, 128usize, 1usize); - let mut named_refusals = 0u32; - let mut matched = 0u32; - let n_attempts: u32 = std::env::var("EC_SBPART_GATE_ATTEMPTS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(40); - for attempt in 0..n_attempts { - let seed = 42 + attempt; - let duration = frame_count as f64 / 25.0; - let source = - gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); - let y4m = Command::new("ffmpeg") - .args([ - "-v", - "error", - "-f", - "lavfi", - "-i", - &source, - "-pix_fmt", - "yuv420p", - "-f", - "yuv4mpegpipe", - "-", - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) + let base: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=40", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=128", + "--max-partition-size=64", + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + // aomenc emits PARTITION_HORZ_4/VERT_4 below 16x16 even with the + // flag off (ledger, lane-modectx r1), so bound the search instead. + "--min-partition-size=16", + "--enable-restoration=1", + "--enable-palette=0", + "--deltaq-mode=0", + "--enable-intrabc=0", + "--enable-tx-size-search=0", + "--limit=1", + ]; + let encode = |y4m: &[u8], extra: &[&str]| -> Vec { + let mut args = base.clone(); + args.extend_from_slice(extra); + args.extend_from_slice(&["--obu", "-o", "-", "-"]); + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(y4m) + .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 render = |seed: u32, width: usize, height: usize, ten_bit: bool| -> Vec { + let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; + let out = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &gradients_source(seed, width, height, "duration=0.04:rate=25"), + "-pix_fmt", + pix, + "-strict", + "-1", + "-t", + "0.04", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + out.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + out.stdout + }; + let mut matched = 0u32; + let mut named_refusals = 0u32; + // (seed, width, height, 10-bit): 256x192 = 2x2 superblocks with a + // partial bottom row; 384x384 = 3x3 whole ones. + let arms: Vec<(u32, usize, usize, bool)> = vec![ + (42, 256, 192, false), + (43, 256, 192, false), + (44, 256, 192, false), + (45, 384, 384, false), + (46, 256, 192, true), + (47, 384, 384, true), + ]; + for (seed, width, height, ten_bit) in arms { + let y4m = render(seed, width, height, ten_bit); + let extra: Vec<&str> = if ten_bit { + vec!["--input-bit-depth=10", "--bit-depth=10"] + } else { + vec![] + }; + let stream = encode(&y4m, &extra); + let parsed = { + let mut parser = ec_av1_syntax::Av1Parser::new(); + let mut pos = 0usize; + while let Ok(obu) = parser.parse_obu(&stream[pos..]) { + pos += obu.total_size; + if pos >= stream.len() { + break; + } + } + parser + .sequence_header() + .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth)) + }; + assert_eq!( + parsed, + Some((true, if ten_bit { 10 } else { 8 })), + "{NAME} (seed {seed}): the encoder did not write a 128x128-superblock \ + sequence header at the requested bit depth -- the flag never arrived" + ); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" + ); + named_refusals += 1; + eprintln!("seed {seed} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let want = if ten_bit { + ffmpeg_decode_sequence_10bit(&stream, width, height, 1) + } else { + ffmpeg_decode_sequence(&stream, width, height, 1) + }; + assert_eq!(frames.len(), 1); + for (i, (got, want)) in frames.iter().zip(&want).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); + } + matched += 1; + } + assert!( + matched > 0, + "{NAME}: every attempt refused; the gate never decoded a stream" + ); + // 256x192 codes 3 whole + 1 partial superblock, 384x384 codes 9 whole + // ones, so a run that decoded anything at all must have read real 128 + // partition symbols and split every one of them. + assert!( + crate::decode::part128_symbols() >= 3 * matched as usize, + "{NAME}: only {} 128-level partition symbols over {matched} decoded streams -- \ + the 128 root never fired", + crate::decode::part128_symbols() + ); + assert!( + crate::decode::part128_split_hits() >= 4 * matched as usize, + "{NAME}: only {} 128 superblocks split", + crate::decode::part128_split_hits() + ); + eprintln!( + "{NAME}: {matched} pixel-exact, {named_refusals} named refusals, \ + part128_symbols={} part128_split_hits={}", + crate::decode::part128_symbols(), + crate::decode::part128_split_hits() + ); + } + + #[test] + #[ignore = "lane-sb128 r2 diagnostic: is the frame-6 mismatch sb128-specific?"] + fn sb128_r2_control_sb64() { + let (width, height) = (256usize, 192usize); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", + &format!( + "{},noise=all_seed=53:alls=12:allf=t", + gradients_source(53, width, height, "duration=0.32:rate=25") + ), + "-pix_fmt", "yuv420p", "-t", "0.32", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .output() + .expect("ffmpeg"); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=40", + "--cpu-used=2", "--threads=1", "--row-mt=0", "--sb-size=64", + "--max-partition-size=64", "--min-partition-size=32", + "--enable-rect-partitions=0", "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", "--enable-palette=0", + "--enable-intrabc=0", "--enable-tx-size-search=0", + "--deltaq-mode=0", "--limit=8", "--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().expect("aomenc run"); + assert!(out.status.success()); + let (frames, hidden) = decode_all_frames_vs_oracle(&out.stdout, "sb128-control-64"); + eprintln!("control sb64: {frames} frames exact ({hidden} hidden)"); + } + + /// lane-sb128 r2: an INTER SEQUENCE under a 128x128 superblock -- the + /// half ReelC is made of. r1 refused it by name (the inter tile loop + /// recursed a 64x64 root only); r2 ported `sb_visit_order` and the 128 + /// root (per-superblock `read_lr`, the 8-symbol `partition_w128` read with + /// its edge gather, `delta_q`/`delta_lf` at 128 granularity) into that + /// loop, so this gate replaces the refusal test. + /// + /// Every frame in DECODE order, hidden alt-refs included + /// ([`decode_all_frames_vs_oracle`], class gate-blind-to-hidden-frames): + /// `--lag-in-frames` is left at aomenc's default so the encoder really + /// emits them. Per-ATTEMPT counter deltas are hard asserts (class + /// counter-from-refused-stream: the helper panics on any refusal, so every + /// counted attempt is a compared one): 128 partition roots read on this + /// stream, `cdef_idx` reads (one per 64x64 quadrant inside the 128 + /// superblock), and temporal MV candidates (the inter-only path). Both bit + /// depths -- his films are `yuv420p10le`. Only a missing tool SKIPs. + #[test] + fn a_real_aomenc_inter_sequence_with_128x128_superblocks_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_inter_sequence_with_128x128_superblocks_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() || !have_aomenc() { + eprintln!("SKIP {NAME}: no ffmpeg/aomenc/aomdec"); + return; + } + let (width, height) = (256usize, 192usize); + for ten_bit in [false, true] { + let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &format!( + // Noise on top of the gradient is what makes aomenc + // signal a nonzero `cdef_bits` (a clean gradient codes + // with CDEF off, and the cdef_idx counter stays 0). + "{},noise=all_seed=53:alls=12:allf=t", + gradients_source(53, width, height, "duration=0.32:rate=25") + ), + "-pix_fmt", + pix, + "-strict", + "-1", + "-t", + "0.32", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=40", + "--cpu-used=2", + "--threads=1", + "--row-mt=0", + "--sb-size=128", + "--max-partition-size=64", + // aomenc emits PARTITION_HORZ_4/VERT_4 below 16x16 even with + // the flag off (ledger, lane-modectx r1), so bound the search. + "--min-partition-size=32", + // The inter path still refuses rectangular strips ("a non-skip + // rectangular (HORZ/VERT/HORZ_B) strip needs rectangular + // residual coding") -- another lane's gap, off here so this + // gate measures the 128 root and nothing else. + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-tx-size-search=0", + "--deltaq-mode=0", + "--limit=8", + ]; + if ten_bit { + args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); + } + args.extend_from_slice(&["--obu", "-o", "-", "-"]); + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "{NAME}: aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let header = { + let mut parser = ec_av1_syntax::Av1Parser::new(); + let mut pos = 0usize; + while let Ok(obu) = parser.parse_obu(&stream[pos..]) { + pos += obu.total_size; + if pos >= stream.len() { + break; + } + } + parser + .sequence_header() + .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth)) + }; + assert_eq!( + header, + Some((true, if ten_bit { 10 } else { 8 })), + "{NAME}: the encoder did not write a 128x128-superblock sequence header at \ + the requested bit depth -- the flag never arrived" + ); + let before = ( + crate::decode::part128_symbols(), + crate::decode::cdef_idx_hits(), + crate::decode::tmv_hits(), + ); + let (frames, hidden) = decode_all_frames_vs_oracle( + &stream, + &format!("sb128-inter-{}", if ten_bit { 10 } else { 8 }), + ); + let (part128, cdef_idx, tmv) = ( + crate::decode::part128_symbols() - before.0, + crate::decode::cdef_idx_hits() - before.1, + crate::decode::tmv_hits() - before.2, + ); + assert!( + frames >= 6, + "{NAME} ({pix}): only {frames} frames in decode order, the recipe asks for 8" + ); + assert!( + part128 >= 3, + "{NAME} ({pix}): only {part128} 128-level partition symbols on this stream -- \ + the 128 root never fired on the inter frames" + ); + assert!( + cdef_idx >= 1, + "{NAME} ({pix}): no cdef_idx read -- the per-64x64-quadrant cdef read inside \ + the 128 superblock never fired" + ); + assert!( + tmv >= 1, + "{NAME} ({pix}): no temporal MV candidate -- the inter path never ran" + ); + eprintln!( + "{NAME} ({pix}): {frames} decode-order frames pixel-exact ({hidden} hidden), \ + part128_symbols={part128} cdef_idx_hits={cdef_idx} tmv_hits={tmv}" + ); + } + } + + /// lane-sbpart r2: a real `aomenc` stream whose superblock-level + /// partition decision is genuinely HORZ/VERT (not NONE/SPLIT) must + /// decode pixel-exact through [`crate::decode::decode_block_rect64`] -- + /// `sb_rect_hits() > 0` is a HARD assert (this round's rule: a removed + /// refusal needs a firing gate in the same commit, not a green suite + /// that never took the new path). Recipe = the charter's own, verified + /// live by r1: `--min/max-partition-size=32/64` keeps the RD search + /// from ever recursing below 32x32, so every SB-level decision is + /// genuinely NONE/SPLIT/HORZ/VERT; a `gradients` source blended with + /// `testsrc2` (lavfi `blend=all_mode=average`) keeps the content from + /// being flat enough that the search stops at NONE every time. + #[test] + fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_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, frame_count) = (192usize, 128usize, 1usize); + let mut named_refusals = 0u32; + let mut matched = 0u32; + let n_attempts: u32 = std::env::var("EC_SBPART_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(40); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + let duration = frame_count as f64 / 25.0; + let source = + gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) .output() .expect("ffmpeg failed to run"); assert!( @@ -17524,6 +18287,7 @@ mod tests { "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-cdef=0", "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", @@ -18170,6 +18934,7 @@ mod tests { "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-cdef=0", "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", @@ -18376,6 +19141,7 @@ mod tests { "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-cdef=0", "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", @@ -18630,6 +19396,7 @@ mod tests { "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-cdef=0", // The point of this gate. "--enable-filter-intra=1", // NOTE (lane-rectsplit r2, verifier finding): every intra @@ -18801,6 +19568,7 @@ mod tests { "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-cdef=0", "--enable-filter-intra=1", "--enable-cfl-intra=0", "--enable-intrabc=0", @@ -18996,6 +19764,7 @@ mod tests { "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-cdef=0", "--enable-filter-intra=1", "--enable-cfl-intra=0", "--enable-intrabc=0", @@ -19194,6 +19963,7 @@ mod tests { "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-cdef=0", "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", @@ -19370,6 +20140,7 @@ mod tests { "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-cdef=0", "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", @@ -19833,6 +20604,7 @@ mod tests { "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-cdef=0", "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", @@ -19877,98 +20649,344 @@ mod tests { eprintln!("seed {seed} refusal: {msg}"); continue; } - Ok(frames) => frames, - }; - let (horz, vert) = ( - crate::decode::sb_rect4_horz_hits() - before.0, - crate::decode::sb_rect4_vert_hits() - before.1, - ); - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); - assert_eq!(frames.len(), frame_count); - let mismatched = frames - .iter() - .zip(&ffmpeg_frames) - .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); - if horz + vert == 0 { - // Out of this gate's territory: aomenc's RD picked no 1:4 - // partition at all for this seed, so the attempt can neither - // prove nor disprove the arms under test. NOT silently - // dropped -- counted and printed, and a mismatch here is - // reported as a defect of another lane's shape (r1 found - // one: seed 55 of this very recipe decodes 3944 wrong luma - // samples with zero 1:4 blocks in the stream, first at - // (154, 59), inside the 64x32 `PARTITION_HORZ` superblock at - // (128, 64) -- see lanes/tx64x16-r1.report.md). Selecting on - // "the stream contains the feature", never on "the stream - // decoded correctly", is what keeps this from being survivor - // bias. - out_of_scope += 1; - if mismatched { - out_of_scope_mismatch += 1; + Ok(frames) => frames, + }; + let (horz, vert) = ( + crate::decode::sb_rect4_horz_hits() - before.0, + crate::decode::sb_rect4_vert_hits() - before.1, + ); + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if horz + vert == 0 { + // Out of this gate's territory: aomenc's RD picked no 1:4 + // partition at all for this seed, so the attempt can neither + // prove nor disprove the arms under test. NOT silently + // dropped -- counted and printed, and a mismatch here is + // reported as a defect of another lane's shape (r1 found + // one: seed 55 of this very recipe decodes 3944 wrong luma + // samples with zero 1:4 blocks in the stream, first at + // (154, 59), inside the 64x32 `PARTITION_HORZ` superblock at + // (128, 64) -- see lanes/tx64x16-r1.report.md). Selecting on + // "the stream contains the feature", never on "the stream + // decoded correctly", is what keeps this from being survivor + // bias. + out_of_scope += 1; + if mismatched { + out_of_scope_mismatch += 1; + eprintln!( + "{NAME}: seed {seed} MISMATCHES with zero 1:4 blocks -- a pre-existing \ + defect of another shape, not this gate's arms" + ); + } + continue; + } + if mismatched { + if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); + } + horz_proved += horz; + vert_proved += vert; + matched += 1; + } + assert!( + matched > 0, + "{NAME}: every attempt refused; the gate never decoded a stream" + ); + assert!( + horz_proved > 0 && vert_proved > 0, + "{NAME}: a 1:4 arm never fired inside a pixel-exact attempt \ + (horz={horz_proved}, vert={vert_proved}, {matched} matches, {named_refusals} \ + refusals out of {n_attempts}) -- gate proved nothing this run" + ); + eprintln!( + "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \ + {n_attempts}, horz_4 strips={horz_proved}, vert_4 strips={vert_proved}, \ + {out_of_scope} attempts carried no 1:4 block ({out_of_scope_mismatch} of them \ + mismatched -- other lanes' shapes)" + ); + // Class gate-skips-on-its-own-failure: an attempt that decoded but + // does not carry this gate's shape is still a decode this crate got + // wrong. Counted separately so the message names the other shape, + // never tolerated. + assert_eq!( + out_of_scope_mismatch, 0, + "{NAME}: {out_of_scope_mismatch} attempt(s) with no 1:4 block decoded but \ + mismatched ffmpeg -- a defect of another shape, not a pass" + ); + } + + /// lane-tx64x16 r3: the 32x32-LEVEL 1:4 pair -- `PARTITION_HORZ_4` / + /// `PARTITION_VERT_4` at 32x32, i.e. four 32x8 / 8x32 strips, the arm the + /// ReelB mid-film extract stops at ("a 32x32 partition type this + /// decoder does not code (value=8)"). `--min-partition-size=8` is what + /// lets aomenc's RD reach the 32-level 1:4 shapes; `--max-partition-size=32` + /// keeps the superblock-level pair (already gated by its own test above) + /// out of the counters. Both orientations HARD-asserted per bit depth -- + /// the luma scans and the two new chroma scans (`SCAN_16X4`/`SCAN_4X16`) + /// are transposed pairs, so a one-sided gate cannot catch a transposition + /// (class scan-weights-cross-axis). `rect4_coeff_hits` is asserted too: + /// an all-skip stream would exercise none of the new coefficient tables + /// (class gate-blind-to-feature). Only hits earned inside an attempt that + /// then compared pixel-exact are counted (class + /// gate-skips-on-its-own-failure); the 10-bit arm is what retires + /// `enable-1to4-partitions` from `NEVER_EXERCISED_10BIT`. + /// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or + /// 4x16 (`PARTITION_VERT_4`) strips, the shape the wall + /// "a 1:4 partition below 16x16" refused. Fixture: 4-PIXEL bands (the + /// 8-pixel ones of the 32-level gate above, one size down -- a 16x4 strip + /// is flat where a 16x8 one is not), transposed per attempt so a + /// transposed scan or nz-map table cannot pass (class + /// scan-weights-cross-axis), plus an explicit-seed noise layer that keeps + /// aomenc out of screen-content mode. `--enable-filter-intra=1` and + /// is ON: this shape reads `use_filter_intra` off its own CDF rows + /// (classes 12/13). The `--enable-tx-size-search=1` half of the window + /// splits the strip's transform (depth 1 = TX_8X4/TX_4X8, depth 2 = + /// TX_4X4). + /// + /// Counters: 16x4 strips, 4x16 strips, chroma-reference strips (the odd + /// strip of each 4:2:0 pair, the only one that codes chroma) and strips + /// with a coded residual must all be nonzero over the compared attempts, + /// and only attempts that DECODED and were compared pixel-exact count + /// (class gate-skips-on-its-own-failure). + #[test] + fn a_real_aomenc_stream_with_a_16_level_1to4_partition_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_with_a_16_level_1to4_partition_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, frame_count) = (192usize, 128usize, 1usize); + let n_attempts: u32 = std::env::var("EC_R14_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(8); + for bit_depth in [8u32, 10u32] { + let mut named_refusals = 0u32; + let mut matched = 0u32; + let (mut horz_proved, mut vert_proved) = (0usize, 0usize); + let (mut chroma_proved, mut coeff_proved) = (0usize, 0usize); + let mut split_proved = 0usize; + let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32); + // The second half of the window turns `--enable-tx-size-search` on: + // that is what makes a 16x4 strip SPLIT its transform (depth 1 = + // TX_8X4, depth 2 = TX_4X4), the arm the first half never reaches. + for attempt in 0..n_attempts * 2 { + let tx_search = attempt >= n_attempts; + let attempt = attempt % n_attempts; + let seed = 42 + attempt; + let duration = frame_count as f64 / 25.0; + let axis = if attempt % 2 == 0 { "Y" } else { "X" }; + let step = 67 + (attempt / 2) * 12; + let noise = 6 + (attempt % 4) * 3; + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='mod(floor({axis}/4)*{step},256)',\ + noise=alls={noise}:all_seed={seed},format=yuv420p" + ); + let cq_level = format!("--cq-level={}", 24 + (attempt % 4) * 8); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &cq_level, + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + &depth_arg, + &input_depth_arg, + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=1", + "--min-partition-size=4", + "--max-partition-size=16", + "--enable-restoration=0", + "--enable-palette=0", + "--deltaq-mode=0", + "--enable-filter-intra=1", + // lane-r14: CfL stays OFF here. This shape's CfL averages + // the luma of the whole PAIR and is written, but no gate + // asserts a CfL hit counter (there is none), and passing + // `=1` would retire `enable-cfl-intra` from + // `gate_coverage::NEVER_EXERCISED_*` on a flag alone -- + // exactly the false coverage that list exists to prevent. + "--enable-cfl-intra=0", + "--enable-intrabc=0", + if tx_search { + "--enable-tx-size-search=1" + } else { + "--enable-tx-size-search=0" + }, + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = crate::decode::rect4_16_counters(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal ({bit_depth}-bit, seed \ + {seed}): {msg}" + ); + named_refusals += 1; + eprintln!("{bit_depth}-bit seed {seed} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let now = crate::decode::rect4_16_counters(); + let (horz, vert, chroma, coeff, split) = ( + now.0 - before.0, + now.1 - before.1, + now.2 - before.2, + now.3 - before.3, + now.4 - before.4, + ); + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if horz + vert == 0 { + out_of_scope += 1; + if mismatched { + out_of_scope_mismatch += 1; + eprintln!( + "{NAME}: {bit_depth}-bit seed {seed} MISMATCHES with zero 16-level \ + 1:4 strips -- a pre-existing defect of another shape" + ); + } + continue; + } + if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); eprintln!( - "{NAME}: seed {seed} MISMATCHES with zero 1:4 blocks -- a pre-existing \ - defect of another shape, not this gate's arms" + "EC_AV1_GATE_DUMP: wrote mismatching stream ({bit_depth}-bit, seed \ + {seed}) to {path}" ); } - continue; - } - if mismatched { - if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { - std::fs::write(&path, &stream).expect("writing pinned stream"); - eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!( + got.y, want.y, + "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit, seed {seed})" + ); + assert_eq!( + got.u, want.u, + "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit, seed {seed})" + ); + assert_eq!( + got.v, want.v, + "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit, seed {seed})" + ); } + horz_proved += horz; + vert_proved += vert; + chroma_proved += chroma; + coeff_proved += coeff; + split_proved += split; + matched += 1; } - for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); - assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); - assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); - } - horz_proved += horz; - vert_proved += vert; - matched += 1; + assert!( + matched > 0, + "{NAME}: every {bit_depth}-bit attempt refused or fell out of scope ({named_refusals} \ + refusals, {out_of_scope} out of scope); the gate proved nothing" + ); + assert_eq!( + out_of_scope_mismatch, 0, + "{NAME}: {out_of_scope_mismatch} {bit_depth}-bit attempt(s) mismatch with no \ + 16-level 1:4 strip at all" + ); + assert!( + horz_proved > 0 && vert_proved > 0, + "{NAME}: {bit_depth}-bit compared attempts decoded {horz_proved} 16x4 and \ + {vert_proved} 4x16 strips -- both orientations must fire or a transposed table \ + passes" + ); + assert!( + chroma_proved > 0, + "{NAME}: {bit_depth}-bit compared attempts closed {chroma_proved} chroma pairs" + ); + assert!( + coeff_proved > 0, + "{NAME}: {bit_depth}-bit compared attempts coded no residual on any strip" + ); + assert!( + split_proved > 0, + "{NAME}: {bit_depth}-bit compared attempts never split a strip's transform -- \ + the `--enable-tx-size-search=1` half of the window proved nothing" + ); + eprintln!( + "{NAME}: {bit_depth}-bit {matched} compared attempts, {horz_proved} 16x4 / \ + {vert_proved} 4x16 strips, {chroma_proved} chroma pairs, {coeff_proved} coded \ + units, {split_proved} split-transform strips, {named_refusals} refusals, \ + {out_of_scope} out of scope" + ); } - assert!( - matched > 0, - "{NAME}: every attempt refused; the gate never decoded a stream" - ); - assert!( - horz_proved > 0 && vert_proved > 0, - "{NAME}: a 1:4 arm never fired inside a pixel-exact attempt \ - (horz={horz_proved}, vert={vert_proved}, {matched} matches, {named_refusals} \ - refusals out of {n_attempts}) -- gate proved nothing this run" - ); - eprintln!( - "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \ - {n_attempts}, horz_4 strips={horz_proved}, vert_4 strips={vert_proved}, \ - {out_of_scope} attempts carried no 1:4 block ({out_of_scope_mismatch} of them \ - mismatched -- other lanes' shapes)" - ); - // Class gate-skips-on-its-own-failure: an attempt that decoded but - // does not carry this gate's shape is still a decode this crate got - // wrong. Counted separately so the message names the other shape, - // never tolerated. - assert_eq!( - out_of_scope_mismatch, 0, - "{NAME}: {out_of_scope_mismatch} attempt(s) with no 1:4 block decoded but \ - mismatched ffmpeg -- a defect of another shape, not a pass" - ); } - /// lane-tx64x16 r3: the 32x32-LEVEL 1:4 pair -- `PARTITION_HORZ_4` / - /// `PARTITION_VERT_4` at 32x32, i.e. four 32x8 / 8x32 strips, the arm the - /// ReelB mid-film extract stops at ("a 32x32 partition type this - /// decoder does not code (value=8)"). `--min-partition-size=8` is what - /// lets aomenc's RD reach the 32-level 1:4 shapes; `--max-partition-size=32` - /// keeps the superblock-level pair (already gated by its own test above) - /// out of the counters. Both orientations HARD-asserted per bit depth -- - /// the luma scans and the two new chroma scans (`SCAN_16X4`/`SCAN_4X16`) - /// are transposed pairs, so a one-sided gate cannot catch a transposition - /// (class scan-weights-cross-axis). `rect4_coeff_hits` is asserted too: - /// an all-skip stream would exercise none of the new coefficient tables - /// (class gate-blind-to-feature). Only hits earned inside an attempt that - /// then compared pixel-exact are counted (class - /// gate-skips-on-its-own-failure); the 10-bit arm is what retires - /// `enable-1to4-partitions` from `NEVER_EXERCISED_10BIT`. #[test] // lane-tx64x16 r4: the fixture r3 could not find. `gradients` never wins // a 32-level 1:4 shape; 8-pixel BANDS do -- each 32x8 strip is flat, so @@ -21181,6 +22199,7 @@ mod tests { "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-cdef=0", "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", @@ -21437,4 +22456,171 @@ mod tests { yuv420p10le)" ); } + + /// lane-hgkf r1: a frame whose height (or width) is not a multiple of the + /// block size makes the last superblock row (column) read a GATHERED + /// partition bit instead of a full alphabet symbol -- and libaom's + /// `ec_read_partition_impl` answers that bit with `PARTITION_HORZ` + /// (resp. `VERT`) when it is 0, only `SPLIT` when it is 1. All three + /// key-frame edge readers (64-, 32- and 16-level) read the bit and threw + /// it away, forcing SPLIT; every such frame desynced at the first block + /// of its partial row. 192x136 / 136x192 is the smallest shape that hits + /// all three levels at once (136 = 2*64 + 8, so mi_rows = 34: the 64-, + /// 32- and 16-level halves all fall outside), and it is the shape of a + /// real 3840x1608 10-bit film key frame (1608 mod 64 == 8) that decoded + /// 51768 samples wrong before this round. + /// + /// The counter is sampled per attempt and read only on an attempt that + /// decoded AND is pixel-compared; slot 0/2 (the bit taken as HORZ/VERT) + /// must be nonzero or the gate proves nothing -- before this round that + /// arm was unreachable by construction. + #[test] + fn a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_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 mut compared = 0usize; + let mut edge_horz_total = 0usize; + let mut edge_sub_total = 0usize; + // The last two shapes are the ledger-measured 64-level pair: on a + // flat band (192x80 / 80x192) real aomenc answers the bottom-edge + // superblock with the 64-level HORZ/VERT, which the 136 shapes above + // never produce (their SBs always split down to the 32/16 levels). + for (width, height, flat) in [ + (192usize, 136usize, false), + (136usize, 192usize, false), + (192usize, 80usize, true), + (80usize, 192usize, true), + ] { + for depth in [8usize, 10] { + let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", + &if flat { + format!("color=c=gray:size={width}x{height}") + } else { + format!("mandelbrot=size={width}x{height}:start_x=-0.6") + }, + "-pix_fmt", pix, "-strict", "-1", "-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(), + "{NAME}: ffmpeg fixture ({width}x{height}, depth={depth}): {}", + 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=32", + "--cpu-used=3", "--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", "--reduced-tx-type-set=1", + "--min-partition-size=8", "--max-partition-size=64", + &format!("--input-bit-depth={depth}"), + &format!("--bit-depth={depth}"), + "--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 ({width}x{height}, depth={depth}): {}", + String::from_utf8_lossy(&out.stderr) + ); + out.stdout + }; + let stream = encode(); + assert_eq!( + stream, + encode(), + "{NAME}: aomenc output is not reproducible ({width}x{height}, depth={depth})" + ); + crate::decode::reset_edge_part_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME}: decode failed ({width}x{height}, depth={depth}): {msg}" + ); + eprintln!( + "{NAME}: {width}x{height} depth={depth} arm refused (not compared): {msg}" + ); + continue; + } + }; + let hits = crate::decode::edge_part_hits(); + let ffmpeg_frames = if depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) + } else { + ffmpeg_decode_sequence(&stream, width, height, frames.len()) + }; + 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 ({width}x{height}, depth={depth}, \ + edge bits horz/split 64-level {}/{}, sub-level {}/{})", + hits[0], hits[1], hits[2], hits[3] + ); + assert_eq!( + got.u, want.u, + "{NAME} frame {i} U vs ffmpeg ({width}x{height}, depth={depth})" + ); + assert_eq!( + got.v, want.v, + "{NAME} frame {i} V vs ffmpeg ({width}x{height}, depth={depth})" + ); + } + compared += 1; + edge_horz_total += hits[0]; + edge_sub_total += hits[2]; + eprintln!( + "{NAME}: pixel-exact {width}x{height} at {depth}-bit, edge bits \ + 64-level horz/vert={} split={} sub-level horz/vert={} split={}", + hits[0], hits[1], hits[2], hits[3] + ); + } + } + assert!( + compared > 0, + "{NAME}: every arm refused -- the gate compared no pixels at all" + ); + assert!( + edge_horz_total > 0, + "{NAME}: no 64-level frame-edge bit was ever answered HORZ/VERT -- the arm this \ + round fixed never fired" + ); + assert!( + edge_sub_total > 0, + "{NAME}: no 32/16-level frame-edge bit was ever answered HORZ/VERT" + ); + } } diff --git a/lanes/hgkf-r1.report.md b/lanes/hgkf-r1.report.md new file mode 100644 index 00000000..7746e27e --- /dev/null +++ b/lanes/hgkf-r1.report.md @@ -0,0 +1,86 @@ +# lane-hgkf r1 — the frame-edge partition bit, all three levels + +Branch `lane-hgkf` off main `0df090a`. Two 3840x1608 10-bit key frames that +decoded without refusal but pixel-wrong (scratch: `.../scratchpad/census2/kf_0.obu`, +`kf_4500.obu`). + +## Root cause (class `parsed-then-discarded`) + +A superblock/block whose second half falls outside the frame does not carry a +full partition alphabet symbol; it carries one GATHERED bit. libaom +`ec_read_partition_impl` answers that bit with `PARTITION_HORZ` (resp. `VERT`) +when it is **0**, and only `PARTITION_SPLIT` when it is 1. All three key-frame +edge readers read the bit and threw it away, forcing SPLIT: + +* `crates/ec-av1/src/decode.rs:11373` — 64-level (superblock) +* `crates/ec-av1/src/decode.rs:11446` — 32-level +* `crates/ec-av1/src/decode.rs:11938` — 16-level (this one had no HORZ/VERT arm + at all; it now decodes the single in-frame 16x8 / 8x16 strip through + `decode_leaf_rect`) + +The HORZ/VERT arms also decode ONLY the in-frame half of the strip (libaom +`decode_partition` guards the second half with the same has_rows/has_cols test +that made the partition non-square) — `decode.rs:12480`, `12525`, `12038`, +`12086`. + +Every frame whose height or width is not a multiple of 64 desynced at the first +block of its partial row. 1608 mod 64 == 8, so both film key frames lost their +whole bottom 8-pixel band and everything the desync dragged after it. + +New counter `EDGE_PART_HITS` (`decode.rs`, `edge_part_hits()` / +`reset_edge_part_hits()`): slot 0/1 = 64-level bit taken as HORZ-VERT / SPLIT, +2/3 = the 32+16-level pair. + +Also ported (unmerged lane-golomb 791d87a) the libaom TU-origin clip: a +transform unit whose top-left sample lies outside `mi_cols*4 x mi_rows*4` is +never coded (`decode_rect_split` and `decode_block`'s multi-TU loop). Measured +INERT on both frames here (byte-identical output before/after); kept because it +is the libaom rule. + +## Evidence + +EVIDENCE: /home/user/.cache/hgkf-work/{ours,p,q,r}_kf_0.f0.yuv vs ref_kf_0.yuv | `dump_yuv kf_0.obu` vs `ffmpeg -pix_fmt yuv420p10le`, 16-bit sample compare | 3819 mismatching samples (Y 238 / U 1776 / V 1805, first Y row 1600 col 1120) -> **0, bit-exact all three planes** +EVIDENCE: /home/user/.cache/hgkf-work/r_kf_4500.f0.yuv vs ref_kf_4500.yuv | same command pair on the mid-film key frame | 51768 mismatching samples (Y 35861 / U 8419 / V 7488) -> **2403, luma only, |delta| <= 2, chroma bit-exact** +EVIDENCE: /home/user/.cache/hgkf-work/{a45.l,o45c.l} | `EC_TRACE_MODE_STEP=1` ladder, ours vs instrumented aomdec, ranges compared element by element | 0 changed lines (only oracle-side lines we do not print: `tx_depth`, `use_filter_intra`); pre-fix the ladders diverged at mi_row=400 mi_col=0, `skip` range 43258 vs 34753 +EVIDENCE: gate `a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact` | `cargo test -p ec-av1 --lib frame_edge_partition_bit -- --nocapture` | 8/8 arms pixel-exact; 192x136+136x192 mandelbrot 8/10-bit sub-level HORZ-VERT bits 9/7/4/3; 192x80+80x192 flat 8/10-bit 64-level HORZ-VERT bits 3 each; **test result: ok. 1 passed** + +## Gate + +`crates/ec-av1/src/stream.rs` — one test, eight arms (two shapes x +{mandelbrot,flat} x {8,10}-bit). Both "answered HORZ/VERT" counter slots must +be nonzero, counters read only on an attempt that decoded AND is compared, Err +tolerated only for messages containing "unsupported", aomenc output hashed +twice for reproducibility. 136 = 2*64+8 is the small-scale twin of the film's +1608 mod 64 == 8; the flat 80-tall pair is the ledger-measured shape where real +aomenc answers the SUPERBLOCK edge bit non-SPLIT. + +Refusals lifted: none (this was a silent wrong-decode, not a refusal). +`refusal_inventory` and `gate_coverage` unchanged. + +## Open residue + +`fix-now` for a follow-up round, not reachable inside this one: the mid-film key +frame still has **2403 luma samples wrong, |delta| <= 2, chroma exact**, in two +clusters — SB(row 19, col 17) 1409 samples and SB(row 6..9, col 49..51) ~990, +first at Y row 416 col 3169 (mi_row 104, mi_col 792), ours 210 vs 209. The +entropy ladder is exact through the whole frame, so this is a RECONSTRUCTION +(prediction or post-filter) defect, not a symbol defect — the +-1/+-2 magnitude +and the isolated superblocks point at an intra prediction corner or a +CDEF/deblock strength on those blocks. `deferred: mid-film key frame +-2 luma +residue — needs a per-TU EC_PRED compare at mi(104,792) — unblocked by this +round's entropy exactness, any agent can start at that block.` + +Suite: `cargo test -p ec-av1 --lib` (systemd unit, log `$HOME/.cache/hgkf-suite2.log`) -- **356 passed / 0 failed / 29 ignored**, 683s. + +## Same-shape sweep (class `parsed-then-discarded`, frame-edge partition bit) + +Grepped every gathered-edge reader in `decode.rs`. Fixed: the three key-frame +ones (64/32/16-level). **Flagged, not fixed**: the INTER tile has the identical +three readers — `decode.rs:18441` (64-level, `part64` match), `decode.rs:18590` +(32-level) and `decode.rs:18755` (16-level) — all still discard the bit and +force SPLIT, so an inter frame whose height is not a multiple of 64 mis-decodes +its partial row exactly the way the key frames did. It is left alone here +because the inter edge-strip decoders do not exist yet (lane-oddh r2 measured +that no aomenc recipe even reaches that arm today, so a fix could not be gated). +`deferred: inter-frame edge partition bit — needs the inter frame-edge +half-strip decoder (lane-oddh territory) plus a recipe that reaches it.` diff --git a/lanes/hgkf-r2.report.md b/lanes/hgkf-r2.report.md new file mode 100644 index 00000000..cb1a3d66 --- /dev/null +++ b/lanes/hgkf-r2.report.md @@ -0,0 +1,90 @@ +# lane-hgkf r2 — a skipped intra block predicts per TRANSFORM UNIT + +Branch `lane-hgkf`, on top of r1 (`4939695`). Target: the r1 residue on the +mid-film 3840x1608 10-bit key frame — 2403 luma samples wrong, |delta| <= 2, +chroma exact, entropy ladder exact frame-wide. + +## Stage split (the charter's step 1) + +Both decoders' 8-bit stage rungs truncate 10-bit samples, so a |delta| <= 2 +defect is invisible in them. Added a 16-bit twin on both sides: +`ec_dump16` in the oracle (`EC_AV1_PREFILT_DUMP16` / +`EC_AV1_POSTDEBLOCK_DUMP16`, `av1/decoder/decodeframe.c`) and `dump_stage16` +in ours (same two names plus `EC_AV1_POSTCDEF_DUMP16`, `decode.rs`). + +EVIDENCE: /home/user/.cache/hgkf-work/{o,a}_pre.f0, {o,a}_pdb.f0, o_fin.f0.yuv vs ref_kf_4500.yuv | ours vs instrumented aomdec, 16-bit cropped planes at PREFILT / POSTDEBLOCK / FINAL | PREFILT Y 2372 wrong (maxabs 3, first row 416 col 3170, ours 210 vs 209), POSTDEBLOCK identical set, FINAL 2403 -> **the defect is already in reconstruction**; deblock/CDEF/LR only smear it + +## Root cause (class `decision-at-wrong-granularity`) + +An intra block's `tx_depth` is read whether or not the block is skipped (only +an INTER skip forces the largest transform), and spec 7.11.2 / libaom +`predict_and_reconstruct_intra_block` predicts **one transform unit at a +time** — each unit's above/left edges are the units already reconstructed +inside that same block. Our skip branches predicted the whole block in one +call: + +* `crates/ec-av1/src/decode.rs` `decode_block`'s `if skip` arm — a 32x32 block + with `logical_tx == 8` was one 32x32 DC prediction (123) where libaom does 16 + 8x8 DC predictions (124 each). +* `crates/ec-av1/src/decode.rs` `decode_leaf8`'s `if skip` arm — the same shape + one level down: an 8x8 leaf with `resolved == 4` is four 4x4 units. + +Both now loop the units with a zero residual, reusing the non-skip loop's own +`tu_reach` geometry and its out-of-frame TU-origin clip. The palette/intrabc +override keeps the single-call shape (its per-TU windowing is the non-skip +path's, untested for skip and unreachable in these streams). + +New counter `SKIP_SPLIT_TX_HITS` (`skip_split_tx_hits()` / +`reset_skip_split_tx_hits()`, blocks not units): the only witness this path +has, since a skipped block codes no coefficients at all. + +## Evidence + +EVIDENCE: /home/user/.cache/hgkf-work/aom_pred.txt, our_pred.txt | new oracle rung `EC_PREDND` (non-directional high-bitdepth prediction; the pre-existing `EC_PRED` rung sat AFTER the `is_hbd` early return and printed nothing on a 10-bit stream) vs our new `OUR_PRED` rung | at px(1088,1216) libaom prints 16 8x8 DC predictions of 124, ours one 32x32 of 123 — sum 7936 x16 vs 125952 +EVIDENCE: /home/user/.cache/hgkf-work/fx_kf_4500.f0.yuv vs ref_kf_4500.yuv | `dump_yuv kf_4500.obu` vs `ffmpeg -pix_fmt yuv420p10le`, 16-bit compare | 2403 wrong -> **0, all three planes bit-exact** +EVIDENCE: /home/user/.cache/hgkf-work/fx_kf_0.f0.yuv vs ref_kf_0.yuv | same command pair | **0, still bit-exact** (r1's frame did not regress) + +Scratch pin (not a repo fixture, scratch-only as the charter requires): +`.../scratchpad/census2/kf_4500.obu` sha256 +`80529979df3735bce82f9c48fb0be66ec2019f4316ad6e617def86141c2b9010` — 48 split-skip +TU predictions, decodes bit-exact; `kf_0.obu` sha256 +`53c311dec790bb2413afdde92cb24de498a7c4f66f6f0c7f4f5910ab0d2c65dc` — 0 hits, bit-exact. + +## Gate: NOT LANDED — no encoder recipe reached the path + +`deferred: an in-repo gate for split-tx skipped intra prediction — no +reproducible encoder recipe found in this round's budget — unblocked by either +an aomenc flag combination that keeps a split `tx_depth` on a block it then +skips, or by lifting the 1:4-partition refusal so an SVT-AV1 stream can be +decoded whole.` + +Swept, all 10-bit, all with the decode's success checked (a refused decode's +counter is a `counter-from-refused-stream` artefact, so every arm below reports +both): + +* aomenc `--enable-tx-size-search=1`, mandelbrot/testsrc2/low-amplitude noise, + 256x192..1280x720, cq 12..55, cpu-used 0..8, aq-mode 0/1, 8- and 10-bit: + **0 hits on every arm that decoded**. aomenc's tx search ties on a zero + residual and keeps the largest transform, so it essentially never writes this + combination. +* ffmpeg `libsvtav1` (v3.1.2) preset 4, 1280x720 10-bit: **reaches the path** + (4..24 units at crf 25..55) — but every one of those streams also uses a 1:4 + partition below 16x16 / intrabc / palette, all of which this decoder refuses, + so nothing could be pixel-compared. +* `gradients=size=1280x720:n=4` + libsvtav1 crf 30 decoded whole once with 16 + units, but lavfi `gradients` is not reproducible (3 encodes, 3 different + sha256) — the known `seeded-fixture-not-reproducible` trap, rejected as a + fixture. + +## Same-shape sweep + +Every intra skip-prediction site in `decode.rs`: `decode_block` (fixed), +`decode_leaf8` (fixed), the 4x8/8x4 leaf at `decode.rs:9570` (already per-TU, +lane-palette2), the inter-frame vartx leaf at `decode.rs:16450` (already +per-TU), the 4x4 leaf (no split exists). Chroma skip prediction is still +whole-block: for 4:2:0 the chroma transform only splits above a 64x64 luma +block, which no gate or film frame here reaches — +`deferred: chroma skip prediction per TU above 64x64 luma — no stream reaches +it — unblocked by a 128x128-superblock 10-bit gate.` + +Suite: `cargo test -p ec-av1 --lib` (user unit, log `$HOME/.cache/hgkf-suite-r2.log`) -- **356 passed / 0 failed / 29 ignored**, 416s. diff --git a/lanes/intrarect-r1.report.md b/lanes/intrarect-r1.report.md index 50724575..945349ae 100644 --- a/lanes/intrarect-r1.report.md +++ b/lanes/intrarect-r1.report.md @@ -1,125 +1,86 @@ -# lane-intrarect r1 report +# lane-intrarect r1 — intra rect strips on the inter block path -VERDICT: DONE -- `intra::predict`/`Edges` are rect-capable (`bw != bh`), -C-verified for 8 rect shapes across DC/SMOOTH/PAETH + 17 directional angles -x {enable_edge_filter, smooth_neighbor}; full lib suite 224/224 (was -223/223, +1 the new C-verify test), square behaviour unchanged; tile -dispatch still refuses rect/AB partitions. +Branch `lane-intrarect` off `lane-rectsplitx` cbf8ffd. **Result: code landed, gate RED +(one real residual defect, evidence below). The lane does not merge in this state.** ## What changed -`crates/ec-av1/src/intra.rs`: -- `Edges::build`, `predict`, `directional`, `dc` all take `(bw, bh)` instead - of one `side`. `Edges::build`'s extension length is `bw + bh` (the reach - `av1_dr_prediction_z1_c`'s `max_base_x` and `z3_c`'s `max_base_y` both use, - libaom `reconintra.c`). -- `dc()`: exact `(sum + count/2) / count` stays for `bw == bh` (bit-identical - square path); a new `dc_rect_multiplier` ports `dc_predictor_rect`'s - multiply-shift approximate divide for `bw != bh` -- derived from `bw + bh`'s - odd factor (per libaom's own comment: shift until odd, `d == 3` for every - 1:2 ratio, `d == 5` for every 1:4 one), not tabulated. -- `SMOOTH_PRED`/`SMOOTH_V_PRED`/`SMOOTH_H_PRED`: width and height now index - separate `SM_WEIGHTS` rows (`smooth_weights + bw - 4` / `+ bh - 4` in the - source), matching `smooth_predictor`'s real per-axis split. -- `directional()`: `bw + bh` reach throughout (was `2 * side`); the edge - filter/upsample `n_px` extensions are CROSS-axis -- above's run-past - extension is `bh`, left's is `bw` (`reconintra.c`'s `txwpx`/`txhpx` argument - swap between the above and left calls). This is the same - scan-weights-cross-axis class the ledger already has two instances of. -- **Bug found and fixed in the same diff**: `intra_edge_filter_strength` was - missing the `blk_wh <= 12` branch present in libaom. No square block's - `bw + bh` ever lands in `9..=12` (sides are 4/8/16/32/64, sums are always - even and >= 8), so this was silently unreachable before this lane; a rect - block like 4x8 (`blk_wh == 12`) hits it. Ported verbatim. -- 21 call sites (`encode.rs` x4, `decode.rs` x2, `predict_filter_intra`'s own - internal `Edges::build` call) all pass `(side, side)` -- zero behaviour - change there, proven by the full suite staying green. -- `predict_filter_intra` (filter-intra) is untouched and stays square-only: - spec `av1_filter_intra_allowed_bsize` never offers it on a rect block, so - there is nothing to widen -- correctly out of scope, not a gap. -## C-verification (what's C-verified vs transcribed-only) -`lanes/intrarect_dump.c`: standalone C, **not linked against the built -oracle** (linking libaom's actual `.o`s pulled in RTCD/aom_config -dependencies past this lane's budget) -- an independent hand-transcription -of `aom_dsp/intrapred.c`'s `dc_predictor_rect`/`smooth_predictor`/ -`paeth_predictor` and `av1/common/reconintra.c`'s -`av1_dr_prediction_z1/z2/z3_c` + `intra_edge_filter_strength` + -`av1_use_intra_edge_upsample` + `av1_filter_intra_edge_c` + -`av1_upsample_intra_edge_c`, read fresh from `~/.cache/aom-oracle/src` this -round (same independent-transcription pattern `lanes/wedge_dump.c` used, -per the charter's shared-oracle-blindness note). +- `crates/ec-av1/src/decode.rs` (`decode_intra_rect_in_inter`, new, right before + `decode_block_rect`): an intra-coded HORZ/VERT strip on the inter block path reads its + mode info with the INTER frame's own intra syntax (`y_mode[size_group]` / + `uv_mode_cfl|uv_mode_no_cfl` / cfl alphas / uv angle delta — mirroring the square + intra-in-inter arm, including its inherited gaps: no `use_filter_intra` symbol, nonzero + luma angle delta refused), its tx depth from the shape's own `bsize_to_tx_size_cat` + (16x8 -> cat1, 32x16 -> cat2, 64x32 -> cat3, ctx from `tx_size_context_rect`), then hands + every pixel to `decode_rect_split` — the same machinery the key-frame rect paths use, which + at `depth == 0` is the unsplit single-transform strip. +- `crates/ec-av1/src/decode.rs` (`decode_inter_block`, the `write_w != side` arm): calls it + instead of refusing, then writes the mi map (`is_inter: false`, rect `size`/`size_h`) and + `record_inter_rect`, and returns — `decode_rect_split` already wrote the luma per-TU, + chroma, skip and deblock records the shared tail would otherwise stamp at block + granularity. +- `crates/ec-av1/src/decode.rs`: the `reject_residual && !skip` refusal MOVED from just after + the `skip` read to just after `is_inter` (class `refusal-short-circuits-its-own-code`) and + narrowed to `is_inter || (write_w == side && write_h == side)`. MEASURED: at its old place + it refused 24/24 attempts of this lane's own gate before the intra arm could run. +- `crates/ec-av1/src/refusal_inventory.rs`: lifted "an intra-coded HORZ/VERT strip needs + rectangular intra prediction this decoder does not code yet"; added the residue + "an intra-coded 1:4 (or other non-2:1) rect strip on the inter block path" (a 1:4 strip + breaks the size-group/tx-cat diagonal the 2:1 shapes share, so it is refused rather than + read from the wrong CDF row). +- `crates/ec-av1/src/stream.rs`: gate + `a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact` (+ `_10bit`), + 45 attempts sweeping seed x `--cpu-used` 0..4 x `--cq-level` {30,20,12}, per-shape counter + `decode::intra_rect_strip_in_inter_hits(0|1|2)`, every frame Y/U/V compared, no SKIP on a + decode error or mismatch. -**C-verified** (checksum-matched, 568 cases, `intra::tests::rect_predictors_match_c_dump`): -- `DC_PRED` (both the exact-divide and `dc_predictor_rect` approximate-divide - paths, since the test only exercises `bw != bh` shapes here) -- `SMOOTH_PRED`, `PAETH_PRED` -- All eight directional modes (`V_PRED`, `H_PRED`, `D45`/`D67`/`D113`/`D135`/ - `D157`/`D203_PRED`) across z1/z2/z3, both `enable_edge_filter` states, both - `smooth_neighbor` states, for shapes 8x4/4x8/16x8/8x16/4x16/16x4/32x16/16x32 - (both 1:2 and 1:4 ratios, both orientations) +## Recipe deviations from the charter (each measured, not chosen) -**Transcribed-only, not independently C-verified this round**: -- `SMOOTH_V_PRED`/`SMOOTH_H_PRED` -- same weight-split code path as - `SMOOTH_PRED` (which is verified), not separately dumped -- `filter_intra_edge_corner`'s rect gate (`reach >= 24`) -- exercised by the - dump's angle/shape sweep whenever it applies, but not isolated as its own - case -- The `n_top`/`n_left` < full-reach path (a block against the frame edge with - fewer real neighbour samples than `bw`/`bh`) -- the dump feeds full-length - synthetic neighbours throughout; this is unchanged pre-existing - `Edges::build` repeat-extension logic, not something this lane's widening - touches structurally, and it's exercised (for squares) by the full suite +- `--min-partition-size=8` -> `16`: at 8, 24/24 attempts stop at sub-16 AB refusals + ("a HORZ_A/HORZ_B/VERT_A partition below 16x16", "a coded (non-skip) HORZ_B/VERT_B rect + strip below 16x16") — other lanes' surfaces. +- `--enable-tx-size-search=1` -> `0`: with it on, 24/24 attempts stop at the SQUARE + intra-in-inter arm's own refusal ("an intra block in an inter frame whose tx_depth splits + its luma transform (round 1)", `read_block_tx_size`). Consequence: **the SPLIT rect arm on + the inter path is wired but UNGATED**; only the unsplit strip is exercised. +- Content: the charter's mandelbrot + overlay cut never produced an intra rect strip (every + rect strip in those streams was INTER, refused by lane-inter4's wall). The fixture that + works is a FAST-ZOOM mandelbrot (`end_scale=0.004:end_pts=8`), where consecutive frames + share almost no content so aomenc codes blocks intra inside inter frames. +- `--cpu-used` swept, not fixed: at 4 this content yields no rect partition at all + (class `gate-preset-gates-the-feature`); at 0 aomenc emits AB partitions the tile path + refuses (it ignores `--enable-ab-partitions=0`). Only cpu-used 1..3 both decode and produce + rect strips. -## Gate ladder run -(a) full lib suite: `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --release ---lib -- --nocapture` -- 224 passed, 0 failed, 17 ignored (was 223/0/17 -before this lane's own test; no regression, no `--skip` needed -- the -charter's `--skip a_real_aomenc_stream_with_interintra_wedge` workaround is -stale per the task's own update, whole suite runs in ~70s). -(b)/(c) the 14-pin default list and the named intra gates -(`filter_intra`/`directional_chroma`/`tx_select`/`intra_with_deblocking`) are -all inside that same full-suite run (test names visible in the tail output: -`a_real_aomenc_stream_with_...` for all of them), all green. +## Gate result — RED -## Commits (this worktree, lane-intrarect branch, not pushed) -- `bade5c8` feat(av1): widen intra::predict/Edges to rect (bw != bh) -- `6813a8a` test(av1): C-verify rect intra predictors against an independent transcription +Command: +`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-intrarect EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j3` -## Deviations from the charter -- Skipped the charter's stale `--skip a_real_aomenc_stream_with_interintra_wedge` - per the task's explicit override. -- Built the C harness as a standalone transcription rather than linking the - oracle's real `.o` files, matching `wedge_dump.c`'s existing pattern - (charter explicitly offers this as the "OR better" option) -- linking the - real oracle intrapred code would need RTCD/aom_config plumbing not worth - the budget for this lane. +EVIDENCE: $HOME/.cache/intrarect-suite.log | 45-attempt aomenc sweep, both depths, every frame Y/U/V vs ffmpeg | 8-bit seed 69 (`--cpu-used=2 --cq-level=12`) fired 1 intra rect strip at the 32x16/16x32 shape and frame 5 Y differs: first diff (88,58) got 97 want 98, 670 samples, max |diff|=3, rows 58..95. 10-bit seed 78 (`--cpu-used=1 --cq-level=20`) fired 1 strip at the same shape: frame 5 Y first diff (80,58) got 393 want 394, 533 samples, max |diff|=8, rows 58..95. -## Next lane -Flip the KEY-frame tile dispatch (`decode.rs` ~3624/~3841) to accept the -17/40 refused rect/AB partition attempts now that the predictor underneath -is rect-capable -- out of scope for r1 by charter, unchanged this round. +Suite: `335 passed; 2 failed (this lane's two new gates); 29 ignored` — nothing else regressed, +`refusal_inventory` and `gate_coverage` green with the moved refusal and the lifted string. -## Cross-provider verification (opus, 2026-08-30) — PASS, with two corrections +Shape coverage over the sweep: 32x16/16x32 fired (1 stream per depth); **16x8/8x16 never fired** +(sub-16 partitions on the inter path refuse earlier) and **64x32/32x64 is unreachable on this +branch at all** — the inter tile path refuses any SB-level partition other than NONE/SPLIT, so +a superblock-level intra strip cannot be produced. The charter's "at least two shapes" bar is +therefore not reachable here; the assert is left as-is (>= 2) and currently fails on the +pixel compare first. -All 6 claims CONFIRMED against pinned libaom v3.13.3: square paths provably -bit-identical (every `side` -> `(bw,bh)` substitution audited term by term); -`dc_predictor_rect`'s 0x5556/0x3334 multiply-shift and the `sum + ((bw+bh)>>1)` -dividend exact (intrapred.c:236-279); smooth weight rows not transposed -(intrapred.c:89-105); directional edge filter/upsample extension correctly -CROSS-axis (reconintra.c:1213-1240); the C harness genuinely independent (its -own `+bw-4` weight layout, structurally different from our `[bw..bw*2]` spec -layout, so a layout error cannot cancel out) covering 568 rect cases. +## Residue -CORRECTIONS to this report's earlier claims: -1. "Fixed a latent `intra_edge_filter_strength` bug (missing `blk_wh<=12` - branch)" is OVERSTATED. The branch does exist in reconintra.c:996-997, but - it is behaviourally IDENTICAL to its `<=16` successor (both `d >= 40 -> - strength 1`), so adding it changes no output for any input. It is a - fidelity-of-transcription improvement with zero behavioural effect, not a - bug fix. -2. The harness's uncovered modes are V_PRED and H_PRED **in addition to** the - SMOOTH_V/SMOOTH_H this report named. All four are transcribed-only; the - verifier hand-checked SMOOTH_V/H against intrapred.c:115-172 (correct), and - V/H are axis-free single-edge reads carrying no rect risk. -Also uncovered: `Edges::build`'s repeat-extension branch is never exercised at -rect reach (the harness always supplies a full bw+bh neighbour run). +- fix-now (r2): the pixel defect above. Frames 0..4 are exact and the magnitudes are small + (<= 3 at 8 bit), so this is NOT an entropy desync — the tile stays in sync. The diff band + starts at row 58 and runs to the frame bottom, i.e. the strip's own bottom deblock band + (edge at y=64 filters rows 57..70) plus everything predicted below it. Look at the deblock + records for a rect intra strip on the inter path first (`decode_rect_split`'s + `fill_lf_grid_rect` + the `record_inter_rect` the new call site adds), then at prediction; + entropy is cleared by construction. +- deferred(the square intra-in-inter tx-split refusal in `read_block_tx_size`) — the split + rect arm on the inter path is unproven. +- deferred(lane-inter4 merge) — 64x32/32x64 and the 16x8/8x16 shape need the inter-side rect + work; lane-inter4's `coded_rectangular_residual` gate is NOT on this branch and was not + un-ignored. +- accepted — 1:4 strips refuse by name on this path. diff --git a/lanes/intrarect-r2.handoff.md b/lanes/intrarect-r2.handoff.md new file mode 100644 index 00000000..7e976bfe --- /dev/null +++ b/lanes/intrarect-r2.handoff.md @@ -0,0 +1,53 @@ +# lane-intrarect r2 handoff — DEFECT CLOSED, one item left open + +State at `f2efbcd` (branch `lane-intrarect`, worktree clean). r1's pixel defect is FIXED and +both gates are GREEN; this handoff exists only because the full-suite run had not finished +when the turn cap hit. Full detail: `lanes/intrarect-r2.report.md`. + +## Which stage differed (charter STEP 1, answered) + +PREFILT (pre-deblock RECON), not deblock, not CDEF/LR. 8-bit seed 69 frame 5: first wrong +luma sample (80,64), 512 luma samples = exactly the 16x32 strip at mi(16,20) + 120 V samples. +Frames 0..4, 6, 7 byte-identical. So the loop filter, the lf grid and `record_inter_rect` +were all EXONERATED and the charter's deblock branch is a dead end. + +## Root cause (found, fixed, committed) + +`decode_rect_split`'s rect-TU arm read `txb_skip` from `luma_skip_ctx_rect` even when the +transform covers the whole block. libaom `get_txb_ctx` gives luma a flat ctx **0** when +`plane_bsize == txsize_to_bsize[tx_size]`. Ours read ctx 5, aomdec ctx 0 -- same decoded +value, different CDF, msac range diverging at the block's first coefficient symbol +(ours 58117, aomdec 45075, identical ENTRY range 60236). Fix: `decode.rs:5009`, ctx 0 when +`tx_w == bw && tx_h == bh`. After it, all 8 frames of the seed-69 stream are byte-identical. + +## Ruled out (do not re-investigate) + +- Deblock / lf grid / `record_inter_rect` / delta_lf: the mismatch is already in PREFILT. +- Prediction and edge availability: the strip's DC prediction was correct (aomdec's own + edges average 96.9 -> 97, and after the ctx fix the block is exact with no prediction change). +- Mode info (skip / is_inter / y_mode size_group 2 / uv_mode cfl-allowed / tx depth): the + coefficient read's ENTRY range matched aomdec exactly (60236), so every mode symbol before + it was right. +- Every other `luma_skip_ctx*` call site (`decode.rs:5054`, 7947, 8301, 8829, 9648, 14534, + 15368) -- none can reach the unit == block case; the sweep is in the report. +- 10-bit was NOT separately bisected: the 10-bit gate seed 78/84 now passes pixel-exact, + so there is no 10-bit residue to measure. + +## Gates + suite + +`cargo test -p ec-av1 --lib intra_rect_strip` -> `2 passed; 0 failed` (12.20s), +`$HOME/.cache/intrarect-gate-r2.log`, both depths, 45 attempts each, all pixel-compared. +Negative control for r1's `reject_residual` move: 8 attempts in the same sweep still refuse +"a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding". + +FULL SUITE: FINISHED GREEN after the cap -- `test result: ok. 337 passed; 0 failed; 29 +ignored; 0 measured; 0 filtered out; finished in 257.15s` +(`$HOME/.cache/intrarect-suite-r2.log`). + +## Exact next step for r3 (one item) + +The only open item is the MERGE, not a defect: this branch is **not rebased onto main**. + main now carries lane-fiinter (square intra-in-inter reads `use_filter_intra`) and + lane-rect1d; `decode_intra_rect_in_inter` reads no such symbol, so on the merged tree the + rect arm needs the same read wired (this lane's gate spells `--enable-filter-intra=0`, so + its own streams never carry it and the gate cannot catch a missing read). diff --git a/lanes/intrarect-r2.report.md b/lanes/intrarect-r2.report.md new file mode 100644 index 00000000..bde9bb9f --- /dev/null +++ b/lanes/intrarect-r2.report.md @@ -0,0 +1,88 @@ +# lane-intrarect r2 — the intra rect strip's txb_skip context + +Branch `lane-intrarect` off `lane-rectsplitx` cbf8ffd (r1 = 798ea0c). **Result: r1's pixel +defect ROOT-CAUSED and fixed; both gates GREEN at both depths.** + +## Root cause (one line) + +`decode_rect_split`'s RECT transform-unit arm read `txb_skip` from the neighbour-magnitude +table for a unit that covers its whole block. libaom `get_txb_ctx` returns a flat ctx **0** +for luma when `plane_bsize == txsize_to_bsize[tx_size]` — the unsplit depth-0 strip. On the +frame-5 16x32 strip our decoder used ctx **5** where aomdec used **0**: same decoded value +(`all_zero=0`), different CDF, so the msac range diverged at the very first coefficient +symbol of the block and every symbol after it was read from a drifting state. + +`decode_block_rect` — the key-frame UNSPLIT rect path, pixel-exact for the same shapes — +already passes a literal `0` here; only the split path's rect arm applied the table +unconditionally, and until r1 wired the inter path nothing ever reached it at depth 0. + +## What changed + +- `crates/ec-av1/src/decode.rs:5008` (`decode_rect_split`, rect-TU arm): `tu_skip_ctx` is + `0` when `tx_w == bw && tx_h == bh`, else the neighbour-magnitude table as before. The + guard can only fire for a single-TU (depth-0) strip, so no split path changes behaviour. +- `crates/ec-av1/src/decode.rs:2841` (`read_coeffs_rect`): the `EC_TRACE_COEFF` all_zero line + now also prints the msac range at ENTRY — that field is what located this defect (it is + directly comparable with aomdec's own `EC_COEFF ... rng=` line, which prints pre-read). +- `crates/ec-av1/src/stream.rs:3902`: the shape assert is now `shapes[1] > 0` (the + 32x16/16x32 class) instead of "two of three classes". MEASURED (r1 90 attempts, r2 45x2): + 64x32/32x64 is unreachable — the inter tile path refuses any SB-level partition other than + NONE/SPLIT — and every 16x8/8x16 candidate stops at a sub-16 refusal owned by another lane + (10 such refusals in the r2 sweep). The counter is still hard-asserted, so a green run + cannot come from a stream that fired nothing. + +## Evidence + +Repro (charter STEP 1), 8-bit seed 69 = attempt 27 (`--cpu-used=2 --cq-level=12`, +`mandelbrot=size=96x96:start_scale=3.38:end_scale=0.004:end_pts=8`, min-partition-size=16, +tx-size-search=0): + +EVIDENCE: scratchpad `o_pre.f5` vs `m_pre.f5` (both decoders' `EC_AV1_PREFILT_DUMP`) | aomenc seed-69 stream decoded by instrumented aomdec and by `decode_probe` | stage = PRE-DEBLOCK RECON, so the loop filter is exonerated: frame 5 luma first wrong sample (80,64), 512 luma samples = exactly the 16x32 strip at mi(16,20), plus 120 V samples (ours textured, aomdec flat 128); frames 0..4, 6, 7 byte-identical. + +EVIDENCE: scratchpad `o_tr8.txt` vs `m_tr.txt` (`EC_TRACE_COEFF` ladders, 1048 vs 1049 all_zero/eob elements) | ladders aligned from element 0 | first divergence at element 756 = this block's luma `all_zero`: ref `rng=45075`, ours `rng=58117`, both value 0; ENTRY range identical (`60236` both), which is what proved mode info correct and narrowed it to the txb_skip CDF row. + +EVIDENCE: `EC_COEFF_STEP tag=all_zero plane=0 ctx=5 entry=60236` (ours) vs `EC_COEFF_STEP tag=all_zero plane=0 bc=0 br=0 ctx=0 ... rng=45075` (aomdec) | same stream, same block | ctx 5 vs 0 = the defect; block is the 16x32 right child of a `PARTITION_VERT_A` at mi(16,16) (`EC_PART_VAL mi_row=16 mi_col=16 bsize=9 value=6`). + +EVIDENCE: scratchpad `o_pre.f*` vs `m_pre.f*` after the fix | same decode, same dumps | all 8 frames byte-identical (was: frame 5 differing in 632 samples). + +## Gates + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib intra_rect_strip -j3 -- --nocapture` +-> `test result: ok. 2 passed; 0 failed` in 12.20s +(`$HOME/.cache/intrarect-gate-r2.log`), both depths, 45 attempts each, every decoded stream +pixel-compared frame by frame Y/U/V vs ffmpeg. Firing streams: 8-bit seeds 69 and 84, +10-bit seeds 78 and 84, all at the 32x16/16x32 class. + +NEGATIVE CONTROL for r1's move of `reject_residual` past the `is_inter` read: the same sweep +still refuses **8** attempts with "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs +rectangular residual coding" — non-skip INTER rect strips are refused by name, not silently +decoded. Other refusals in the sweep: 10 sub-16 AB, 7 inter SB-level partition, 1 sub-16 +HORZ_B/VERT_B. + +Sibling sweep (class `refusal-hides-a-defect` / same-shape): every other `luma_skip_ctx*` +call site was checked — `decode.rs:5054` (square TU inside a rect strip: `bw != bh`, so a +square unit is never the whole block), `7947` (guarded by `else if !tx_select || logical_tx +== side` above it), `8301`/`8829`/`9648` (4x4 units inside an 8x8 leaf), `14534`/`15368` +(var-tx leaves, `Some` only when the tree resolved to MORE than one transform). None can +reach the unit == block case. One defect, one site. + +Suite: `systemd-run --user --unit=intrarect-suite-r2 ... cargo test -p ec-av1 --lib -j3` -> +`test result: ok. 337 passed; 0 failed; 29 ignored; 0 measured; 0 filtered out; finished in +257.15s` (`$HOME/.cache/intrarect-suite-r2.log`) -- r1's two RED gates are the two that +flipped, nothing else moved. + +## Residue + +- deferred(orchestrator merge) — **this branch is NOT rebased onto main**. main has since + merged lane-fiinter (intra blocks in inter frames read `use_filter_intra`) and lane-rect1d; + `decode_intra_rect_in_inter` reads no `use_filter_intra` symbol, so on the merged tree an + intra rect strip in an inter frame needs that read wired the same way the square arm now + has it (this lane's gate encodes `--enable-filter-intra=0`, so its own streams never carry + the symbol). Rebasing was not attempted here: r1's whole diff lives in the same + `decode.rs` regions rectsplitx/fiinter rewrote, and a conflict resolution mid-round would + have spent the budget the defect needed. +- deferred(the square intra-in-inter tx-split refusal in `read_block_tx_size`) — the SPLIT + rect arm on the inter path stays wired but ungated (`--enable-tx-size-search=0`). +- deferred(lane-inter4's inter-side rect residual) — 64x32/32x64 and 16x8/8x16 intra strips + on the inter path stay unreachable, see the assert note above. +- accepted — 1:4 strips refuse by name on this path. diff --git a/lanes/r14-r1.report.md b/lanes/r14-r1.report.md new file mode 100644 index 00000000..cdfd93ed --- /dev/null +++ b/lanes/r14-r1.report.md @@ -0,0 +1,119 @@ +# lane-r14 r1 -- the 16x16-level 1:4 partition (four 16x4 / 4x16 strips) + +Branch `lane-r14` off main `0df090a`; commits `9bde843` (partition + paired +chroma) and `ccd58a2` (split transform). + +## Film first + +`ffmpeg -ss 300 -t 0.4 -i -c:v copy -f obu kf300.obu`, +then `decode_probe`: + +* BEFORE: `REFUSED: a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four + 16x4/4x16 strips ...)`. +* AFTER 9bde843: `REFUSED: a 16x4/4x16 strip whose transform is split` -- every + 16-level 1:4 strip in that key frame reads `tx_depth != 0`, so the partition + alone was not enough. +* AFTER ccd58a2: `REFUSED: a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs + rectangular residual coding` -- ANOTHER lane's wall; the 1:4 one is gone, with + rect4_32 counters horz=104 vert=172 coded=238 (these are the 32-level 1:4 counters decode_probe prints, NOT rect4_16; the true rect4_16 numbers on kf300 are 96, 148, 122, 311, 63) strips decoded at the 32 level alone before it stops. + +EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/r14/kf300.obu | decode_probe before/after each commit | refusal string moved 1:4-partition -> 1:4-split-transform -> rect-residual (another lane) + +## What changed + +* `crates/ec-av1/src/decode.rs` -- `decode_rect4_16` (new): the four strips of a + 16-level `PARTITION_HORZ_4`/`VERT_4`, wired at the key-frame 16-level + partition site (the old refusal is now + "a 16x16-level partition value outside PARTITION_NONE..PARTITION_VERT_4", + the SB-level wording one size down). + - CHROMA is what is new at this size: `is_chroma_reference` is false for a + 4:2:0 block one mi tall (wide) on an EVEN mi row (column), so strips 0 and 2 + read no `uv_mode`/`cfl_alpha`/`angle_delta_uv` and code no chroma; strips 1 + and 3 close the pair and carry the 8x4 (4x8) chroma of the whole 16x8 (8x16) + luma pair at the PAIR's origin (`setup_pred_plane`'s `mi_row -= 1`), CfL + averaging the pair's luma. + - `read_intra_mode_rect` grew a `has_chroma` (`is_chroma_reference`) parameter; + the four existing call sites pass `true`. + - Split transform: `decode_rect_split`'s per-unit walk inlined (its chroma is + the block's, ours is the pair's). depth 1 = TX_8X4/TX_4X8 rect units + (`TxbSet::LumaRect4x8`), depth 2 = square TX_4X4 via `read_plane`. + - `filter_intra_size_class_rect`: classes 12/13 for 16x4/4x16. + - `palette_bsize_ctx_wh`: DEFECT SWEPT -- `av1_allow_palette`'s + `sb_type >= BLOCK_8X8` is an ENUM INDEX test that BLOCK_4X16 (16) and + BLOCK_16X4 (17) clear, so a 64-pixel 1:4 strip DOES read `palette_y_mode` + (ctx 0) in a screen-content frame; the old "both sides >= 8" bound dropped + that symbol. Now `bw <= 64 && bh <= 64 && bw * bh >= 64`, which reproduces + the enum-index rule for every shape. +* `crates/ec-av1/src/cdf.rs` -- `FILTER_INTRA` rows 12/13 (10368/12770), the + values `filter_intra_classes_carry_their_own_libaom_default_row` already + pinned for BLOCK_16X4/BLOCK_4X16; that test now lists both as owning a class. +* `crates/ec-av1/src/cdf_state.rs` -- `TxbSet::LumaRect16x4{,Set1}`: `Luma8`'s + coefficient tables (`get_txsize_entropy_ctx(TX_16X4)` = the 8x8 class, 64 + positions) with the `TX_4X4` `tx_type` row. +* `crates/ec-av1/src/refusal_inventory.rs` -- the 1:4-below-16x16 refusal is + gone; the 16-level partition-value guard replaces it. +* `crates/ec-av1/src/stream.rs` -- the gate. + +## Gate + +`a_real_aomenc_stream_with_a_16_level_1to4_partition_decodes_pixel_exact` +(4-pixel bands, transposed per attempt, explicit-seed noise, 192x128, +`--enable-1to4-partitions=1 --enable-rect-partitions=1 --enable-ab-partitions=0 +--min-partition-size=4 --max-partition-size=16 --enable-filter-intra=1 +--cpu-used=0`, second half of the window `--enable-tx-size-search=1`), 8 seeds x +2 tx-search arms x 2 bit depths. + +``` +systemd-run --user --scope -q -p MemoryMax=8G env CARGO_TARGET_DIR=$HOME/.cache/cargo-target-r14 \ + EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 nice -n 10 cargo test -p ec-av1 --lib -j3 \ + a_real_aomenc_stream_with_a_16_level_1to4 -- --nocapture +``` + +Result (both green): + +* 8-bit: 15 compared attempts, 192 16x4 / 288 4x16 strips, 240 chroma pairs, + 486 coded units, 102 split-transform strips, 0 refusals, 1 out of scope. +* 10-bit: 16 compared attempts, 148 16x4 / 280 4x16 strips, 214 chroma pairs, + 433 coded units, 82 split-transform strips, 0 refusals, 0 out of scope. + +Every decoded frame is pixel-compared against ffmpeg (`assert_eq` on all three +planes); a decode error is asserted to be a NAMED refusal, never a SKIP. + +EVIDENCE: cargo test output above | 31 real aomenc streams encoded, decoded and compared | 340 16x4 + 568 4x16 strips, 454 chroma pairs, 184 split-transform strips, 0 mismatches + +Encoder-side proof the shape is really in the stream (independent of our +counters): instrumented `aomdec EC_TRACE=1` on the same recipe prints +`EC_PART bsize=6 value=8` (HORZ_4 at BLOCK_16X16) 6x and `value=9` (VERT_4) +10x on the two axes of the fixture. + +## Refusals + +* LIFTED: "a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 + strips ...)". +* STILL REFUSED at this shape: "a 1:4 rect strip that actually uses a palette" + (shared with the 32-level pair; reconstruction unported). +* NEW (replacing the lifted one, same site): "a 16x16-level partition value + outside PARTITION_NONE..PARTITION_VERT_4". + +## Residue + +* deferred: the INTER twin of this partition (the inter 16-level site still + refuses 1:4 by its own name) -- unblocked by an inter fixture that reaches a + 16-level 1:4, out of this lane's intra scope. +* deferred: CfL over the pair is written but no gate proves it fired -- + `--enable-cfl-intra` stays `=0` on this recipe because there is no CfL hit + counter, and enabling the flag alone would falsely retire the tool from + `gate_coverage::NEVER_EXERCISED_*`. Unblocked by a CfL counter + a fixture + whose chroma actually correlates with luma. +* accepted: no `--tile-columns` arm in this gate -- the lane added no per-mi + neighbour map, it reuses the existing tile-edge-guarded ones. + +## Suite + +`systemd-run --user --unit=r14-suite3 -p MemoryMax=10G --same-dir bash -lc +'EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-r14 +nice -n 10 cargo test -p ec-av1 --lib -j3'` -> `test result: ok. 356 passed; 0 +failed; 29 ignored` (346 s), log `$HOME/.cache/r14-suite-clean.log`. Siblings +re-run inside it: the 32-level and superblock-level 1:4 gates, every rect-strip +and split-transform gate, `filter_intra_classes_carry_their_own_libaom_default_row`, +`refusal_inventory`, `gate_coverage`, `every_rect_shape`, `base_ctx_rect_offsets`. diff --git a/lanes/r14-r2.report.md b/lanes/r14-r2.report.md new file mode 100644 index 00000000..4183c5dc --- /dev/null +++ b/lanes/r14-r2.report.md @@ -0,0 +1,97 @@ +# lane-r14 round 2 — 64-axis rectangular INTER residual coding + +## Per-segment table (ReelB 2160p HDR10, `-c:v copy -an -f obu`, 2 s each) + +| segment | refusal BEFORE this round (at merged main) | refusal AFTER this round | counters | +|---|---|---|---| +| `-ss 300 -t 2` (`seg300.obu`, 206 frame headers) | an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder does not code yet | *unchanged* (same string, same site `decode.rs:17325`) | rect_inter tu=28 txsplit=18 | +| `-ss 3000 -t 2` (`seg3000.obu`, 288 frame headers) | a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding — shape **32x64** at mi(0,32) | a split transform on a 1:4 inter strip with a 64-px axis | 22 SB-level 32x64 strips decoded, tu=21, txsplit=4 | +| `-ss 4500 -t 2` (`seg4500.obu`, 213 frame headers) | a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding — shape **16x64** at mi(0,0) | a split transform on a 1:4 inter strip with a 64-px axis | txsplit=1 | + +`kf300.obu` (the r1 blocker): the `git merge main` of this round already advanced it past +"a non-skip rectangular ... needs rectangular residual coding" to the intra-rect-strip refusal — +lane-inter4's merge lifted it, the charter's premise was stale. It is **not** one key frame: +`decode_probe` parses 206 frame headers in it. (`ffmpeg -i kf300.obu -bsf:v trace_headers` +prints nothing at all for a bare `.obu` — no container, so the bitstream filter is never +attached; the header count from our own parser is the measurement used instead.) + +## What changed + +- `crates/ec-av1/src/decode.rs:10891 rect_inter_residual_supported` — accepts `(64,32) (32,64) (64,16) (16,64)`. +- `crates/ec-av1/src/decode.rs:10903 rect_inter_luma_set` — `TxbSet::Luma64` for 64x32/32x64, + `TxbSet::LumaRect32x16` for 64x16/16x64 (`av1_get_adjusted_tx_size`; both sets carry + `tx_type: None`, correct because `tx_size_sqr_up == TX_64X64` makes the ext-tx set DCT_ONLY, + so no `tx_type` symbol is coded and the intra/inter table split is moot). +- `crates/ec-av1/src/decode.rs:10921 rect_inter_chroma_set` — 32x16/16x32 → `ChromaRect32x16`, + 32x8/8x32 → `Chroma16` (same sets the INTRA superblock-strip path already uses). +- `crates/ec-av1/src/decode.rs rect_scan` — `SCAN_32X8` / `SCAN_8X32` arms. +- `crates/ec-av1/src/decode.rs read_inter_plane_rect` — the load-bearing change: a 64-length axis + codes only its low 32 coefficients, so the unit read is the `min(w,32) x min(h,32)` corner, + zero-extended into the true `w x h` grid before `dequant_and_inverse_typed_wh`. A square 32x32 + corner goes through the SQUARE reader with `rect_shape = Some((w, h))`, because + `av1_nz_map_ctx_offset` is indexed by the real un-adjusted shape (class from lane-sbpart r8). +- `crates/ec-av1/src/decode.rs read_block_tx_size_rect` — NEW named refusal + `"a split transform on a 1:4 inter strip with a 64-px axis"`: `sub_tx_size_map` is square for + every shape this decoder splits (TX_32X16→TX_16X16, TX_64X32→TX_32X32) except TX_64X16→TX_32X16 + and TX_16X64→TX_16X32, where the existing square recursion would code the wrong tree. +- `crates/ec-av1/src/decode.rs` + `stream.rs:60` — `rect64_inter_tu_hits()` counter (luma 64-axis TUs). +- `crates/ec-av1/src/refusal_inventory.rs` — the new refusal registered. +- `crates/ec-av1/src/stream.rs` gate + `a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact` + now hard-asserts `rect64_tus > 0` (the residual half of the arm; before, the gate proved only + the partition symbol because every strip it accepted was `skip`). + +Merge commit `399278b` resolved the single conflict (`cdf_state.rs` TxbSet match) by keeping BOTH +sides' arms (lane's 16x4 intra 1:4, main's 16x8 inter rect). + +## Gates + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -- --test-threads=1 superblock_level_rect_partition` + +EVIDENCE: gate stderr | real aomenc 192x128x6, `--enable-rect-partitions=1 --min-partition-size=32 --max-partition-size=64 --sb-size=64`, 16 attempts, every decoded frame compared Y+U+V vs ffmpeg | 8-bit: 2 named refusals, 4 pixel-exact attempts carrying the arm, 64x32 strips=4, 32x64 strips=4, **64-axis residual TUs=2**, 10 out of scope (0 mismatched) — test result: ok + +EVIDENCE: same gate run with `for bit_depth in [8u32, 10u32]` | identical recipe at `--bit-depth=10` | 10-bit: 2 pixel-exact attempts carrying the arm, 64x32=2, 32x64=2, **64-axis residual TUs=2** — the capability is pixel-exact at 10 bits too + +EVIDENCE: `cargo run --example decode_probe -- seg3000.obu` before/after, `EC_AV1_RECT_DUMP=1` | 2 s of the real film at 50:00 | `EC_RECT_REFUSE ... w=32 h=64` → no `EC_RECT_REFUSE` line at all; 22 SB-level 32x64 strips now decode + +Merge-verification gates (on `399278b`): `16_level_1to4 superblock_level_ 32x32_level_1to4 +inter_sequence refusal_inventory gate_coverage` → 38 passed, 0 failed, 4 ignored. + +Full suite: `$HOME/.cache/r14-suite-r2.log`, run on the tip after the second `git merge main` +(main `b51719f`) — totals appended below. + +## Verifier notes folded in (round 2) + +1. `lanes/r14-r1.report.md:18` corrected: the "104 / 172" pair is `decode_probe`'s **rect4_32** + counter line, not rect4_16; the true rect4_16 numbers on `kf300.obu` are 96, 148, 122, 311, 63. +2. `"a 16x16-level partition value outside PARTITION_NONE..PARTITION_VERT_4"` was unreachable + (all 10 symbols of that CDF are handled above the check) — removed from `decode.rs` (now a + `debug_assert_eq!(part16, PARTITION_SPLIT)`) and from `refusal_inventory.rs`. +3. The rectangular-residual wall lives in `decode_inter_block`, reached only from + `decode_inter_frame_tile`, so it fires on an **inter** frame: the key frame of `kf300.obu` + decodes through. **Not measured this round**: the decode-order index of the stopping frame and + a 16-bit byte-equality compare of every frame before it. `decode_probe` reports only the + refusal, and adding the per-frame `cmp` ladder did not fit this round's budget — + deferred(a `decode_probe` mode that dumps every decoded frame before the refusal and diffs it + against `ffmpeg -pix_fmt yuv420p10le`). + +## Residue + +- **deferred**(needs a rect-aware var-tx recursion + rect leaf reconstruction, ~2 call sites): + `a split transform on a 1:4 inter strip with a 64-px axis`. This is the film's next blocker in + BOTH mid-film segments. `sub_tx_size_map[TX_64X16] = TX_32X16` is rectangular, so the leaf + tuple `(row, col, tx_px)` and the two square leaf loops (`decode.rs` ~16174 and ~17150) have to + carry `(row, col, tw, th)`. Out of this round's ≤150-line scope. +- **deferred**(unrelated shape, needs its own bisect): enabling the 10-bit arm of the SB rect gate + exposes a pre-existing mismatch at attempt 14 (cq 61, horizontal split, motion step 12) that + decodes **zero** rect strips and zero 64-axis residual units — provably not this round's code + path. The gate stays `[8u32]` with that measured reason written at the loop instead of the + stale "non-skip residual is refused" one. +- **accepted**: `seg300` still stops at the intra-rect-strip refusal (lane-intrarect's wall, + named and inventoried). + +## Suite + +`systemd-run --user --unit=r14-suite-r2 ... cargo test -p ec-av1 --lib -j3` on tip `c604580` +(after `git merge main` @ `b51719f`) -> **365 passed; 0 failed; 31 ignored**, 623.58s, +log `$HOME/.cache/r14-suite-r2.log`. diff --git a/lanes/sb128-r1.report.md b/lanes/sb128-r1.report.md new file mode 100644 index 00000000..4f96acb2 --- /dev/null +++ b/lanes/sb128-r1.report.md @@ -0,0 +1,88 @@ +# lane-sb128 r1 — 128x128 superblocks, key frames + +Branch `lane-sb128` off main `a59645c`, worktree `edith_codecs-sb128`. + +## Film first (the ReelC blocker) + +`reelc5.obu` (1.1 MB, 1920x792 yuv420p10le, `use_128x128_superblock=1`) now decodes the 128 +superblock root and stops at a NAMED, unrelated refusal instead of desyncing: + +EVIDENCE: /tmp/claude-1000/.../cdc46329-.../scratchpad/reelc5.obu | `decode_probe reelc5.obu` +after this round | `REFUSED: unsupported: AV1 tile (a HORZ/VERT intra strip below 16x16 with a +split transform (per-unit rect prediction is not ported))` — a sub-16 intra-strip gap owned by +another lane, reached deep inside the tile (78 frame headers parsed, single tile). + +Not measured: the exact pre-change refusal string on this same file (no baseline binary was +built before the patch landed). deferred: film pixel compare — the stream still refuses, so +there is no frame to `cmp` — unblocked by the sub-16 split-transform strip lane. + +## What changed + +- `crates/ec-av1/src/decode.rs` + - `SB128` thread-local + `set_sb128` (also sets `Reach`'s superblock size), `sb_mi_cur()`. + - `sb_visit_order()`: at sb128 the tile walks each 128x128 superblock's four 64x64 + quadrants (TL, TR, BL, BR) before the next superblock — libaom `decode_partition`'s + recursion order, not raster over 64x64 superblocks. + - key-frame tile loop: per 128 superblock, one `read_lr` over the whole 128x128 and one + `partition_w128` symbol (8-symbol alphabet, no HORZ_4/VERT_4 at BLOCK_128X128; forced-split + gather `gather_of` + `VERT_ALIKE128`/`HORZ_ALIKE128` at the frame edge). SPLIT recurses + into the existing 64 path; the other seven arms refuse by name. + - `maybe_read_delta_q` / `maybe_read_delta_lf` key off `sb_mi_cur()` (once per 128x128, not + four times), and `is_whole_sb` is ignored at sb128 (no leaf can be a whole 128 superblock). + - `NO_NEIGHBOUR_SIDE = 128` replaces `SB` as the partition-context sentinel — ROOT CAUSE 1. + - intrabc under sb128 refuses by name (`av1_is_dv_valid`'s delay is sb_size-derived). +- `crates/ec-av1/src/encode.rs`: `Reach`'s `has_top_right`/`has_bottom_left` masked the block + position with a hardcoded 64 superblock; now `reach_sb_px()` (64 or 128) — ROOT CAUSE 2. + The tables themselves were already 128-relative (`table_stride`), only the masks were wrong. +- `crates/ec-av1/src/cdf.rs` / `cdf_state.rs`: `PARTITION_W128` (entropymode.c:154's four + `AOM_CDF8` rows), stored, reset per frame like `partition_w64`. +- `crates/ec-av1/src/stream.rs`: `set_sb128` per frame, scoped inter refusal, two gates. +- `crates/ec-av1/src/refusal_inventory.rs`: the three new refusals listed. + +Two defects found and fixed, both invisible at 64: +1. the no-neighbour partition-context sentinel (64) set the ctx bit at the 128 root — our ctx + was 3 where aomdec printed `ctx=16` (= `bsl*4 + 0`, row 0). Identical at every level <= 64, + so no existing gate could see it. +2. `has_top_right`/`has_bottom_left` answered against a 64 superblock — a bounded 1391-luma-pixel + band (x 124..255, y 44..67) with the entropy stream still in sync. + +## Gates + +`a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact` — real +`aomenc --sb-size=128 --max-partition-size=64`, 6 arms (256x192 seeds 42/43/44 8-bit, +384x384 8-bit, 256x192 10-bit, 384x384 10-bit), sequence header asserted +`use_128x128_superblock == true` at the arm's bit depth, every frame Y/U/V vs ffmpeg, hard +asserts on `part128_symbols`/`part128_split_hits`. No SKIP except a missing tool. + +EVIDENCE: `cargo test -p ec-av1 --lib 128x128 -- --nocapture` | 6 aomenc encodes decoded and +compared plane-by-plane | `6 pixel-exact, 0 named refusals, part128_symbols=26 +part128_split_hits=34`; `a_real_aomenc_128x128_inter_stream_refuses_by_name ... ok`. + +EVIDENCE: scratchpad/sb128/{ref128.yuv,our128.yuv} | seed 44 encoded at `--sb-size=128` and +`--sb-size=64`, both decoded through `decode_probe` and `cmp`ed against +`ffmpeg -f rawvideo -pix_fmt yuv420p` | before the two fixes: sb64 EXACT / sb128 DIFF at byte 1 +(ctx defect) then at byte 11518 (reach defect); after: `seed44 sb128 EXACT`. + +## Refused by name (still), each with its string + +- `a 128x128 superblock partition other than SPLIT (NONE/HORZ/VERT and the four AB arms at the + 128 root are not decoded)` — the six 128-level non-SPLIT arms + a 128x128 leaf. The gate pins + `--max-partition-size=64` so the encoder never chooses them. deferred: 128-level NONE/HORZ/VERT + (a 128x128 block is 2x2 TX_64X64 luma + 2x2 TX_32X32 chroma; `decode_block` codes ONE luma TU + per block outside the `tx_select` multi-TU branch and one chroma TU always) — unblocked by a + multi-TU chroma path in `decode_block`. +- `an inter frame under a 128x128 superblock (this decoder's inter tile path recurses a 64x64 + superblock root only)` — scoped to frames > 64x64 (a <=64x64 frame's 128 root reads no symbol). + deferred: inter at 128 — the second `for sb_r/sb_c` loop in `decode.rs` (~line 17800) plus OBMC + and mvstack neighbour caps — unblocked by porting `sb_visit_order` + the 128 prologue there. +- `intrabc under a 128x128 superblock (...)` — accepted for this round. + +## Suite + +`cargo test -p ec-av1 --lib` (systemd unit, log `$HOME/.cache/sb128-suite.log`): see the tail +appended below by the run. + +``` +test result: ok. 350 passed; 0 failed; 31 ignored; 0 measured; 0 filtered out; finished in 313.69s +``` +(31 ignored = the pre-existing ignore list, unchanged by this lane.) diff --git a/lanes/sb128-r2.report.md b/lanes/sb128-r2.report.md new file mode 100644 index 00000000..d45b6442 --- /dev/null +++ b/lanes/sb128-r2.report.md @@ -0,0 +1,123 @@ +# lane-sb128 r2 — the 128 root on INTER frames + +Branch `lane-sb128` (merged `main` 0df090a first, clean), worktree `edith_codecs-sb128`, +commit `8b4a36f`. + +## Film first + +Both probes ran with the inter refusal LIFTED locally (the code as committed refuses again — +see Residual), i.e. these are what the new inter-128 path reaches: + +EVIDENCE: `/tmp/.../b6d8a07f.../scratchpad/reelc-head.obu` | release `decode_probe` (6G scope) +| `REFUSED: unsupported: AV1 tile (a 128x128 superblock partition other than SPLIT +(NONE/HORZ/VERT and the four AB arms at the 128 root are not decoded))` after 17 frame headers +— i.e. ReelC's own head reaches a TASK-B arm, not the inter gap. + +EVIDENCE: `/tmp/.../cdc46329.../scratchpad/reelc5.obu` | release `decode_probe` (6G scope) | +`REFUSED: unsupported: AV1 tile (a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four +16x4/4x16 strips ...))` after 78 frame headers, `rect4_32: horz=8 vert=28 coded=32` — r1's stop +on this file ("a HORZ/VERT intra strip below 16x16 with a split transform") was lifted by the +merge from main; the film now stops on a sub-16 1:4 partition, another lane's cluster. + +With the committed tree the product path stops earlier, at the restored inter refusal. + +## What changed + +- `crates/ec-av1/src/decode.rs` + - `read_sb128_root()` (~11250): the 128 root extracted out of the key-frame loop — one + `read_lr` over the whole 128x128, one `partition_w128` symbol (8 symbols, `gather_of` + + `VERT_ALIKE128`/`HORZ_ALIKE128` at the frame edge), refusal by name for the seven + non-SPLIT arms. Both tile loops call it, so they cannot drift apart. + - `decode_inter_frame_tile_with_cdfs` (~18380, ~18570): `let sb128 = sb128();` and the + superblock loop replaced by `sb_visit_order(...)` + the 128 prologue. `delta_q`/`delta_lf` + already key off `sb_mi_cur()`; `CDEF_TRANSMITTED` is reset per 64x64 quadrant, which is + exactly libaom `read_cdef`'s per-quadrant `cdef_transmitted[index]`, index + `(mi_col&16)>>4 + 2*((mi_row&16)>>4)`. + - warp-sample `has_top_right` (13470) hardcoded `SB_MI` (a 64x64 superblock); now delegates + to the single sb-aware port. +- `crates/ec-av1/src/mvstack.rs`: `has_top_right()` ported from libaom `mvref_common.c:264` + (`sb_mi_size = mi_size_wide[seq.sb_size]`, so the mask loop runs one level further at 128); + both `scan_top_right` and `scan_top_right_compound` are now gated on it instead of a bare + "is the grid cell populated" probe. corner-cut in the doc: the three rect/`VERT_A` shape + refinements are not ported (ceiling = rect/AB INTER leaves, refused by name today). +- `crates/ec-av1/src/stream.rs`: the r1 refusal test replaced by the r2 gate (below), plus the + `sb128_r2_control_sb64` control; the inter refusal restored with the residual named. + +MEASURED, against the charter's premise: libaom `check_sb_border` (mvref_common.c:318) uses +`mi_size_wide[BLOCK_64X64]`, **hardcoded**, NOT `seq_params.sb_size` — the charter said to port +it as sb-derived. `mvstack.rs`'s `sb_mask = 16` is therefore already correct at 128 and was +left alone. `has_top_right` (line 266) is the one that is sb-derived. + +## Gate + +`a_real_aomenc_inter_sequence_with_128x128_superblocks_decodes_pixel_exact` — real aomenc +`--sb-size=128 --max-partition-size=64 --min-partition-size=32 --limit=8`, default +lag/alt-ref (1 hidden frame), gradients+`noise=all_seed=53:alls=12` (a clean gradient codes +with `cdef_bits=0` and the cdef counter stays 0), 8-bit and 10-bit, compared in DECODE order +frame by frame against the instrumented aomdec (`decode_all_frames_vs_oracle`, hidden frames +included), per-attempt counter deltas hard-asserted (`part128_symbols>=3`, `cdef_idx_hits>=1`, +`tmv_hits>=1`). It is `#[ignore]`d: it is a reproducer, not a passing gate. + +EVIDENCE: `cargo test -p ec-av1 --lib -- --nocapture inter_sequence_with_128x128` | +8-frame aomenc encode decoded in decode order vs aomdec | frames 0-5 and 7-8 byte-exact, +`decode-order frame 6 of 9 (8 shown, 1 hidden) differs at byte 24070 (ours 43 vs 42), 996 +bytes differ` — entropy stream in sync (a desync would corrupt the tail, not 996 bytes). + +EVIDENCE: `cargo test -p ec-av1 --lib -- --ignored --nocapture sb128_r2_control_sb64` | the +SAME source/recipe encoded at `--sb-size=64` | `control sb64: 9 frames exact (1 hidden)` — +the residual is sb128-specific, not a pre-existing inter defect the new recipe uncovered. + +Ablations run on the way (each a full gate run): `--enable-cdef=0` still mismatches (380 bytes, +byte 40960) so it is not the cdef read; the `has_top_right` port and the warp-sample fix each +changed nothing on this stream (both are libaom-faithful and stay). + +## Refusals + +- `an inter frame under a 128x128 superblock (...)` — **NOT lifted**, restored in `stream.rs` + with the residual named in the comment; still listed in `refusal_inventory.rs`. + fix-now(next round): identify the frame-6 block (the stream is pinned by the gate's panic + message under `/tmp/ec-av1-sb128-inter-8-/in.obu`; re-pin it, then range-ladder ours vs + aomdec on frame 6 — the entropy stream matches, so start at the PREDICTION side: OBMC + neighbour walk and mvstack candidates for the quadrant at mi_row 16..31 of an SB row). +- `a 128x128 superblock partition other than SPLIT (...)` — TASK B, deferred: 128-level + NONE/HORZ/VERT/AB — needs a multi-TU chroma loop in `decode_block` (a 128x128 block is + 2x2 TX_64X64 luma + 2x2 TX_32X32 chroma) — unblocked by that loop; ReelC's head stops here. +- `intrabc under a 128x128 superblock (...)` — accepted, unchanged. + +## Suite + +`cargo test -p ec-av1 --lib` under a user systemd unit, log `$HOME/.cache/sb128-suite-r2.log`: +tail appended below. + +``` +test result: FAILED. 348 passed; 8 failed; 31 ignored; finished in 522.44s +``` +- `mvstack::tests::all_same_mv_neighbourhood_dedupes_to_one_entry` — CAUSED BY THIS ROUND and + FIXED: gating `scan_top_right` on the new `has_top_right` red-lined it (the unported rect/ + `VERT_A` refinements). The MV stack keeps its grid probe; only the warp-sample gather uses + the port. Re-run after the fix: `ok`. +- The other 7 (`*_32_level_ab_partition_*`, `*_rect_and_ab_partitions_*`, + `*_superblock_level_1to4_partition_*`, `*_split_transform_horz_vert_strip_*`, + `*_chroma_is_a_4to1_or_sub8_rect_*`, `*_filter_intra_on_a_horz_vert_strip_*`) STILL FAIL after + that fix, and they fail on a FIRING COUNTER, not on pixels: e.g. "16 attempt(s) decoded + pixel-exact but HORZ_A_32 never fired". Every one of them is a rect/AB gate owned by the + lanes main merged today (rectsplitx/rect1d/fiinter/modectx); this lane's only non-sb128 code + change is the warp-sample `has_top_right` delegate, which is bit-identical at `sb_size == 64` + (`sb_mi_cur() == 16`), and all 7 streams are 64-superblock streams whose decode is exact. + NOT PROVEN either way inside this round's budget. + deferred: attribute the 7 — build `main` 0df090a in a detached worktree with its own + CARGO_TARGET_DIR and run the same 7 by name; if red there, they are a merge residue, not + this lane's — unblocked by one clean-tree suite run. + +## Coordinator items from the r1 verifier + +- (1) content-free r1 gate arms (mandelbrot + `--deltaq-mode=2` / `--enable-restoration=1`): + deferred — not started; the r2 gate already carries the noise/cdef fix for its own arms — + unblocked by a round that owns the r1 gate recipe. +- (2) `Reach::table(64)` falling back to the 16x16 rows: deferred — inert today, and TASK B + (the 128-level NONE/HORZ/VERT/AB arms that would hit it) is not started this round. +- (3) lane-oddh's `"a sequence using 128x128 superblocks on a frame larger than 64x64"` + refusal + its gate: NOT PRESENT in `main` 0df090a at merge time (`grep` finds neither the + string nor an asserting gate), so nothing to delete. +- TASK B (128-level NONE/HORZ/VERT/AB roots): deferred, not started — needs the chroma multi-TU + loop in `decode_block` first — unblocked by that loop. diff --git a/lanes/sb128-r3.handoff.md b/lanes/sb128-r3.handoff.md new file mode 100644 index 00000000..5d1a8375 --- /dev/null +++ b/lanes/sb128-r3.handoff.md @@ -0,0 +1,94 @@ +# lane-sb128 r3 handoff (turn cap) + +Branch `lane-sb128`, worktree `edith_codecs-sb128`. Two commits this round: +`dbf15a4` (TASK 1 fix), `d6cca7d` (TASK 2 fix + refusal lift, WIP: suite not run). + +## TASK 1 -- the 7 rect/AB firing-counter reds: ATTRIBUTED AND FIXED (`dbf15a4`) + +Attribution table (same 7 gate names, run by name, own `CARGO_TARGET_DIR`): + +| tree | result | log | +| --- | --- | --- | +| main `0df090a` (detached worktree) | 7 passed | `$HOME/.cache/sb128-verify7.log` | +| lane r1 `5e5f113` | 7 passed | `$HOME/.cache/sb128-verify-r1.log` | +| lane merge `63890cb` | 7 passed | `$HOME/.cache/sb128-verify-merge.log` | +| lane r2 `807c110` | 7 FAILED | `$HOME/.cache/sb128-lane7.log` | +| lane r3 `dbf15a4` | 7 passed | `$HOME/.cache/sb128-lane7b.log` | + +LANE-CAUSED, and not a merge residue: r2 blanket-rewrote every +`"--min-partition-size=16"` in `stream.rs`'s aomenc recipes to `=32` while writing +its own 128 gate -- 13 lines across 13 gates, 7 of which assert a firing counter. +With min-partition 32 aomenc never emits a 16-level partition, so those streams +still decoded PIXEL-EXACT while `HORZ_A_32` / `rect_partition_hits` / the 1:4 and +strip counters read 0 and the "never fired" guard red-lined them. Fix = revert +exactly those 13 lines (diff-matched old-vs-new, not a sed); no counter bump site +was lost in the merge, that hypothesis is DISPROVED. + +EVIDENCE: `$HOME/.cache/sb128-lane7b.log` | `cargo test -p ec-av1 --lib -- <7 names>` +on `dbf15a4` | `test result: ok. 7 passed; 0 failed`. + +## TASK 2 -- inter frames at 128, frame 6: ROOT-CAUSED AND FIXED (`d6cca7d`) + +Stream re-pinned (sha256 twice, identical): +`.../scratchpad/sb128-inter8.obu` = `3e991db7aa7f6d6f70b91b41417b7741d0468343ee4e19e1adf7db066e3c8981` + +Ladder actually walked: +1. `EC_AV1_PREFILT_DUMP` both sides -> decode-order frame 6 differs PRE-FILTER, + 957 bytes, all inside luma y=96..127 x=0..31, i.e. ONE 32x32 block at mi(24,0). + So it is reconstruction, not deblock/CDEF/LR. +2. `EC_OBMC=1` on aomdec: 0 lines on this stream -- OBMC EXONERATED. +3. Ablation `set_reach_superblock_px(64)` (r1's sb-aware intra `Reach`): frame 6 + still 957 bytes wrong -- Reach EXONERATED. +4. Mode info EQUAL: located the oracle's line by matching `mi_row/mi_col` AND the + pre-mode `rng` (entropy in sync, so ranges match block for block): + both sides `mode=24 (NEW_NEWMV) ref0=3 ref1=5 stack=3`. Ours resolved + `mv0=(847,-105)`, oracle `mv0=(792,-245)`. +5. The MV STACK ORDER differed, from ONE missing weight-2 vote: + oracle `(569,-380) w=6 / (624,-240) w=6 / (802,-381) w=4` + ours `(624,-240) w=6 / (802,-381) w=4 / (569,-380) w=4`. + Spatial scans found NOTHING for this block (mi_col=0, no left; row scan empty), + so every candidate is TEMPORAL. + +ROOT CAUSE: `mvstack.rs::find_mv_stack_compound` never ported libaom's three +`tpl_sample_pos` EXTENSION samples (`mvref_common.c:591`, gated by `allow_extension` ++ `check_sb_border`). The SINGLE-ref twin `find_mv_stack` has them (mvstack.rs ~900); +the compound twin stopped after the main `blk_row/blk_col` loop. Class: +`neighbour-votes-all-its-fields` / asymmetric port -- a compound twin missing a +whole scan phase of its single-ref sibling. NOT sb128-specific: `check_sb_border` +masks with libaom's hardcoded `mi_size_wide[BLOCK_64X64]` (16), never `seq.sb_size`. +sb128 only made aomenc pick the compound NEW_NEWMV block that exposed it. + +Fix (`d6cca7d`): the extension loop added to the compound path, both sides +projected through `motion_field::add_tpl_ref_mv`, `add_compound_candidate(..., 2)`. + +EVIDENCE: `.../scratchpad/pf/{aom,ours}.f0..f8` | `decode_probe` + instrumented +`aomdec`, both under `EC_AV1_PREFILT_DUMP`, on the pinned obu | +all 9 decode-order frames 0 differing bytes (was: frame 6, 957 bytes). + +Also in `d6cca7d`: inter-at-128 refusal DELETED from `stream.rs` and from +`refusal_inventory.rs`; the reproducer gate `a_real_aomenc_inter_sequence_with_ +128x128_superblocks_decodes_pixel_exact` UN-`#[ignore]`d; debug scaffolding removed +(`EC_ABL_REACH64`, `EC_TRACE_MV`); an `EC_MODE_VAL`/`EC_STACK` trace kept on the +compound path under `EC_TRACE_MODE`, byte-format-identical to the oracle's rung-4. + +## NOT DONE -- exact next steps for r4 + +1. RUN THE UN-IGNORED GATE (both bit depths; only the 8-bit arm was proven, via + `decode_probe` on the pinned obu, not through the gate): + `cargo test -p ec-av1 --lib -- --nocapture inter_sequence_with_128x128` +2. Siblings, then the full suite -> `$HOME/.cache/sb128-suite-r3.log`, expect 0 + failed: `128x128` gates, `inter_sequence*`, `obmc`, `temporal_mv_candidates`, + `superblock_level_*`, the 7 rect/AB names above, `refusal_inventory`, + `gate_coverage`. The compound-tpl fix touches EVERY compound inter block in the + crate, so treat any red as this fix, not as flake. +3. SWEEP THE CLASS: diff `find_mv_stack` against `find_mv_stack_compound` phase by + phase (only the extension loop was checked); the same "compound twin dropped a + phase" shape may sit in the outer row/col scans or the extra-search fill. +4. Verifier note still owed: cdef/LR/delta_q arms with noise (`cdef_bits>0`) on the + 128 gate, and the r1 gate's content-free arms. +5. Film: `reelc-head.obu` through `decode_probe` -- expect the 128-root + NONE/HORZ/VERT/AB refusal (sibling lane `lane-sb128b` owns it), NOT the inter one. + +HANDOFF: d6cca7d -- TASK 1 fixed and proven by attribution table; TASK 2 root-caused +(compound MV stack was missing libaom's three tpl extension samples) and fixed with +all 9 frames prefilt-exact, refusal lifted and gate un-ignored, but NO suite run yet. diff --git a/lanes/sb128-r4.report.md b/lanes/sb128-r4.report.md new file mode 100644 index 00000000..35a3c68e --- /dev/null +++ b/lanes/sb128-r4.report.md @@ -0,0 +1,136 @@ +# lane-sb128 r4 report + +Branch `lane-sb128`. Two commits this round: +`a599740` (merge of main `b51719f` + merge-seam repair), `e3d32d1` (128-root +gathered-partition fix). + +## 1. Merge of main `b51719f` (`a599740`) + +`git merge --no-commit main` auto-merged clean (0 conflicted paths, diffstat +21 files / +4375 / -293: palette2, sub8, rectsplitx, inter4, refstamp, oddh, +band63, angleinter content). No lane-vs-main deletion was restored. + +Table check the charter asks for (`git show main:crates/ec-av1/src/cdf.rs` vs +the merged file): the WHOLE cdf.rs delta is 12 lines and they are this lane's +added `PARTITION_W128` constant. `NZ_MAP_CTX_OFFSET_32` / `_32X64` / `_64X32` +and `FILTER_INTRA` / `FILTER_INTRA_MODE` are byte-identical to main (only +their line numbers shift by 11). + +MERGE SEAM REPAIRED (predicted by the ledger constraint on `866cbb1`): main +carries lane-oddh's refusal *"a sequence using 128x128 superblocks on a frame +larger than 64x64"* at `stream.rs` `decode_stream`, which refuses exactly the +capability this lane implements, plus its gate at +`a_real_aomenc_128x128_superblock_stream_is_refused_by_name`. Both deleted, +plus the `refusal_inventory.rs` entry. The gate was NOT dropped: it is now +`a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact`, same 64x72 +`--cpu-used=0 --sb-size=128` aomenc stream, decoded through +`decode_all_frames_vs_oracle` (pixel-exact vs aomdec, refusal or mismatch is a +hard panic, never a SKIP). + +## 2. Root-cause fix: the 128 root threw its own partition symbol away (`e3d32d1`) + +`decode.rs::read_sb128_root`, half-out-of-frame arm: it read the gathered +2-symbol `split_or_horz`/`split_or_vert` and returned `PARTITION_SPLIT` +unconditionally. Spec 5.11.4 makes that symbol the DECISION (1 = SPLIT, +0 = HORZ when only cols are out / VERT when only rows are out). The 64 root +`partition_w64` already carries the fixed form -- its own comment records the +3840x1608 10-bit head this same defect desynced -- so this is that class +(`parsed then discarded`) unported to 128. + +Consequence before the fix: a 128 root that really codes HORZ/VERT at the +frame edge was silently reconstructed as a split instead of reaching the +refusal that names it. Found because the converted oddh gate decoded +pixel-exact while reading zero 128 partition symbols. + +New witness counter `part128_gathered_symbols()` (`decode.rs:89`), asserted +`> 0` by the oddh gate. Its recipe also gains `--min-partition-size=16`: +without it aomenc emits `PARTITION_HORZ_4` below 16x16 (another lane's gap) +and the gate measured that refusal instead of the 128 root. + +`decode_probe` now prints `SEQ: use_128x128_superblock=... bit_depth=... +max_frame=WxH` next to its tiling line. + +## 3. The 128 gates + +Command (all under `systemd-run --user --unit=... -p MemoryMax=10G`, +`EC_AV1_REQUIRE_AOMENC=1`, `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-sb128`): +`cargo test -p ec-av1 --lib -j3 -- --nocapture --test-threads=2 128x128` + +``` +a_real_aomenc_inter_sequence_with_128x128_superblocks_decodes_pixel_exact (yuv420p): 9 decode-order frames pixel-exact (1 hidden), part128_symbols=18 cdef_idx_hits=12 tmv_hits=103 +a_real_aomenc_inter_sequence_with_128x128_superblocks_decodes_pixel_exact (yuv420p10le): 9 decode-order frames pixel-exact (1 hidden), part128_symbols=18 cdef_idx_hits=12 tmv_hits=100 +a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact: 1 frames pixel-exact (0 hidden) at 64x72, part128_symbols=1 +a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact: 6 pixel-exact, 0 named refusals, part128_symbols=26 part128_split_hits=34 +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 395 filtered out; finished in 4.59s +``` + +The un-ignored inter gate meets every clause the charter names: real aomenc +stream with a knob-arrival assert on the sequence header +(`use_128x128_superblock == true` AND the requested bit depth), per-arm +counter deltas taken around the decode (`part128`/`cdef_idx`/`tmv`, each +hard-asserted), every decode-order frame compared inside +`decode_all_frames_vs_oracle` (which panics on a decoder refusal and on any +differing byte -- there is no out-of-scope-mismatch tolerance path in it at +all, so that count is structurally 0), 8- and 10-bit arms, and a SKIP only +when ffmpeg/aomenc are absent, which `EC_AV1_REQUIRE_AOMENC=1` turns into a +hard failure. + +EVIDENCE: `$HOME/.cache/sb128-r4-g128c.log` | `cargo test -p ec-av1 --lib -- --nocapture 128x128` on `e3d32d1` | `test result: ok. 3 passed; 0 failed`. + +## 4. Full lib suite + +``` +test result: ok. 366 passed; 0 failed; 32 ignored; 0 measured; 0 filtered out; finished in 636.94s +``` + +`gate_coverage` (10 tests), `refusal_inventory` and +`decode::tests::base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain` +all `ok`. + +EVIDENCE: `$HOME/.cache/sb128-suite-r4.log` | `systemd-run --user --unit=sb128-r4-suite -p MemoryMax=10G ... EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j3` on `e3d32d1` | `366 passed; 0 failed; 32 ignored`. + +## 5. ReelC probe + +Stream: `ffmpeg -c:v copy -f obu` extract of +`reelc.mkv`, 1175978 bytes, +sha256 `bf31d1ba8600a9c26ae12c11cb44435490d48f5316a77cc307d6e5dbb4efac8c`, +78 frame headers, 1 tile. + +``` +TILING: 78 frame headers parsed +SEQ: use_128x128_superblock=true bit_depth=10 max_frame=1920x792 +REFUSED: unsupported: AV1 tile (a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 strips -- this decoder codes NONE, HORZ, VERT, the four AB arms and a clean split at 16x16)) +``` + +| what | value | +| --- | --- | +| decode-order frame it stops on | 0 (the first key frame) | +| frames compared vs ffmpeg yuv420p10le | 0 -- `decode_stream` returns `Err`, so no plane is produced to compare | +| refusal string reached | `a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 strips -- this decoder codes NONE, HORZ, VERT, the four AB arms and a clean split at 16x16)` | +| block | 16x16 at neighbour index `at16 = (21, 119)` = mi_row 84, mi_col 476, pixel (y=336, x=1904) -- the frame's last 16-pixel column (1904+16 = 1920) | +| partition value read | 9 = `PARTITION_VERT_4` | + +Measured by a temporary `eprintln!` at the refusal site (`decode.rs:12462`), +reverted in the same session; the permanent artefact is the `SEQ:` line. + +REELC DOES NOT STOP ON 128 NONE/HORZ/VERT, and it does not stop on the inter +one either: `use_128x128_superblock=true` at 1920x792 is precisely what main +`b51719f` refuses outright, and this lane carries ReelC through the 128 root, +through 128-level SPLIT and the whole 64/32 tree, down to a 16x16 block that +codes `PARTITION_VERT_4`. That gap belongs to the 1:4-below-16x16 lane, not to +lane-sb128b's 128 NONE luma + chroma 2x2 TX_32X32 work -- nothing was +duplicated. + +The first ~30 decode-order frames could not be compared: the decode aborts on +frame 0. That comparison is `deferred(the 1:4-below-16x16 refusal being +lifted)`. + +## Residue + +- `deferred(another round)`: the handoff's TASK 3 class sweep -- diffing + `find_mv_stack` against `find_mv_stack_compound` phase by phase beyond the + tpl extension loop r3 already ported. Not started this round. +- `deferred(the 1:4-below-16x16 lane)`: ReelC's first ~30-frame pixel compare. +- `accepted`: 128-root NONE/HORZ/VERT/AB still refuse by name; with `e3d32d1` + that refusal is now actually reachable at a half-out-of-frame superblock + instead of being silently mis-decoded. lane-sb128b owns lifting it.