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 dbef2e14..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, diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 2b01d282..7eef9418 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -267,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], @@ -737,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); @@ -902,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, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 9b3064e9..b4a7ad28 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()); @@ -2508,6 +2581,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; @@ -3735,10 +3820,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)], @@ -3803,7 +3888,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), @@ -3811,7 +3896,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. @@ -4150,8 +4235,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); @@ -12600,6 +12685,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, @@ -12632,6 +12842,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(|| { @@ -12769,19 +12985,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); @@ -14844,34 +15083,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 @@ -16063,6 +16284,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 @@ -20132,6 +20369,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)); @@ -20353,19 +20591,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 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 8c0fd438..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); @@ -1623,6 +1660,47 @@ pub fn find_mv_stack_compound( } blk_row += step_h; } + // lane-sb128 r3: libaom's three `tpl_sample_pos` EXTENSION samples + // (mvref_common.c:591), which the single-ref twin already ports and + // this compound path dropped. `check_sb_border`'s mask is libaom's + // hardcoded `mi_size_wide[BLOCK_64X64]` (16), NOT the sequence's + // superblock size. Missing them cost one weight-2 vote on a + // candidate, which reordered the stack and gave a NEW_NEWMV block a + // different predictor -- 957 wrong pixels on one 32x32 block of one + // frame with the entropy stream in sync. + let allow_extension = (2..16).contains(&bh4) && (2..16).contains(&bw4); + if allow_extension { + let (voffset, hoffset) = (bh4.max(2) as isize, bw4.max(2) as isize); + let sb_mask = 16isize; + for (row_off, col_off) in [ + (voffset, -2isize), + (voffset, hoffset), + (voffset - 2, hoffset), + ] { + let row = (mi_row as isize & (sb_mask - 1)) + row_off; + let col = (mi_col as isize & (sb_mask - 1)) + col_off; + if row < 0 || row >= sb_mask || col < 0 || col >= sb_mask { + continue; + } + let cand0 = crate::motion_field::add_tpl_ref_mv( + field, mi_row, mi_col, row_off, col_off, cur_offset_0, + allow_high_precision_mv, + ); + let cand1 = crate::motion_field::add_tpl_ref_mv( + field, mi_row, mi_col, row_off, col_off, cur_offset_1, + allow_high_precision_mv, + ); + if cand0.is_some() || cand1.is_some() { + any_hit = true; + add_compound_candidate( + &mut candidates, + cand0.map_or((0, 0), |c| c.mv), + cand1.map_or((0, 0), |c| c.mv), + 2, + ); + } + } + } if any_hit { TMV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 59c87d46..9581323a 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -42,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", @@ -49,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", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index bfef83f9..eab98345 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -510,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 @@ -531,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 @@ -1103,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; @@ -1139,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()) @@ -1169,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}" ); } @@ -2755,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", @@ -13645,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", @@ -17073,6 +17069,7 @@ mod tests { "--cpu-used=4", &aq, "--deltaq-mode=0", + "--enable-cdef=0", "--kf-max-dist=1000", "--threads=1", "--row-mt=0", @@ -17802,6 +17799,417 @@ mod tests { ); } + /// 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_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"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + 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`] -- @@ -17879,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", @@ -18245,6 +18654,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", @@ -18451,6 +18861,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", @@ -18705,6 +19116,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 @@ -18876,6 +19288,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", @@ -19071,6 +19484,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", @@ -19269,6 +19683,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", @@ -19445,6 +19860,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", @@ -19908,6 +20324,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", @@ -21502,6 +21919,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", 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.