forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-coef' (d1f7fca6): msac 64-bit refill window + inlined symbol reads, static default_scan tables (was a Vec regenerated per transform block), stack level buffer in read_coeffs; byte-exact, -2.0% instructions on the 4K segment

Browse files at this commit

1e1c40e53a41fd33f93a754a4ded03b944f52fd0Ahmet Kaan GümüşParent: 5a5f1948841aa8
crates/ec-av1/src/decode.rsmodified+36 -9
@@ -5029,7 +5029,26 @@ pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
5029 5029
5030 /// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk5030 /// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
5031 /// [`crate::tile`]'s writer generates its scan tables with.5031 /// [`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> {
5033 let mut scan = Vec::with_capacity(side * side);5052 let mut scan = Vec::with_capacity(side * side);
5034 for d in 0..(2 * side - 1) {5053 for d in 0..(2 * side - 1) {
5035 let lo = d.saturating_sub(side - 1);5054 let lo = d.saturating_sub(side - 1);
@@ -5725,10 +5744,18 @@ fn read_coeffs(
5725 class_scan = class_scan_table(side, class);5744 class_scan = class_scan_table(side, class);
5726 &class_scan5745 &class_scan
5727 };5746 };
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];
5729 for scan_idx in (0..eob).rev() {5756 for scan_idx in (0..eob).rev() {
5730 let pos = scan[scan_idx] as usize;5757 let pos = scan[scan_idx] as usize;
5731- let (row, col) = (pos / side, pos % side);5758+ let (row, col) = (pos >> sh, pos & col_mask);
5732 let level = if scan_idx == eob - 1 {5759 let level = if scan_idx == eob - 1 {
5733 let ctx = eob_coeff_ctx(scan_idx, side * side);5760 let ctx = eob_coeff_ctx(scan_idx, side * side);
5734 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;5761 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
@@ -5739,7 +5766,7 @@ fn read_coeffs(
5739 }5766 }
5740 v5767 v
5741 } else {5768 } 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);
5743 let v = dec.symbol(&mut coding.base[ctx]) as i32;5770 let v = dec.symbol(&mut coding.base[ctx]) as i32;
5744 if ec_trace_coeff {5771 if ec_trace_coeff {
5745 let (rng, _) = dec.debug_state();5772 let (rng, _) = dec.debug_state();
@@ -5758,7 +5785,7 @@ fn read_coeffs(
5758 v5785 v
5759 };5786 };
5760 let level = if level > NUM_BASE_LEVELS {5787 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);
5762 let mut level = level;5789 let mut level = level;
5763 let mut sent = 0;5790 let mut sent = 0;
5764 loop {5791 loop {
@@ -8785,7 +8812,7 @@ fn decode_rect_split(
8785 let (corner, tu_tx_type) = read_coeffs(8812 let (corner, tu_tx_type) = read_coeffs(
8786 dec,8813 dec,
8787 &mut coding,8814 &mut coding,
8788- &default_scan(TX32),8815+ default_scan(TX32),
8789 0,8816 0,
8790 dc_sign_ctx(tu_around.2),8817 dc_sign_ctx(tu_around.2),
8791 TxType::DctDct,8818 TxType::DctDct,
@@ -11309,7 +11336,7 @@ fn decode_rect4_16_strip(
11309 dec,11336 dec,
11310 cdfs,11337 cdfs,
11311 txbset_for(tx_w, reduced_tx_set),11338 txbset_for(tx_w, reduced_tx_set),
11312- &default_scan(tx_w),11339+ default_scan(tx_w),
11313 0,11340 0,
11314 tu_around,11341 tu_around,
11315 mode,11342 mode,
@@ -26522,7 +26549,7 @@ fn decode_inter_block(
26522 // top-left 32x32 of frequencies (spec 5.11.40), so26549 // top-left 32x32 of frequencies (spec 5.11.40), so
26523 // the scan and `tx_side` are the CODED corner while26550 // the scan and `tx_side` are the CODED corner while
26524 // `side` stays the transform's true 64.26551 // `side` stays the transform's true 64.
26525- &default_scan(tx_px.min(32)),26552+ default_scan(tx_px.min(32)),
26526 0,26553 0,
26527 neighbours.around_mi(tu_mi, tx_px)[0],26554 neighbours.around_mi(tu_mi, tx_px)[0],
26528 mode,26555 mode,
@@ -30397,7 +30424,7 @@ fn decode_inter_block8(
30397 // CDF row is the intra dir (`fi_tx_row` inside30424 // CDF row is the intra dir (`fi_tx_row` inside
30398 // `read_plane` maps a filter-intra block's).30425 // `read_plane` maps a filter-intra block's).
30399 txbset_for(tx_px, reduced_tx_set),30426 txbset_for(tx_px, reduced_tx_set),
30400- &default_scan(tx_px),30427+ default_scan(tx_px),
30401 0,30428 0,
30402 neighbours.around_mi(tu_mi, tx_px)[0],30429 neighbours.around_mi(tu_mi, tx_px)[0],
30403 mode,30430 mode,
crates/ec-av1/src/msac.rsmodified+59 -17
@@ -229,6 +229,7 @@ impl SymbolEncoder {
229 /// The CDF adaptation of spec 8.3.2: every boundary moves a `rate`-dependent229 /// The CDF adaptation of spec 8.3.2: every boundary moves a `rate`-dependent
230 /// fraction of the way towards the extreme the observed symbol implies, and the230 /// fraction of the way towards the extreme the observed symbol implies, and the
231 /// counter in the last entry slows the rate down for the first 32 symbols.231 /// counter in the last entry slows the rate down for the first 32 symbols.
232+#[inline]
232 fn update_cdf(cdf: &mut [u16], symbol: usize) {233 fn update_cdf(cdf: &mut [u16], symbol: usize) {
233 let nsyms = cdf.len() - 1;234 let nsyms = cdf.len() - 1;
234 let count = cdf[nsyms];235 let count = cdf[nsyms];
@@ -253,6 +254,15 @@ pub struct SymbolDecoder<'a> {
253 data: &'a [u8],254 data: &'a [u8],
254 /// Next bit to read, as a bit offset into `data`.255 /// Next bit to read, as a bit offset into `data`.
255 bit: usize,256 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,
256 value: u32,266 value: u32,
257 range: u32,267 range: u32,
258 /// Bits left before the decoder starts padding with zeros (spec268 /// Bits left before the decoder starts padding with zeros (spec
@@ -267,6 +277,9 @@ impl<'a> SymbolDecoder<'a> {
267 let mut d = SymbolDecoder {277 let mut d = SymbolDecoder {
268 data,278 data,
269 bit: 0,279 bit: 0,
280+ win: 0,
281+ win_bits: 0,
282+ pos: 0,
270 value: 0,283 value: 0,
271 range: 1 << 15,284 range: 1 << 15,
272 max_bits: 8 * data.len() as i32 - 15,285 max_bits: 8 * data.len() as i32 - 15,
@@ -278,26 +291,51 @@ impl<'a> SymbolDecoder<'a> {
278 }291 }
279 292
280 /// `f(n)`: the next `n` bits, most significant first, zero past the end.293 /// `f(n)`: the next `n` bits, most significant first, zero past the end.
294+ #[inline]
281 fn f(&mut self, n: u32) -> u32 {295 fn f(&mut self, n: u32) -> u32 {
282 debug_assert!(n <= 32, "f(n) reads at most 32 bits");296 debug_assert!(n <= 32, "f(n) reads at most 32 bits");
283 if n == 0 {297 if n == 0 {
284 return 0;298 return 0;
285 }299 }
286- // The bit-at-a-time form of this loop was the renormalisation cost300+ if self.win_bits < n {
287- // inside every `symbol_fixed`. Five bytes cover any 32-bit field at301+ self.refill();
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));
295 }302 }
303+ let v = (self.win >> (64 - n)) as u32;
304+ self.win <<= n;
305+ self.win_bits -= n;
296 self.bit += n as usize;306 self.bit += n as usize;
297- ((acc >> (40 - off - n)) & ((1u64 << n) - 1)) as u32307+ 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+ }
298 }335 }
299 336
300 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.337 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.
338+ #[inline]
301 pub fn symbol(&mut self, cdf: &mut [u16]) -> usize {339 pub fn symbol(&mut self, cdf: &mut [u16]) -> usize {
302 let s = self.symbol_fixed(cdf);340 let s = self.symbol_fixed(cdf);
303 update_cdf(cdf, s);341 update_cdf(cdf, s);
@@ -307,23 +345,27 @@ impl<'a> SymbolDecoder<'a> {
307 /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec345 /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec
308 /// uses for the literal and equiprobable reads, mirroring346 /// uses for the literal and equiprobable reads, mirroring
309 /// [`SymbolEncoder::symbol_fixed`].347 /// [`SymbolEncoder::symbol_fixed`].
348+ #[inline]
310 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {349 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {
311 let nsyms = cdf.len() - 1;350 let nsyms = cdf.len() - 1;
312 let mut cur = self.range;351 let mut cur = self.range;
313- let mut prev;352+ let mut prev = cur;
314- let mut symbol = 0;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;
315 // Loop-invariant: the coder's range does not move until the symbol is357 // Loop-invariant: the coder's range does not move until the symbol is
316 // chosen, so its top byte is computed once rather than per candidate.358 // chosen, so its top byte is computed once rather than per candidate.
317 let base = self.range >> 8;359 let base = self.range >> 8;
318- loop {360+ for (i, &c) in cdf[..nsyms].iter().enumerate() {
319 prev = cur;361 prev = cur;
320- let f = u32::from(CDF_TOP - cdf[symbol]);362+ let f = u32::from(CDF_TOP - c);
321 cur = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))363 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;
323 if self.value >= cur {365 if self.value >= cur {
366+ symbol = i;
324 break;367 break;
325 }368 }
326- symbol += 1;
327 }369 }
328 self.range = prev - cur;370 self.range = prev - cur;
329 self.value -= cur;371 self.value -= cur;
@@ -390,7 +432,7 @@ pub(crate) mod tests {
390 for start in 0..(data.len() * 8 + 16) {432 for start in 0..(data.len() * 8 + 16) {
391 for n in 0..=32u32 {433 for n in 0..=32u32 {
392 let mut d = SymbolDecoder::new(&data);434 let mut d = SymbolDecoder::new(&data);
393- d.bit = start;435+ d.seek_bits(start);
394 let got = d.f(n);436 let got = d.f(n);
395 assert_eq!(got, per_bit(start, n), "start {start} width {n}");437 assert_eq!(got, per_bit(start, n), "start {start} width {n}");
396 assert_eq!(d.bit, start + n as usize, "start {start} width {n} advance");438 assert_eq!(d.bit, start + n as usize, "start {start} width {n} advance");