diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 863915c0..d9664710 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 a7a98588..9b36a7d7 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1554,7 +1554,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 @@ -4661,6 +4661,46 @@ 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. Read through +/// a process-global (not a thread-local) because the tile writers run on +/// worker threads; `2` is "the environment has not been read yet". +static SB128: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + +/// Whether this process's sequences code 128x128 superblocks. +pub(crate) fn sb128_on() -> bool { + use std::sync::atomic::Ordering::Relaxed; + match SB128.load(Relaxed) { + 2 => { + let on = crate::envflags::var("EC_AV1_SB128").ok().is_some_and(|v| v != "0"); + SB128.store(u8::from(on), Relaxed); + on + } + v => v == 1, + } +} + +/// Forces [`sb128_on`] for the rest of the process -- the superblock size is +/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`), +/// exactly like the speed-preset gates. +#[cfg(test)] +pub(crate) fn force_sb128(on: bool) { + SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed); +} + +/// 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) { @@ -7011,8 +7051,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 @@ -7024,7 +7064,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()); @@ -7310,9 +7351,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; @@ -10626,8 +10671,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. @@ -10648,7 +10693,8 @@ pub(crate) fn encode_inter_frame( sb_q.clone().unwrap_or_default(), base_q_idx, ); - 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/encoder.rs b/crates/ec-av1/src/encoder.rs index cbe1d4ee..15728108 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -3027,6 +3027,69 @@ mod tests { /// reconstruction. The counter is the point (class /// `gate-blind-to-feature`): without it a green three-way compare says /// nothing about whether a single 64x64 block was ever written. + /// lane-sb128 step 1: the same static clip under a 128x128 SUPERBLOCK. + /// Every partition decision below the root is the one the 64-superblock + /// encoder makes -- the root itself is always `PARTITION_SPLIT` into the + /// four 64x64 superblocks -- so the only thing this proves is the + /// structural syntax: the root's own partition symbol, its loop + /// restoration read once over the 128 span at the 128 unit size, and + /// libaom's TL/TR/BL/BR visit order. 256x128 is 2x1 128x128 superblocks + /// per frame over three frames, so the root fires 6 times. + /// + /// `#[ignore]`: [`crate::encode::force_sb128`] moves a process-global + /// (the superblock size is a sequence field), so this gate runs alone: + /// + /// cargo test -p ec-av1 --release --lib -- --ignored \ + /// a_static_clip_codes_128x128_superblock_roots --nocapture + #[test] + #[ignore = "sets the process-global superblock size: run it alone"] + fn a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact() { + let _knobs = crate::speed::knob_write(); + let _gate_lock = crate::stream::tests::lock_gate_counters(); + crate::encode::force_sb128(true); + let (width, height) = (256usize, 128usize); + let still = test_card(width, height, 0); + let sources: Vec = (0..3).map(|_| still.clone()).collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 8, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + let _ = crate::tile::take_sb128_root_hits(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let roots = crate::tile::take_sb128_root_hits(); + assert!( + roots >= 4, + "a 128x128-superblock clip coded {roots} superblock roots, wanted at least 4" + ); + eprintln!("128x128 superblock roots: {roots}"); + + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + assert!( + crate::decode::part128_split_hits() >= 4, + "our decoder read no 128x128 superblock root" + ); + if !have_ffmpeg() { + eprintln!("SKIP the ffmpeg half: no ffmpeg"); + return; + } + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert_eq!(&got, b, "frame {i}: ffmpeg and our decoder disagree"); + } + } + #[test] fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() { let _knobs = crate::speed::knob_write(); diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 5b9b63ee..c9392f35 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -85,19 +85,136 @@ 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)); +} + +/// How many 128x128 superblock roots the writers have coded since the last +/// [`take_sb128_root_hits`] -- a gate reports how often the root fires rather +/// than assuming it does (class `gate-blind-to-feature`). Process-global +/// rather than thread-local because the tiles of one frame are written on +/// worker threads. +static SB128_ROOT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The 128x128-root count since the last call, and zero it. +pub fn take_sb128_root_hits() -> usize { + SB128_ROOT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + +/// 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, +) { + SB128_ROOT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + 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 +294,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 }; @@ -1779,6 +1901,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; @@ -2030,10 +2160,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)], @@ -2086,8 +2216,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); @@ -2731,10 +2861,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(|| { @@ -5892,10 +6040,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..f1db5c6a --- /dev/null +++ b/lanes/sb128.report.md @@ -0,0 +1,76 @@ +# 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*. + +### Structural cost, measured (640x384 pin clip, 4 pictures, q=150) + +| arm | bytes | vs its own control | +|---|---|---| +| 64 SB, LR on (the shipped stream) | 8562 | -- | +| 128 SB, LR on | 8547 | **-15 (-0.18%)** | +| 64 SB, `EC_AV1_LR=0` | 8530 | -- | +| 128 SB, `EC_AV1_LR=0` | 8537 | **+7 (+0.08%)** | + +So the two effects separate cleanly: + +- The extra partition symbols cost **+7 bytes** over 60 roots (15 128-roots + per frame x 4 pictures), i.e. ~0.93 bits per root -- a SPLIT at a + neighbourless root is nearly free on the `partition_w128` CDF. +- The loop-restoration unit, forced 64 -> 128 by the superblock size, saves + **22 bytes** (60 units per frame -> 15), and the net is -15 bytes. + +CDEF indexing did NOT move: the spec clears `cdef_idx` per 64x64 unit inside +a 128 superblock (`clear_cdef` at the superblock, one `-1` per 64x64 +position), our decoder resets `cdef_transmitted` at every 64 quadrant, and +the writer's one-slot "already written" marker keys on the 64 grid, which the +TL/TR/BL/BR order keeps contiguous. Nothing about the CDEF plan changed. + +### Witness (step 1) + +`encoder::tests::a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact` +(`--ignored`, it sets the process-global superblock size): 256x128 x 3 +frames, **8** 128x128 superblock roots written, our decoder reads >= 4 +`PARTITION_SPLIT` roots, and every frame is byte-exact between our decoder +and ffmpeg. + + cargo test -p ec-av1 --release --lib -- --ignored \ + a_static_clip_codes_128x128_superblock_roots --nocapture +