diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 590bf883..6a3106d8 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -552,20 +552,37 @@ fn intra_predict_u8( smooth_neighbor: bool, dst: &mut [u8], fctx: &crate::decode::FrameCtx, ) { - let above16: Option> = above.map(|s| s.iter().map(|&v| u16::from(v)).collect()); - let left16: Option> = left.map(|s| s.iter().map(|&v| u16::from(v)).collect()); - let mut dst16 = vec![0u16; dst.len()]; + // Three heap allocations per call became three stack buffers: this runs + // once per mode per trial, and an edge is at most `bw + bh` samples while + // a block is at most `BLOCK * BLOCK`. Same samples either way. + let mut above_buf = [0u16; 2 * BLOCK]; + let mut left_buf = [0u16; 2 * BLOCK]; + let mut dst_buf = [0u16; BLOCK * BLOCK]; + let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| { + for (d, &v) in buf[..src.len()].iter_mut().zip(src) { + *d = u16::from(v); + } + }; + if let Some(s) = above { + widen(s, &mut above_buf); + } + if let Some(s) = left { + widen(s, &mut left_buf); + } + let above16 = above.map(|s| &above_buf[..s.len()]); + let left16 = left.map(|s| &left_buf[..s.len()]); + let dst16 = &mut dst_buf[..dst.len()]; crate::intra::predict( mode, angle_delta, - above16.as_deref(), - left16.as_deref(), + above16, + left16, corner.map(u16::from), bw, bh, enable_edge_filter, smooth_neighbor, - &mut dst16, fctx, + dst16, fctx, ); for (d, &s) in dst.iter_mut().zip(dst16.iter()) { *d = s as u8; @@ -1244,6 +1261,40 @@ impl Plane<'_> { /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names. #[allow(clippy::too_many_arguments)] + /// Sum of absolute differences between the source block at `(x, y)` and a + /// `side x side` prediction, as the whole number it is. + /// + /// Bit-identical to the `f64` accumulation it replaces: every partial sum + /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds + /// exactly, so no add here rounds and the order of the adds cannot change + /// the result. Dropping the per-pixel `i / side` and `i % side` -- an + /// integer division per sample -- is what lets the row walk vectorize. + fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 { + let mut sad = 0u32; + for row in 0..side { + let source = &self.source[(y + row) * self.width + x..][..side]; + for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) { + sad += u32::from(s.abs_diff(p)); + } + } + f64::from(sad) + } + + /// Squared error between the source block at `(x, y)` and a reconstruction + /// of it. Exact for the same reason [`Self::block_sad`] is: the largest + /// total is `255^2 * 64 * 64`, under 2^28. + fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 { + let mut sse = 0u64; + for row in 0..side { + let source = &self.source[(y + row) * self.width + x..][..side]; + for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..side]) { + let d = u32::from(s.abs_diff(r)); + sse += u64::from(d * d); + } + } + sse as f64 + } + fn trial_typed( &self, at: At, @@ -1293,19 +1344,12 @@ impl Plane<'_> { #[cfg(test)] stage_add(2, t.elapsed()); - let mut reconstruction = vec![0u8; side * side]; - let mut sse = 0.0; - for row in 0..side { - for col in 0..side { - let i = row * side + col; - let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; - reconstruction[i] = sample; - let error = f64::from( - i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), - ); - sse += error * error; - } - } + let reconstruction: Vec = prediction + .iter() + .zip(&coded) + .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) + .collect(); + let sse = self.block_sse(x, y, side, &reconstruction); // What the levels cost is priced through the same CDFs the tile writer // will code them with, so the search ranks modes -- and the partition // trial ranks trees -- by the bits they actually spend. @@ -1353,16 +1397,7 @@ impl Plane<'_> { set: TxbSet, ) -> Trial { if skip { - let mut sse = 0.0; - for row in 0..side { - for col in 0..side { - let error = f64::from( - i32::from(self.source[(y + row) * self.width + x + col]) - - i32::from(prediction[row * side + col]), - ); - sse += error * error; - } - } + let sse = self.block_sse(x, y, side, prediction); return Trial { levels: vec![0i32; side * side], reconstruction: prediction.to_vec(), @@ -1385,19 +1420,12 @@ impl Plane<'_> { let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); #[cfg(test)] stage_add(2, t.elapsed()); - let mut reconstruction = vec![0u8; side * side]; - let mut sse = 0.0; - for row in 0..side { - for col in 0..side { - let i = row * side + col; - let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; - reconstruction[i] = sample; - let error = f64::from( - i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), - ); - sse += error * error; - } - } + let reconstruction: Vec = prediction + .iter() + .zip(&coded) + .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) + .collect(); + let sse = self.block_sse(x, y, side, &reconstruction); #[cfg(test)] let t = std::time::Instant::now(); let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { @@ -1482,17 +1510,13 @@ impl Plane<'_> { /// `source`), since [`Self::source`] itself is the whole plane, strided /// by [`Self::width`]. fn source_block(&self, x: usize, y: usize, side: usize) -> Vec { - (y..y + side) - .flat_map(|row| self.source[row * self.width + x..][..side].to_vec()) - .collect() + rows_of(self.source, self.width, x, y, side) } /// The reconstructed samples of one square, so that a partition trial can /// be undone. fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec { - (y..y + side) - .flat_map(|row| self.reconstruction[row * self.width + x..][..side].to_vec()) - .collect() + rows_of(&self.reconstruction, self.width, x, y, side) } /// Puts a snapshot back. @@ -1534,16 +1558,7 @@ impl Plane<'_> { false, &mut prediction, fctx, ); - let sad: f64 = (0..side * side) - .map(|i| { - let (row, col) = (i / side, i % side); - f64::from( - (i32::from(self.source[(y + row) * self.width + x + col]) - - i32::from(prediction[i])) - .abs(), - ) - }) - .sum(); + let sad = self.block_sad(x, y, side, &prediction); (sad + lambda * mode_bits[usize::from(mode)], mode) }) .collect() @@ -1591,17 +1606,8 @@ impl Plane<'_> { false, &mut prediction, fctx, ); - let sad: f64 = if want_sad { - (0..side * side) - .map(|i| { - let (row, col) = (i / side, i % side); - f64::from( - (i32::from(self.source[(y + row) * self.width + x + col]) - - i32::from(prediction[i])) - .abs(), - ) - }) - .sum() + let sad = if want_sad { + self.block_sad(x, y, side, &prediction) } else { 0.0 }; @@ -3783,6 +3789,19 @@ fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: O /// The reconstructed samples one 32x32 square covers in all three planes, so /// that a partition trial can be undone. +/// One square of a plane, row-major, the inverse of [`Plane::restore`]. +/// +/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces, +/// which allocated and freed a `Vec` per row of every block it copied -- +/// `Plane::snapshot` runs once per partition trial. +fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec { + let mut out = vec![0u8; side * side]; + for row in 0..side { + out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]); + } + out +} + fn snapshot( luma: &Plane, chroma: &[Plane; 2], diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index acd2e304..a6eadd52 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -1442,6 +1442,34 @@ fn axis_basis(n: usize, kind: TxType1d) -> &'static [f64] { cache[k][idx].get_or_init(|| build_axis_basis(n, kind)) } +/// [`axis_basis`] transposed: `[i * n + u]` is basis function `u`'s sample +/// `i`. Both of [`forward_transform_2d_typed`]'s passes sum over the sample +/// index and are independent across the basis index, so this layout makes the +/// basis index the contiguous one and the two matmuls vectorize -- without +/// touching either sum's order, which is what keeps the levels bit-identical +/// to the strided `.map().sum()` this replaced. +fn axis_basis_t(n: usize, kind: TxType1d) -> &'static [f64] { + use std::sync::OnceLock; + static CACHE: OnceLock<[[OnceLock>; 5]; 3]> = OnceLock::new(); + let cache = CACHE.get_or_init(|| std::array::from_fn(|_| std::array::from_fn(|_| OnceLock::new()))); + let k = match kind { + TxType1d::Dct => 0, + TxType1d::Adst => 1, + TxType1d::Identity => 2, + }; + let idx = (n.trailing_zeros() as usize).saturating_sub(2); + cache[k][idx].get_or_init(|| { + let basis = axis_basis(n, kind); + let mut t = vec![0.0f64; n * n]; + for u in 0..n { + for i in 0..n { + t[i * n + u] = basis[u * n + i]; + } + } + t + }) +} + /// [`forward_transform_2d`] for a block whose transform type is not /// `DCT_DCT` -- what an intra chroma block coded in a non-`DC_PRED` mode /// gets, since chroma never codes a `tx_type` symbol and the decoder derives @@ -1461,8 +1489,14 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType "a flipped ADST needs its residual mirrored before this basis applies" ); let (row_kind, col_kind) = tx_type.axes(); - let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind)); + let (hb, vb) = (axis_basis_t(side, row_kind), axis_basis_t(side, col_kind)); let mut rows = vec![0.0f64; side * side]; + // Which rows of `rows` the pass below actually fills; the column pass + // walks only those. A row of `+0.0` contributes `0.0 * b` terms, which + // are `+-0.0`, and adding either to a running sum that is never `-0.0` + // (it starts at `+0.0` and `x + -x` is `+0.0`) leaves it unchanged. + let mut filled: [usize; 64] = [0; 64]; + let mut nfilled = 0usize; // Zero in, zero out, and `rows` is already zero here -- the skip // [`forward_rows`] takes for the same reason, which this path was // missing: a census of the BD gate's own ladder (lane-av1fwd) found 68% @@ -1476,12 +1510,16 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType continue; } any = true; - for v in 0..side { - rows[i * side + v] = source - .iter() - .zip(&hb[v * side..][..side]) - .map(|(&r, &b)| f64::from(r) * b) - .sum(); + filled[nfilled] = i; + nfilled += 1; + let out = &mut rows[i * side..][..side]; + // `k` ascending is the term order the strided `.map().sum()` had, so + // every lane's partial sums are the same values in the same order. + for (k, &r) in source.iter().enumerate() { + let r = f64::from(r); + for (o, &b) in out.iter_mut().zip(&hb[k * side..][..side]) { + *o += r * b; + } } } if !any { @@ -1489,10 +1527,15 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType } let mut out = vec![0.0f64; side * side]; for u in 0..side { - let column = &vb[u * side..][..side]; - for v in 0..side { - let sum: f64 = (0..side).map(|i| rows[i * side + v] * column[i]).sum(); - out[u * side + v] = INVERSE_GAIN_RECIPROCAL * sum; + let acc = &mut out[u * side..][..side]; + for &i in &filled[..nfilled] { + let c = vb[i * side + u]; + for (a, &r) in acc.iter_mut().zip(&rows[i * side..][..side]) { + *a += r * c; + } + } + for a in acc.iter_mut() { + *a *= INVERSE_GAIN_RECIPROCAL; } } out @@ -2613,6 +2656,90 @@ mod tests { /// full-range noise. A single differing lane at any size would be a /// silent pixel drift on whatever stream first reaches it. #[cfg(target_arch = "x86_64")] + /// [`forward_transform_2d_typed`]'s contiguous-basis passes are the + /// strided `.map().sum()` they replaced, bit for bit. + /// + /// The reordering is safe only because each output's terms stay in the + /// same order -- only the loop that iterates the *outputs* moved -- so + /// this compares raw bit patterns, not an epsilon: any reassociation + /// would show up here as a last-place difference at some size. + #[test] + fn the_typed_forward_transform_is_bit_identical_to_the_strided_form() { + fn strided(residual: &[i32], side: usize, tx_type: TxType) -> Vec { + let (row_kind, col_kind) = tx_type.axes(); + let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind)); + let mut rows = vec![0.0f64; side * side]; + for i in 0..side { + let source = &residual[i * side..][..side]; + if source.iter().all(|&r| r == 0) { + continue; + } + for v in 0..side { + rows[i * side + v] = source + .iter() + .zip(&hb[v * side..][..side]) + .map(|(&r, &b)| f64::from(r) * b) + .sum(); + } + } + let mut out = vec![0.0f64; side * side]; + for u in 0..side { + let column = &vb[u * side..][..side]; + for v in 0..side { + let sum: f64 = (0..side).map(|i| rows[i * side + v] * column[i]).sum(); + out[u * side + v] = INVERSE_GAIN_RECIPROCAL * sum; + } + } + out + } + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let types = [ + TxType::Idtx, + TxType::AdstAdst, + TxType::AdstDct, + TxType::DctAdst, + TxType::VDct, + TxType::HDct, + ]; + for side in [4usize, 8, 16, 32] { + for tx_type in types { + // ADST is undefined above 16 (the spec's 32+ sets are + // DCT/identity only), so those pairs never reach this path. + let adst = matches!(tx_type.axes(), (TxType1d::Adst, _) | (_, TxType1d::Adst)); + if side > 16 && adst { + continue; + } + for round in 0..8 { + // Round 0 is an all-zero residual and round 1 has whole + // zero rows, so both skips are exercised at every size. + let residual: Vec = (0..side * side) + .map(|i| match round { + 0 => 0, + 1 if (i / side) % 2 == 0 => 0, + _ => (next() % 511) as i32 - 255, + }) + .collect(); + let ours = forward_transform_2d_typed(&residual, side, tx_type); + let theirs = strided(&residual, side, tx_type); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + assert_eq!( + a.to_bits(), + b.to_bits(), + "{tx_type:?} {side}x{side} round {round} coefficient {i}: \ + {a} vs {b}" + ); + } + } + } + } + } + #[test] fn the_avx2_dct_matches_the_scalar_one_over_the_full_range() { if !std::arch::is_x86_feature_detected!("avx2") {