From e749a4d73f944c8283900be760c3f290f1189096 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Sep 2026 06:24:49 +0300 Subject: [PATCH] feat(av1): decode 128x128 superblocks on key frames (the ReelC blocker) His ReelC encode codes use_128x128_superblock=1 (aomdec EC_TRACE: EC_PART mi_row=0 mi_col=0 bsize=15); ec-av1 never read that sequence bit and decoded every frame as 64x64 superblocks, so every earlier ReelC stop was a desync artefact. - decode.rs: SB128 thread-local + set_sb128; the key-frame tile loop now walks the 64x64 quadrants in libaom's nested order (sb_visit_order), reads the 128 root's loop-restoration units once per 128x128 and one partition symbol off the 8-symbol partition_w128 CDF (forced-split gather at the frame edge), and recurses SPLIT into the existing 64 path; the other seven 128-level arms refuse by name. delta_q/delta_lf now key off the real superblock size. - Neighbours' no-neighbour partition-context sentinel was SB (64), which reads identically up to the 64 root but set the bit at BLOCK_128X128 -- the 128 symbol came off CDF row 3 where libaom uses row 0. - Reach (has_top_right/has_bottom_left) masked the block's position with a hardcoded 64 superblock; libaom masks with the sequence's own sb_size. - stream.rs: inter frames under a 128 superblock refuse by name (scoped to frames larger than one 64x64 superblock, since a <=64x64 frame decodes identically either way). Gates: a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact (6/6 pixel-exact, 8- and 10-bit, 256x192 + 384x384, part128_symbols=26, part128_split_hits=34) and a_real_aomenc_128x128_inter_stream_refuses_by_name. --- crates/ec-av1/src/cdf.rs | 11 ++ crates/ec-av1/src/cdf_state.rs | 4 + crates/ec-av1/src/decode.rs | 236 +++++++++++++++++++++++--- crates/ec-av1/src/encode.rs | 47 +++-- crates/ec-av1/src/stream.rs | 301 +++++++++++++++++++++++++++++++++ 5 files changed, 559 insertions(+), 40 deletions(-) diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index fa42e872..49a012d8 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 f4d4dd64..e9c1ad99 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -223,6 +223,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], @@ -693,6 +695,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); @@ -858,6 +861,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 b54d9bd0..77c08675 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -56,6 +56,67 @@ 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). +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) }; +} + +/// 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()) +} + +/// The one 128-level partition arm this decoder codes so far. +const PART128_NON_SPLIT_REFUSAL: &str = + "a 128x128 superblock partition other than SPLIT (NONE/HORZ/VERT/HORZ_A/HORZ_B/VERT_A/VERT_B at the 128 root are not decoded)"; + +/// [`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 @@ -206,10 +267,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; @@ -261,10 +326,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()); @@ -2151,6 +2220,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; @@ -3376,10 +3457,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)], @@ -3444,7 +3525,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), @@ -3452,7 +3533,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. @@ -3791,8 +3872,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); @@ -10659,6 +10740,50 @@ 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 +} + pub(crate) fn decode_key_frame_tile_with_cdfs( tiles: &[&[u8]], tile_info: &TileInfo, @@ -10691,6 +10816,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(|| { @@ -10828,19 +10959,74 @@ 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 { + let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI); + crate::restoration::read_lr( + &mut dec, + &mut cdfs, + lr, + &mut lr_grid, + &mut 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 { + match (has_cols128, has_rows128) { + (true, false) => { + dec.symbol_fixed(&gather_of( + &cdfs.partition_w128[ctx128], + &VERT_ALIKE128, + )); + } + (false, true) => { + dec.symbol_fixed(&gather_of( + &cdfs.partition_w128[ctx128], + &HORZ_ALIKE128, + )); + } + _ => {} + } + PARTITION_SPLIT + }; + if part128 != PARTITION_SPLIT { + return Err(unsupported(PART128_NON_SPLIT_REFUSAL)); + } + PART128_SPLIT_HITS.with(|c| c.set(c.get() + 1)); + } + 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); diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 1ba18ed6..f6558880 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. /// @@ -1296,19 +1316,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; @@ -1329,20 +1349,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; @@ -1416,7 +1436,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; @@ -1447,11 +1467,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/stream.rs b/crates/ec-av1/src/stream.rs index cdbe5fbc..822d6e60 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -480,6 +480,26 @@ 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: `use_128x128_superblock` (spec 5.5.1). The key-frame + // tile path reads the 128 partition root and recurses SPLIT into the + // four 64x64 quadrants; the inter tile path is still written for a + // 64x64 root only (its own superblock loop, OBMC/mvstack neighbour + // caps and `read_cdef` reset all key off `SB_MI`), so refuse there by + // name rather than desync. 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 refusal is scoped to 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); + if sb128_active && header.frame_type != FrameType::Key { + return Err(Error::unsupported( + "AV1 decode_stream", + "an inter frame under a 128x128 superblock (this decoder's inter tile path recurses a 64x64 superblock root only)", + )); + } // 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 @@ -15412,6 +15432,287 @@ 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() + ); + } + + /// lane-sb128 r1: the inter half of a `--sb-size=128` stream is refused by + /// NAME (the inter tile path still recurses a 64x64 root only), never + /// silently decoded at the wrong superblock size the way this decoder did + /// before this round -- which is what made every earlier ReelC "stop" a + /// desync artefact rather than a real capability gap. + #[test] + fn a_real_aomenc_128x128_inter_stream_refuses_by_name() { + const NAME: &str = "a_real_aomenc_128x128_inter_stream_refuses_by_name"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() || !have_aomenc() { + eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); + return; + } + let (width, height) = (256usize, 192usize); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &gradients_source(51, width, height, "duration=0.24:rate=25"), + "-pix_fmt", + "yuv420p", + "-t", + "0.24", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!(y4m.status.success(), "ffmpeg fixture"); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=40", + "--cpu-used=1", + "--threads=1", + "--row-mt=0", + "--sb-size=128", + "--max-partition-size=64", + "--deltaq-mode=0", + "--limit=6", + "--lag-in-frames=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"); + let err = decode_stream(&out.stdout) + .err() + .map(|e| e.to_string()) + .unwrap_or_default(); + assert!( + err.contains("an inter frame under a 128x128 superblock"), + "{NAME}: expected the scoped inter refusal, got: {err:?}" + ); + eprintln!("{NAME}: {err}"); + } + /// 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`] --