forge
Explore
Log in

Don't you dare go Hollow

instrument(av1): a LAST2 SAD census and a frame-level interpolation filter knob

Browse files at this commit

012b9fc4622fe0043241483c49ac4a61287edea8Ahmet Kaan GümüşParent: 606d0d9
The census answers whether a second retained past reference is worth its
slot bookkeeping and its second motion search before either is built; the
filter knob makes the frame's kernel reach the search, the trials and the
trial decode through FrameCtx instead of a hardwired Regular in mc::predict.
crates/ec-av1/src/decode.rsmodified+10 -0
@@ -69,6 +69,14 @@ pub(crate) struct FrameCtx {
6969 pub(crate) capture_stages: std::cell::Cell<bool>,
7070 pub(crate) stages: std::cell::RefCell<Option<FilterStages>>,
7171 pub(crate) sb128_flag: std::cell::Cell<bool>,
72+ /// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every
73+ /// motion compensation of THIS frame runs, already resolved to a kernel.
74+ /// `mc::predict` used to hardwire `Regular`, so the encoder's search,
75+ /// trial and recon could only ever build a REGULAR prediction whatever
76+ /// the frame header said; it lives here (and is copied by
77+ /// [`filter_ctx_copy`]) so a tile-search worker thread reads the same
78+ /// kernel the frame header wrote instead of the default.
79+ pub(crate) interp_filter: std::cell::Cell<crate::mc::InterpFilterKind>,
7280 /// lane-lossless: this frame's `CodedLossless` (spec 5.9.12) -- every
7381 /// segment at `qindex == 0` with zero plane deltas. It forces TX_4X4 with
7482 /// the Walsh-Hadamard transform on every plane, drops the `tx_type`
@@ -163,6 +171,7 @@ impl FrameCtx {
163171 // (`set_sb128`, stream.rs). The encoder's own contexts start at
164172 // the size this process encodes -- see [`FrameCtx::for_encoder`].
165173 sb128_flag: std::cell::Cell::new(false),
174+ interp_filter: std::cell::Cell::new(crate::mc::InterpFilterKind::Regular),
166175 lossless_flag: std::cell::Cell::new(false),
167176 cdef_bits: std::cell::Cell::new(0),
168177 bit_depth: std::cell::Cell::new(8),
@@ -260,6 +269,7 @@ impl<T: ?Sized> WithRef for T {}
260269 pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
261270 let out = FrameCtx::new();
262271 out.bit_depth.set(fctx.bit_depth.get());
272+ out.interp_filter.set(fctx.interp_filter.get());
263273 out.grain_bit_depth.set(fctx.grain_bit_depth.get());
264274 out.superres.set(fctx.superres.get());
265275 out.seg_mi_dims.set(fctx.seg_mi_dims.get());
crates/ec-av1/src/encode.rsmodified+138 -6
@@ -1807,6 +1807,23 @@ pub(crate) fn key_frame_headers_colour(
18071807 /// 1 still holds the key frame however long the GOP runs.
18081808 pub const GOLDEN_SLOT: u8 = 1;
18091809
1810+/// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every inter
1811+/// frame this encoder writes carries. `EC_AV1_INTERP=smooth|sharp` codes the
1812+/// EIGHTTAP_SMOOTH / EIGHTTAP_SHARP kernel instead of the default REGULAR --
1813+/// one filter for the whole frame, which is what libaom does on this content
1814+/// too (`lanes/obmc3.report.md` read `switchable_interp 0/0` out of its own
1815+/// stream, so a per-BLOCK filter search has no bits to win). The kernel
1816+/// reaches the search, the trials and the recon through
1817+/// `FrameCtx::interp_filter`, so the stream a decoder reads and the
1818+/// prediction the search priced are the same one.
1819+fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter {
1820+ match std::env::var("EC_AV1_INTERP").ok().as_deref() {
1821+ Some("smooth") => ec_av1_syntax::InterpolationFilter::EighttapSmooth,
1822+ Some("sharp") => ec_av1_syntax::InterpolationFilter::EighttapSharp,
1823+ _ => ec_av1_syntax::InterpolationFilter::Eighttap,
1824+ }
1825+}
1826+
18101827 /// The frame header for a shown inter frame that predicts from the single
18111828 /// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
18121829 /// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
@@ -5506,7 +5523,7 @@ fn obmc_prediction(
55065523 x / 2,
55075524 y / 2,
55085525 &refpix,
5509- Some(mc::InterpFilterKind::Regular),
5526+ Some(fctx.interp_filter.get()),
55105527 frame_width,
55115528 )
55125529 .ok()?;
@@ -6900,6 +6917,10 @@ pub(crate) fn encode_key_frame_inner(
69006917 render: (usize, usize),
69016918 color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
69026919 ) -> Result<Encoded> {
6920+ // lane-refs: an intra frame runs no motion compensation, and the
6921+ // context is shared across the sequence -- put the kernel back to the
6922+ // default so nothing reads the previous inter frame's.
6923+ fctx.interp_filter.set(mc::InterpFilterKind::Regular);
69036924 picture.check()?;
69046925 if modes.is_empty() {
69056926 return Err(Error::unsupported(
@@ -8169,8 +8190,8 @@ fn mc_trial_compound_typed(
81698190 mc::REF_NO_SCALE,
81708191 side,
81718192 side,
8172- mc::InterpFilterKind::Regular,
8173- mc::InterpFilterKind::Regular,
8193+ fctx.interp_filter.get(),
8194+ fctx.interp_filter.get(),
81748195 dst,
81758196 );
81768197 }
@@ -8262,8 +8283,8 @@ fn predict_compound_u8(
82628283 mc::REF_NO_SCALE,
82638284 side,
82648285 side,
8265- mc::InterpFilterKind::Regular,
8266- mc::InterpFilterKind::Regular,
8286+ fctx.interp_filter.get(),
8287+ fctx.interp_filter.get(),
82678288 dst,
82688289 );
82698290 }
@@ -10213,6 +10234,12 @@ pub(crate) fn encode_inter_frame(
1021310234 )?;
1021410235 header.render_width = render.0 as u32;
1021510236 header.render_height = render.1 as u32;
10237+ // lane-refs: this frame's motion-compensation kernel, written into the
10238+ // header AND armed on the context every prediction reads, in one place so
10239+ // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched
10240+ // tile decodes to different pixels than the encoder scored).
10241+ header.interpolation_filter = frame_interp_filter();
10242+ fctx.interp_filter.set(mc::InterpFilterKind::from_header(header.interpolation_filter));
1021610243 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
1021710244 // The order hint behind each `ref_frame_idx` entry. The flat path's own
1021810245 // slot plan (`inter_frame_headers_slots`) is: every reference but
@@ -11233,7 +11260,7 @@ pub(crate) fn encode_inter_frame(
1123311260 lf,
1123411261 h.allow_high_precision_mv,
1123511262 h.force_integer_mv,
11236- Some(mc::InterpFilterKind::Regular),
11263+ Some(fctx.interp_filter.get()),
1123711264 seq.enable_dual_filter,
1123811265 h.reference_select,
1123911266 tx_select,
@@ -16579,4 +16606,109 @@ mod tests {
1657916606 eprintln!("PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}",
1658016607 e.stream.len(), crate::speed::speed(), crate::encoder::Pyramid::from_env(), last_sequence_pyramid());
1658116608 }
16609+ /// lane-refs: IS A SECOND PAST REFERENCE WORTH RETAINING? `encoder.rs`'s
16610+ /// `ref_frame_idx` maps `LAST2`/`LAST3` onto `LAST`'s own DPB slot, so no
16611+ /// block can predict from the picture before `LAST` -- while rav1e's ARFs
16612+ /// read LAST@-4 plus LAST2@-8 and libaom holds up to seven distinct
16613+ /// pictures. Building that (a second retained slot, the search offering
16614+ /// it, a witness, a second motion search per block) is a week of wall on
16615+ /// the stage that already owns most of the encode, so this census prices
16616+ /// the lever FIRST (class `gate-blind-to-feature`, "count how often the
16617+ /// feature would fire before building the machine").
16618+ ///
16619+ /// The measurement is on the gate's own window and loader (`gate_crop`,
16620+ /// 12 pictures) of the two real films: every 16x16 luma block of every
16621+ /// picture gets one full-pel diamond search against the NEAR reference
16622+ /// and the same search against the FAR one, at the two lags the pyramid
16623+ /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF
16624+ /// level, rav1e's own pair. Reported per lag: the share of blocks the far
16625+ /// reference wins at all and by more than 10%, and -- the number the
16626+ /// decision is taken on -- the total SAD of best-of-{near, far} against
16627+ /// the total SAD of near alone, which is the prediction energy a second
16628+ /// reference could remove before any rate is paid for naming it.
16629+ ///
16630+ /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture
16631+ #[test]
16632+ #[ignore = "reads the real films"]
16633+ fn last2_census() {
16634+ if !have_ffmpeg() {
16635+ eprintln!("SKIP last2_census: no ffmpeg");
16636+ return;
16637+ }
16638+ const SIDE: usize = 16;
16639+ // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or
16640+ // `None` when the displaced block leaves the picture.
16641+ let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
16642+ let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
16643+ if sy < 0 || sx < 0 {
16644+ return None;
16645+ }
16646+ let (sy, sx) = (sy as usize, sx as usize);
16647+ if sy + SIDE > r.height || sx + SIDE > r.width {
16648+ return None;
16649+ }
16650+ let mut acc = 0u64;
16651+ for row in 0..SIDE {
16652+ let c = &cur.y[(by + row) * cur.width + bx..][..SIDE];
16653+ let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
16654+ acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
16655+ }
16656+ Some(acc)
16657+ };
16658+ // A log-step diamond from the zero motion vector: the cheapest search
16659+ // that still finds real pans. Both references get exactly this one,
16660+ // so the comparison is search-fair.
16661+ let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 {
16662+ let mut best = (sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX), (0isize, 0isize));
16663+ let mut step = 16isize;
16664+ while step >= 1 {
16665+ let centre = best.1;
16666+ for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
16667+ let mv = (centre.0 + dy * step, centre.1 + dx * step);
16668+ if let Some(s) = sad(cur, r, bx, by, mv) {
16669+ if s < best.0 {
16670+ best = (s, mv);
16671+ }
16672+ }
16673+ }
16674+ step /= 2;
16675+ }
16676+ best.0
16677+ };
16678+ println!("| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |");
16679+ println!("|---|---|---|---|---|---|---|---|");
16680+ for (name, path, seek) in native_gate_clips() {
16681+ if !name.starts_with("film ") {
16682+ continue;
16683+ }
16684+ let (vf, cw, ch) = crate::probe::gate_crop(&path);
16685+ let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12);
16686+ for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] {
16687+ let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64);
16688+ let (mut near_sad, mut best_sad) = (0u64, 0u64);
16689+ for i in far..pictures.len() {
16690+ let cur = &pictures[i];
16691+ let (rn, rf) = (&pictures[i - near], &pictures[i - far]);
16692+ for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
16693+ for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
16694+ let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by));
16695+ blocks += 1;
16696+ wins += u64::from(f < n);
16697+ big += u64::from(f as f64 * 1.1 < n as f64);
16698+ near_sad += n;
16699+ best_sad += n.min(f);
16700+ }
16701+ }
16702+ }
16703+ let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64;
16704+ println!(
16705+ "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |",
16706+ pct(wins),
16707+ pct(big),
16708+ 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64,
16709+ );
16710+ }
16711+ }
16712+ }
16713+
1658216714 }
crates/ec-av1/src/mc.rsmodified+6 -1
@@ -1048,7 +1048,12 @@ pub(crate) fn predict(
10481048 y_q4,
10491049 block_w,
10501050 block_h,
1051- InterpFilterKind::Regular,
1051+ // lane-refs: the FRAME's kernel (spec 6.8.9), not a hardwired
1052+ // `Regular` -- `FrameCtx::interp_filter` is what the encoder set from
1053+ // the header it is about to write, and every decode leaves it at
1054+ // `Regular` (the decoder's own inter path calls
1055+ // `predict_with_filters` with the kernels it parsed).
1056+ fctx.interp_filter.get(),
10521057 dst, fctx,
10531058 );
10541059 }
lanes/refs.report.mdadded+28 -0
@@ -0,0 +1,28 @@
1+# lane-refs — the reference set and the frame interpolation filter
2+
3+Worktree `edith_codecs-refs`, branch `lane-refs` off main 68e96c56. Every gate
4+arm is the prebuilt release lib-test binary; rows are read off each log's own
5+header line.
6+
7+## 0. Controls (12-frame native gate)
8+
9+(pending — arms `rf-c1`/`rf-c2` running)
10+
11+## 1. LAST2 — the census first
12+
13+`encoder.rs`'s `ref_frame_idx` maps LAST2/LAST3 onto LAST's own DPB slot, so
14+the second past picture is not merely unoffered, it is not retained. Before
15+building the slot bookkeeping + a second motion search (the stage that already
16+owns most of the encode wall; `search_inter_block`'s `extra` references are
17+search-FREE for exactly that reason), `last2_census` prices the lever.
18+
19+(table pending)
20+
21+## 2. The frame interpolation filter
22+
23+Wired: `FrameCtx::interp_filter` carries the frame's kernel to the search,
24+the trials, the compound predictors and the trial decode, and
25+`encode_inter_frame` writes the SAME kernel into the header. `EC_AV1_INTERP=
26+smooth|sharp` selects it; the default stays REGULAR and byte-identical.
27+
28+(table pending)