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/decode.rs b/crates/ec-av1/src/decode.rs index 747ed67a..73df97da 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -6617,6 +6617,7 @@ struct BlkCell { /// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a /// chroma transform straddling the true, odd-sized frame edge see its /// neighbour's state clamped at its own subsampled edge rather than luma's. +#[derive(Clone)] struct Neighbours { above: Vec<[Neighbour; 3]>, left: Vec<[Neighbour; 3]>, @@ -19703,6 +19704,119 @@ fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> { PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p } } +/// The pre-filter reconstruction of one coded frame, plus the per-block state +/// the loop filters read. +/// +/// The encoder's filter search ([`crate::filter_search::pick_filters`]) +/// decodes the same coded tile under ~25 candidate deblock/CDEF parameter +/// sets to score each one, and the entropy decode and reconstruction it +/// repeats are identical every time -- both filters run after it, on the +/// finished planes. That re-parse was 24% of the encoder's profile. A caller +/// arms [`arm_filter_replay`] around ONE decode and then re-runs the filters +/// alone through [`replay_filters`]; the result is the same picture the full +/// decode would have returned, because it is the same two calls on a copy of +/// the same planes. +pub(crate) struct FilterReplay { + y: PlaneBuf<'static>, + u: PlaneBuf<'static>, + v: PlaneBuf<'static>, + neighbours: Neighbours, + frame_width: usize, + frame_height: usize, + width: usize, + height: usize, +} + +thread_local! { + /// Set by [`arm_filter_replay`] for the span of one decode. + static REPLAY_ARMED: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// What that decode captured, until [`clear_filter_replay`]. + static REPLAY: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// Capture this thread's next decode's pre-filter frame (see [`FilterReplay`]). +pub(crate) fn arm_filter_replay() { + REPLAY_ARMED.set(true); +} + +/// Drop the armed flag and anything captured: the tile it belongs to is done. +pub(crate) fn clear_filter_replay() { + REPLAY_ARMED.set(false); + REPLAY.with_borrow_mut(|r| *r = None); +} + +/// The capture itself, called from the decoder's own pre-filter point. Owns +/// copies of the planes, since the caller filters them in place. +fn capture_filter_replay( + y: &PlaneBuf<'_>, + u: &PlaneBuf<'_>, + v: &PlaneBuf<'_>, + neighbours: &Neighbours, + frame_width: usize, + frame_height: usize, + width: usize, + height: usize, +) { + if !REPLAY_ARMED.replace(false) { + return; + } + let own = |p: &PlaneBuf<'_>| PlaneBuf { data: std::borrow::Cow::Owned(p.data.to_vec()), ..*p }; + REPLAY.with_borrow_mut(|slot| { + *slot = Some(FilterReplay { + y: own(y), + u: own(u), + v: own(v), + neighbours: neighbours.clone(), + frame_width, + frame_height, + width, + height, + }); + }); +} + +/// The filter half of a captured decode, under new parameters: exactly the +/// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a +/// copy of the captured planes. `None` when nothing is captured (the caller +/// then decodes for real). +pub(crate) fn replay_filters( + loop_filter: &LoopFilterParams, + cdef: &CdefParams, + fctx: &FrameCtx, +) -> Option { + REPLAY.with_borrow(|slot| { + let r = slot.as_ref()?; + let copy = |p: &PlaneBuf<'_>| PlaneBuf { + data: std::borrow::Cow::Owned(p.data.to_vec()), + ..*p + }; + let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v)); + apply_deblock( + &mut y, + &mut u, + &mut v, + loop_filter, + &r.neighbours, + r.frame_width, + r.frame_height, + fctx, + ); + apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx); + // The capture only happens on the shape the decoder's own tail + // returns whole (no superres, no loop restoration, no crop), so this + // is that tail. + fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None); + Some(Picture { + width: r.width, + height: r.height, + y: y.data.into_owned(), + u: u.data.into_owned(), + v: v.data.into_owned(), + }) + }) +} + /// The output crop, taking the plane by value: a frame whose width is /// already superblock-aligned (only its height is padded) has a padded /// buffer whose stride equals the visible width, so the crop is a pure @@ -22935,6 +23049,28 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( let _ = f.write_all(&crop_wide(&v)); } } + // lane-av1fwd: the encoder's filter search re-decodes this same key + // frame tile per candidate -- capture it once (see [`FilterReplay`]), + // on the shape whose tail is the two filter calls and nothing else. + if superres(fctx).is_none() + && frame_width as usize == width + && frame_height as usize == height + && !(0..3).any(|p| { + lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None + && lr.loop_restoration_size[p] != 0 + }) + { + capture_filter_replay( + &y, + &u, + &v, + &neighbours, + frame_width as usize, + frame_height as usize, + width, + height, + ); + } apply_deblock( &mut y, &mut u, @@ -35565,6 +35701,27 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( p.finish(); } drop(pipe); + // lane-av1fwd: the encoder scores ~25 filter candidates against this + // same coded tile ([`FilterReplay`]). Capture the reconstruction here, + // before either filter has touched it -- but only on the shape whose + // tail is exactly `apply_deblock` + `apply_cdef` and nothing else. + if !pipelined + && !lr_active + && superres(fctx).is_none() + && frame_width as usize == width + && frame_height as usize == height + { + capture_filter_replay( + &y, + &u, + &v, + &neighbours, + frame_width as usize, + frame_height as usize, + width, + height, + ); + } if pipelined { cdef_scan_counters(&neighbours); } else { diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 485e8cb3..07e7147a 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -3177,15 +3177,29 @@ fn pick_and_apply_filters( let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows); let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize); let none_lr = LoopRestorationParams::default(); - let (lf, cdef, idx_grid, picture) = crate::filter_search::pick_filters( - |lf, cdef| decode(lf, cdef, &hdr, tile, &none_lr), + // Every candidate scores the same coded tile: decode it once and re-run + // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of + // the encoder's profile before this). The per-64x64 error the CDEF + // preset search reads comes off the REPLAYED picture, which is the same + // picture a decode produces -- that is what the replay is pinned on. + crate::decode::clear_filter_replay(); + let search_result = crate::filter_search::pick_filters( + |lf, cdef| { + if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) { + return Ok(picture); + } + crate::decode::arm_filter_replay(); + decode(lf, cdef, &hdr, tile, &none_lr) + }, source, luma.width, (fw, fh), damping, (sb_cols, sb_rows), lambda, - )?; + ); + crate::decode::clear_filter_replay(); + let (lf, cdef, idx_grid, picture) = search_result?; header.loop_filter = lf; header.cdef = cdef; // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not @@ -7202,6 +7216,49 @@ mod tests { (ladder, wall) } + /// Byte-exactness gate for encoder work that is meant to change only + /// how long the encoder takes. + /// + /// The BD gate above measures quality, which a speed lane can move by a + /// hair without failing anything; this pins the streams themselves. + /// Every number below was measured 2026-09-06: first on lane-av1fwd + /// (whose three speed steps left them identical to `a6649c4e`'s), then + /// re-measured on the lane-av1lr merge, which legitimately moves them -- + /// per-64x64 `cdef_idx` literals and the per-unit loop restoration + /// syntax are new bits in the tile, and both streams came out SMALLER + /// (7823 -> 7796, 28189 -> 28182 bytes) for it. + #[test] + fn the_encoders_own_streams_are_byte_identical_to_their_pins() { + if !have_ffmpeg() { + eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg"); + return; + } + let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); + if !clip.exists() { + eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip"); + return; + } + let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4); + // FNV-1a over the stream: a witness that every coded bit is where it + // was, which a byte count alone is not. + let fnv = |b: &[u8]| { + b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| { + (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3) + }) + }; + let pins: [(u8, usize, u64); 2] = + [(150, 7796, 0x70db_e81d_606b_034c), (60, 28182, 0xb23d_005b_1f2e_e008)]; + for (q, bytes, hash) in pins { + let encoded = encode_sequence(&source, q, 0.5).unwrap(); + assert_eq!( + (encoded.stream.len(), fnv(&encoded.stream)), + (bytes, hash), + "q={q}: the encoder's stream moved" + ); + } + } + /// A ladder is only a ladder if both axes rise together. fn assert_monotone(name: &str, ladder: &[(f64, f64)]) { assert_eq!(ladder.len(), 4, "{name}: wanted four quality points"); @@ -7238,6 +7295,25 @@ mod tests { /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s | /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s | /// + /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long + /// the encoder takes -- every stream it writes is byte-identical, so the + /// BD columns are this box's own re-run of the same recipe rather than a + /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs + /// rav1e). What moved is the wall of the four encodes: + /// + /// | clip | wall ours before | after | instructions:u before -> after | + /// |---|---|---|---| + /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) | + /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) | + /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) | + /// + /// Three exact steps, none of which touches a coded bit: the coefficient + /// rate pricer stopped rebuilding every CDF table per candidate + /// (`tile::coeff_bits`), the filter search stopped re-decoding its own + /// tile once per candidate (`decode::FilterReplay`), and the forward + /// transform stopped transforming the all-zero residual that 70% of its + /// calls carry. + /// /// The three steps of that lane, same recipe (vs libaom, then vs rav1e): /// /// | step | 1080p | 2160p | screen | diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 4fa74075..1f4a3ea4 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}; @@ -2296,18 +2297,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 @@ -2317,7 +2348,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], diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index 8a7429d1..acd2e304 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -1463,8 +1463,19 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType 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]; + // 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% + // of the 1.9M calls here carry an all-zero residual, and another 6.5M + // individual rows of the rest are zero. A row of zeros contributes only + // `0.0 * b` terms, and a sum of zeros is `+0.0`, so this is exact. + let mut any = false; for i in 0..side { let source = &residual[i * side..][..side]; + if source.iter().all(|&r| r == 0) { + continue; + } + any = true; for v in 0..side { rows[i * side + v] = source .iter() @@ -1473,6 +1484,9 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType .sum(); } } + if !any { + return rows; + } let mut out = vec![0.0f64; side * side]; for u in 0..side { let column = &vb[u * side..][..side]; @@ -1914,20 +1928,20 @@ pub fn quantize(coeffs: &[f64], side: usize, bit_depth: u8, q_idx: i32, deadzone let dc = f64::from(crate::quant::dc_q(bit_depth, q_idx)); let ac = f64::from(crate::quant::ac_q(bit_depth, q_idx)); let mut levels = vec![0i32; side * side]; - for (i, &c) in coeffs.iter().enumerate() { - let (row, col) = (i / side, i % side); - if row >= 32 || col >= 32 { - continue; + let coded = side.min(32); + for row in 0..coded { + for col in 0..coded { + let i = row * side + col; + let q = if i == 0 { dc } else { ac }; + let scaled = coeffs[i] / q; + let magnitude = scaled.abs() + deadzone; + let level = if magnitude < 1.0 { + 0 + } else { + magnitude.floor().min(f64::from(i32::MAX)) as i32 + }; + levels[i] = if scaled < 0.0 { -level } else { level }; } - let q = if i == 0 { dc } else { ac }; - let scaled = c / q; - let magnitude = scaled.abs() + deadzone; - let level = if magnitude < 1.0 { - 0 - } else { - magnitude.floor().min(f64::from(i32::MAX)) as i32 - }; - levels[i] = if scaled < 0.0 { -level } else { level }; } levels } @@ -1941,6 +1955,13 @@ pub fn forward_and_quantize( q_idx: i32, deadzone: f64, ) -> Vec { + // 72% of this encoder's forward DCTs are of an all-zero residual + // (measured over the BD gate's own ladder, lane-av1fwd): every row and + // every column of the network is skipped for them anyway, so the levels + // are zero without allocating the row pass's buffer at all. + if residual.iter().all(|&r| r == 0) { + return vec![0i32; side * side]; + } // Fused: the levels are formed straight off the fixed-point coefficients, // so neither the `Vec` of coefficients nor the pass that reads it // exists.