forge
Explore
Log in

Don't you dare go Hollow

A one-frame lookahead builds a per-superblock lambda weight from how much of a frame the next one references

Browse files at this commit

9b24d77f333efc22c586070fa8d5a6ea808cf80fAhmet Kaan GümüşParent: 12f1dab
  • feat
    • a one-frame lookahead builds a per-superblock lambda weight from how much of a frame the next one references
Show full message
feat(av1): a one-frame lookahead builds a per-superblock lambda weight from how much of a frame the next one references
crates/ec-av1/src/encode.rsmodified+211 -4
@@ -4859,6 +4859,7 @@ fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
48594859 }
48604860
48614861 /// What the luma mode search picks between, and under what terms.
4862+#[derive(Clone, Copy)]
48624863 struct Search<'a> {
48634864 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
48644865 /// luma search then offers a palette candidate beside the intra modes.
@@ -7293,6 +7294,144 @@ fn search_inter_block(
72937294 )
72947295 }
72957296
7297+/// lane-av1tpl: the strength `k` of the temporal lambda weighting
7298+/// ([`tpl_sb_factors`]). 0 keeps every block at the frame's own lambda, which
7299+/// is what every measurement before this lane was taken on. Swept by
7300+/// `EC_AV1_TPL=<k>`.
7301+const TPL_STRENGTH: f64 = 0.0;
7302+
7303+fn tpl_strength() -> f64 {
7304+ std::env::var("EC_AV1_TPL")
7305+ .ok()
7306+ .and_then(|v| v.parse::<f64>().ok())
7307+ .filter(|k| k.is_finite() && *k >= 0.0)
7308+ .unwrap_or(TPL_STRENGTH)
7309+}
7310+
7311+/// Nanoseconds the lookahead pass ([`tpl_reference_map`]) has spent this
7312+/// process, so the gate can price it against the encode it rides on.
7313+static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
7314+
7315+/// How much of THIS frame the next one will predict from, per 16x16 cell: one
7316+/// coarse full-pel motion pass of the next SOURCE frame against this one
7317+/// (libaom's `tpl` lookahead in its cheapest possible shape -- no transform,
7318+/// no propagation chain, just referenced area). A cell's value is the area of
7319+/// it that the next frame's blocks land on, in units of its own area, so 1.0
7320+/// is "referenced exactly once".
7321+///
7322+/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
7323+/// the left/above winners, first-best tie-break. The map is built once on the
7324+/// frame's own thread and read-only afterwards, so it cannot make a tile's
7325+/// bytes depend on the thread count.
7326+fn tpl_reference_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
7327+ let start = std::time::Instant::now();
7328+ let (cells_x, cells_y) = (width / 16, height / 16);
7329+ let mut area = vec![0.0f64; cells_x * cells_y];
7330+ // SAD of the next frame's 16x16 block at (bx, by) against this frame at
7331+ // that block displaced by (mx, my); a displacement that leaves the frame
7332+ // is not a candidate at all.
7333+ let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
7334+ let (sx, sy) = (bx as i32 + mx, by as i32 + my);
7335+ if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
7336+ return u32::MAX;
7337+ }
7338+ let (sx, sy) = (sx as usize, sy as usize);
7339+ let mut sum = 0u32;
7340+ for r in 0..16 {
7341+ let a = &next[(by + r) * width + bx..][..16];
7342+ let b = &cur[(sy + r) * width + sx..][..16];
7343+ sum += a.iter().zip(b).map(|(&p, &q)| u32::from(p.abs_diff(q))).sum::<u32>();
7344+ }
7345+ sum
7346+ };
7347+ let mut above = vec![(0i32, 0i32); cells_x];
7348+ for cy in 0..cells_y {
7349+ let mut left = (0i32, 0i32);
7350+ for cx in 0..cells_x {
7351+ let (bx, by) = (cx * 16, cy * 16);
7352+ let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
7353+ for cand in [left, above[cx]] {
7354+ if cand != (0, 0) {
7355+ let s = sad(bx, by, cand);
7356+ if s < best.0 {
7357+ best = (s, cand);
7358+ }
7359+ }
7360+ }
7361+ for step in [8i32, 4, 2, 1] {
7362+ let centre = best.1;
7363+ for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
7364+ let mv = (centre.0 + dx, centre.1 + dy);
7365+ if mv.0.abs() > 32 || mv.1.abs() > 32 {
7366+ continue;
7367+ }
7368+ let s = sad(bx, by, mv);
7369+ if s < best.0 {
7370+ best = (s, mv);
7371+ }
7372+ }
7373+ }
7374+ let (mv, _) = (best.1, best.0);
7375+ left = mv;
7376+ above[cx] = mv;
7377+ // The 16x16 window of THIS frame that block referenced, spread
7378+ // over the (at most four) cells it overlaps.
7379+ let (x0, y0) = ((bx as i32 + mv.0) as usize, (by as i32 + mv.1) as usize);
7380+ for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
7381+ let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
7382+ for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
7383+ let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
7384+ area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
7385+ }
7386+ }
7387+ }
7388+ }
7389+ TPL_NANOS.fetch_add(
7390+ start.elapsed().as_nanos() as u64,
7391+ std::sync::atomic::Ordering::Relaxed,
7392+ );
7393+ area
7394+}
7395+
7396+/// [`tpl_reference_map`]'s per-cell referenced-ness turned into one lambda
7397+/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
7398+/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
7399+/// Decreasing in referenced-ness (a block the next frame leans on is coded
7400+/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
7401+/// total lambda scale is only redistributed, never moved -- a global move is
7402+/// the thing lane-av1lambda already measured inert.
7403+fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
7404+ let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
7405+ let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
7406+ let mut out = Vec::with_capacity(sb_cols * sb_rows);
7407+ for sr in 0..sb_rows {
7408+ for sc in 0..sb_cols {
7409+ let mut sum = 0.0;
7410+ for r in 0..4 {
7411+ for c in 0..4 {
7412+ sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
7413+ }
7414+ }
7415+ let w_rel = sum / 16.0 / mean;
7416+ out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
7417+ }
7418+ }
7419+ if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
7420+ let mut hist = [0usize; 8];
7421+ for w in map {
7422+ hist[((w / mean * 2.0) as usize).min(7)] += 1;
7423+ }
7424+ let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
7425+ eprintln!(
7426+ "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
7427+ sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
7428+ map.len(),
7429+ TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
7430+ );
7431+ }
7432+ out
7433+}
7434+
72967435 /// Where one inter frame sits in a coding-order pyramid: which DPB slots its
72977436 /// references name, which slot it refreshes, whether it is shown when it is
72987437 /// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
@@ -7352,6 +7491,11 @@ pub(crate) fn encode_inter_frame(
73527491 // Where this frame sits in the coding-order pyramid; `None` is the flat
73537492 // one-shown-frame-per-picture stream this encoder wrote before.
73547493 pyramid: Option<PyramidFrame>,
7494+ // lane-av1tpl: the NEXT picture's source, padded like this one. Present,
7495+ // it buys the one-frame lookahead the per-superblock lambda weighting
7496+ // reads ([`tpl_reference_map`]); `None` (every streaming caller, which
7497+ // has no lookahead buffer) codes the frame at one lambda, as before.
7498+ lookahead: Option<&Picture>,
73557499 ) -> Result<Encoded> {
73567500 picture.check()?;
73577501 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
@@ -7510,6 +7654,19 @@ pub(crate) fn encode_inter_frame(
75107654 screen,
75117655 };
75127656 let mode_bits_table = inter_mode_bits();
7657+ // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
7658+ // this frame the NEXT one predicts from. Off (`None`) without a
7659+ // lookahead picture or at strength 0.
7660+ let tpl_k = tpl_strength();
7661+ let tpl_factors: Option<Vec<f64>> = lookahead
7662+ .filter(|_| tpl_k > 0.0)
7663+ .filter(|n| n.width == picture.width && n.height == picture.height)
7664+ .map(|n| {
7665+ let next_y8: Vec<u8> = n.y.iter().map(|&v| v as u8).collect();
7666+ let map = tpl_reference_map(&picture_y8, &next_y8, picture.width, picture.height);
7667+ tpl_sb_factors(&map, picture.width / 16, picture.height / 16, tpl_k)
7668+ });
7669+ let tpl_sb_cols = picture.width / SUPERBLOCK;
75137670
75147671 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
75157672 // coding surface's: `blocks` carries one entry per 32x32 block the tile
@@ -7578,6 +7735,16 @@ pub(crate) fn encode_inter_frame(
75787735 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
75797736 for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {
75807737 for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {
7738+ // lane-av1tpl: this superblock's own lambda -- every RD decision
7739+ // under it (partition, mode, tx, motion) reads `search.lambda`,
7740+ // so scaling the one field here scales all of them.
7741+ let search = match &tpl_factors {
7742+ Some(f) => Search {
7743+ lambda: search.lambda * f[sb_r * tpl_sb_cols + sb_c],
7744+ ..search
7745+ },
7746+ None => search,
7747+ };
75817748 for quadrant in 0..4 {
75827749 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
75837750 // Same filter as the tile writer's: a quadrant whose own mi
@@ -8289,6 +8456,10 @@ pub(crate) fn encode_sequence_with_ctx(
82898456 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
82908457 for (i, picture) in rest.iter().enumerate() {
82918458 picture.check_even()?;
8459+ // lane-av1tpl: the one-frame lookahead the per-superblock lambda
8460+ // weighting reads -- the NEXT picture's source at this frame's coded
8461+ // (padded) size. The last frame of the sequence has none.
8462+ let lookahead = rest.get(i + 1).map(|n| n.padded_to(SUPERBLOCK));
82928463 if (picture.width, picture.height) != render {
82938464 return Err(Error::unsupported(
82948465 "AV1 encode",
@@ -8308,6 +8479,7 @@ pub(crate) fn encode_sequence_with_ctx(
83088479 Some(&golden),
83098480 prev2.as_ref(), fctx,
83108481 None,
8482+ lookahead.as_ref(),
83118483 )?;
83128484 stream.extend_from_slice(&inter.stream);
83138485 carried = inter.next_cdfs.clone();
@@ -8323,6 +8495,41 @@ pub(crate) fn encode_sequence_with_ctx(
83238495 #[cfg(test)]
83248496 mod tests {
83258497
8498+ /// lane-av1tpl's map and its lambda factors, on the two properties every
8499+ /// decision under them rests on: a frame the next one repeats exactly is
8500+ /// referenced once per cell (w = 1 everywhere, so every factor is 1 and
8501+ /// the weighting is a no-op), and the factor DECREASES in
8502+ /// referenced-ness -- a block the next frame leans on twice as hard as
8503+ /// the frame's mean is coded at a smaller lambda (more distortion-averse)
8504+ /// than one nothing points at.
8505+ #[test]
8506+ fn tpl_map_is_flat_on_a_repeated_frame_and_its_factor_falls_with_referencedness() {
8507+ let (w, h) = (64usize, 64usize);
8508+ let frame: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
8509+ let map = super::tpl_reference_map(&frame, &frame, w, h);
8510+ assert_eq!(map.len(), 16, "4x4 cells of 16x16");
8511+ for (i, &v) in map.iter().enumerate() {
8512+ assert!((v - 1.0).abs() < 1e-9, "cell {i} referenced {v} times, want exactly 1");
8513+ }
8514+ let factors = super::tpl_sb_factors(&map, 4, 4, 1.0);
8515+ assert_eq!(factors.len(), 1);
8516+ assert!((factors[0] - 1.0).abs() < 1e-9, "a flat map must not move any lambda");
8517+
8518+ // Two superblocks of cells side by side, 8 cells wide and 4 tall:
8519+ // superblock 0 covers columns 0..4 and is referenced four times as
8520+ // much as superblock 1 in columns 4..8, so its factor must be the
8521+ // smaller of the two and the frame mean must sit between them.
8522+ let by_col: Vec<f64> = (0..32)
8523+ .map(|i| if (i % 8) < 4 { 2.0 } else { 0.5 })
8524+ .collect();
8525+ for k in [0.25f64, 0.5, 1.0, 2.0] {
8526+ let f = super::tpl_sb_factors(&by_col, 8, 4, k);
8527+ assert_eq!(f.len(), 2);
8528+ assert!(f[0] < 1.0 && f[1] > 1.0, "k={k}: factors {f:?} must straddle 1");
8529+ assert!(f[0] < f[1], "k={k}: the referenced half must get the smaller lambda");
8530+ }
8531+ }
8532+
83268533 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
83278534 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
83288535 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
@@ -10787,7 +10994,7 @@ mod tests {
1078710994 let padded_pic = picture.padded_to(SUPERBLOCK);
1078810995 let t = Instant::now();
1078910996 let inter =
10790- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None).unwrap();
10997+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None, None).unwrap();
1079110998 let inter_t = t.elapsed();
1079210999 eprintln!(
1079311000 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
@@ -10885,7 +11092,7 @@ mod tests {
1088511092 stage_reset();
1088611093 let t = Instant::now();
1088711094 let inter =
10888- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None).unwrap();
11095+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None, None).unwrap();
1088911096 let total_t = t.elapsed();
1089011097 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
1089111098 let accounted = motion_search + transform_quant + entropy;
@@ -11063,7 +11270,7 @@ mod tests {
1106311270 0.5,
1106411271 1,
1106511272 flat_order_hints(1, 0, false),
11066- (width, height), None, None, None, fctx, None,
11273+ (width, height), None, None, None, fctx, None, None,
1106711274 )
1106811275 .unwrap();
1106911276 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
@@ -11081,7 +11288,7 @@ mod tests {
1108111288 0.5,
1108211289 1,
1108311290 flat_order_hints(1, 0, false),
11084- (width, height), None, None, None, fctx, None,
11291+ (width, height), None, None, None, fctx, None, None,
1108511292 )
1108611293 .unwrap();
1108711294 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
crates/ec-av1/src/encoder.rsmodified+6 -0
@@ -803,6 +803,9 @@ impl Av1Encoder {
803803 self.prev2.as_ref(),
804804 &self.fctx,
805805 None,
806+ // The streaming facade holds no lookahead buffer
807+ // (lane-av1tpl).
808+ None,
806809 )?
807810 };
808811
@@ -959,6 +962,9 @@ impl Av1Encoder {
959962 show_frame,
960963 sign_bias,
961964 }),
965+ // The streaming facade holds no lookahead buffer, so the
966+ // temporal lambda weighting is off on this path (lane-av1tpl).
967+ None,
962968 ) }();
963969 // Name the pyramid position in any failure: an error out of the tile
964970 // writer or the filter search is otherwise indistinguishable between