From 7947a2db5bd9a8a078c20a1607c633c2aba98903 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 07:30:06 +0300 Subject: [PATCH] perf(av1): the coefficient rate pricer stops rebuilding every CDF table per candidate `tile::coeff_bits` is called once per priced candidate and built a whole `Cdfs` each time -- 9% of the encoder's profile between `Cdfs::new` and the copy behind it. It now keeps one pristine and one scratch `Cdfs` per q-context per thread and restores only the tables `write_coeffs` adapts, so the price is taken against exactly the same state as before. `partition_bits` builds its read-only tables once. Byte-exact: the four-point ladder of the 1080p gate clip is identical (17643/32317/53048/76330 bytes, same FNV-1a per stream); 9.58s -> 8.24s. --- crates/ec-av1/examples/enc_probe.rs | 56 +++++++++++++++++++++++++++ crates/ec-av1/src/tile.rs | 60 ++++++++++++++++++++++------- 2 files changed, 103 insertions(+), 13 deletions(-) create mode 100644 crates/ec-av1/examples/enc_probe.rs diff --git a/crates/ec-av1/examples/enc_probe.rs b/crates/ec-av1/examples/enc_probe.rs new file mode 100644 index 00000000..6f44fc6b --- /dev/null +++ b/crates/ec-av1/examples/enc_probe.rs @@ -0,0 +1,56 @@ +//! Encode-side profiling driver: the BD gate's own ladder, without ffmpeg's +//! decode side or the reference encoders, so `perf record` attributes only +//! our encoder. Also the byte-exactness gate for encoder-internal rewrites: +//! it prints each point's stream length and a hash of its bytes. +//! +//! Usage: `enc_probe [q,q,..]` + +use std::process::Command; + +fn main() { + let a: Vec = std::env::args().skip(1).collect(); + let (clip, width, height, frames) = ( + a[0].clone(), + a[1].parse::().unwrap(), + a[2].parse::().unwrap(), + a[3].parse::().unwrap(), + ); + let qs: Vec = a + .get(4) + .map_or_else(|| vec![150, 120, 90, 60], |s| s.split(',').map(|q| q.parse().unwrap()).collect()); + + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i", &clip, "-frames:v", &frames.to_string()]) + .args(["-vf", &format!("scale={width}:{height}")]) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .expect("ffmpeg failed to run"); + assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); + let (luma, chroma) = (width * height, width * height / 4); + let frame_len = luma + 2 * chroma; + let source: Vec = (0..frames) + .map(|i| { + let b = &out.stdout[i * frame_len..][..frame_len]; + ec_av1::encode::Picture { + width, + height, + y: b[..luma].iter().map(|&v| u16::from(v)).collect(), + u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), + v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), + } + }) + .collect(); + + let start = std::time::Instant::now(); + for q in qs { + let e = ec_av1::encode::encode_sequence(&source, q, 0.5).unwrap(); + // FNV-1a over the stream: a byte-exactness witness, not a checksum + // with any other job. + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for &b in &e.stream { + h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); + } + println!("q={q} bytes={} fnv1a={h:016x}", e.stream.len()); + } + println!("wall {:.3}s", start.elapsed().as_secs_f64()); +} diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 8a495fd0..82aa2349 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -9,6 +9,7 @@ //! It is the skeleton the block modes, transform sizes and coefficients hang //! off as they arrive. +use std::cell::RefCell; use std::sync::LazyLock; use ec_core::{Error, Result}; @@ -2131,18 +2132,48 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { default_scan(TX32), ] }); - let mut cdfs = Cdfs::new(q_ctx); - let mut coding = cdfs.txb(set, DC_PRED); - let scan = match coding.side { - TX4 => &SCANS[0], - TX8 => &SCANS[1], - TX16 => &SCANS[2], - _ => &SCANS[3], - }; - let mut enc = SymbolEncoder::new(); - enc.reset_bits(); - write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None); - enc.bits() + // `Cdfs::new` builds every table a tile writer adapts -- tens of + // kilobytes -- and this function is called once per priced candidate: + // together with the copy behind it that was 9% of the encoder's profile + // (`__memmove` 6.0% + `Cdfs::new` 3.4%, both under this call). Only the + // tables `write_coeffs` touches change, so keep one scratch `Cdfs` per + // q-context per thread beside a pristine one and restore just those from + // it. The state the price is taken against is identical to a fresh + // `Cdfs::new(q_ctx)`, so every price is bit-identical. + thread_local! { + static PRICING: RefCell<[Option>; 4]> = + const { RefCell::new([None, None, None, None]) }; + } + PRICING.with_borrow_mut(|slots| { + let slot = slots[q_ctx.min(3)] + .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx)))); + let (pristine, scratch) = (&mut slot.0, &mut slot.1); + let src = pristine.txb(set, DC_PRED); + let mut coding = scratch.txb(set, DC_PRED); + coding.txb_skip.copy_from_slice(src.txb_skip); + coding.eob_pt.copy_from_slice(src.eob_pt); + if let (Some(dst), Some(src)) = (coding.eob_pt_class1.as_mut(), src.eob_pt_class1) { + dst.copy_from_slice(src); + } + *coding.eob_extra = *src.eob_extra; + *coding.base = *src.base; + *coding.base_eob = *src.base_eob; + *coding.br = *src.br; + *coding.dc_sign = *src.dc_sign; + if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) { + dst.copy_from_slice(src); + } + let scan = match coding.side { + TX4 => &SCANS[0], + TX8 => &SCANS[1], + TX16 => &SCANS[2], + _ => &SCANS[3], + }; + let mut enc = SymbolEncoder::new(); + enc.reset_bits(); + write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None); + enc.bits() + }) } /// What the partition symbol of a block of `side` samples costs, in bits, when @@ -2152,7 +2183,10 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { /// than it is — because the search that reads it runs before the tile knows /// what its neighbours will be. pub(crate) fn partition_bits(side: usize, split: bool) -> f64 { - let cdfs = Cdfs::new(2); + // Read-only, and the same tables every call: built once (see + // [`coeff_bits`] for why that matters here). + static CDFS: LazyLock = LazyLock::new(|| Cdfs::new(2)); + let cdfs = &*CDFS; let cdf: &[u16] = match side { SB => &cdfs.partition_w64[0], BLOCK => &cdfs.partition_w32[0],