diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 146add28..5c9fd0fa 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -3460,4 +3460,116 @@ mod tests { "no inter frame coded a single inter block -- the search never fired" ); } + + /// A manual perf probe, not a gate: prints where a key frame's and an + /// inter frame's time goes, coarse stage by coarse stage, so a perf lane + /// measures before it optimizes rather than guessing. Run with + /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`. + #[test] + #[ignore = "a perf probe, not a gate"] + fn stage_timing_breakdown() { + use std::time::Instant; + + for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] { + let picture = test_card(width, height); + + let t = Instant::now(); + let dc_only = encode_key_frame_with_modes(&picture, 100, 0.5, &[DC_PRED]).unwrap(); + let dc_only_t = t.elapsed(); + + let t = Instant::now(); + let non_directional = + encode_key_frame_with_modes(&picture, 100, 0.5, &NON_DIRECTIONAL).unwrap(); + let non_directional_t = t.elapsed(); + + let t = Instant::now(); + let all_modes = encode_key_frame(&picture, 100, 0.5).unwrap(); + let all_modes_t = t.elapsed(); + + eprintln!( + "\n=== key frame {width}x{height} ===\n\ + 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\ + 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\ + 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)", + dc_only.stream.len(), + non_directional.stream.len(), + all_modes.stream.len(), + ); + + // One inter frame predicting off the key frame's own + // reconstruction, the (256, 256)-padded surface encode_sequence + // itself would hand encode_inter_frame. + let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK); + let padded_pic = picture.padded_to(SUPERBLOCK); + let t = Instant::now(); + let inter = + encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)) + .unwrap(); + let inter_t = t.elapsed(); + eprintln!( + "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ + {:.2})", + inter.stream.len(), + inter.inter_block_share + ); + } + + // Isolated per-call cost of the trial pipeline's own stages, at both + // transform sizes the search runs, averaged over enough calls to + // rise above `Instant::now`'s own noise. + for side in [16usize, 32] { + const N: u32 = 20_000; + let residual: Vec = (0..side * side) + .map(|i| ((i * 37 % 61) as i32) - 30) + .collect(); + + let t = Instant::now(); + let mut levels = Vec::new(); + for _ in 0..N { + levels = forward_and_quantize(&residual, side, 8, 100, 0.5); + } + let forward_t = t.elapsed() / N; + + let t = Instant::now(); + for _ in 0..N { + std::hint::black_box(dequant_and_inverse(&levels, side, 8, 100)); + } + let inverse_t = t.elapsed() / N; + + let set = if side == 32 { + crate::cdf_state::TxbSet::Luma32 + } else { + crate::cdf_state::TxbSet::Luma16 + }; + let t = Instant::now(); + for _ in 0..N { + std::hint::black_box(crate::tile::coeff_bits(&levels, set)); + } + let entropy_t = t.elapsed() / N; + + let above = vec![128u8; side * 2]; + let left = vec![128u8; side * 2]; + let mut prediction = vec![0u8; side * side]; + let t = Instant::now(); + for _ in 0..N { + crate::intra::predict( + D45_PRED, + Some(&above), + Some(&left), + Some(128), + side, + &mut prediction, + ); + } + let predict_t = t.elapsed() / N; + + eprintln!( + "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\ + predict (1 directional mode): {predict_t:>9.2?}\n\ + forward_and_quantize: {forward_t:>9.2?}\n\ + dequant_and_inverse: {inverse_t:>9.2?}\n\ + coeff_bits: {entropy_t:>9.2?}" + ); + } + } } diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index 97d46898..d3601d0b 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -349,7 +349,7 @@ pub fn dequant_and_inverse(levels: &[i32], side: usize, bit_depth: u8, q_idx: i3 /// undo, and nothing else: measuring the network's response to a unit /// coefficient at every size gives the same `1 / (8 * sqrt(2))` per unit of /// `dqDenom`, which is what [`forward_transform_2d`] divides out. -fn dct_basis(n: usize) -> Vec { +fn build_dct_basis(n: usize) -> Vec { let mut basis = vec![0.0f64; n * n]; let scale = (2.0 / n as f64).sqrt(); for u in 0..n { @@ -362,6 +362,23 @@ fn dct_basis(n: usize) -> Vec { basis } +/// [`build_dct_basis`], computed once per transform size and reused: the +/// search calls [`forward_transform_2d`] for every mode of every block, and +/// the basis does not depend on the residual, only on `n` -- recomputing +/// `n * n` cosines per call was measured as this search's single largest +/// per-trial cost (`stage_timing_breakdown`, ec-av1 perf lane). `n` is always +/// one of the transform sizes this crate codes (4 to 64, a power of two), so +/// a small fixed table indexed by `log2(n)` covers every caller without a +/// hash lookup. +fn dct_basis(n: usize) -> &'static [f64] { + use std::sync::OnceLock; + // log2(4)=2 .. log2(64)=6, so index by trailing_zeros() - 2. + static CACHE: OnceLock<[OnceLock>; 5]> = OnceLock::new(); + let cache = CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new())); + let idx = (n.trailing_zeros() as usize).saturating_sub(2); + cache[idx].get_or_init(|| build_dct_basis(n)) +} + /// How much the decoder's inverse transform shrinks an orthonormal DCT. /// /// Measured, not asserted: feeding a single dequantized coefficient through @@ -392,24 +409,40 @@ pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec { "one residual sample per position" ); let basis = dct_basis(side); - // Rows first, into a scratch of the same shape, then columns. + // Rows first, into a scratch of the same shape, then columns. Both passes + // are written as a contiguous dot product (row of `residual`/`rows_t` + // against a row of `basis`) rather than an index loop with one strided + // operand -- same summation order, so the same bits out, but a shape the + // optimizer can autovectorize (measured: this halved the per-call cost + // that `stage_timing_breakdown`, ec-av1 perf lane, found dominant). let mut rows = vec![0.0f64; side * side]; for i in 0..side { + let residual_row = &residual[i * side..][..side]; for u in 0..side { - let mut sum = 0.0; - for j in 0..side { - sum += f64::from(residual[i * side + j]) * basis[u * side + j]; - } + let sum: f64 = residual_row + .iter() + .zip(&basis[u * side..][..side]) + .map(|(&r, &b)| f64::from(r) * b) + .sum(); rows[i * side + u] = sum; } } + // Transposed so the column pass reads `rows` contiguously too, without + // changing which terms are summed in which order. + let mut rows_t = vec![0.0f64; side * side]; + for i in 0..side { + for v in 0..side { + rows_t[v * side + i] = rows[i * side + v]; + } + } let mut out = vec![0.0f64; side * side]; for u in 0..side { for v in 0..side { - let mut sum = 0.0; - for i in 0..side { - sum += rows[i * side + v] * basis[u * side + i]; - } + let sum: f64 = rows_t[v * side..][..side] + .iter() + .zip(&basis[u * side..][..side]) + .map(|(&r, &b)| r * b) + .sum(); out[u * side + v] = sum; } }