forge
Explore
Log in

Don't you dare go Hollow

Coefficient reading -- buffered msac bit window, static scan tables, no per-block level allocation

Browse files at this commit

8841aa8c913dddf0dcfe6ca20ef00fcf45a3337dAhmet Kaan GümüşParent: 5a5f194
  • perf
    • coefficient reading -- buffered msac bit window, static scan tables, no per-block level allocation
Show full message
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.rsmodified+36 -9
@@ -5029,7 +5029,26 @@ pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
50295029
50305030 /// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
50315031 /// [`crate::tile`]'s writer generates its scan tables with.
5032-fn default_scan(side: usize) -> Vec<u16> {
5032+fn default_scan(side: usize) -> &'static [u16] {
5033+ // One table per transform side (4/8/16/32), built once: this used to be a
5034+ // fresh heap allocation plus the whole anti-diagonal walk on every
5035+ // transform block read.
5036+ static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
5037+ [
5038+ default_scan_gen(4),
5039+ default_scan_gen(8),
5040+ default_scan_gen(16),
5041+ default_scan_gen(32),
5042+ ]
5043+ });
5044+ assert!(
5045+ matches!(side, 4 | 8 | 16 | 32),
5046+ "no default scan for a {side}-point transform"
5047+ );
5048+ &SCANS[side.trailing_zeros() as usize - 2]
5049+}
5050+
5051+fn default_scan_gen(side: usize) -> Vec<u16> {
50335052 let mut scan = Vec::with_capacity(side * side);
50345053 for d in 0..(2 * side - 1) {
50355054 let lo = d.saturating_sub(side - 1);
@@ -5725,10 +5744,18 @@ fn read_coeffs(
57255744 class_scan = class_scan_table(side, class);
57265745 &class_scan
57275746 };
5728- let mut levels = vec![0i32; side * side];
5747+ // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
5748+ // coefficient `pos / side`, `pos % side` was a hardware divide where a
5749+ // shift and a mask say the same thing, and the level buffer fits a fixed
5750+ // 32x32 frame of stack instead of a heap allocation per transform block.
5751+ debug_assert!(side.is_power_of_two() && side <= 32);
5752+ let sh = side.trailing_zeros();
5753+ let col_mask = side - 1;
5754+ let mut levels_buf = [0i32; 32 * 32];
5755+ let levels = &mut levels_buf[..side * side];
57295756 for scan_idx in (0..eob).rev() {
57305757 let pos = scan[scan_idx] as usize;
5731- let (row, col) = (pos / side, pos % side);
5758+ let (row, col) = (pos >> sh, pos & col_mask);
57325759 let level = if scan_idx == eob - 1 {
57335760 let ctx = eob_coeff_ctx(scan_idx, side * side);
57345761 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
@@ -5739,7 +5766,7 @@ fn read_coeffs(
57395766 }
57405767 v
57415768 } else {
5742- let ctx = base_ctx(&levels, side, row, col, class, rect_shape);
5769+ let ctx = base_ctx(levels, side, row, col, class, rect_shape);
57435770 let v = dec.symbol(&mut coding.base[ctx]) as i32;
57445771 if ec_trace_coeff {
57455772 let (rng, _) = dec.debug_state();
@@ -5758,7 +5785,7 @@ fn read_coeffs(
57585785 v
57595786 };
57605787 let level = if level > NUM_BASE_LEVELS {
5761- let ctx = br_ctx(&levels, side, row, col, class);
5788+ let ctx = br_ctx(levels, side, row, col, class);
57625789 let mut level = level;
57635790 let mut sent = 0;
57645791 loop {
@@ -8785,7 +8812,7 @@ fn decode_rect_split(
87858812 let (corner, tu_tx_type) = read_coeffs(
87868813 dec,
87878814 &mut coding,
8788- &default_scan(TX32),
8815+ default_scan(TX32),
87898816 0,
87908817 dc_sign_ctx(tu_around.2),
87918818 TxType::DctDct,
@@ -11309,7 +11336,7 @@ fn decode_rect4_16_strip(
1130911336 dec,
1131011337 cdfs,
1131111338 txbset_for(tx_w, reduced_tx_set),
11312- &default_scan(tx_w),
11339+ default_scan(tx_w),
1131311340 0,
1131411341 tu_around,
1131511342 mode,
@@ -26522,7 +26549,7 @@ fn decode_inter_block(
2652226549 // top-left 32x32 of frequencies (spec 5.11.40), so
2652326550 // the scan and `tx_side` are the CODED corner while
2652426551 // `side` stays the transform's true 64.
26525- &default_scan(tx_px.min(32)),
26552+ default_scan(tx_px.min(32)),
2652626553 0,
2652726554 neighbours.around_mi(tu_mi, tx_px)[0],
2652826555 mode,
@@ -30397,7 +30424,7 @@ fn decode_inter_block8(
3039730424 // CDF row is the intra dir (`fi_tx_row` inside
3039830425 // `read_plane` maps a filter-intra block's).
3039930426 txbset_for(tx_px, reduced_tx_set),
30400- &default_scan(tx_px),
30427+ default_scan(tx_px),
3040130428 0,
3040230429 neighbours.around_mi(tu_mi, tx_px)[0],
3040330430 mode,
crates/ec-av1/src/msac.rsmodified+59 -17
@@ -229,6 +229,7 @@ impl SymbolEncoder {
229229 /// The CDF adaptation of spec 8.3.2: every boundary moves a `rate`-dependent
230230 /// fraction of the way towards the extreme the observed symbol implies, and the
231231 /// counter in the last entry slows the rate down for the first 32 symbols.
232+#[inline]
232233 fn update_cdf(cdf: &mut [u16], symbol: usize) {
233234 let nsyms = cdf.len() - 1;
234235 let count = cdf[nsyms];
@@ -253,6 +254,15 @@ pub struct SymbolDecoder<'a> {
253254 data: &'a [u8],
254255 /// Next bit to read, as a bit offset into `data`.
255256 bit: usize,
257+ /// The bits from `bit` onward, left-aligned at the MSB, zero past the end
258+ /// of `data`; only the top `win_bits` are valid. The renormalisation of
259+ /// every symbol read one to fifteen bits, and assembling them out of
260+ /// `data` per read was five byte loads and two variable shifts each; the
261+ /// window pays that once per eight bytes instead.
262+ win: u64,
263+ win_bits: u32,
264+ /// Next byte of `data` to shift into `win`.
265+ pos: usize,
256266 value: u32,
257267 range: u32,
258268 /// Bits left before the decoder starts padding with zeros (spec
@@ -267,6 +277,9 @@ impl<'a> SymbolDecoder<'a> {
267277 let mut d = SymbolDecoder {
268278 data,
269279 bit: 0,
280+ win: 0,
281+ win_bits: 0,
282+ pos: 0,
270283 value: 0,
271284 range: 1 << 15,
272285 max_bits: 8 * data.len() as i32 - 15,
@@ -278,26 +291,51 @@ impl<'a> SymbolDecoder<'a> {
278291 }
279292
280293 /// `f(n)`: the next `n` bits, most significant first, zero past the end.
294+ #[inline]
281295 fn f(&mut self, n: u32) -> u32 {
282296 debug_assert!(n <= 32, "f(n) reads at most 32 bits");
283297 if n == 0 {
284298 return 0;
285299 }
286- // The bit-at-a-time form of this loop was the renormalisation cost
287- // inside every `symbol_fixed`. Five bytes cover any 32-bit field at
288- // any bit offset, and a byte past the end reads as zero exactly as
289- // the per-bit `unwrap_or(0)` did.
290- let start = self.bit >> 3;
291- let off = (self.bit & 7) as u32;
292- let mut acc = 0u64;
293- for k in 0..5 {
294- acc = (acc << 8) | u64::from(self.data.get(start + k).copied().unwrap_or(0));
300+ if self.win_bits < n {
301+ self.refill();
295302 }
303+ let v = (self.win >> (64 - n)) as u32;
304+ self.win <<= n;
305+ self.win_bits -= n;
296306 self.bit += n as usize;
297- ((acc >> (40 - off - n)) & ((1u64 << n) - 1)) as u32
307+ v
308+ }
309+
310+ /// Tops the window back up to at least 57 bits, reading bytes past the end
311+ /// of `data` as zero exactly as the per-read `unwrap_or(0)` did.
312+ fn refill(&mut self) {
313+ while self.win_bits <= 56 {
314+ let byte = self.data.get(self.pos).copied().unwrap_or(0);
315+ self.pos += 1;
316+ self.win |= u64::from(byte) << (56 - self.win_bits);
317+ self.win_bits += 8;
318+ }
319+ }
320+
321+ /// Repositions the window at an arbitrary bit offset (the `f(n)` test's
322+ /// only way in now that `bit` alone no longer names the read position).
323+ #[cfg(test)]
324+ fn seek_bits(&mut self, bit: usize) {
325+ self.bit = bit;
326+ self.pos = bit >> 3;
327+ self.win = 0;
328+ self.win_bits = 0;
329+ let skip = (bit & 7) as u32;
330+ if skip > 0 {
331+ self.refill();
332+ self.win <<= skip;
333+ self.win_bits -= skip;
334+ }
298335 }
299336
300337 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.
338+ #[inline]
301339 pub fn symbol(&mut self, cdf: &mut [u16]) -> usize {
302340 let s = self.symbol_fixed(cdf);
303341 update_cdf(cdf, s);
@@ -307,23 +345,27 @@ impl<'a> SymbolDecoder<'a> {
307345 /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec
308346 /// uses for the literal and equiprobable reads, mirroring
309347 /// [`SymbolEncoder::symbol_fixed`].
348+ #[inline]
310349 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {
311350 let nsyms = cdf.len() - 1;
312351 let mut cur = self.range;
313- let mut prev;
314- let mut symbol = 0;
352+ let mut prev = cur;
353+ // The last boundary is always `CDF_TOP`, whose `cur` is 0, so the walk
354+ // always stops inside the alphabet; iterating the slice instead of
355+ // indexing it says so to the bounds checker.
356+ let mut symbol = nsyms - 1;
315357 // Loop-invariant: the coder's range does not move until the symbol is
316358 // chosen, so its top byte is computed once rather than per candidate.
317359 let base = self.range >> 8;
318- loop {
360+ for (i, &c) in cdf[..nsyms].iter().enumerate() {
319361 prev = cur;
320- let f = u32::from(CDF_TOP - cdf[symbol]);
362+ let f = u32::from(CDF_TOP - c);
321363 cur = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
322- + EC_MIN_PROB * (nsyms - 1 - symbol) as u32;
364+ + EC_MIN_PROB * (nsyms - 1 - i) as u32;
323365 if self.value >= cur {
366+ symbol = i;
324367 break;
325368 }
326- symbol += 1;
327369 }
328370 self.range = prev - cur;
329371 self.value -= cur;
@@ -390,7 +432,7 @@ pub(crate) mod tests {
390432 for start in 0..(data.len() * 8 + 16) {
391433 for n in 0..=32u32 {
392434 let mut d = SymbolDecoder::new(&data);
393- d.bit = start;
435+ d.seek_bits(start);
394436 let got = d.f(n);
395437 assert_eq!(got, per_bit(start, n), "start {start} width {n}");
396438 assert_eq!(d.bit, start + n as usize, "start {start} width {n} advance");