A one-frame lookahead builds a per-superblock lambda weight from how much of a frame the next one references
Browse files at this commit9b24d77f333efc22c586070fa8d5a6ea808cf80fParent: 12f1dab- feat
- a one-frame lookahead builds a per-superblock lambda weight from how much of a frame the next one references
2 changed files +217 -4
- crates/ec-av1/src/encode.rs +211 -4
- crates/ec-av1/src/encoder.rs +6 -0
crates/ec-av1/src/encode.rsmodified+211 -4
| @@ -4859,6 +4859,7 @@ fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { | ||
| 4859 | 4859 | } |
| 4860 | 4860 | |
| 4861 | 4861 | /// What the luma mode search picks between, and under what terms. |
| 4862 | +#[derive(Clone, Copy)] | |
| 4862 | 4863 | struct Search<'a> { |
| 4863 | 4864 | /// This frame's `allow_screen_content_tools` ([`screen_content`]): the |
| 4864 | 4865 | /// luma search then offers a palette candidate beside the intra modes. |
| @@ -7293,6 +7294,144 @@ fn search_inter_block( | ||
| 7293 | 7294 | ) |
| 7294 | 7295 | } |
| 7295 | 7296 | |
| 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 | + | |
| 7296 | 7435 | /// Where one inter frame sits in a coding-order pyramid: which DPB slots its |
| 7297 | 7436 | /// references name, which slot it refreshes, whether it is shown when it is |
| 7298 | 7437 | /// coded, and the `ref_frame_sign_bias` that follows from all of it. `None` |
| @@ -7352,6 +7491,11 @@ pub(crate) fn encode_inter_frame( | ||
| 7352 | 7491 | // Where this frame sits in the coding-order pyramid; `None` is the flat |
| 7353 | 7492 | // one-shown-frame-per-picture stream this encoder wrote before. |
| 7354 | 7493 | 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>, | |
| 7355 | 7499 | ) -> Result<Encoded> { |
| 7356 | 7500 | picture.check()?; |
| 7357 | 7501 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { |
| @@ -7510,6 +7654,19 @@ pub(crate) fn encode_inter_frame( | ||
| 7510 | 7654 | screen, |
| 7511 | 7655 | }; |
| 7512 | 7656 | 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; | |
| 7513 | 7670 | |
| 7514 | 7671 | // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded |
| 7515 | 7672 | // coding surface's: `blocks` carries one entry per 32x32 block the tile |
| @@ -7578,6 +7735,16 @@ pub(crate) fn encode_inter_frame( | ||
| 7578 | 7735 | let mut blocks: Vec<(usize, Quadrant)> = Vec::new(); |
| 7579 | 7736 | for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize { |
| 7580 | 7737 | 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 | + }; | |
| 7581 | 7748 | for quadrant in 0..4 { |
| 7582 | 7749 | let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); |
| 7583 | 7750 | // Same filter as the tile writer's: a quadrant whose own mi |
| @@ -8289,6 +8456,10 @@ pub(crate) fn encode_sequence_with_ctx( | ||
| 8289 | 8456 | let mut frames = vec![crop_encoded(&key, render.0, render.1)]; |
| 8290 | 8457 | for (i, picture) in rest.iter().enumerate() { |
| 8291 | 8458 | 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)); | |
| 8292 | 8463 | if (picture.width, picture.height) != render { |
| 8293 | 8464 | return Err(Error::unsupported( |
| 8294 | 8465 | "AV1 encode", |
| @@ -8308,6 +8479,7 @@ pub(crate) fn encode_sequence_with_ctx( | ||
| 8308 | 8479 | Some(&golden), |
| 8309 | 8480 | prev2.as_ref(), fctx, |
| 8310 | 8481 | None, |
| 8482 | + lookahead.as_ref(), | |
| 8311 | 8483 | )?; |
| 8312 | 8484 | stream.extend_from_slice(&inter.stream); |
| 8313 | 8485 | carried = inter.next_cdfs.clone(); |
| @@ -8323,6 +8495,41 @@ pub(crate) fn encode_sequence_with_ctx( | ||
| 8323 | 8495 | #[cfg(test)] |
| 8324 | 8496 | mod tests { |
| 8325 | 8497 | |
| 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 | + | |
| 8326 | 8533 | /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a |
| 8327 | 8534 | /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a |
| 8328 | 8535 | /// row holds `32 >> bw_in_mi_log2` bits and the table holds |
| @@ -10787,7 +10994,7 @@ mod tests { | ||
| 10787 | 10994 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 10788 | 10995 | let t = Instant::now(); |
| 10789 | 10996 | 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(); | |
| 10791 | 10998 | let inter_t = t.elapsed(); |
| 10792 | 10999 | eprintln!( |
| 10793 | 11000 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ |
| @@ -10885,7 +11092,7 @@ mod tests { | ||
| 10885 | 11092 | stage_reset(); |
| 10886 | 11093 | let t = Instant::now(); |
| 10887 | 11094 | 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(); | |
| 10889 | 11096 | let total_t = t.elapsed(); |
| 10890 | 11097 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); |
| 10891 | 11098 | let accounted = motion_search + transform_quant + entropy; |
| @@ -11063,7 +11270,7 @@ mod tests { | ||
| 11063 | 11270 | 0.5, |
| 11064 | 11271 | 1, |
| 11065 | 11272 | flat_order_hints(1, 0, false), |
| 11066 | - (width, height), None, None, None, fctx, None, | |
| 11273 | + (width, height), None, None, None, fctx, None, None, | |
| 11067 | 11274 | ) |
| 11068 | 11275 | .unwrap(); |
| 11069 | 11276 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); |
| @@ -11081,7 +11288,7 @@ mod tests { | ||
| 11081 | 11288 | 0.5, |
| 11082 | 11289 | 1, |
| 11083 | 11290 | flat_order_hints(1, 0, false), |
| 11084 | - (width, height), None, None, None, fctx, None, | |
| 11291 | + (width, height), None, None, None, fctx, None, None, | |
| 11085 | 11292 | ) |
| 11086 | 11293 | .unwrap(); |
| 11087 | 11294 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); |
crates/ec-av1/src/encoder.rsmodified+6 -0
| @@ -803,6 +803,9 @@ impl Av1Encoder { | ||
| 803 | 803 | self.prev2.as_ref(), |
| 804 | 804 | &self.fctx, |
| 805 | 805 | None, |
| 806 | + // The streaming facade holds no lookahead buffer | |
| 807 | + // (lane-av1tpl). | |
| 808 | + None, | |
| 806 | 809 | )? |
| 807 | 810 | }; |
| 808 | 811 | |
| @@ -959,6 +962,9 @@ impl Av1Encoder { | ||
| 959 | 962 | show_frame, |
| 960 | 963 | sign_bias, |
| 961 | 964 | }), |
| 965 | + // The streaming facade holds no lookahead buffer, so the | |
| 966 | + // temporal lambda weighting is off on this path (lane-av1tpl). | |
| 967 | + None, | |
| 962 | 968 | ) }(); |
| 963 | 969 | // Name the pyramid position in any failure: an error out of the tile |
| 964 | 970 | // writer or the filter search is otherwise indistinguishable between |