forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'main' (45b942bd) into lane-av1lr

Browse files at this commit

3bf4b1bf19a38750e25c326a66b2175882836884Ahmet Kaan GümüşParent: 2b5ba1793d97dc
Five hunks in `pick_and_apply_filters` and its two call sites, resolved
so both lanes survive: the deblocking/CDEF coordinate search runs
through main's `FilterReplay` (one decode, then the filters alone per
candidate), and the per-64x64 error this lane's CDEF preset search reads
comes off those REPLAYED pictures -- the replay is pinned byte-exact
against a decode, so the per-unit measurement is the same measurement.
The tile recode with `cdef_idx` literals and the one capturing decode
the loop restoration stage needs both run after the replay is cleared.

The byte pins move, as that lane's own comment said they would for new
tile syntax: 7823 -> 7796 bytes at q=150 and 28189 -> 28182 at q=60,
both SMALLER, re-measured on this merged tree.
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/decode.rsmodified+157 -0
@@ -6617,6 +6617,7 @@ struct BlkCell {
66176617 /// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
66186618 /// chroma transform straddling the true, odd-sized frame edge see its
66196619 /// neighbour's state clamped at its own subsampled edge rather than luma's.
6620+#[derive(Clone)]
66206621 struct Neighbours {
66216622 above: Vec<[Neighbour; 3]>,
66226623 left: Vec<[Neighbour; 3]>,
@@ -19703,6 +19704,119 @@ fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> {
1970319704 PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p }
1970419705 }
1970519706
19707+/// The pre-filter reconstruction of one coded frame, plus the per-block state
19708+/// the loop filters read.
19709+///
19710+/// The encoder's filter search ([`crate::filter_search::pick_filters`])
19711+/// decodes the same coded tile under ~25 candidate deblock/CDEF parameter
19712+/// sets to score each one, and the entropy decode and reconstruction it
19713+/// repeats are identical every time -- both filters run after it, on the
19714+/// finished planes. That re-parse was 24% of the encoder's profile. A caller
19715+/// arms [`arm_filter_replay`] around ONE decode and then re-runs the filters
19716+/// alone through [`replay_filters`]; the result is the same picture the full
19717+/// decode would have returned, because it is the same two calls on a copy of
19718+/// the same planes.
19719+pub(crate) struct FilterReplay {
19720+ y: PlaneBuf<'static>,
19721+ u: PlaneBuf<'static>,
19722+ v: PlaneBuf<'static>,
19723+ neighbours: Neighbours,
19724+ frame_width: usize,
19725+ frame_height: usize,
19726+ width: usize,
19727+ height: usize,
19728+}
19729+
19730+thread_local! {
19731+ /// Set by [`arm_filter_replay`] for the span of one decode.
19732+ static REPLAY_ARMED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
19733+ /// What that decode captured, until [`clear_filter_replay`].
19734+ static REPLAY: std::cell::RefCell<Option<FilterReplay>> =
19735+ const { std::cell::RefCell::new(None) };
19736+}
19737+
19738+/// Capture this thread's next decode's pre-filter frame (see [`FilterReplay`]).
19739+pub(crate) fn arm_filter_replay() {
19740+ REPLAY_ARMED.set(true);
19741+}
19742+
19743+/// Drop the armed flag and anything captured: the tile it belongs to is done.
19744+pub(crate) fn clear_filter_replay() {
19745+ REPLAY_ARMED.set(false);
19746+ REPLAY.with_borrow_mut(|r| *r = None);
19747+}
19748+
19749+/// The capture itself, called from the decoder's own pre-filter point. Owns
19750+/// copies of the planes, since the caller filters them in place.
19751+fn capture_filter_replay(
19752+ y: &PlaneBuf<'_>,
19753+ u: &PlaneBuf<'_>,
19754+ v: &PlaneBuf<'_>,
19755+ neighbours: &Neighbours,
19756+ frame_width: usize,
19757+ frame_height: usize,
19758+ width: usize,
19759+ height: usize,
19760+) {
19761+ if !REPLAY_ARMED.replace(false) {
19762+ return;
19763+ }
19764+ let own = |p: &PlaneBuf<'_>| PlaneBuf { data: std::borrow::Cow::Owned(p.data.to_vec()), ..*p };
19765+ REPLAY.with_borrow_mut(|slot| {
19766+ *slot = Some(FilterReplay {
19767+ y: own(y),
19768+ u: own(u),
19769+ v: own(v),
19770+ neighbours: neighbours.clone(),
19771+ frame_width,
19772+ frame_height,
19773+ width,
19774+ height,
19775+ });
19776+ });
19777+}
19778+
19779+/// The filter half of a captured decode, under new parameters: exactly the
19780+/// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a
19781+/// copy of the captured planes. `None` when nothing is captured (the caller
19782+/// then decodes for real).
19783+pub(crate) fn replay_filters(
19784+ loop_filter: &LoopFilterParams,
19785+ cdef: &CdefParams,
19786+ fctx: &FrameCtx,
19787+) -> Option<Picture> {
19788+ REPLAY.with_borrow(|slot| {
19789+ let r = slot.as_ref()?;
19790+ let copy = |p: &PlaneBuf<'_>| PlaneBuf {
19791+ data: std::borrow::Cow::Owned(p.data.to_vec()),
19792+ ..*p
19793+ };
19794+ let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v));
19795+ apply_deblock(
19796+ &mut y,
19797+ &mut u,
19798+ &mut v,
19799+ loop_filter,
19800+ &r.neighbours,
19801+ r.frame_width,
19802+ r.frame_height,
19803+ fctx,
19804+ );
19805+ apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx);
19806+ // The capture only happens on the shape the decoder's own tail
19807+ // returns whole (no superres, no loop restoration, no crop), so this
19808+ // is that tail.
19809+ fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
19810+ Some(Picture {
19811+ width: r.width,
19812+ height: r.height,
19813+ y: y.data.into_owned(),
19814+ u: u.data.into_owned(),
19815+ v: v.data.into_owned(),
19816+ })
19817+ })
19818+}
19819+
1970619820 /// The output crop, taking the plane by value: a frame whose width is
1970719821 /// already superblock-aligned (only its height is padded) has a padded
1970819822 /// 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(
2293523049 let _ = f.write_all(&crop_wide(&v));
2293623050 }
2293723051 }
23052+ // lane-av1fwd: the encoder's filter search re-decodes this same key
23053+ // frame tile per candidate -- capture it once (see [`FilterReplay`]),
23054+ // on the shape whose tail is the two filter calls and nothing else.
23055+ if superres(fctx).is_none()
23056+ && frame_width as usize == width
23057+ && frame_height as usize == height
23058+ && !(0..3).any(|p| {
23059+ lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
23060+ && lr.loop_restoration_size[p] != 0
23061+ })
23062+ {
23063+ capture_filter_replay(
23064+ &y,
23065+ &u,
23066+ &v,
23067+ &neighbours,
23068+ frame_width as usize,
23069+ frame_height as usize,
23070+ width,
23071+ height,
23072+ );
23073+ }
2293823074 apply_deblock(
2293923075 &mut y,
2294023076 &mut u,
@@ -35565,6 +35701,27 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3556535701 p.finish();
3556635702 }
3556735703 drop(pipe);
35704+ // lane-av1fwd: the encoder scores ~25 filter candidates against this
35705+ // same coded tile ([`FilterReplay`]). Capture the reconstruction here,
35706+ // before either filter has touched it -- but only on the shape whose
35707+ // tail is exactly `apply_deblock` + `apply_cdef` and nothing else.
35708+ if !pipelined
35709+ && !lr_active
35710+ && superres(fctx).is_none()
35711+ && frame_width as usize == width
35712+ && frame_height as usize == height
35713+ {
35714+ capture_filter_replay(
35715+ &y,
35716+ &u,
35717+ &v,
35718+ &neighbours,
35719+ frame_width as usize,
35720+ frame_height as usize,
35721+ width,
35722+ height,
35723+ );
35724+ }
3556835725 if pipelined {
3556935726 cdef_scan_counters(&neighbours);
3557035727 } else {
crates/ec-av1/src/encode.rsmodified+79 -3
@@ -3177,15 +3177,29 @@ fn pick_and_apply_filters(
31773177 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
31783178 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
31793179 let none_lr = LoopRestorationParams::default();
3180- let (lf, cdef, idx_grid, picture) = crate::filter_search::pick_filters(
3181- |lf, cdef| decode(lf, cdef, &hdr, tile, &none_lr),
3180+ // Every candidate scores the same coded tile: decode it once and re-run
3181+ // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
3182+ // the encoder's profile before this). The per-64x64 error the CDEF
3183+ // preset search reads comes off the REPLAYED picture, which is the same
3184+ // picture a decode produces -- that is what the replay is pinned on.
3185+ crate::decode::clear_filter_replay();
3186+ let search_result = crate::filter_search::pick_filters(
3187+ |lf, cdef| {
3188+ if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
3189+ return Ok(picture);
3190+ }
3191+ crate::decode::arm_filter_replay();
3192+ decode(lf, cdef, &hdr, tile, &none_lr)
3193+ },
31823194 source,
31833195 luma.width,
31843196 (fw, fh),
31853197 damping,
31863198 (sb_cols, sb_rows),
31873199 lambda,
3188- )?;
3200+ );
3201+ crate::decode::clear_filter_replay();
3202+ let (lf, cdef, idx_grid, picture) = search_result?;
31893203 header.loop_filter = lf;
31903204 header.cdef = cdef;
31913205 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
@@ -7202,6 +7216,49 @@ mod tests {
72027216 (ladder, wall)
72037217 }
72047218
7219+ /// Byte-exactness gate for encoder work that is meant to change only
7220+ /// how long the encoder takes.
7221+ ///
7222+ /// The BD gate above measures quality, which a speed lane can move by a
7223+ /// hair without failing anything; this pins the streams themselves.
7224+ /// Every number below was measured 2026-09-06: first on lane-av1fwd
7225+ /// (whose three speed steps left them identical to `a6649c4e`'s), then
7226+ /// re-measured on the lane-av1lr merge, which legitimately moves them --
7227+ /// per-64x64 `cdef_idx` literals and the per-unit loop restoration
7228+ /// syntax are new bits in the tile, and both streams came out SMALLER
7229+ /// (7823 -> 7796, 28189 -> 28182 bytes) for it.
7230+ #[test]
7231+ fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
7232+ if !have_ffmpeg() {
7233+ eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
7234+ return;
7235+ }
7236+ let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7237+ .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
7238+ if !clip.exists() {
7239+ eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip");
7240+ return;
7241+ }
7242+ let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
7243+ // FNV-1a over the stream: a witness that every coded bit is where it
7244+ // was, which a byte count alone is not.
7245+ let fnv = |b: &[u8]| {
7246+ b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
7247+ (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
7248+ })
7249+ };
7250+ let pins: [(u8, usize, u64); 2] =
7251+ [(150, 7796, 0x70db_e81d_606b_034c), (60, 28182, 0xb23d_005b_1f2e_e008)];
7252+ for (q, bytes, hash) in pins {
7253+ let encoded = encode_sequence(&source, q, 0.5).unwrap();
7254+ assert_eq!(
7255+ (encoded.stream.len(), fnv(&encoded.stream)),
7256+ (bytes, hash),
7257+ "q={q}: the encoder's stream moved"
7258+ );
7259+ }
7260+ }
7261+
72057262 /// A ladder is only a ladder if both axes rise together.
72067263 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
72077264 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
@@ -7238,6 +7295,25 @@ mod tests {
72387295 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
72397296 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
72407297 ///
7298+ /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
7299+ /// the encoder takes -- every stream it writes is byte-identical, so the
7300+ /// BD columns are this box's own re-run of the same recipe rather than a
7301+ /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
7302+ /// rav1e). What moved is the wall of the four encodes:
7303+ ///
7304+ /// | clip | wall ours before | after | instructions:u before -> after |
7305+ /// |---|---|---|---|
7306+ /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
7307+ /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
7308+ /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
7309+ ///
7310+ /// Three exact steps, none of which touches a coded bit: the coefficient
7311+ /// rate pricer stopped rebuilding every CDF table per candidate
7312+ /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
7313+ /// tile once per candidate (`decode::FilterReplay`), and the forward
7314+ /// transform stopped transforming the all-zero residual that 70% of its
7315+ /// calls carry.
7316+ ///
72417317 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
72427318 ///
72437319 /// | step | 1080p | 2160p | screen |
crates/ec-av1/src/tile.rsmodified+47 -13
@@ -9,6 +9,7 @@
99 //! It is the skeleton the block modes, transform sizes and coefficients hang
1010 //! off as they arrive.
1111
12+use std::cell::RefCell;
1213 use std::sync::LazyLock;
1314
1415 use ec_core::{Error, Result};
@@ -2296,18 +2297,48 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
22962297 default_scan(TX32),
22972298 ]
22982299 });
2299- let mut cdfs = Cdfs::new(q_ctx);
2300- let mut coding = cdfs.txb(set, DC_PRED);
2301- let scan = match coding.side {
2302- TX4 => &SCANS[0],
2303- TX8 => &SCANS[1],
2304- TX16 => &SCANS[2],
2305- _ => &SCANS[3],
2306- };
2307- let mut enc = SymbolEncoder::new();
2308- enc.reset_bits();
2309- write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None);
2310- enc.bits()
2300+ // `Cdfs::new` builds every table a tile writer adapts -- tens of
2301+ // kilobytes -- and this function is called once per priced candidate:
2302+ // together with the copy behind it that was 9% of the encoder's profile
2303+ // (`__memmove` 6.0% + `Cdfs::new` 3.4%, both under this call). Only the
2304+ // tables `write_coeffs` touches change, so keep one scratch `Cdfs` per
2305+ // q-context per thread beside a pristine one and restore just those from
2306+ // it. The state the price is taken against is identical to a fresh
2307+ // `Cdfs::new(q_ctx)`, so every price is bit-identical.
2308+ thread_local! {
2309+ static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> =
2310+ const { RefCell::new([None, None, None, None]) };
2311+ }
2312+ PRICING.with_borrow_mut(|slots| {
2313+ let slot = slots[q_ctx.min(3)]
2314+ .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx))));
2315+ let (pristine, scratch) = (&mut slot.0, &mut slot.1);
2316+ let src = pristine.txb(set, DC_PRED);
2317+ let mut coding = scratch.txb(set, DC_PRED);
2318+ coding.txb_skip.copy_from_slice(src.txb_skip);
2319+ coding.eob_pt.copy_from_slice(src.eob_pt);
2320+ if let (Some(dst), Some(src)) = (coding.eob_pt_class1.as_mut(), src.eob_pt_class1) {
2321+ dst.copy_from_slice(src);
2322+ }
2323+ *coding.eob_extra = *src.eob_extra;
2324+ *coding.base = *src.base;
2325+ *coding.base_eob = *src.base_eob;
2326+ *coding.br = *src.br;
2327+ *coding.dc_sign = *src.dc_sign;
2328+ if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) {
2329+ dst.copy_from_slice(src);
2330+ }
2331+ let scan = match coding.side {
2332+ TX4 => &SCANS[0],
2333+ TX8 => &SCANS[1],
2334+ TX16 => &SCANS[2],
2335+ _ => &SCANS[3],
2336+ };
2337+ let mut enc = SymbolEncoder::new();
2338+ enc.reset_bits();
2339+ write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None);
2340+ enc.bits()
2341+ })
23112342 }
23122343
23132344 /// 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 {
23172348 /// than it is — because the search that reads it runs before the tile knows
23182349 /// what its neighbours will be.
23192350 pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
2320- let cdfs = Cdfs::new(2);
2351+ // Read-only, and the same tables every call: built once (see
2352+ // [`coeff_bits`] for why that matters here).
2353+ static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
2354+ let cdfs = &*CDFS;
23212355 let cdf: &[u16] = match side {
23222356 SB => &cdfs.partition_w64[0],
23232357 BLOCK => &cdfs.partition_w32[0],
crates/ec-av1/src/transform.rsmodified+34 -13
@@ -1463,8 +1463,19 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType
14631463 let (row_kind, col_kind) = tx_type.axes();
14641464 let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind));
14651465 let mut rows = vec![0.0f64; side * side];
1466+ // Zero in, zero out, and `rows` is already zero here -- the skip
1467+ // [`forward_rows`] takes for the same reason, which this path was
1468+ // missing: a census of the BD gate's own ladder (lane-av1fwd) found 68%
1469+ // of the 1.9M calls here carry an all-zero residual, and another 6.5M
1470+ // individual rows of the rest are zero. A row of zeros contributes only
1471+ // `0.0 * b` terms, and a sum of zeros is `+0.0`, so this is exact.
1472+ let mut any = false;
14661473 for i in 0..side {
14671474 let source = &residual[i * side..][..side];
1475+ if source.iter().all(|&r| r == 0) {
1476+ continue;
1477+ }
1478+ any = true;
14681479 for v in 0..side {
14691480 rows[i * side + v] = source
14701481 .iter()
@@ -1473,6 +1484,9 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType
14731484 .sum();
14741485 }
14751486 }
1487+ if !any {
1488+ return rows;
1489+ }
14761490 let mut out = vec![0.0f64; side * side];
14771491 for u in 0..side {
14781492 let column = &vb[u * side..][..side];
@@ -1914,20 +1928,20 @@ pub fn quantize(coeffs: &[f64], side: usize, bit_depth: u8, q_idx: i32, deadzone
19141928 let dc = f64::from(crate::quant::dc_q(bit_depth, q_idx));
19151929 let ac = f64::from(crate::quant::ac_q(bit_depth, q_idx));
19161930 let mut levels = vec![0i32; side * side];
1917- for (i, &c) in coeffs.iter().enumerate() {
1918- let (row, col) = (i / side, i % side);
1919- if row >= 32 || col >= 32 {
1920- continue;
1931+ let coded = side.min(32);
1932+ for row in 0..coded {
1933+ for col in 0..coded {
1934+ let i = row * side + col;
1935+ let q = if i == 0 { dc } else { ac };
1936+ let scaled = coeffs[i] / q;
1937+ let magnitude = scaled.abs() + deadzone;
1938+ let level = if magnitude < 1.0 {
1939+ 0
1940+ } else {
1941+ magnitude.floor().min(f64::from(i32::MAX)) as i32
1942+ };
1943+ levels[i] = if scaled < 0.0 { -level } else { level };
19211944 }
1922- let q = if i == 0 { dc } else { ac };
1923- let scaled = c / q;
1924- let magnitude = scaled.abs() + deadzone;
1925- let level = if magnitude < 1.0 {
1926- 0
1927- } else {
1928- magnitude.floor().min(f64::from(i32::MAX)) as i32
1929- };
1930- levels[i] = if scaled < 0.0 { -level } else { level };
19311945 }
19321946 levels
19331947 }
@@ -1941,6 +1955,13 @@ pub fn forward_and_quantize(
19411955 q_idx: i32,
19421956 deadzone: f64,
19431957 ) -> Vec<i32> {
1958+ // 72% of this encoder's forward DCTs are of an all-zero residual
1959+ // (measured over the BD gate's own ladder, lane-av1fwd): every row and
1960+ // every column of the network is skipped for them anyway, so the levels
1961+ // are zero without allocating the row pass's buffer at all.
1962+ if residual.iter().all(|&r| r == 0) {
1963+ return vec![0i32; side * side];
1964+ }
19441965 // Fused: the levels are formed straight off the fixed-point coefficients,
19451966 // so neither the `Vec<f64>` of coefficients nor the pass that reads it
19461967 // exists.