From 8841aa8c913dddf0dcfe6ca20ef00fcf45a3337d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 5 Sep 2026 10:41:10 +0300 Subject: [PATCH] perf(av1): coefficient reading -- buffered msac bit window, static scan tables, no per-block level allocation The frame thread's coefficient path paid four avoidable costs per transform block, all bit-exact to remove: * every symbol's renormalisation assembled five bytes out of the payload and shifted twice; `SymbolDecoder` now keeps a 64-bit window refilled once per eight bytes (`bulk_bit_reads_match_the_per_bit_form` still pins `f(n)` against the per-bit form, through the new `seek_bits`); * `symbol_fixed`/`symbol`/`f`/`update_cdf` were out-of-line across codegen units, and the CDF walk indexed a slice the bounds checker could not see the end of -- inlined, and the walk iterates instead; * `default_scan` allocated a `Vec` and regenerated the whole anti-diagonal walk on every block: one table per side (4/8/16/32), built once; * `read_coeffs` divided by the transform side per coefficient (always a power of two) and allocated its level buffer per block. instructions:u on the 4K segment at one thread: 570.76 G -> 559.11 G (-2.0%). All 12 gate hashes unchanged at 1/4/16 threads; lib suite 500 passed, 27 ignored. --- crates/ec-av1/src/decode.rs | 45 +++++++++++++++++----- crates/ec-av1/src/msac.rs | 76 ++++++++++++++++++++++++++++--------- 2 files changed, 95 insertions(+), 26 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 1534da5f..ea4d20a6 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -5029,7 +5029,26 @@ pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize { /// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk /// [`crate::tile`]'s writer generates its scan tables with. -fn default_scan(side: usize) -> Vec { +fn default_scan(side: usize) -> &'static [u16] { + // One table per transform side (4/8/16/32), built once: this used to be a + // fresh heap allocation plus the whole anti-diagonal walk on every + // transform block read. + static SCANS: std::sync::LazyLock<[Vec; 4]> = std::sync::LazyLock::new(|| { + [ + default_scan_gen(4), + default_scan_gen(8), + default_scan_gen(16), + default_scan_gen(32), + ] + }); + assert!( + matches!(side, 4 | 8 | 16 | 32), + "no default scan for a {side}-point transform" + ); + &SCANS[side.trailing_zeros() as usize - 2] +} + +fn default_scan_gen(side: usize) -> Vec { let mut scan = Vec::with_capacity(side * side); for d in 0..(2 * side - 1) { let lo = d.saturating_sub(side - 1); @@ -5725,10 +5744,18 @@ fn read_coeffs( class_scan = class_scan_table(side, class); &class_scan }; - let mut levels = vec![0i32; side * side]; + // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per- + // coefficient `pos / side`, `pos % side` was a hardware divide where a + // shift and a mask say the same thing, and the level buffer fits a fixed + // 32x32 frame of stack instead of a heap allocation per transform block. + debug_assert!(side.is_power_of_two() && side <= 32); + let sh = side.trailing_zeros(); + let col_mask = side - 1; + let mut levels_buf = [0i32; 32 * 32]; + let levels = &mut levels_buf[..side * side]; for scan_idx in (0..eob).rev() { let pos = scan[scan_idx] as usize; - let (row, col) = (pos / side, pos % side); + let (row, col) = (pos >> sh, pos & col_mask); let level = if scan_idx == eob - 1 { let ctx = eob_coeff_ctx(scan_idx, side * side); let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1; @@ -5739,7 +5766,7 @@ fn read_coeffs( } v } else { - let ctx = base_ctx(&levels, side, row, col, class, rect_shape); + let ctx = base_ctx(levels, side, row, col, class, rect_shape); let v = dec.symbol(&mut coding.base[ctx]) as i32; if ec_trace_coeff { let (rng, _) = dec.debug_state(); @@ -5758,7 +5785,7 @@ fn read_coeffs( v }; let level = if level > NUM_BASE_LEVELS { - let ctx = br_ctx(&levels, side, row, col, class); + let ctx = br_ctx(levels, side, row, col, class); let mut level = level; let mut sent = 0; loop { @@ -8785,7 +8812,7 @@ fn decode_rect_split( let (corner, tu_tx_type) = read_coeffs( dec, &mut coding, - &default_scan(TX32), + default_scan(TX32), 0, dc_sign_ctx(tu_around.2), TxType::DctDct, @@ -11309,7 +11336,7 @@ fn decode_rect4_16_strip( dec, cdfs, txbset_for(tx_w, reduced_tx_set), - &default_scan(tx_w), + default_scan(tx_w), 0, tu_around, mode, @@ -26522,7 +26549,7 @@ fn decode_inter_block( // top-left 32x32 of frequencies (spec 5.11.40), so // the scan and `tx_side` are the CODED corner while // `side` stays the transform's true 64. - &default_scan(tx_px.min(32)), + default_scan(tx_px.min(32)), 0, neighbours.around_mi(tu_mi, tx_px)[0], mode, @@ -30397,7 +30424,7 @@ fn decode_inter_block8( // CDF row is the intra dir (`fi_tx_row` inside // `read_plane` maps a filter-intra block's). txbset_for(tx_px, reduced_tx_set), - &default_scan(tx_px), + default_scan(tx_px), 0, neighbours.around_mi(tu_mi, tx_px)[0], mode, diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index 1ab4c595..8ab905e3 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -229,6 +229,7 @@ impl SymbolEncoder { /// The CDF adaptation of spec 8.3.2: every boundary moves a `rate`-dependent /// fraction of the way towards the extreme the observed symbol implies, and the /// counter in the last entry slows the rate down for the first 32 symbols. +#[inline] fn update_cdf(cdf: &mut [u16], symbol: usize) { let nsyms = cdf.len() - 1; let count = cdf[nsyms]; @@ -253,6 +254,15 @@ pub struct SymbolDecoder<'a> { data: &'a [u8], /// Next bit to read, as a bit offset into `data`. bit: usize, + /// The bits from `bit` onward, left-aligned at the MSB, zero past the end + /// of `data`; only the top `win_bits` are valid. The renormalisation of + /// every symbol read one to fifteen bits, and assembling them out of + /// `data` per read was five byte loads and two variable shifts each; the + /// window pays that once per eight bytes instead. + win: u64, + win_bits: u32, + /// Next byte of `data` to shift into `win`. + pos: usize, value: u32, range: u32, /// Bits left before the decoder starts padding with zeros (spec @@ -267,6 +277,9 @@ impl<'a> SymbolDecoder<'a> { let mut d = SymbolDecoder { data, bit: 0, + win: 0, + win_bits: 0, + pos: 0, value: 0, range: 1 << 15, max_bits: 8 * data.len() as i32 - 15, @@ -278,26 +291,51 @@ impl<'a> SymbolDecoder<'a> { } /// `f(n)`: the next `n` bits, most significant first, zero past the end. + #[inline] fn f(&mut self, n: u32) -> u32 { debug_assert!(n <= 32, "f(n) reads at most 32 bits"); if n == 0 { return 0; } - // The bit-at-a-time form of this loop was the renormalisation cost - // inside every `symbol_fixed`. Five bytes cover any 32-bit field at - // any bit offset, and a byte past the end reads as zero exactly as - // the per-bit `unwrap_or(0)` did. - let start = self.bit >> 3; - let off = (self.bit & 7) as u32; - let mut acc = 0u64; - for k in 0..5 { - acc = (acc << 8) | u64::from(self.data.get(start + k).copied().unwrap_or(0)); + if self.win_bits < n { + self.refill(); } + let v = (self.win >> (64 - n)) as u32; + self.win <<= n; + self.win_bits -= n; self.bit += n as usize; - ((acc >> (40 - off - n)) & ((1u64 << n) - 1)) as u32 + v + } + + /// Tops the window back up to at least 57 bits, reading bytes past the end + /// of `data` as zero exactly as the per-read `unwrap_or(0)` did. + fn refill(&mut self) { + while self.win_bits <= 56 { + let byte = self.data.get(self.pos).copied().unwrap_or(0); + self.pos += 1; + self.win |= u64::from(byte) << (56 - self.win_bits); + self.win_bits += 8; + } + } + + /// Repositions the window at an arbitrary bit offset (the `f(n)` test's + /// only way in now that `bit` alone no longer names the read position). + #[cfg(test)] + fn seek_bits(&mut self, bit: usize) { + self.bit = bit; + self.pos = bit >> 3; + self.win = 0; + self.win_bits = 0; + let skip = (bit & 7) as u32; + if skip > 0 { + self.refill(); + self.win <<= skip; + self.win_bits -= skip; + } } /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2. + #[inline] pub fn symbol(&mut self, cdf: &mut [u16]) -> usize { let s = self.symbol_fixed(cdf); update_cdf(cdf, s); @@ -307,23 +345,27 @@ impl<'a> SymbolDecoder<'a> { /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec /// uses for the literal and equiprobable reads, mirroring /// [`SymbolEncoder::symbol_fixed`]. + #[inline] pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize { let nsyms = cdf.len() - 1; let mut cur = self.range; - let mut prev; - let mut symbol = 0; + let mut prev = cur; + // The last boundary is always `CDF_TOP`, whose `cur` is 0, so the walk + // always stops inside the alphabet; iterating the slice instead of + // indexing it says so to the bounds checker. + let mut symbol = nsyms - 1; // Loop-invariant: the coder's range does not move until the symbol is // chosen, so its top byte is computed once rather than per candidate. let base = self.range >> 8; - loop { + for (i, &c) in cdf[..nsyms].iter().enumerate() { prev = cur; - let f = u32::from(CDF_TOP - cdf[symbol]); + let f = u32::from(CDF_TOP - c); cur = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) - + EC_MIN_PROB * (nsyms - 1 - symbol) as u32; + + EC_MIN_PROB * (nsyms - 1 - i) as u32; if self.value >= cur { + symbol = i; break; } - symbol += 1; } self.range = prev - cur; self.value -= cur; @@ -390,7 +432,7 @@ pub(crate) mod tests { for start in 0..(data.len() * 8 + 16) { for n in 0..=32u32 { let mut d = SymbolDecoder::new(&data); - d.bit = start; + d.seek_bits(start); let got = d.f(n); assert_eq!(got, per_bit(start, n), "start {start} width {n}"); assert_eq!(d.bit, start + n as usize, "start {start} width {n} advance");