diff --git a/crates/ec-av1/src/film_grain.rs b/crates/ec-av1/src/film_grain.rs index 4ebaad44..8efafb88 100644 --- a/crates/ec-av1/src/film_grain.rs +++ b/crates/ec-av1/src/film_grain.rs @@ -297,6 +297,20 @@ fn scale_lut(lut: &[i32; 256], index: i32, bit_depth: u32) -> i32 { } } +/// [`scale_lut`] evaluated over its whole index domain once per frame. +/// +/// The scaling LUT is fixed for the frame, so the interpolation the spec +/// writes per sample is a pure function of the sample value with at most +/// `256 << (bit_depth - 8)` distinct answers -- 1024 entries at 10 bit. This +/// is the same function, tabulated: `add_noise_to_block` was 9.0% self time +/// and ran that branchy interpolation once per luma sample and twice per +/// chroma sample. +fn expand_scaling_lut(lut: &[i32; 256], bit_depth: u32) -> Vec { + (0..(256i32 << (bit_depth - 8))) + .map(|i| scale_lut(lut, i, bit_depth)) + .collect() +} + /// `add_noise_to_block` (spec 7.18.3.5), 4:2:0 only. `(py0, px0)` is /// the luma-plane pixel origin; the matching chroma origin is `(py0/2, /// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the @@ -306,9 +320,9 @@ fn scale_lut(lut: &[i32; 256], index: i32, bit_depth: u32) -> i32 { fn add_noise_to_block( fg: &FilmGrainParams, mc_identity: bool, - scaling_y: &[i32; 256], - scaling_cb: &[i32; 256], - scaling_cr: &[i32; 256], + scaling_y: &[i32], + scaling_cb: &[i32], + scaling_cr: &[i32], picture: &mut Picture, py0: i32, px0: i32, @@ -386,9 +400,9 @@ fn add_noise_to_block( >> 6) + cb_offset) .clamp(0, index_max); - let delta = (scale_lut(scaling_cb, scaled, bit_depth) * cb_grain[gidx] - + rounding_offset) - >> scaling_shift; + let delta = + (scaling_cb[scaled as usize] * cb_grain[gidx] + rounding_offset) + >> scaling_shift; picture.u[cidx] = ((picture.u[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16; } @@ -397,25 +411,27 @@ fn add_noise_to_block( >> 6) + cr_offset) .clamp(0, index_max); - let delta = (scale_lut(scaling_cr, scaled, bit_depth) * cr_grain[gidx] - + rounding_offset) - >> scaling_shift; + let delta = + (scaling_cr[scaled as usize] * cr_grain[gidx] + rounding_offset) + >> scaling_shift; picture.v[cidx] = ((picture.v[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16; } } } if apply_y { + // Both operands are contiguous along a row, so the row bases are + // computed once instead of a multiply-add per sample. + let width = (half_w * 2) as usize; for i in 0..half_h * 2 { - for j in 0..half_w * 2 { - let pidx = ((py0 + i) * y_stride + (px0 + j)) as usize; - let gidx = ((lg_row0 + i) * lg_stride + (lg_col0 + j)) as usize; - let delta = (scale_lut(scaling_y, picture.y[pidx] as i32, bit_depth) - * luma_grain[gidx] - + rounding_offset) - >> scaling_shift; - picture.y[pidx] = - ((picture.y[pidx] as i32 + delta).clamp(min_luma, max_luma)) as u16; + let prow = ((py0 + i) * y_stride + px0) as usize; + let grow = ((lg_row0 + i) * lg_stride + lg_col0) as usize; + let pixels = &mut picture.y[prow..prow + width]; + let grain = &luma_grain[grow..grow + width]; + for (p, &g) in pixels.iter_mut().zip(grain) { + let delta = + (scaling_y[*p as usize] * g + rounding_offset) >> scaling_shift; + *p = ((*p as i32 + delta).clamp(min_luma, max_luma)) as u16; } } } @@ -609,6 +625,11 @@ pub(crate) fn apply_grain( ) }; + let expand_bd = grain_bit_depth(); + let scaling_y = expand_scaling_lut(&scaling_y, expand_bd); + let scaling_cb = expand_scaling_lut(&scaling_cb, expand_bd); + let scaling_cr = expand_scaling_lut(&scaling_cr, expand_bd); + let overlap = fg.overlap_flag; let mut y_line_buf = vec![0i32; (y_stride * 2).max(1) as usize]; diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index b9be77e2..1ab4c595 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -279,13 +279,22 @@ impl<'a> SymbolDecoder<'a> { /// `f(n)`: the next `n` bits, most significant first, zero past the end. fn f(&mut self, n: u32) -> u32 { - let mut v = 0; - for _ in 0..n { - let byte = self.data.get(self.bit >> 3).copied().unwrap_or(0); - v = (v << 1) | u32::from((byte >> (7 - (self.bit & 7))) & 1); - self.bit += 1; + debug_assert!(n <= 32, "f(n) reads at most 32 bits"); + if n == 0 { + return 0; } - v + // 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)); + } + self.bit += n as usize; + ((acc >> (40 - off - n)) & ((1u64 << n) - 1)) as u32 } /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2. @@ -303,10 +312,13 @@ impl<'a> SymbolDecoder<'a> { let mut cur = self.range; let mut prev; let mut symbol = 0; + // 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 { prev = cur; let f = u32::from(CDF_TOP - cdf[symbol]); - cur = (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) + cur = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) + EC_MIN_PROB * (nsyms - 1 - symbol) as u32; if self.value >= cur { break; @@ -358,6 +370,34 @@ impl<'a> SymbolDecoder<'a> { pub(crate) mod tests { use super::*; + /// `f(n)` now assembles five bytes and shifts instead of walking bits. + /// This pins it against the per-bit form it replaced, at every start + /// offset, every width up to 32, and past the end of the buffer (where + /// both forms must read zeros). + #[test] + fn bulk_bit_reads_match_the_per_bit_form() { + let data: Vec = (0..40u32).map(|i| (i * 37 + 11) as u8).collect(); + let per_bit = |start: usize, n: u32| -> u32 { + let mut bit = start; + let mut v = 0u32; + for _ in 0..n { + let byte = data.get(bit >> 3).copied().unwrap_or(0); + v = (v << 1) | u32::from((byte >> (7 - (bit & 7))) & 1); + bit += 1; + } + v + }; + for start in 0..(data.len() * 8 + 16) { + for n in 0..=32u32 { + let mut d = SymbolDecoder::new(&data); + d.bit = 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"); + } + } + } + // `tile.rs`'s own tests reach `SymbolDecoder` through this path; it now // lives in the outer module (non-test code decodes with it too), so this // re-export is what keeps those call sites resolving unmodified. diff --git a/crates/ec-av1/src/quant.rs b/crates/ec-av1/src/quant.rs index a42166c5..8da4c346 100644 --- a/crates/ec-av1/src/quant.rs +++ b/crates/ec-av1/src/quant.rs @@ -226,11 +226,45 @@ pub fn dequant(levels: &[i32], side: usize, bit_depth: u8, q_idx: i32) -> Vec Vec { - levels - .iter() - .enumerate() - .map(|(i, &l)| dequant_coeff_wh(l, i == 0, bit_depth, q_idx, dc_delta, ac_delta, w, h)) - .collect() + let mut out = Vec::new(); + dequant_wh_into(levels, &mut out, w, h, bit_depth, q_idx, dc_delta, ac_delta); + out +} + +/// [`dequant_wh`] into a caller-owned buffer, with the two quantizer-table +/// lookups, the area denominator and the clamp bound hoisted out of the +/// per-coefficient loop -- they depend only on the transform, and this loop +/// runs once per coefficient of every transform unit in the stream (7.8% +/// self time). A zero level dequantizes to zero for every parameter set, so +/// the common all-but-EOB tail costs a compare instead of a 64-bit multiply +/// and divide. The arithmetic on a non-zero level is the spec's, unchanged. +#[allow(clippy::too_many_arguments)] +pub fn dequant_wh_into( + levels: &[i32], + out: &mut Vec, + w: usize, + h: usize, + bit_depth: u8, + q_idx: i32, + dc_delta: i32, + ac_delta: i32, +) { + let dcq = i64::from(dc_q(bit_depth, q_idx + dc_delta)); + let acq = i64::from(ac_q(bit_depth, q_idx + ac_delta)); + let denom = dq_denom_area(w * h); + let bound = 1i64 << (7 + u32::from(bit_depth)); + let apply = |l: i32, q: i64| -> i32 { + let dq = i64::from(l) * q; + let sign = if dq < 0 { -1 } else { 1 }; + let dq2 = sign * ((dq.abs() & 0xFF_FFFF) / denom); + dq2.clamp(-bound, bound - 1) as i32 + }; + out.clear(); + out.reserve(levels.len()); + out.extend(levels.iter().map(|&l| if l == 0 { 0 } else { apply(l, acq) })); + if let (Some(dst), Some(&l)) = (out.first_mut(), levels.first()) { + *dst = if l == 0 { 0 } else { apply(l, dcq) }; + } } #[cfg(test)] @@ -254,6 +288,29 @@ mod tests { assert_eq!([4, 8, 16, 32, 64].map(dq_denom), [1, 1, 1, 2, 4]); } + /// The hoisted buffer form must agree with the per-coefficient spec + /// function it replaced, at every level sign, both quantizer roles and + /// every denominator band. + #[test] + fn buffered_dequant_matches_the_per_coefficient_form() { + let levels: Vec = (0..64).map(|i| (i as i32 - 32) * 37).collect(); + let mut out = Vec::new(); + for (w, h) in [(4, 4), (16, 16), (32, 32), (64, 64), (8, 32), (16, 4)] { + for bit_depth in [8u8, 10, 12] { + for (q_idx, dc, ac) in [(20, 0, 0), (140, -8, 5), (255, 12, -12)] { + let n = (w * h).min(levels.len()); + dequant_wh_into(&levels[..n], &mut out, w, h, bit_depth, q_idx, dc, ac); + for (i, &got) in out.iter().enumerate() { + let want = dequant_coeff_wh( + levels[i], i == 0, bit_depth, q_idx, dc, ac, w, h, + ); + assert_eq!(got, want, "{w}x{h} depth {bit_depth} q {q_idx} coeff {i}"); + } + } + } + } + } + /// Negative levels round toward zero, so a level and its negation /// dequantize to values that differ only in sign. #[test] diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index b68061ed..8cb14750 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -8,7 +8,7 @@ //! rounded DCT would drift away from the decoder by a sample here and there. /// `Cos128_Lookup` (spec 7.13.2.1): `4096 * cos(angle * pi / 128)` rounded. -static COS128_LOOKUP: [i32; 65] = [ +const COS128_LOOKUP: [i32; 65] = [ 4096, 4095, 4091, 4085, 4076, 4065, 4052, 4036, 4017, 3996, 3973, 3948, 3920, 3889, 3857, 3822, 3784, 3745, 3703, 3659, 3612, 3564, 3513, 3461, 3406, 3349, 3290, 3229, 3166, 3102, 3035, 2967, 2896, 2824, 2751, 2675, 2598, 2520, 2440, 2359, 2276, 2191, 2106, 2019, 1931, 1842, 1751, 1660, @@ -18,15 +18,32 @@ static COS128_LOOKUP: [i32; 65] = [ /// The fixed-point position of the cosine table. const COS_BITS: usize = 12; +/// [`COS128_LOOKUP`] unfolded to the whole circle at compile time -- the same +/// four quadrant cases the spec writes, evaluated once here so a butterfly's +/// cosine is one load instead of a four-way branch per call. +const fn build_cos128_full() -> [i32; 256] { + let mut t = [0i32; 256]; + let mut a = 0usize; + while a < 256 { + t[a] = if a <= 64 { + COS128_LOOKUP[a] + } else if a <= 128 { + -COS128_LOOKUP[128 - a] + } else if a <= 192 { + -COS128_LOOKUP[a - 128] + } else { + COS128_LOOKUP[256 - a] + }; + a += 1; + } + t +} + +static COS128_FULL: [i32; 256] = build_cos128_full(); + /// `cos128(angle)` (spec 7.13.2.1), folded from the quarter table. fn cos128(angle: i32) -> i32 { - let angle2 = (angle & 255) as usize; - match angle2 { - 0..=64 => COS128_LOOKUP[angle2], - 65..=128 => -COS128_LOOKUP[128 - angle2], - 129..=192 => -COS128_LOOKUP[angle2 - 128], - _ => COS128_LOOKUP[256 - angle2], - } + COS128_FULL[(angle & 255) as usize] } /// `sin128(angle)` (spec 7.13.2.1). @@ -34,9 +51,39 @@ fn sin128(angle: i32) -> i32 { cos128(angle - 64) } +/// `brev(numBits, x)` (spec 7.13.2.1) tabulated at compile time, one row per +/// `num_bits`. The bit-fold ran per butterfly index at runtime and was the +/// single hottest instruction sequence in `inverse_dct`'s annotation. +const fn build_brev(num_bits: u32) -> [u8; 64] { + let mut t = [0u8; 64]; + let n0 = 1usize << num_bits; + let mut x = 0usize; + while x < n0 { + let mut v = 0usize; + let mut i = 0u32; + while i < num_bits { + v |= ((x >> i) & 1) << (num_bits - 1 - i); + i += 1; + } + t[x] = v as u8; + x += 1; + } + t +} + +static BREV_TAB: [[u8; 64]; 7] = [ + build_brev(0), + build_brev(1), + build_brev(2), + build_brev(3), + build_brev(4), + build_brev(5), + build_brev(6), +]; + /// `brev(numBits, x)` (spec 7.13.2.1): the bit reversal of the low `num_bits`. fn brev(num_bits: u32, x: usize) -> usize { - (0..num_bits).fold(0, |t, i| t | (((x >> i) & 1) << (num_bits - 1 - i))) + BREV_TAB[num_bits as usize][x] as usize } /// `Round2(x, n)` (spec 4.7): shift down `n` places, rounding halves up. @@ -85,9 +132,13 @@ fn hadamard(t: &mut [i32], a: usize, b: usize, flip: bool, r: usize) { /// of the first `1 << n` entries. fn permute(t: &mut [i32], n: u32) { let n0 = 1usize << n; - let copy: Vec = t[..n0].to_vec(); + // A stack copy: this ran once per 1D transform and its `Vec` was the + // `malloc` at the top of every `inverse_dct` frame in the annotation. + let mut copy = [0i32; 64]; + copy[..n0].copy_from_slice(&t[..n0]); + let tab = &BREV_TAB[n as usize]; for (i, v) in t[..n0].iter_mut().enumerate() { - *v = copy[brev(n, i)]; + *v = copy[tab[i] as usize]; } } @@ -828,54 +879,90 @@ pub fn inverse_transform_2d_typed_wh( assert_eq!(dequant.len(), w * h, "one coefficient per position"); let row_clamp = usize::from(bit_depth) + 8; let col_clamp = (usize::from(bit_depth) + 6).max(16); - let mut residual = vec![0i32; w * h]; let (row_kind, col_kind) = tx_type.axes(); let (ud_flip, lr_flip) = tx_type.flip(); // `get_rect_tx_log_ratio` (`av1_inv_txfm2d.c:248`): the scale fires only // at ratio exactly 1, never 0 (square) or 2 (e.g. 4x16/16x4/8x32/32x8/ // 16x64/64x16). let rect_scale = (log2w as i32 - log2h as i32).abs() == 1; - - let mut t = [0i32; 64]; - for i in 0..h { - for j in 0..w { - let c = if i < 32 && j < 32 { dequant[i * w + j] } else { 0 }; - t[j] = if rect_scale { - round2(c * 2896, 12) - } else { - c - }; - } - inverse_1d(&mut t, log2w, row_clamp, row_kind); - for j in 0..w { - // The row's output is shifted, then clamped before the column - // transform reads it back. - residual[i * w + j] = clamp_range(round2(t[j], row_shift_wh(w, h)), col_clamp); - } - } - + // Loop-invariant: the shift is keyed on the transform size, and was being + // looked up through a match once per output sample. + let shift = row_shift_wh(w, h); // A FLIPADST axis reads the row-pass output right-to-left and/or writes // its own output bottom-to-top (`inv_txfm2d_add_c`, `av1_inv_txfm2d.c` - // lines 291-314): `out` is a second buffer, not `residual` reused in + // lines 291-314): `out` is a second buffer, not the row scratch reused in // place, because a flipped read/write pair aliases a column this same // loop has not visited yet (column `j`'s write target under `lr_flip` // is a column an unflipped loop would still need to read from later). // `lr_flip` mirrors over `w` (the row axis), `ud_flip` over `h`. let mut out = vec![0i32; w * h]; - for j in 0..w { - let src_col = if lr_flip { w - 1 - j } else { j }; + let cols = w.min(32); + ROW_SCRATCH.with(|cell| { + let mut scratch = cell.borrow_mut(); + if scratch.len() < w * h { + scratch.resize(64 * 64, 0); + } + let residual = &mut scratch[..w * h]; + let mut t = [0i32; 64]; for i in 0..h { - t[i] = residual[i * w + src_col]; + let dst = &mut residual[i * w..(i + 1) * w]; + // Rows at or past 32 carry no coefficients (the spec zeroes them + // before the row transform), and a zero row transforms to a zero + // row: every butterfly and Hadamard of zeros is zero, and + // `Round2(0, n)` is zero at every `n`, so this is the full + // network's own answer, not an approximation of it. + let src = if i < 32 { &dequant[i * w..i * w + cols] } else { &[][..] }; + if src.iter().all(|&c| c == 0) { + dst.fill(0); + continue; + } + if rect_scale { + for (tj, &c) in t[..cols].iter_mut().zip(src) { + *tj = round2(c * 2896, 12); + } + } else { + t[..cols].copy_from_slice(src); + } + t[cols..w].fill(0); + inverse_1d(&mut t, log2w, row_clamp, row_kind); + // The row's output is shifted, then clamped before the column + // transform reads it back. + for (d, &v) in dst.iter_mut().zip(t[..w].iter()) { + *d = clamp_range(round2(v, shift), col_clamp); + } } - inverse_1d(&mut t, log2h, col_clamp, col_kind); - for i in 0..h { - let dst_row = if ud_flip { h - 1 - i } else { i }; - out[dst_row * w + j] = round2(t[i], 4); + + for j in 0..w { + let src_col = if lr_flip { w - 1 - j } else { j }; + let mut any = 0i32; + for i in 0..h { + let v = residual[i * w + src_col]; + t[i] = v; + any |= v; + } + // Same zero-in/zero-out argument as the row pass, and `out` is + // already zero at every position this column would write. + if any == 0 { + continue; + } + inverse_1d(&mut t, log2h, col_clamp, col_kind); + for i in 0..h { + let dst_row = if ud_flip { h - 1 - i } else { i }; + out[dst_row * w + j] = round2(t[i], 4); + } } - } + }); out } +thread_local! { + /// Row-pass scratch, reused per thread. The row pass writes every position + /// it later reads, so the buffer needs no zeroing, and the two `Vec`s this + /// function allocated per transform unit become one. + static ROW_SCRATCH: std::cell::RefCell> = + const { std::cell::RefCell::new(Vec::new()) }; +} + /// [`inverse_transform_2d_typed`] at `DCT_DCT`, this crate's original /// (and still most common) transform. pub fn inverse_transform_2d(dequant: &[i32], side: usize, bit_depth: u8) -> Vec { @@ -916,8 +1003,19 @@ pub fn dequant_and_inverse_typed_wh( ac_delta: i32, tx_type: TxType, ) -> Vec { - let dq = crate::quant::dequant_wh(levels, w, h, bit_depth, q_idx, dc_delta, ac_delta); - inverse_transform_2d_typed_wh(&dq, w, h, bit_depth, tx_type) + DQ_SCRATCH.with(|cell| { + let mut dq = cell.borrow_mut(); + crate::quant::dequant_wh_into(levels, &mut dq, w, h, bit_depth, q_idx, dc_delta, ac_delta); + inverse_transform_2d_typed_wh(&dq, w, h, bit_depth, tx_type) + }) +} + +thread_local! { + /// The dequantized grid, reused per thread: it lives only until the + /// inverse transform has read it, so it was a `Vec` allocated and dropped + /// once per transform unit. + static DQ_SCRATCH: std::cell::RefCell> = + const { std::cell::RefCell::new(Vec::new()) }; } /// [`dequant_and_inverse_typed`] at `DCT_DCT`, no per-plane quantizer delta. @@ -1217,6 +1315,45 @@ pub fn forward_and_quantize( mod tests { use super::*; + /// The row and column passes skip an all-zero vector instead of running + /// the butterfly network over it. That is only bit-exact because a zero + /// vector transforms to a zero vector at every size, type and bit depth -- + /// which is what this pins, per 1D transform and end to end. + #[test] + fn a_zero_vector_transforms_to_zero() { + for log2 in 2..=6u32 { + for kind in [TxType1d::Dct, TxType1d::Adst, TxType1d::Identity] { + if kind == TxType1d::Adst && log2 > 4 { + continue; + } + if kind == TxType1d::Identity && log2 > 5 { + continue; + } + for bit_depth in [8u8, 10, 12] { + let r = (usize::from(bit_depth) + 6).max(16); + let mut t = [0i32; 64]; + inverse_1d(&mut t, log2, r, kind); + assert!( + t.iter().all(|&v| v == 0), + "1D {kind:?} log2={log2} depth={bit_depth} left a non-zero" + ); + } + } + } + for (w, h) in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64), (8, 16), (16, 8), (4, 16), (32, 8)] { + for tx in [TxType::DctDct, TxType::AdstAdst, TxType::Idtx, TxType::AdstDct, TxType::DctAdst] { + if w.max(h) > 16 && tx != TxType::DctDct && tx != TxType::Idtx { + continue; + } + if w.max(h) > 32 && tx != TxType::DctDct { + continue; + } + let out = inverse_transform_2d_typed_wh(&vec![0i32; w * h], w, h, 10, tx); + assert!(out.iter().all(|&v| v == 0), "2D {w}x{h} {tx:?} left a non-zero"); + } + } + } + /// The orthonormal DCT-II basis the forward transform is written against, /// computed independently of `dct_basis` so a test is not checking a /// function against itself.