forge
Explore
Log in

Don't you dare go Hollow

The coefficient rate pricer stops rebuilding every CDF table per candidate

Browse files at this commit

7947a2db5bd9a8a078c20a1607c633c2aba98903Ahmet Kaan GümüşParent: 1b6265b
  • perf
    • the coefficient rate pricer stops rebuilding every CDF table per candidate
Show full message
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.rsadded+56 -0
@@ -0,0 +1,56 @@
1+//! Encode-side profiling driver: the BD gate's own ladder, without ffmpeg's
2+//! decode side or the reference encoders, so `perf record` attributes only
3+//! our encoder. Also the byte-exactness gate for encoder-internal rewrites:
4+//! it prints each point's stream length and a hash of its bytes.
5+//!
6+//! Usage: `enc_probe <clip> <width> <height> <frames> [q,q,..]`
7+
8+use std::process::Command;
9+
10+fn main() {
11+ let a: Vec<String> = std::env::args().skip(1).collect();
12+ let (clip, width, height, frames) = (
13+ a[0].clone(),
14+ a[1].parse::<usize>().unwrap(),
15+ a[2].parse::<usize>().unwrap(),
16+ a[3].parse::<usize>().unwrap(),
17+ );
18+ let qs: Vec<u8> = a
19+ .get(4)
20+ .map_or_else(|| vec![150, 120, 90, 60], |s| s.split(',').map(|q| q.parse().unwrap()).collect());
21+
22+ let out = Command::new("ffmpeg")
23+ .args(["-v", "error", "-i", &clip, "-frames:v", &frames.to_string()])
24+ .args(["-vf", &format!("scale={width}:{height}")])
25+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
26+ .output()
27+ .expect("ffmpeg failed to run");
28+ assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
29+ let (luma, chroma) = (width * height, width * height / 4);
30+ let frame_len = luma + 2 * chroma;
31+ let source: Vec<ec_av1::encode::Picture> = (0..frames)
32+ .map(|i| {
33+ let b = &out.stdout[i * frame_len..][..frame_len];
34+ ec_av1::encode::Picture {
35+ width,
36+ height,
37+ y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
38+ u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
39+ v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
40+ }
41+ })
42+ .collect();
43+
44+ let start = std::time::Instant::now();
45+ for q in qs {
46+ let e = ec_av1::encode::encode_sequence(&source, q, 0.5).unwrap();
47+ // FNV-1a over the stream: a byte-exactness witness, not a checksum
48+ // with any other job.
49+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;
50+ for &b in &e.stream {
51+ h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
52+ }
53+ println!("q={q} bytes={} fnv1a={h:016x}", e.stream.len());
54+ }
55+ println!("wall {:.3}s", start.elapsed().as_secs_f64());
56+}
crates/ec-av1/src/tile.rsmodified+37 -3
@@ -9,6 +9,7 @@
9 //! It is the skeleton the block modes, transform sizes and coefficients hang9 //! It is the skeleton the block modes, transform sizes and coefficients hang
10 //! off as they arrive.10 //! off as they arrive.
11 11
12+use std::cell::RefCell;
12 use std::sync::LazyLock;13 use std::sync::LazyLock;
13 14
14 use ec_core::{Error, Result};15 use ec_core::{Error, Result};
@@ -2131,8 +2132,37 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
2131 default_scan(TX32),2132 default_scan(TX32),
2132 ]2133 ]
2133 });2134 });
2134- let mut cdfs = Cdfs::new(q_ctx);2135+ // `Cdfs::new` builds every table a tile writer adapts -- tens of
2135- let mut coding = cdfs.txb(set, DC_PRED);2136+ // kilobytes -- and this function is called once per priced candidate:
2137+ // together with the copy behind it that was 9% of the encoder's profile
2138+ // (`__memmove` 6.0% + `Cdfs::new` 3.4%, both under this call). Only the
2139+ // tables `write_coeffs` touches change, so keep one scratch `Cdfs` per
2140+ // q-context per thread beside a pristine one and restore just those from
2141+ // it. The state the price is taken against is identical to a fresh
2142+ // `Cdfs::new(q_ctx)`, so every price is bit-identical.
2143+ thread_local! {
2144+ static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> =
2145+ const { RefCell::new([None, None, None, None]) };
2146+ }
2147+ PRICING.with_borrow_mut(|slots| {
2148+ let slot = slots[q_ctx.min(3)]
2149+ .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx))));
2150+ let (pristine, scratch) = (&mut slot.0, &mut slot.1);
2151+ let src = pristine.txb(set, DC_PRED);
2152+ let mut coding = scratch.txb(set, DC_PRED);
2153+ coding.txb_skip.copy_from_slice(src.txb_skip);
2154+ coding.eob_pt.copy_from_slice(src.eob_pt);
2155+ if let (Some(dst), Some(src)) = (coding.eob_pt_class1.as_mut(), src.eob_pt_class1) {
2156+ dst.copy_from_slice(src);
2157+ }
2158+ *coding.eob_extra = *src.eob_extra;
2159+ *coding.base = *src.base;
2160+ *coding.base_eob = *src.base_eob;
2161+ *coding.br = *src.br;
2162+ *coding.dc_sign = *src.dc_sign;
2163+ if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) {
2164+ dst.copy_from_slice(src);
2165+ }
2136 let scan = match coding.side {2166 let scan = match coding.side {
2137 TX4 => &SCANS[0],2167 TX4 => &SCANS[0],
2138 TX8 => &SCANS[1],2168 TX8 => &SCANS[1],
@@ -2143,6 +2173,7 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
2143 enc.reset_bits();2173 enc.reset_bits();
2144 write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None);2174 write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None);
2145 enc.bits()2175 enc.bits()
2176+ })
2146 }2177 }
2147 2178
2148 /// What the partition symbol of a block of `side` samples costs, in bits, when2179 /// 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 {
2152 /// than it is — because the search that reads it runs before the tile knows2183 /// than it is — because the search that reads it runs before the tile knows
2153 /// what its neighbours will be.2184 /// what its neighbours will be.
2154 pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {2185 pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
2155- let cdfs = Cdfs::new(2);2186+ // Read-only, and the same tables every call: built once (see
2187+ // [`coeff_bits`] for why that matters here).
2188+ static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
2189+ let cdfs = &*CDFS;
2156 let cdf: &[u16] = match side {2190 let cdf: &[u16] = match side {
2157 SB => &cdfs.partition_w64[0],2191 SB => &cdfs.partition_w64[0],
2158 BLOCK => &cdfs.partition_w32[0],2192 BLOCK => &cdfs.partition_w32[0],