forge
Explore
Log in

Don't you dare go Hollow

Decode 128x128 superblocks on key frames (the ReelC blocker)

Browse files at this commit

e749a4d73f944c8283900be760c3f290f1189096Ahmet Kaan GümüşParent: 7a9d28d
  • feat
    • decode 128x128 superblocks on key frames (the ReelC blocker)
Show full message
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.rsmodified+11 -0
@@ -8,6 +8,17 @@
8 8
9 /// `Default_Partition_W64_Cdf` (spec 9.4): the ten partition types of a9 /// `Default_Partition_W64_Cdf` (spec 9.4): the ten partition types of a
10 /// 64x64 block, indexed by the context the blocks above and left give.10 /// 64x64 block, indexed by the context the blocks above and left give.
11+/// `default_partition_cdf`'s last four contexts (entropymode.c:154, the
12+/// `AOM_CDF8` rows): the `BLOCK_128X128` root's alphabet is
13+/// `EXT_PARTITION_TYPES - 2 = 8` -- `PARTITION_HORZ_4`/`_VERT_4` do not exist
14+/// at 128 (spec `partition_cdf_length`).
15+pub const PARTITION_W128: [[u16; 9]; 4] = [
16+ [27899, 28219, 28529, 32484, 32539, 32619, 32639, 32768, 0],
17+ [6607, 6990, 8268, 32060, 32219, 32338, 32371, 32768, 0],
18+ [5429, 6676, 7122, 32027, 32227, 32531, 32582, 32768, 0],
19+ [711, 966, 1172, 32448, 32538, 32617, 32664, 32768, 0],
20+];
21+
11 pub const PARTITION_W64: [[u16; 11]; 4] = [22 pub const PARTITION_W64: [[u16; 11]; 4] = [
12 [23 [
13 20137, 21547, 23078, 29566, 29837, 30261, 30524, 30892, 31724, 32768, 0,24 20137, 21547, 23078, 29566, 29837, 30261, 30524, 30892, 31724, 32768, 0,
crates/ec-av1/src/cdf_state.rsmodified+4 -0
@@ -223,6 +223,8 @@ pub(crate) struct TxbTables<'a> {
223 #[derive(Clone)]223 #[derive(Clone)]
224 pub(crate) struct Cdfs {224 pub(crate) struct Cdfs {
225 /// The partition symbol of a 64x64 superblock.225 /// The partition symbol of a 64x64 superblock.
226+ /// `partition_cdf`'s `BLOCK_128X128` rows (8 symbols).
227+ pub partition_w128: [[u16; 9]; 4],
226 pub partition_w64: [[u16; 11]; 4],228 pub partition_w64: [[u16; 11]; 4],
227 /// The partition symbol of a 32x32 block.229 /// The partition symbol of a 32x32 block.
228 pub partition_w32: [[u16; 11]; 4],230 pub partition_w32: [[u16; 11]; 4],
@@ -693,6 +695,7 @@ impl Cdfs {
693 /// into a reference slot for cross-frame forwarding; never on a table695 /// into a reference slot for cross-frame forwarding; never on a table
694 /// still being read within the same tile.696 /// still being read within the same tile.
695 pub(crate) fn reset_counts(&mut self) {697 pub(crate) fn reset_counts(&mut self) {
698+ reset2(&mut self.partition_w128);
696 reset2(&mut self.partition_w64);699 reset2(&mut self.partition_w64);
697 reset2(&mut self.partition_w32);700 reset2(&mut self.partition_w32);
698 reset2(&mut self.txfm_partition);701 reset2(&mut self.txfm_partition);
@@ -858,6 +861,7 @@ impl Cdfs {
858 /// quantizer, so they are the same for every `q_ctx`.861 /// quantizer, so they are the same for every `q_ctx`.
859 pub fn new(q_ctx: usize) -> Cdfs {862 pub fn new(q_ctx: usize) -> Cdfs {
860 Cdfs {863 Cdfs {
864+ partition_w128: cdf::PARTITION_W128,
861 partition_w64: cdf::PARTITION_W64,865 partition_w64: cdf::PARTITION_W64,
862 partition_w32: cdf::PARTITION_W32,866 partition_w32: cdf::PARTITION_W32,
863 skip: cdf::SKIP,867 skip: cdf::SKIP,
crates/ec-av1/src/decode.rsmodified+211 -25
@@ -56,6 +56,67 @@ const PARTITION_VERT_4: usize = 9;
56 const SB_MI: u32 = 16;56 const SB_MI: u32 = 16;
57 const BLOCK_MI: u32 = 8;57 const BLOCK_MI: u32 = 8;
58 58
59+// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
60+// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
61+// superblock's own top-left mi?", the loop-restoration read's unit span, the
62+// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
63+// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
64+// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
65+// inside a 128 superblock).
66+thread_local! {
67+ static SB128: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
68+}
69+
70+/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
71+pub(crate) fn set_sb128(v: bool) {
72+ SB128.with(|c| c.set(v));
73+ crate::encode::set_reach_superblock_px(if v { 128 } else { 64 });
74+}
75+
76+fn sb128() -> bool {
77+ SB128.with(|c| c.get())
78+}
79+
80+/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
81+fn sb_mi_cur() -> u32 {
82+ if sb128() { SB_MI * 2 } else { SB_MI }
83+}
84+
85+/// How many real 128-level partition symbols this decoder has read, and how
86+/// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
87+/// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
88+thread_local! {
89+ static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
90+ static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
91+}
92+
93+/// Current value of [`PART128_SYMBOLS`].
94+pub(crate) fn part128_symbols() -> usize {
95+ PART128_SYMBOLS.with(|c| c.get())
96+}
97+
98+/// Current value of [`PART128_SPLIT_HITS`].
99+pub(crate) fn part128_split_hits() -> usize {
100+ PART128_SPLIT_HITS.with(|c| c.get())
101+}
102+
103+/// The one 128-level partition arm this decoder codes so far.
104+const PART128_NON_SPLIT_REFUSAL: &str =
105+ "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)";
106+
107+/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
108+/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
109+/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
110+/// the 64/32 levels sum 6.
111+fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
112+ let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
113+ [32768 - split, 32768, 0]
114+}
115+
116+/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
117+const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
118+const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
119+
59 // How many `use_filter_intra` symbols this decoder has read as `1`, across120 // How many `use_filter_intra` symbols this decoder has read as `1`, across
60 // every call on the current thread -- the cheap counter [`filter_intra_hits`] gate121 // every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
61 // tests read (before/after, not the absolute value) to prove a stream122 // 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_
206 if !DELTA_Q_PRESENT.with(|c| c.get()) {267 if !DELTA_Q_PRESENT.with(|c| c.get()) {
207 return;268 return;
208 }269 }
209- if mi_r % SB_MI as usize != 0 || mi_c % SB_MI as usize != 0 {270+ let sb_mi = sb_mi_cur() as usize;
271+ if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
210 return;272 return;
211 }273 }
212- if is_whole_sb && skip {274+ // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, which
275+ // it computes against the 64x64 root; under a 128 superblock no leaf this
276+ // decoder codes can be the whole superblock (the root is always SPLIT).
277+ if is_whole_sb && !sb128() && skip {
213 return;278 return;
214 }279 }
215 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;280 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
261 if !DELTA_LF_PRESENT.with(|c| c.get()) {326 if !DELTA_LF_PRESENT.with(|c| c.get()) {
262 return;327 return;
263 }328 }
264- if mi_r % SB_MI as usize != 0 || mi_c % SB_MI as usize != 0 {329+ let sb_mi = sb_mi_cur() as usize;
330+ if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
265 return;331 return;
266 }332 }
267- if is_whole_sb && skip {333+ // `is_whole_sb` is the caller's "this leaf IS the superblock" flag, which
334+ // it computes against the 64x64 root; under a 128 superblock no leaf this
335+ // decoder codes can be the whole superblock (the root is always SPLIT).
336+ if is_whole_sb && !sb128() && skip {
268 return;337 return;
269 }338 }
270 let multi = DELTA_LF_MULTI.with(|c| c.get());339 let multi = DELTA_LF_MULTI.with(|c| c.get());
@@ -2151,6 +2220,18 @@ fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
2151 const SUB_MI: u32 = 4;2220 const SUB_MI: u32 = 4;
2152 const MI: usize = 4;2221 const MI: usize = 4;
2153 const SB: usize = 64;2222 const SB: usize = 64;
2223+/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
2224+/// (tile start, superblock-row start).
2225+///
2226+/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
2227+/// `av1_get_partition_plane_context` reads its own zero-initialised
2228+/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
2229+/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
2230+/// (64), which reads identically at every level up to 64x64 but sets the bit
2231+/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
2232+/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
2233+/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
2234+const NO_NEIGHBOUR_SIDE: usize = 128;
2154 const BLOCK: usize = 32;2235 const BLOCK: usize = 32;
2155 const SUB: usize = 16;2236 const SUB: usize = 16;
2156 const TX32: usize = 32;2237 const TX32: usize = 32;
@@ -3376,10 +3457,10 @@ impl Neighbours {
3376 left_mode: vec![DC_PRED; rows],3457 left_mode: vec![DC_PRED; rows],
3377 above_uv_mode: vec![DC_PRED; cols],3458 above_uv_mode: vec![DC_PRED; cols],
3378 left_uv_mode: vec![DC_PRED; rows],3459 left_uv_mode: vec![DC_PRED; rows],
3379- above_side: vec![SB; cols],3460+ above_side: vec![NO_NEIGHBOUR_SIDE; cols],
3380- left_side: vec![SB; rows],3461+ left_side: vec![NO_NEIGHBOUR_SIDE; rows],
3381- above_side_mi: vec![SB; cols * (SUB / MI)],3462+ above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
3382- left_side_mi: vec![SB; rows * (SUB / MI)],3463+ left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
3383 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],3464 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
3384 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],3465 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
3385 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],3466 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
@@ -3444,7 +3525,7 @@ impl Neighbours {
3444 let end = col1_mi.min(self.above.len());3525 let end = col1_mi.min(self.above.len());
3445 for i in col0_mi.min(end)..end {3526 for i in col0_mi.min(end)..end {
3446 self.above[i] = Default::default();3527 self.above[i] = Default::default();
3447- self.above_side_mi[i] = SB;3528+ self.above_side_mi[i] = NO_NEIGHBOUR_SIDE;
3448 }3529 }
3449 let (sc0, sc1) = (3530 let (sc0, sc1) = (
3450 col0_mi / (SUB / MI),3531 col0_mi / (SUB / MI),
@@ -3452,7 +3533,7 @@ impl Neighbours {
3452 );3533 );
3453 for i in sc0.min(sc1)..sc1 {3534 for i in sc0.min(sc1)..sc1 {
3454 self.above_mode[i] = DC_PRED;3535 self.above_mode[i] = DC_PRED;
3455- self.above_side[i] = SB;3536+ self.above_side[i] = NO_NEIGHBOUR_SIDE;
3456 }3537 }
3457 // lane-inter8 r2: the inter bands are mi-granular, so they reset over3538 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
3458 // the tile's own mi column span directly.3539 // the tile's own mi column span directly.
@@ -3791,8 +3872,8 @@ impl Neighbours {
3791 self.left.iter_mut().for_each(|l| *l = Default::default());3872 self.left.iter_mut().for_each(|l| *l = Default::default());
3792 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);3873 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
3793 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);3874 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
3794- self.left_side.iter_mut().for_each(|s| *s = SB);3875+ self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3795- self.left_side_mi.iter_mut().for_each(|s| *s = SB);3876+ self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
3796 self.left_skip.iter_mut().for_each(|s| *s = false);3877 self.left_skip.iter_mut().for_each(|s| *s = false);
3797 self.left_skip_mode.iter_mut().for_each(|s| *s = false);3878 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
3798 self.left_inter.iter_mut().for_each(|i| *i = false);3879 self.left_inter.iter_mut().for_each(|i| *i = false);
@@ -10659,6 +10740,50 @@ pub(crate) fn take_last_frame_wide_margin() -> Option<Picture> {
10659 /// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table10740 /// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
10660 /// alongside the picture, for the caller to save into whichever reference10741 /// alongside the picture, for the caller to save into whichever reference
10661 /// slots this frame's `refresh_frame_flags` names.10742 /// slots this frame's `refresh_frame_flags` names.
10743+/// The order the 64x64 superblock quadrants of a tile are decoded in.
10744+///
10745+/// At `sb_size == 64` this is plain raster order over the tile's own
10746+/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
10747+/// each 128x128 superblock in raster order and visits its four 64x64
10748+/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
10749+/// 64-level bodies must run in that nested order. `row_start` marks the first
10750+/// item of each *superblock* row (where the left neighbour context resets),
10751+/// `sb_start` the first item of each superblock (where the 128 root's own
10752+/// loop-restoration units and partition symbol are read).
10753+fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
10754+ let mut out = Vec::new();
10755+ if !sb128 {
10756+ for r in r0..r1 {
10757+ for c in c0..c1 {
10758+ out.push((r, c, c == c0, true));
10759+ }
10760+ }
10761+ return out;
10762+ }
10763+ let mut r = r0;
10764+ while r < r1 {
10765+ let mut first_in_row = true;
10766+ let mut c = c0;
10767+ while c < c1 {
10768+ let mut first_in_sb = true;
10769+ for qr in 0..2 {
10770+ for qc in 0..2 {
10771+ let (rr, cc) = (r + qr, c + qc);
10772+ if rr >= r1 || cc >= c1 {
10773+ continue;
10774+ }
10775+ out.push((rr, cc, first_in_row, first_in_sb));
10776+ first_in_row = false;
10777+ first_in_sb = false;
10778+ }
10779+ }
10780+ c += 2;
10781+ }
10782+ r += 2;
10783+ }
10784+ out
10785+}
10786+
10662 pub(crate) fn decode_key_frame_tile_with_cdfs(10787 pub(crate) fn decode_key_frame_tile_with_cdfs(
10663 tiles: &[&[u8]],10788 tiles: &[&[u8]],
10664 tile_info: &TileInfo,10789 tile_info: &TileInfo,
@@ -10691,6 +10816,12 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
10691 return Err(unsupported("a frame with no mode-info grid"));10816 return Err(unsupported("a frame with no mode-info grid"));
10692 }10817 }
10693 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));10818 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
10819+ let sb128 = sb128();
10820+ if sb128 && allow_intrabc {
10821+ return Err(unsupported(
10822+ "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)",
10823+ ));
10824+ }
10694 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));10825 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
10695 INTRABC_MI_GRID.with(|g| {10826 INTRABC_MI_GRID.with(|g| {
10696 *g.borrow_mut() = allow_intrabc.then(|| {10827 *g.borrow_mut() = allow_intrabc.then(|| {
@@ -10828,19 +10959,74 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
10828 );10959 );
10829 TILE_HITS.with(|c| c.set(c.get() + 1));10960 TILE_HITS.with(|c| c.set(c.get() + 1));
10830 10961
10831- for sb_r in sb_r0..sb_r1 {10962+ for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
10832- neighbours.start_row();10963+ if row_start {
10833- for sb_c in sb_c0..sb_c1 {10964+ neighbours.start_row();
10834- crate::restoration::read_lr(10965+ }
10835- &mut dec,10966+ {
10836- &mut cdfs,10967+ // lane-sb128 r1: the 128 root. Its loop-restoration units are read
10837- lr,10968+ // once for the whole 128x128 (spec 5.11.57 is called with the
10838- &mut lr_grid,10969+ // superblock's own size), then one partition symbol off the
10839- &mut lr_reference,10970+ // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
10840- sb_r * SB_MI,10971+ // recurses into the four 64x64 quadrants this decoder codes.
10841- sb_c * SB_MI,10972+ if sb128 && sb_start {
10842- SB_MI,10973+ let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
10843- );10974+ crate::restoration::read_lr(
10975+ &mut dec,
10976+ &mut cdfs,
10977+ lr,
10978+ &mut lr_grid,
10979+ &mut lr_reference,
10980+ mi_r128,
10981+ mi_c128,
10982+ SB_MI * 2,
10983+ );
10984+ let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
10985+ let ctx128 = neighbours.partition_ctx(at128, 128);
10986+ let (has_cols128, has_rows128) =
10987+ (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
10988+ let part128 = if has_cols128 && has_rows128 {
10989+ PART128_SYMBOLS.with(|c| c.set(c.get() + 1));
10990+ let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
10991+ if std::env::var_os("EC_AV1_TRACE").is_some() {
10992+ eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
10993+ }
10994+ p
10995+ } else {
10996+ match (has_cols128, has_rows128) {
10997+ (true, false) => {
10998+ dec.symbol_fixed(&gather_of(
10999+ &cdfs.partition_w128[ctx128],
11000+ &VERT_ALIKE128,
11001+ ));
11002+ }
11003+ (false, true) => {
11004+ dec.symbol_fixed(&gather_of(
11005+ &cdfs.partition_w128[ctx128],
11006+ &HORZ_ALIKE128,
11007+ ));
11008+ }
11009+ _ => {}
11010+ }
11011+ PARTITION_SPLIT
11012+ };
11013+ if part128 != PARTITION_SPLIT {
11014+ return Err(unsupported(PART128_NON_SPLIT_REFUSAL));
11015+ }
11016+ PART128_SPLIT_HITS.with(|c| c.set(c.get() + 1));
11017+ }
11018+ if !sb128 {
11019+ crate::restoration::read_lr(
11020+ &mut dec,
11021+ &mut cdfs,
11022+ lr,
11023+ &mut lr_grid,
11024+ &mut lr_reference,
11025+ sb_r * SB_MI,
11026+ sb_c * SB_MI,
11027+ SB_MI,
11028+ );
11029+ }
10844 CDEF_TRANSMITTED.with(|c| c.set(false));11030 CDEF_TRANSMITTED.with(|c| c.set(false));
10845 let at = (sb_r as usize * 4, sb_c as usize * 4);11031 let at = (sb_r as usize * 4, sb_c as usize * 4);
10846 let ctx = neighbours.partition_ctx(at, SB);11032 let ctx = neighbours.partition_ctx(at, SB);
crates/ec-av1/src/encode.rsmodified+32 -15
@@ -47,6 +47,26 @@ const SUB: usize = 16;
47 /// The side of a superblock, which is what the partition tree starts from.47 /// The side of a superblock, which is what the partition tree starts from.
48 pub(crate) const SUPERBLOCK: usize = 64;48 pub(crate) const SUPERBLOCK: usize = 64;
49 49
50+// lane-sb128 r1: the superblock size in samples the intra-reach rules
51+// (`has_top_right`/`has_bottom_left`) are answered against. libaom masks the
52+// block's mi position with `mi_size_wide[cm->seq_params->sb_size] - 1` and
53+// tests the "top row"/"rightmost column" of THAT superblock, so a 128x128
54+// superblock changes every answer inside it (the tables themselves are
55+// already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`]
56+// stays the encoder's own fixed 64.
57+thread_local! {
58+ static REACH_SB_PX: std::cell::Cell<usize> = const { std::cell::Cell::new(SUPERBLOCK) };
59+}
60+
61+/// Sets the superblock size [`Reach`] answers against (64 or 128).
62+pub(crate) fn set_reach_superblock_px(px: usize) {
63+ REACH_SB_PX.with(|c| c.set(px));
64+}
65+
66+fn reach_sb_px() -> usize {
67+ REACH_SB_PX.with(|c| c.get())
68+}
69+
50 /// How heavily the mode search weighs rate against squared error, in units of70 /// How heavily the mode search weighs rate against squared error, in units of
51 /// the quantizer's reconstruction step squared per bit.71 /// the quantizer's reconstruction step squared per bit.
52 ///72 ///
@@ -1296,19 +1316,19 @@ impl Reach {
1296 /// the transform covering the whole block, luma): everything before the1316 /// the transform covering the whole block, luma): everything before the
1297 /// table lookup is that function's own early-exit ladder.1317 /// table lookup is that function's own early-exit ladder.
1298 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool {1318 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool {
1299- const SB_MI: usize = SUPERBLOCK / 4;1319+ let sb_mi: usize = reach_sb_px() / 4;
1300 let (mi_row, mi_col) = (y / 4, x / 4);1320 let (mi_row, mi_col) = (y / 4, x / 4);
1301 let bw_log2 = (bw / 4).trailing_zeros() as usize;1321 let bw_log2 = (bw / 4).trailing_zeros() as usize;
1302 let bh_log2 = (bh / 4).trailing_zeros() as usize;1322 let bh_log2 = (bh / 4).trailing_zeros() as usize;
1303- let blk_row = (mi_row & (SB_MI - 1)) >> bh_log2;1323+ let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
1304- let blk_col = (mi_col & (SB_MI - 1)) >> bw_log2;1324+ let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
1305 // Top row of the superblock: the top-right pixels are in the (already1325 // Top row of the superblock: the top-right pixels are in the (already
1306 // decoded) superblock above.1326 // decoded) superblock above.
1307 if blk_row == 0 {1327 if blk_row == 0 {
1308 return true;1328 return true;
1309 }1329 }
1310 // Rightmost column: they fall in the superblock to the right.1330 // Rightmost column: they fall in the superblock to the right.
1311- if ((blk_col + 1) << bw_log2) >= SB_MI {1331+ if ((blk_col + 1) << bw_log2) >= sb_mi {
1312 return false;1332 return false;
1313 }1333 }
1314 let table = rect_reach_tables(bw, bh).0;1334 let table = rect_reach_tables(bw, bh).0;
@@ -1329,20 +1349,20 @@ impl Reach {
1329 1349
1330 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].1350 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
1331 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool {1351 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool {
1332- const SB_MI: usize = SUPERBLOCK / 4;1352+ let sb_mi: usize = reach_sb_px() / 4;
1333 let (mi_row, mi_col) = (y / 4, x / 4);1353 let (mi_row, mi_col) = (y / 4, x / 4);
1334 let bw_log2 = (bw / 4).trailing_zeros() as usize;1354 let bw_log2 = (bw / 4).trailing_zeros() as usize;
1335 let bh_log2 = (bh / 4).trailing_zeros() as usize;1355 let bh_log2 = (bh / 4).trailing_zeros() as usize;
1336- let blk_row = (mi_row & (SB_MI - 1)) >> bh_log2;1356+ let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
1337- let blk_col = (mi_col & (SB_MI - 1)) >> bw_log2;1357+ let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
1338 // Leftmost column of the superblock: the bottom-left pixels are in1358 // Leftmost column of the superblock: the bottom-left pixels are in
1339 // the left superblock iff they stay inside its height.1359 // the left superblock iff they stay inside its height.
1340 if blk_col == 0 {1360 if blk_col == 0 {
1341- return (blk_row << bh_log2) + (bh / 4) < SB_MI;1361+ return (blk_row << bh_log2) + (bh / 4) < sb_mi;
1342 }1362 }
1343 // Bottom row (and not the leftmost column): they fall in the1363 // Bottom row (and not the leftmost column): they fall in the
1344 // superblock below, which is not decoded yet.1364 // superblock below, which is not decoded yet.
1345- if ((blk_row + 1) << bh_log2) >= SB_MI {1365+ if ((blk_row + 1) << bh_log2) >= sb_mi {
1346 return false;1366 return false;
1347 }1367 }
1348 let table = rect_reach_tables(bw, bh).1;1368 let table = rect_reach_tables(bw, bh).1;
@@ -1416,7 +1436,7 @@ impl Reach {
1416 fn bottom_left(side: usize, x: usize, y: usize) -> bool {1436 fn bottom_left(side: usize, x: usize, y: usize) -> bool {
1417 let (row, col, per_side) = Self::position(side, x, y);1437 let (row, col, per_side) = Self::position(side, x, y);
1418 if col == 0 {1438 if col == 0 {
1419- return row * side + side < SUPERBLOCK;1439+ return row * side + side < reach_sb_px();
1420 }1440 }
1421 if row + 1 == per_side {1441 if row + 1 == per_side {
1422 return false;1442 return false;
@@ -1447,11 +1467,8 @@ impl Reach {
1447 /// Where a block sits inside its superblock, in blocks of its own size,1467 /// Where a block sits inside its superblock, in blocks of its own size,
1448 /// and how many of them a superblock is across.1468 /// and how many of them a superblock is across.
1449 fn position(side: usize, x: usize, y: usize) -> (usize, usize, usize) {1469 fn position(side: usize, x: usize, y: usize) -> (usize, usize, usize) {
1450- (1470+ let sb = reach_sb_px();
1451- (y % SUPERBLOCK) / side,1471+ ((y % sb) / side, (x % sb) / side, sb / side)
1452- (x % SUPERBLOCK) / side,
1453- SUPERBLOCK / side,
1454- )
1455 }1472 }
1456 1473
1457 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins1474 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
crates/ec-av1/src/stream.rsmodified+301 -0
@@ -480,6 +480,26 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
480 // inter frames are decoded on a thread that previously decoded a480 // inter frames are decoded on a thread that previously decoded a
481 // different sequence would inherit that sequence's bit.481 // different sequence would inherit that sequence's bit.
482 crate::decode::set_enable_edge_filter(enable_edge_filter);482 crate::decode::set_enable_edge_filter(enable_edge_filter);
483+ // lane-sb128 r1: `use_128x128_superblock` (spec 5.5.1). The key-frame
484+ // tile path reads the 128 partition root and recurses SPLIT into the
485+ // four 64x64 quadrants; the inter tile path is still written for a
486+ // 64x64 root only (its own superblock loop, OBMC/mvstack neighbour
487+ // caps and `read_cdef` reset all key off `SB_MI`), so refuse there by
488+ // name rather than desync. A frame at most 64x64 decodes identically
489+ // either way (its 128 root reads no symbol -- neither half is in
490+ // frame, so SPLIT is inferred), so the refusal is scoped to frames
491+ // bigger than one 64x64 superblock.
492+ let use_sb128 = parser
493+ .sequence_header()
494+ .is_some_and(|seq| seq.use_128x128_superblock);
495+ let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);
496+ crate::decode::set_sb128(sb128_active);
497+ if sb128_active && header.frame_type != FrameType::Key {
498+ return Err(Error::unsupported(
499+ "AV1 decode_stream",
500+ "an inter frame under a 128x128 superblock (this decoder's inter tile path recurses a 64x64 superblock root only)",
501+ ));
502+ }
483 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,503 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
484 // which every dequant/inverse-transform clamp reads -- set per frame,504 // which every dequant/inverse-transform clamp reads -- set per frame,
485 // not once per process, for the same cross-sequence-on-one-thread505 // not once per process, for the same cross-sequence-on-one-thread
@@ -15412,6 +15432,287 @@ mod tests {
15412 );15432 );
15413 }15433 }
15414 15434
15435+ /// lane-sb128 r1 gate: a real `aomenc --sb-size=128` stream (the size his
15436+ /// ReelC encode uses -- `EC_TRACE=1 aomdec reelc-head.obu` prints
15437+ /// `EC_PART mi_row=0 mi_col=0 bsize=15` = `BLOCK_128X128`) must decode
15438+ /// pixel-exact. `--max-partition-size=64` keeps the RD search from ever
15439+ /// choosing a 128-level NONE/HORZ/VERT/AB arm, so every 128 root here is
15440+ /// genuinely `PARTITION_SPLIT` -- the one arm
15441+ /// `decode_key_frame_tile_with_cdfs` codes; the other seven refuse by
15442+ /// name (`PART128_NON_SPLIT_REFUSAL`) and stay refused after this round.
15443+ ///
15444+ /// What the 128 root actually changes, and what this gate therefore
15445+ /// proves: the 8-symbol `partition_w128` CDF and its forced-split gather
15446+ /// at the frame edge, the quadrant VISIT ORDER (TL, TR, BL, BR inside one
15447+ /// superblock, not raster over 64x64 superblocks), one loop-restoration
15448+ /// read per 128x128 instead of per 64x64, `delta_q`/`delta_lf` once per
15449+ /// 128x128, and the per-64x64 `cdef_idx` read inside the 128 superblock.
15450+ /// 256x192 gives a 2x2 grid of 128 superblocks whose bottom row is a
15451+ /// partial superblock (the gathered forced-split read); 384x384 gives a
15452+ /// 3x3 grid of whole ones. 8-bit sweep plus one 10-bit stream (his films
15453+ /// are `yuv420p10le`). Only a missing tool SKIPs.
15454+ #[test]
15455+ fn a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact() {
15456+ const NAME: &str = "a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact";
15457+ let _gate_lock = lock_gate_counters();
15458+ if !have_ffmpeg() {
15459+ eprintln!("SKIP {NAME}: no ffmpeg");
15460+ return;
15461+ }
15462+ if !have_aomenc() {
15463+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15464+ return;
15465+ }
15466+ let base: Vec<&str> = vec![
15467+ "--codec=av1",
15468+ "--passes=1",
15469+ "--end-usage=q",
15470+ "--cq-level=40",
15471+ "--cpu-used=0",
15472+ "--threads=1",
15473+ "--row-mt=0",
15474+ "--sb-size=128",
15475+ "--max-partition-size=64",
15476+ "--enable-rect-partitions=1",
15477+ "--enable-ab-partitions=0",
15478+ "--enable-1to4-partitions=0",
15479+ // aomenc emits PARTITION_HORZ_4/VERT_4 below 16x16 even with the
15480+ // flag off (ledger, lane-modectx r1), so bound the search instead.
15481+ "--min-partition-size=16",
15482+ "--enable-restoration=1",
15483+ "--enable-palette=0",
15484+ "--deltaq-mode=0",
15485+ "--enable-intrabc=0",
15486+ "--enable-tx-size-search=0",
15487+ "--limit=1",
15488+ ];
15489+ let encode = |y4m: &[u8], extra: &[&str]| -> Vec<u8> {
15490+ let mut args = base.clone();
15491+ args.extend_from_slice(extra);
15492+ args.extend_from_slice(&["--obu", "-o", "-", "-"]);
15493+ let mut child = Command::new(aomenc_path())
15494+ .args(&args)
15495+ .stdin(Stdio::piped())
15496+ .stdout(Stdio::piped())
15497+ .stderr(Stdio::piped())
15498+ .spawn()
15499+ .expect("aomenc failed to start");
15500+ child
15501+ .stdin
15502+ .take()
15503+ .expect("aomenc stdin")
15504+ .write_all(y4m)
15505+ .expect("writing y4m to aomenc");
15506+ let out = child.wait_with_output().expect("aomenc failed to run");
15507+ assert!(
15508+ out.status.success(),
15509+ "aomenc refused the fixture: {}",
15510+ String::from_utf8_lossy(&out.stderr)
15511+ );
15512+ out.stdout
15513+ };
15514+ let render = |seed: u32, width: usize, height: usize, ten_bit: bool| -> Vec<u8> {
15515+ let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
15516+ let out = Command::new("ffmpeg")
15517+ .args([
15518+ "-v",
15519+ "error",
15520+ "-f",
15521+ "lavfi",
15522+ "-i",
15523+ &gradients_source(seed, width, height, "duration=0.04:rate=25"),
15524+ "-pix_fmt",
15525+ pix,
15526+ "-strict",
15527+ "-1",
15528+ "-t",
15529+ "0.04",
15530+ "-f",
15531+ "yuv4mpegpipe",
15532+ "-",
15533+ ])
15534+ .stdin(Stdio::null())
15535+ .stdout(Stdio::piped())
15536+ .stderr(Stdio::piped())
15537+ .output()
15538+ .expect("ffmpeg failed to run");
15539+ assert!(
15540+ out.status.success(),
15541+ "ffmpeg fixture: {}",
15542+ String::from_utf8_lossy(&out.stderr)
15543+ );
15544+ out.stdout
15545+ };
15546+ let mut matched = 0u32;
15547+ let mut named_refusals = 0u32;
15548+ // (seed, width, height, 10-bit): 256x192 = 2x2 superblocks with a
15549+ // partial bottom row; 384x384 = 3x3 whole ones.
15550+ let arms: Vec<(u32, usize, usize, bool)> = vec![
15551+ (42, 256, 192, false),
15552+ (43, 256, 192, false),
15553+ (44, 256, 192, false),
15554+ (45, 384, 384, false),
15555+ (46, 256, 192, true),
15556+ (47, 384, 384, true),
15557+ ];
15558+ for (seed, width, height, ten_bit) in arms {
15559+ let y4m = render(seed, width, height, ten_bit);
15560+ let extra: Vec<&str> = if ten_bit {
15561+ vec!["--input-bit-depth=10", "--bit-depth=10"]
15562+ } else {
15563+ vec![]
15564+ };
15565+ let stream = encode(&y4m, &extra);
15566+ let parsed = {
15567+ let mut parser = ec_av1_syntax::Av1Parser::new();
15568+ let mut pos = 0usize;
15569+ while let Ok(obu) = parser.parse_obu(&stream[pos..]) {
15570+ pos += obu.total_size;
15571+ if pos >= stream.len() {
15572+ break;
15573+ }
15574+ }
15575+ parser
15576+ .sequence_header()
15577+ .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth))
15578+ };
15579+ assert_eq!(
15580+ parsed,
15581+ Some((true, if ten_bit { 10 } else { 8 })),
15582+ "{NAME} (seed {seed}): the encoder did not write a 128x128-superblock \
15583+ sequence header at the requested bit depth -- the flag never arrived"
15584+ );
15585+ let frames = match decode_stream(&stream) {
15586+ Err(e) => {
15587+ let msg = e.to_string();
15588+ assert!(
15589+ msg.contains("unsupported"),
15590+ "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
15591+ );
15592+ named_refusals += 1;
15593+ eprintln!("seed {seed} refusal: {msg}");
15594+ continue;
15595+ }
15596+ Ok(frames) => frames,
15597+ };
15598+ let want = if ten_bit {
15599+ ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
15600+ } else {
15601+ ffmpeg_decode_sequence(&stream, width, height, 1)
15602+ };
15603+ assert_eq!(frames.len(), 1);
15604+ for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
15605+ assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
15606+ assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
15607+ assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
15608+ }
15609+ matched += 1;
15610+ }
15611+ assert!(
15612+ matched > 0,
15613+ "{NAME}: every attempt refused; the gate never decoded a stream"
15614+ );
15615+ // 256x192 codes 3 whole + 1 partial superblock, 384x384 codes 9 whole
15616+ // ones, so a run that decoded anything at all must have read real 128
15617+ // partition symbols and split every one of them.
15618+ assert!(
15619+ crate::decode::part128_symbols() >= 3 * matched as usize,
15620+ "{NAME}: only {} 128-level partition symbols over {matched} decoded streams -- \
15621+ the 128 root never fired",
15622+ crate::decode::part128_symbols()
15623+ );
15624+ assert!(
15625+ crate::decode::part128_split_hits() >= 4 * matched as usize,
15626+ "{NAME}: only {} 128 superblocks split",
15627+ crate::decode::part128_split_hits()
15628+ );
15629+ eprintln!(
15630+ "{NAME}: {matched} pixel-exact, {named_refusals} named refusals, \
15631+ part128_symbols={} part128_split_hits={}",
15632+ crate::decode::part128_symbols(),
15633+ crate::decode::part128_split_hits()
15634+ );
15635+ }
15636+
15637+ /// lane-sb128 r1: the inter half of a `--sb-size=128` stream is refused by
15638+ /// NAME (the inter tile path still recurses a 64x64 root only), never
15639+ /// silently decoded at the wrong superblock size the way this decoder did
15640+ /// before this round -- which is what made every earlier ReelC "stop" a
15641+ /// desync artefact rather than a real capability gap.
15642+ #[test]
15643+ fn a_real_aomenc_128x128_inter_stream_refuses_by_name() {
15644+ const NAME: &str = "a_real_aomenc_128x128_inter_stream_refuses_by_name";
15645+ let _gate_lock = lock_gate_counters();
15646+ if !have_ffmpeg() || !have_aomenc() {
15647+ eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
15648+ return;
15649+ }
15650+ let (width, height) = (256usize, 192usize);
15651+ let y4m = Command::new("ffmpeg")
15652+ .args([
15653+ "-v",
15654+ "error",
15655+ "-f",
15656+ "lavfi",
15657+ "-i",
15658+ &gradients_source(51, width, height, "duration=0.24:rate=25"),
15659+ "-pix_fmt",
15660+ "yuv420p",
15661+ "-t",
15662+ "0.24",
15663+ "-f",
15664+ "yuv4mpegpipe",
15665+ "-",
15666+ ])
15667+ .stdin(Stdio::null())
15668+ .stdout(Stdio::piped())
15669+ .stderr(Stdio::piped())
15670+ .output()
15671+ .expect("ffmpeg failed to run");
15672+ assert!(y4m.status.success(), "ffmpeg fixture");
15673+ let mut child = Command::new(aomenc_path())
15674+ .args([
15675+ "--codec=av1",
15676+ "--passes=1",
15677+ "--end-usage=q",
15678+ "--cq-level=40",
15679+ "--cpu-used=1",
15680+ "--threads=1",
15681+ "--row-mt=0",
15682+ "--sb-size=128",
15683+ "--max-partition-size=64",
15684+ "--deltaq-mode=0",
15685+ "--limit=6",
15686+ "--lag-in-frames=0",
15687+ "--obu",
15688+ "-o",
15689+ "-",
15690+ "-",
15691+ ])
15692+ .stdin(Stdio::piped())
15693+ .stdout(Stdio::piped())
15694+ .stderr(Stdio::piped())
15695+ .spawn()
15696+ .expect("aomenc failed to start");
15697+ child
15698+ .stdin
15699+ .take()
15700+ .expect("aomenc stdin")
15701+ .write_all(&y4m.stdout)
15702+ .expect("writing y4m to aomenc");
15703+ let out = child.wait_with_output().expect("aomenc failed to run");
15704+ assert!(out.status.success(), "aomenc refused the fixture");
15705+ let err = decode_stream(&out.stdout)
15706+ .err()
15707+ .map(|e| e.to_string())
15708+ .unwrap_or_default();
15709+ assert!(
15710+ err.contains("an inter frame under a 128x128 superblock"),
15711+ "{NAME}: expected the scoped inter refusal, got: {err:?}"
15712+ );
15713+ eprintln!("{NAME}: {err}");
15714+ }
15715+
15415 /// lane-sbpart r2: a real `aomenc` stream whose superblock-level15716 /// lane-sbpart r2: a real `aomenc` stream whose superblock-level
15416 /// partition decision is genuinely HORZ/VERT (not NONE/SPLIT) must15717 /// partition decision is genuinely HORZ/VERT (not NONE/SPLIT) must
15417 /// decode pixel-exact through [`crate::decode::decode_block_rect64`] --15718 /// decode pixel-exact through [`crate::decode::decode_block_rect64`] --