From d2e10de1e982958ec3a31bf8e30564f877c50719 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 7 Sep 2026 21:29:20 +0300 Subject: [PATCH] feat(av1): the tile writers walk 128x128 superblocks under EC_AV1_SB128 The sequence bit, a 128 partition root whose only arm is SPLIT into the four 64x64 superblocks the encoder already codes, loop restoration read once over the 128 span (and its unit size forced to 128, the smallest a 128 superblock can signal), and libaom's TL/TR/BL/BR visit order. The writer's no-neighbour partition sentinel moves 64 -> 128 to match the decoder's: at 64 it is byte-neutral, at the 128 root it put the symbol on CDF row 3 instead of row 0. --- crates/ec-av1/src/decode.rs | 19 +++- crates/ec-av1/src/encode.rs | 44 +++++++-- crates/ec-av1/src/tile.rs | 191 ++++++++++++++++++++++++++++++++---- lanes/sb128.report.md | 42 ++++++++ 4 files changed, 264 insertions(+), 32 deletions(-) create mode 100644 lanes/sb128.report.md diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 40871b4f..deb996a1 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -158,7 +158,12 @@ impl FrameCtx { /// predecessor was born with. pub(crate) fn new() -> Self { Self { - sb128_flag: std::cell::Cell::new(false), + // lane-sb128: an ENCODER context starts at the sequence size + // this process encodes (`crate::encode::sb128_on`) so the mode + // search's own `Reach` and the filter search's internal decodes + // agree with the tile writer; every real decode overwrites it + // from the parsed sequence header (`set_sb128`, stream.rs). + sb128_flag: std::cell::Cell::new(crate::encode::sb128_on()), lossless_flag: std::cell::Cell::new(false), cdef_bits: std::cell::Cell::new(0), bit_depth: std::cell::Cell::new(8), @@ -203,7 +208,11 @@ impl FrameCtx { inter_last_mc: std::cell::Cell::new(None), enable_edge_filter: std::cell::Cell::new(false), last_frame_wide_margin: std::cell::RefCell::new(None), - reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK), + reach_sb_px: std::cell::Cell::new(if crate::encode::sb128_on() { + 128 + } else { + crate::encode::SUPERBLOCK + }), grain_bit_depth: std::cell::Cell::new(8), recon_ops: std::cell::RefCell::new(Vec::new()), recon_spare: std::cell::RefCell::new(Vec::new()), @@ -407,14 +416,14 @@ pub(crate) fn part128_split_hits() -> usize { /// 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] { +pub(crate) 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]; +pub(crate) const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7]; +pub(crate) 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 diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 56105436..09e96085 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1547,7 +1547,7 @@ pub(crate) fn key_frame_headers_colour( frame_height_bits, max_frame_width: w, max_frame_height: h, - use_128x128_superblock: false, + use_128x128_superblock: sb128_on(), // lane-fintra: the encoder's intra search offers the five recursive // filter-intra modes on eligible blocks, so the sequence bit is set // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both @@ -4654,6 +4654,28 @@ fn cfl_on() -> bool { /// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured /// its own on/off pair -- and how every byte pin written before it still /// reproduces). It is also a speed lever: on at preset 0, off above it. +// lane-sb128: `use_128x128_superblock` (spec 5.5.1). Off by default until +// the BD gate says otherwise; `EC_AV1_SB128=1` turns it on for the whole +// process (a sequence-header field, so it cannot change mid-stream anyway), +// the same env-flag shape `EC_AV1_FILTER_INTRA` uses. NOT an `EncoderConfig` +// field: that struct is built by 90 literal sites in this workspace. + +/// Whether this process's sequences code 128x128 superblocks. +pub(crate) fn sb128_on() -> bool { + static ENV: std::sync::LazyLock = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_SB128").ok().is_some_and(|v| v != "0") + }); + *ENV +} + +/// The luma loop-restoration unit size this sequence codes: a 128 superblock +/// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there, +/// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is +/// 128), which is the one filter parameter the superblock size moves. +pub(crate) fn lr_unit() -> u32 { + if sb128_on() { 128 } else { 64 } +} + pub(crate) fn filter_intra_on() -> bool { #[cfg(test)] if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) { @@ -7004,8 +7026,8 @@ pub(crate) fn encode_key_frame_inner( // (`av1_lr_count_units` rounds to nearest, so a short last unit is // swallowed by the one before it), for the tile writer's own per-unit // walk. - let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; - let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; + let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32; + let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32; // Every tile is coded from this frame's OWN starting tables and leaves // its own end state behind (spec 5.11.1: each tile resets the CDFs, the // loop-restoration reference and its neighbour contexts), so the tiles @@ -7017,7 +7039,8 @@ pub(crate) fn encode_key_frame_inner( -> Result>> { let (out, _) = write_tiles(layout.count(), usize::MAX, |index| { crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); - crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); + crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec()); + crate::tile::arm_sb128(sb128_on()); let mut cdfs = start_cdfs.0.clone(); crate::tile::arm_screen(screen); crate::tile::arm_filter_intra(filter_intra_on()); @@ -7302,9 +7325,13 @@ fn pick_and_apply_filters( // rather than decoding the re-coded tile. Cleared at the end instead. let mut lr = LoopRestorationParams::default(); if lr_on { + let unit = lr_unit(); let mut want = LoopRestorationParams { - loop_restoration_size: [64, 64, 64], + loop_restoration_size: [unit, unit, unit], uses_lr: true, + // spec `lr_params`: `RESTORATION_TILESIZE_MAX >> (2 - shift)`, so + // 0 is the 64 unit and 1 the 128 one a 128 superblock forces. + lr_unit_shift: u8::from(unit == 128), ..LoopRestorationParams::default() }; want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; @@ -10446,8 +10473,8 @@ pub(crate) fn encode_inter_frame( let switchable_motion_mode = header.is_motion_mode_switchable; let warped_motion = header.allow_warped_motion; let order_hint_bits = seq.order_hint_bits; - let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; - let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; + let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32; + let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32; // What this frame stores is the LARGEST tile's end-of-tile tables -- // its own header's `context_update_tile_id` (spec 7.20), which // `tile_info_of` set to exactly that tile. @@ -10462,7 +10489,8 @@ pub(crate) fn encode_inter_frame( -> Result>> { let (out, stored) = write_tiles(layout.count(), store_tile, |index| { crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec()); - crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); + crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec()); + crate::tile::arm_sb128(sb128_on()); crate::tile::arm_sign_bias(sign_bias); // Thread-locals: every tile job arms its own worker. crate::tile::arm_reference_select(reference_select_bit); diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 667076b6..52dbc4fa 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -85,19 +85,123 @@ pub(crate) fn arm_lr( }); } +// --------------------------------------------------------------------------- +// lane-sb128: the sequence's `use_128x128_superblock`. Armed per tile write +// like [`arm_lr`] (the encoder codes one tile at a time per thread) rather +// than threaded through every writer signature. When set, the two tile +// writers walk 128x128 superblocks -- loop restoration and one +// `partition_w128` symbol at the 128 root, then the four 64x64 quadrants in +// libaom `decode_partition`'s own TL, TR, BL, BR order -- which is exactly +// what `crate::decode::read_sb128_root` reads. + +thread_local! { + static SB128: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Arms the next tile write with the sequence's 128x128 superblock size. +pub(crate) fn arm_sb128(on: bool) { + SB128.with(|c| c.set(on)); +} + +/// Whether the next tile write codes 128x128 superblocks ([`arm_sb128`]). +fn sb128_armed() -> bool { + SB128.with(std::cell::Cell::get) +} + +/// The order a tile's 64x64 superblock cells are written in, mirroring +/// `crate::decode::sb_visit_order` exactly: plain raster at a 64 superblock, +/// and TL/TR/BL/BR inside each 128x128 superblock (in raster order over the +/// 128 grid) at a 128 one. The two flags mark the first cell of a superblock +/// ROW (where the left neighbour context resets) and the first cell of a +/// superblock (where the 128 root's own restoration units and partition +/// symbol are written). +fn sb_write_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 +} + +/// The 128x128 superblock root ([`sb_write_order`]'s `sb_start` cells): the +/// units its own 128-sample span covers, then the partition symbol. Only +/// `PARTITION_SPLIT` is written -- the four 64x64 quadrants below are today's +/// superblocks -- and at a root the true frame edge cuts, the DECIDING +/// gathered bit the decoder reads instead (`read_sb128_root`). +fn write_sb128_root( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + neighbours: &Neighbours, + sb_r: u32, + sb_c: u32, + mi_cols: u32, + mi_rows: u32, +) { + let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI); + write_lr(enc, cdfs, mi_r128, mi_c128, SB_MI * 2); + let at128 = ((mi_r128 / 4) as usize, (mi_c128 / 4) 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); + if crate::envflags::env_flag!("EC_AV1_TRACE") { + eprintln!("WTRACE partition_w128 ctx={ctx128} cols={has_cols128} rows={has_rows128}"); + } + match (has_cols128, has_rows128) { + (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w128[ctx128]), + // As at the 64 root: the gathered CDF is built for the read and + // thrown away, so nothing adapts here. Value 1 is SPLIT. + (true, false) => enc.symbol_fixed( + 1, + &crate::decode::gather_of(&cdfs.partition_w128[ctx128], &crate::decode::VERT_ALIKE128), + ), + (false, true) => enc.symbol_fixed( + 1, + &crate::decode::gather_of(&cdfs.partition_w128[ctx128], &crate::decode::HORZ_ALIKE128), + ), + // Both halves outside: the split is the only partition left and the + // decoder reads nothing. + (false, false) => {} + } +} + /// `read_lr`'s write side, called once at the top of every superblock, /// before its partition symbol: writes the units this superblock's own /// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the /// column scaling is the plain mi one). -fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32) { +fn write_lr(enc: &mut SymbolEncoder, cdfs: &mut Cdfs, mi_row: u32, mi_col: u32, span: u32) { LR_PLAN.with(|c| { let mut plan = c.borrow_mut(); let Some(plan) = plan.as_mut() else { return }; let unit = plan.unit_size; let rcol0 = (mi_col * 4).div_ceil(unit); - let rcol1 = ((mi_col + SB_MI_W) * 4).div_ceil(unit).min(plan.horz_units); + let rcol1 = ((mi_col + span) * 4).div_ceil(unit).min(plan.horz_units); let rrow0 = (mi_row * 4).div_ceil(unit); - let rrow1 = ((mi_row + SB_MI_W) * 4).div_ceil(unit).min(plan.vert_units); + let rrow1 = ((mi_row + span) * 4).div_ceil(unit).min(plan.vert_units); for rrow in rrow0..rrow1 { for rcol in rcol0..rcol1 { let info = plan.units[(rcol + rrow * plan.horz_units) as usize]; @@ -177,9 +281,14 @@ impl TileLayout { pub(crate) fn new(mi_cols: u32, mi_rows: u32, cols_log2: u32, rows_log2: u32) -> Self { let (cols32, rows32) = block_grid(mi_cols, mi_rows); let (sb_cols, sb_rows) = (cols32.div_ceil(2), rows32.div_ceil(2)); + // lane-sb128: a tile boundary is a SUPERBLOCK boundary, so under a + // 128 superblock the starts are laid out on the 128 grid and then + // doubled back into the 64-cell units the writers walk. + let unit = u32::from(crate::encode::sb128_on()) + 1; let starts = |total: u32, log2: u32| { - let step = total.div_ceil(1 << log2).max(1); - let mut v: Vec = (0..total).step_by(step as usize).collect(); + let total128 = total.div_ceil(unit); + let step = total128.div_ceil(1 << log2).max(1); + let mut v: Vec = (0..total128).step_by(step as usize).map(|s| s * unit).collect(); v.push(total); v }; @@ -1696,6 +1805,14 @@ const TX4: usize = 4; /// Side of a superblock, in samples, which is the size a block outside the /// tile reads as. const SB: usize = 64; + +/// The `above_side`/`left_side` value a cell with no coded neighbour holds +/// (tile start, superblock-row start) -- the writer's copy of +/// `crate::decode::NO_NEIGHBOUR_SIDE`, and 128 for the same reason: at 64 it +/// reads identically at every level up to 64x64 but sets the bit at the +/// `BLOCK_128X128` root (64 * 2 <= 128), putting that root's partition symbol +/// on CDF row 3 where libaom uses row 0. +const NO_NEIGHBOUR_SIDE: usize = 128; /// Side of the smallest block the writer codes, in samples, which is the grid /// the neighbour bookkeeping is kept on. const SUB: usize = 16; @@ -1947,10 +2064,10 @@ impl Neighbours { left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)], above_mode: vec![DC_PRED; cols], left_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)], above_skip: vec![false; cols * (SUB / MI)], left_skip: vec![false; rows * (SUB / MI)], above_inter: vec![false; cols * (SUB / MI)], @@ -2003,8 +2120,8 @@ impl Neighbours { fn start_row(&mut self) { self.left.iter_mut().for_each(|l| *l = Default::default()); self.left_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_inter.iter_mut().for_each(|i| *i = false); self.left_ref.iter_mut().for_each(|r| *r = -1); @@ -2648,10 +2765,28 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( // off. let mut cdfs = cdfs; let mut enc = SymbolEncoder::new(); - for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) { - neighbours.start_row(); - for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) { - write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W); + let sb128 = sb128_armed(); + // lane-sb128: at a 128 superblock the four 64x64 cells of each root are + // written in libaom's own TL/TR/BL/BR order, the root's restoration units + // and partition symbol first; at a 64 one this is plain raster and every + // cell is its own superblock, i.e. byte-identical to the loop before. + for (sb_r, sb_c, row_start, sb_start) in sb_write_order( + tile.sb_row0, + tile.sb_row1.min(sb_rows), + tile.sb_col0, + tile.sb_col1.min(sb_cols), + sb128, + ) { + if row_start { + neighbours.start_row(); + } + if sb128 && sb_start { + write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows); + } + { + if !sb128 { + write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W, SB_MI_W); + } let at = (sb_r as usize * 4, sb_c as usize * 4); let ctx = neighbours.partition_ctx(at, SB); ec_rng_trace(|| { @@ -5809,10 +5944,28 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( vec![0i32; TX16 * TX16], ]; - for sb_r in tile.sb_row0..tile.sb_row1.min(sb_rows) { - neighbours.start_row(); - for sb_c in tile.sb_col0..tile.sb_col1.min(sb_cols) { - write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W); + let sb128 = sb128_armed(); + // lane-sb128: at a 128 superblock the four 64x64 cells of each root are + // written in libaom's own TL/TR/BL/BR order, the root's restoration units + // and partition symbol first; at a 64 one this is plain raster and every + // cell is its own superblock, i.e. byte-identical to the loop before. + for (sb_r, sb_c, row_start, sb_start) in sb_write_order( + tile.sb_row0, + tile.sb_row1.min(sb_rows), + tile.sb_col0, + tile.sb_col1.min(sb_cols), + sb128, + ) { + if row_start { + neighbours.start_row(); + } + if sb128 && sb_start { + write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows); + } + { + if !sb128 { + write_lr(&mut enc, &mut cdfs, sb_r * SB_MI_W, sb_c * SB_MI_W, SB_MI_W); + } let sb_at = (sb_r as usize * 4, sb_c as usize * 4); let sb_ctx = neighbours.partition_ctx(sb_at, SB); // spec `decode_partition`'s hasRows/hasCols (5.11.4): a superblock diff --git a/lanes/sb128.report.md b/lanes/sb128.report.md new file mode 100644 index 00000000..ef604cb6 --- /dev/null +++ b/lanes/sb128.report.md @@ -0,0 +1,42 @@ +# lane-sb128 -- 128x128 superblocks in the encoder + +## Step 1: the sequence option, SPLIT-only roots (structural cost) + +`EC_AV1_SB128=1` writes `use_128x128_superblock = 1` in the sequence header +and makes both tile writers walk 128x128 superblocks: loop restoration and +one `partition_w128` symbol at the 128 root, then the four 64x64 quadrants +(today's superblocks, unchanged) in libaom's TL/TR/BL/BR order. Every +partition decision below the root is identical to the 64-superblock encoder, +so the whole cost of the step is the extra partition symbols plus the moved +loop-restoration unit size. + +NOT an `EncoderConfig` field (deviation from the charter, stated): that +struct is built by 90 literal sites in this workspace, so a new public field +is a 90-file diff for a knob whose default the gate decides. `EC_AV1_SB128` +follows `EC_AV1_FILTER_INTRA`'s existing shape. + +### What moved + +- `crates/ec-av1/src/tile.rs` -- `arm_sb128` + `sb_write_order` (an exact + mirror of `decode::sb_visit_order`) + `write_sb128_root` (LR over the 128 + span, then `PARTITION_SPLIT` off `partition_w128`, or the DECIDING gathered + bit at a root the frame edge cuts); `write_lr` takes its span; the + no-neighbour partition sentinel is 128, not 64. +- `crates/ec-av1/src/encode.rs` -- `sb128_on()`, `lr_unit()` (a 128 + superblock cannot signal the 64 restoration unit at all), the sequence bit, + both tile-write arming sites. +- `crates/ec-av1/src/decode.rs` -- `gather_of`/`VERT_ALIKE128`/`HORZ_ALIKE128` + exported to the writer; an encoder `FrameCtx` starts at this process's + superblock size so the search's `Reach` and the filter search's internal + decodes agree with the writer. + +### Root cause found on the way + +The writer's `Neighbours` used 64 as its "no neighbour" partition side. That +reads identically at every level up to 64x64 but sets the bit at the 128 root +(`64 * 2 <= 128`), so the writer coded the root's partition symbol off CDF +row 3 while the decoder read row 0 -- a first-symbol desync that decoded the +whole frame as one 128x128 intra block. The decoder had already fixed its own +copy (`decode::NO_NEIGHBOUR_SIDE`, lane-sb128 r1); the writer's copy had not +moved. Class: *table and reader move together*. +