forge
Explore
Log in

Don't you dare go Hollow

A propagating lookahead lambda map -- mc_dep chained back through a D-frame window

Browse files at this commit

65f31640606c1f3a9819dc97393bd556d774bccbAhmet Kaan GümüşParent: c2623dd
  • feat
    • a propagating lookahead lambda map -- mc_dep chained back through a D-frame window
Show full message
feat(av1): a propagating lookahead lambda map -- mc_dep chained back through a D-frame window

The one-frame area map only knew how much of this frame the next one
lands on; it was flat by construction. This walks a window of D source
frames back to front, accumulating max(intra - inter, 0) + mc_dep along
each cell's coarse motion chain, and turns the accumulated dependence
into a per-16x16 lambda factor applied at 32x32 (the finest granularity
at which the whole-vs-split RD comparison stays self-consistent).

The streaming facade queues D-1 pictures so its window is the one the
sequence path builds; both read tpl_depth(), so they cannot disagree.
crates/ec-av1/src/encode.rsmodified+206 -120
@@ -7295,7 +7295,7 @@ fn search_inter_block(
7295 }7295 }
7296 7296
7297 /// lane-av1tpl: the strength `k` of the temporal lambda weighting7297 /// lane-av1tpl: the strength `k` of the temporal lambda weighting
7298-/// ([`tpl_sb_factors`]). 0 keeps every block at the frame's own lambda, which7298+/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
7299 /// is what every measurement before this lane was taken on. Swept by7299 /// is what every measurement before this lane was taken on. Swept by
7300 /// `EC_AV1_TPL=<k>`.7300 /// `EC_AV1_TPL=<k>`.
7301 ///7301 ///
@@ -7325,28 +7325,42 @@ fn tpl_strength() -> f64 {
7325 .unwrap_or(TPL_STRENGTH)7325 .unwrap_or(TPL_STRENGTH)
7326 }7326 }
7327 7327
7328-/// Nanoseconds the lookahead pass ([`tpl_reference_map`]) has spent this7328+/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
7329+/// the frame being coded: 1 turns the weighting off (nothing to propagate
7330+/// from), 2 is lane-av1tpl's one-frame map. Swept by `EC_AV1_TPL_D=<d>`.
7331+///
7332+/// The streaming facade holds `depth - 1` pictures back so it feeds
7333+/// `encode_inter_frame` the same window `encode_sequence` does; both read
7334+/// THIS function, so the two paths cannot disagree about the window.
7335+const TPL_DEPTH: usize = 4;
7336+
7337+pub(crate) fn tpl_depth() -> usize {
7338+ std::env::var("EC_AV1_TPL_D")
7339+ .ok()
7340+ .and_then(|v| v.parse::<usize>().ok())
7341+ .filter(|d| *d >= 1)
7342+ .unwrap_or(TPL_DEPTH)
7343+ .max(1)
7344+}
7345+
7346+/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
7329 /// process, so the gate can price it against the encode it rides on.7347 /// process, so the gate can price it against the encode it rides on.
7330 static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);7348 static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
7331 7349
7332-/// How much of THIS frame the next one will predict from, per 16x16 cell: one7350+/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
7333-/// coarse full-pel motion pass of the next SOURCE frame against this one7351+/// the winning displacement and its SAD.
7334-/// (libaom's `tpl` lookahead in its cheapest possible shape -- no transform,
7335-/// no propagation chain, just referenced area). A cell's value is the area of
7336-/// it that the next frame's blocks land on, in units of its own area, so 1.0
7337-/// is "referenced exactly once".
7338 ///7352 ///
7339 /// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at7353 /// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
7340-/// the left/above winners, first-best tie-break. The map is built once on the7354+/// the left/above winners, first-best tie-break. Built once on the frame's
7341-/// frame's own thread and read-only afterwards, so it cannot make a tile's7355+/// own thread and read-only afterwards, so it cannot make a tile's bytes
7342-/// bytes depend on the thread count.7356+/// depend on the thread count.
7343-fn tpl_reference_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {7357+fn tpl_coarse_pass(
7344- let start = std::time::Instant::now();7358+ cur: &[u8],
7359+ next: &[u8],
7360+ width: usize,
7361+ height: usize,
7362+) -> Vec<((i32, i32), u32)> {
7345 let (cells_x, cells_y) = (width / 16, height / 16);7363 let (cells_x, cells_y) = (width / 16, height / 16);
7346- let mut area = vec![0.0f64; cells_x * cells_y];
7347- // SAD of the next frame's 16x16 block at (bx, by) against this frame at
7348- // that block displaced by (mx, my); a displacement that leaves the frame
7349- // is not a candidate at all.
7350 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {7364 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
7351 let (sx, sy) = (bx as i32 + mx, by as i32 + my);7365 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
7352 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {7366 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
@@ -7361,6 +7375,7 @@ fn tpl_reference_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Ve
7361 }7375 }
7362 sum7376 sum
7363 };7377 };
7378+ let mut out = Vec::with_capacity(cells_x * cells_y);
7364 let mut above = vec![(0i32, 0i32); cells_x];7379 let mut above = vec![(0i32, 0i32); cells_x];
7365 for cy in 0..cells_y {7380 for cy in 0..cells_y {
7366 let mut left = (0i32, 0i32);7381 let mut left = (0i32, 0i32);
@@ -7388,61 +7403,118 @@ fn tpl_reference_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Ve
7388 }7403 }
7389 }7404 }
7390 }7405 }
7391- let (mv, _) = (best.1, best.0);7406+ left = best.1;
7392- left = mv;7407+ above[cx] = best.1;
7393- above[cx] = mv;7408+ out.push((best.1, best.0));
7394- // The 16x16 window of THIS frame that block referenced, spread7409+ }
7395- // over the (at most four) cells it overlaps.7410+ }
7396- let (x0, y0) = ((bx as i32 + mv.0) as usize, (by as i32 + mv.1) as usize);7411+ out
7397- for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {7412+}
7398- let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);7413+
7399- for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {7414+/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
7400- let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);7415+/// transform: here, the mean absolute deviation of the cell from its own DC.
7401- area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;7416+/// It is the denominator every propagated cost is read against, so only its
7417+/// SHAPE across the frame matters, not its scale.
7418+fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
7419+ let (cells_x, cells_y) = (width / 16, height / 16);
7420+ let mut out = Vec::with_capacity(cells_x * cells_y);
7421+ for cy in 0..cells_y {
7422+ for cx in 0..cells_x {
7423+ let (bx, by) = (cx * 16, cy * 16);
7424+ let mut sum = 0u32;
7425+ for r in 0..16 {
7426+ sum += frame[(by + r) * width + bx..][..16].iter().map(|&p| u32::from(p)).sum::<u32>();
7427+ }
7428+ let dc = ((sum + 128) / 256) as u8;
7429+ let mut cost = 0u32;
7430+ for r in 0..16 {
7431+ cost += frame[(by + r) * width + bx..][..16]
7432+ .iter()
7433+ .map(|&p| u32::from(p.abs_diff(dc)))
7434+ .sum::<u32>();
7435+ }
7436+ out.push(cost);
7437+ }
7438+ }
7439+ out
7440+}
7441+
7442+/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
7443+/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
7444+/// much of the WHOLE lookahead window leans on that cell.
7445+///
7446+/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
7447+/// coarse pass gives a displacement and an inter cost; a cell's own
7448+/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
7449+/// cell well saves the frames that predict from it -- and it is splatted,
7450+/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
7451+/// displacement lands on. Walking `f` from the far end of the window back to
7452+/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
7453+/// area map could not do at all.
7454+///
7455+/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
7456+/// factor over the frame is exactly 1: a cell the window leans on is coded
7457+/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
7458+/// scale only moves around, never up or down -- a global move is what
7459+/// lane-av1lambda already measured inert.
7460+fn tpl_lambda_factors(frames: &[&[u8]], width: usize, height: usize, k: f64) -> Vec<f64> {
7461+ let start = std::time::Instant::now();
7462+ let (cells_x, cells_y) = (width / 16, height / 16);
7463+ let cells = cells_x * cells_y;
7464+ let levels = frames.len();
7465+ let intra: Vec<Vec<u32>> = frames.iter().map(|f| tpl_intra_costs(f, width, height)).collect();
7466+ let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
7467+ .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
7468+ .collect();
7469+ let mut mc_dep = vec![vec![0.0f64; cells]; levels];
7470+ for f in (1..levels).rev() {
7471+ for cy in 0..cells_y {
7472+ for cx in 0..cells_x {
7473+ let ci = cy * cells_x + cx;
7474+ let (mv, inter) = passes[f - 1][ci];
7475+ let saved = f64::from(intra[f][ci].saturating_sub(inter));
7476+ let propagate = saved + mc_dep[f][ci];
7477+ if propagate <= 0.0 {
7478+ continue;
7479+ }
7480+ // The 16x16 window of the PREVIOUS frame this cell predicted
7481+ // from, spread over the cells it overlaps.
7482+ let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
7483+ let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
7484+ for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
7485+ let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
7486+ for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
7487+ let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
7488+ mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
7489+ }
7402 }7490 }
7403 }7491 }
7404 }7492 }
7405 }7493 }
7494+ let mut out: Vec<f64> = (0..cells)
7495+ .map(|c| {
7496+ let r = mc_dep[0][c] / f64::from(intra[0][c].max(1));
7497+ 1.0 / (1.0 + k * r)
7498+ })
7499+ .collect();
7500+ let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
7501+ for f in &mut out {
7502+ *f = (*f / mean).clamp(0.25, 4.0);
7503+ }
7406 TPL_NANOS.fetch_add(7504 TPL_NANOS.fetch_add(
7407 start.elapsed().as_nanos() as u64,7505 start.elapsed().as_nanos() as u64,
7408 std::sync::atomic::Ordering::Relaxed,7506 std::sync::atomic::Ordering::Relaxed,
7409 );7507 );
7410- area
7411-}
7412-
7413-/// [`tpl_reference_map`]'s per-cell referenced-ness turned into one lambda
7414-/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
7415-/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
7416-/// Decreasing in referenced-ness (a block the next frame leans on is coded
7417-/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
7418-/// total lambda scale is only redistributed, never moved -- a global move is
7419-/// the thing lane-av1lambda already measured inert.
7420-fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
7421- let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
7422- let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
7423- let mut out = Vec::with_capacity(sb_cols * sb_rows);
7424- for sr in 0..sb_rows {
7425- for sc in 0..sb_cols {
7426- let mut sum = 0.0;
7427- for r in 0..4 {
7428- for c in 0..4 {
7429- sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
7430- }
7431- }
7432- let w_rel = sum / 16.0 / mean;
7433- out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
7434- }
7435- }
7436 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {7508 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
7437 let mut hist = [0usize; 8];7509 let mut hist = [0usize; 8];
7438- for w in map {7510+ for &f in &out {
7439- hist[((w / mean * 2.0) as usize).min(7)] += 1;7511+ hist[((f * 4.0) as usize).min(7)] += 1;
7440 }7512 }
7441 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));7513 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
7514+ let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
7442 eprintln!(7515 eprintln!(
7443- "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \7516+ "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
7444- sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",7517+ range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
7445- map.len(),
7446 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,7518 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
7447 );7519 );
7448 }7520 }
@@ -7508,11 +7580,11 @@ pub(crate) fn encode_inter_frame(
7508 // Where this frame sits in the coding-order pyramid; `None` is the flat7580 // Where this frame sits in the coding-order pyramid; `None` is the flat
7509 // one-shown-frame-per-picture stream this encoder wrote before.7581 // one-shown-frame-per-picture stream this encoder wrote before.
7510 pyramid: Option<PyramidFrame>,7582 pyramid: Option<PyramidFrame>,
7511- // lane-av1tpl: the NEXT picture's source, padded like this one. Present,7583+ // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
7512- // it buys the one-frame lookahead the per-superblock lambda weighting7584+ // them), padded like this one -- the lookahead window the per-block
7513- // reads ([`tpl_reference_map`]); `None` (every streaming caller, which7585+ // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
7514- // has no lookahead buffer) codes the frame at one lambda, as before.7586+ // EMPTY slice codes the frame at one lambda, as before.
7515- lookahead: Option<&Picture>,7587+ lookahead: &[Picture],
7516 ) -> Result<Encoded> {7588 ) -> Result<Encoded> {
7517 picture.check()?;7589 picture.check()?;
7518 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {7590 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
@@ -7675,15 +7747,18 @@ pub(crate) fn encode_inter_frame(
7675 // this frame the NEXT one predicts from. Off (`None`) without a7747 // this frame the NEXT one predicts from. Off (`None`) without a
7676 // lookahead picture or at strength 0.7748 // lookahead picture or at strength 0.
7677 let tpl_k = tpl_strength();7749 let tpl_k = tpl_strength();
7678- let tpl_factors: Option<Vec<f64>> = lookahead7750+ let window: Vec<&Picture> = lookahead
7679- .filter(|_| tpl_k > 0.0)7751+ .iter()
7680- .filter(|n| n.width == picture.width && n.height == picture.height)7752+ .take_while(|n| n.width == picture.width && n.height == picture.height)
7681- .map(|n| {7753+ .collect();
7682- let next_y8: Vec<u8> = n.y.iter().map(|&v| v as u8).collect();7754+ let tpl_sources: Vec<Vec<u8>> =
7683- let map = tpl_reference_map(&picture_y8, &next_y8, picture.width, picture.height);7755+ window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect();
7684- tpl_sb_factors(&map, picture.width / 16, picture.height / 16, tpl_k)7756+ let tpl_factors: Option<Vec<f64>> = (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| {
7685- });7757+ let mut frames: Vec<&[u8]> = vec![&picture_y8];
7686- let tpl_sb_cols = picture.width / SUPERBLOCK;7758+ frames.extend(tpl_sources.iter().map(Vec::as_slice));
7759+ tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k)
7760+ });
7761+ let tpl_cells_x = picture.width / 16;
7687 7762
7688 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded7763 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
7689 // coding surface's: `blocks` carries one entry per 32x32 block the tile7764 // coding surface's: `blocks` carries one entry per 32x32 block the tile
@@ -7752,18 +7827,25 @@ pub(crate) fn encode_inter_frame(
7752 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();7827 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
7753 for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {7828 for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {
7754 for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {7829 for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {
7755- // lane-av1tpl: this superblock's own lambda -- every RD decision
7756- // under it (partition, mode, tx, motion) reads `search.lambda`,
7757- // so scaling the one field here scales all of them.
7758- let search = match &tpl_factors {
7759- Some(f) => Search {
7760- lambda: search.lambda * f[sb_r * tpl_sb_cols + sb_c],
7761- ..search
7762- },
7763- None => search,
7764- };
7765 for quadrant in 0..4 {7830 for quadrant in 0..4 {
7766 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);7831 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
7832+ // lane-av1tpl2: this 32x32 block's own lambda -- every RD
7833+ // decision under it (partition, mode, tx, motion) reads
7834+ // `search.lambda`, so scaling the one field here scales all
7835+ // of them. 32x32 and not the 16x16 the map is built at
7836+ // because the whole-vs-split comparison right below weighs
7837+ // one 32x32 cost against four 16x16 ones: a per-leaf lambda
7838+ // would make those two numbers incomparable.
7839+ let search = match &tpl_factors {
7840+ Some(f) => {
7841+ let mean = (0..4)
7842+ .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
7843+ .sum::<f64>()
7844+ / 4.0;
7845+ Search { lambda: search.lambda * mean, ..search }
7846+ }
7847+ None => search,
7848+ };
7767 // Same filter as the tile writer's: a quadrant whose own mi7849 // Same filter as the tile writer's: a quadrant whose own mi
7768 // origin is not inside the true frame is never coded.7850 // origin is not inside the true frame is never coded.
7769 if r32 >= rows || c32 >= cols {7851 if r32 >= rows || c32 >= cols {
@@ -8473,10 +8555,15 @@ pub(crate) fn encode_sequence_with_ctx(
8473 let mut frames = vec![crop_encoded(&key, render.0, render.1)];8555 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
8474 for (i, picture) in rest.iter().enumerate() {8556 for (i, picture) in rest.iter().enumerate() {
8475 picture.check_even()?;8557 picture.check_even()?;
8476- // lane-av1tpl: the one-frame lookahead the per-superblock lambda8558+ // lane-av1tpl2: the lookahead window the per-block lambda weighting
8477- // weighting reads -- the NEXT picture's source at this frame's coded8559+ // propagates back through -- the next [`tpl_depth`] - 1 pictures'
8478- // (padded) size. The last frame of the sequence has none.8560+ // sources at this frame's coded (padded) size. The tail of the
8479- let lookahead = rest.get(i + 1).map(|n| n.padded_to(SUPERBLOCK));8561+ // sequence gets a shorter window, and the last frame none at all.
8562+ let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
8563+ .iter()
8564+ .take(tpl_depth() - 1)
8565+ .map(|n| n.padded_to(SUPERBLOCK))
8566+ .collect();
8480 if (picture.width, picture.height) != render {8567 if (picture.width, picture.height) != render {
8481 return Err(Error::unsupported(8568 return Err(Error::unsupported(
8482 "AV1 encode",8569 "AV1 encode",
@@ -8496,7 +8583,7 @@ pub(crate) fn encode_sequence_with_ctx(
8496 Some(&golden),8583 Some(&golden),
8497 prev2.as_ref(), fctx,8584 prev2.as_ref(), fctx,
8498 None,8585 None,
8499- lookahead.as_ref(),8586+ &lookahead,
8500 )?;8587 )?;
8501 stream.extend_from_slice(&inter.stream);8588 stream.extend_from_slice(&inter.stream);
8502 carried = inter.next_cdfs.clone();8589 carried = inter.next_cdfs.clone();
@@ -8512,38 +8599,37 @@ pub(crate) fn encode_sequence_with_ctx(
8512 #[cfg(test)]8599 #[cfg(test)]
8513 mod tests {8600 mod tests {
8514 8601
8515- /// lane-av1tpl's map and its lambda factors, on the two properties every8602+ /// lane-av1tpl2's propagated map, on the two properties every decision
8516- /// decision under them rests on: a frame the next one repeats exactly is8603+ /// under it rests on: a frame the whole lookahead window repeats exactly
8517- /// referenced once per cell (w = 1 everywhere, so every factor is 1 and8604+ /// (uniform texture) leans on every cell alike, so every factor is 1 and
8518- /// the weighting is a no-op), and the factor DECREASES in8605+ /// the weighting is a no-op; and where the window really does save bits
8519- /// referenced-ness -- a block the next frame leans on twice as hard as8606+ /// by predicting -- the textured half of a frame whose other half is
8520- /// the frame's mean is coded at a smaller lambda (more distortion-averse)8607+ /// flat -- the factor FALLS below 1, i.e. that half is coded more
8521- /// than one nothing points at.8608+ /// distortion-averse than the half nothing gains from.
8522 #[test]8609 #[test]
8523- fn tpl_map_is_flat_on_a_repeated_frame_and_its_factor_falls_with_referencedness() {8610+ fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
8524 let (w, h) = (64usize, 64usize);8611 let (w, h) = (64usize, 64usize);
8525- let frame: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();8612+ let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
8526- let map = super::tpl_reference_map(&frame, &frame, w, h);8613+ let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
8527- assert_eq!(map.len(), 16, "4x4 cells of 16x16");8614+ let f = super::tpl_lambda_factors(&frames, w, h, 1.0);
8528- for (i, &v) in map.iter().enumerate() {8615+ assert_eq!(f.len(), 16, "4x4 cells of 16x16");
8529- assert!((v - 1.0).abs() < 1e-9, "cell {i} referenced {v} times, want exactly 1");8616+ for (i, &v) in f.iter().enumerate() {
8530- }8617+ assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda");
8531- let factors = super::tpl_sb_factors(&map, 4, 4, 1.0);8618+ }
8532- assert_eq!(factors.len(), 1);8619+
8533- assert!((factors[0] - 1.0).abs() < 1e-9, "a flat map must not move any lambda");8620+ // Left half textured, right half constant: the window saves bits
8534-8621+ // predicting the left half and nothing at all on the right.
8535- // Two superblocks of cells side by side, 8 cells wide and 4 tall:8622+ let split: Vec<u8> = (0..w * h)
8536- // superblock 0 covers columns 0..4 and is referenced four times as8623+ .map(|i| if i % w < 32 { ((i * 37) % 251) as u8 } else { 128 })
8537- // much as superblock 1 in columns 4..8, so its factor must be the
8538- // smaller of the two and the frame mean must sit between them.
8539- let by_col: Vec<f64> = (0..32)
8540- .map(|i| if (i % 8) < 4 { 2.0 } else { 0.5 })
8541 .collect();8624 .collect();
8625+ let frames: Vec<&[u8]> = vec![&split, &split, &split];
8542 for k in [0.25f64, 0.5, 1.0, 2.0] {8626 for k in [0.25f64, 0.5, 1.0, 2.0] {
8543- let f = super::tpl_sb_factors(&by_col, 8, 4, k);8627+ let f = super::tpl_lambda_factors(&frames, w, h, k);
8544- assert_eq!(f.len(), 2);8628+ for r in 0..4 {
8545- assert!(f[0] < 1.0 && f[1] > 1.0, "k={k}: factors {f:?} must straddle 1");8629+ let (lean, idle) = (f[r * 4], f[r * 4 + 3]);
8546- assert!(f[0] < f[1], "k={k}: the referenced half must get the smaller lambda");8630+ assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1");
8631+ assert!(idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1");
8632+ }
8547 }8633 }
8548 }8634 }
8549 8635
@@ -11011,7 +11097,7 @@ mod tests {
11011 let padded_pic = picture.padded_to(SUPERBLOCK);11097 let padded_pic = picture.padded_to(SUPERBLOCK);
11012 let t = Instant::now();11098 let t = Instant::now();
11013 let inter =11099 let inter =
11014- 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();11100+ 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();
11015 let inter_t = t.elapsed();11101 let inter_t = t.elapsed();
11016 eprintln!(11102 eprintln!(
11017 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \11103 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
@@ -11109,7 +11195,7 @@ mod tests {
11109 stage_reset();11195 stage_reset();
11110 let t = Instant::now();11196 let t = Instant::now();
11111 let inter =11197 let inter =
11112- 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();11198+ 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();
11113 let total_t = t.elapsed();11199 let total_t = t.elapsed();
11114 let [motion_search, interpolation, transform_quant, entropy] = stage_read();11200 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
11115 let accounted = motion_search + transform_quant + entropy;11201 let accounted = motion_search + transform_quant + entropy;
@@ -11287,7 +11373,7 @@ mod tests {
11287 0.5,11373 0.5,
11288 1,11374 1,
11289 flat_order_hints(1, 0, false),11375 flat_order_hints(1, 0, false),
11290- (width, height), None, None, None, fctx, None, None,11376+ (width, height), None, None, None, fctx, None, &[],
11291 )11377 )
11292 .unwrap();11378 .unwrap();
11293 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);11379 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
@@ -11305,7 +11391,7 @@ mod tests {
11305 0.5,11391 0.5,
11306 1,11392 1,
11307 flat_order_hints(1, 0, false),11393 flat_order_hints(1, 0, false),
11308- (width, height), None, None, None, fctx, None, None,11394+ (width, height), None, None, None, fctx, None, &[],
11309 )11395 )
11310 .unwrap();11396 .unwrap();
11311 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);11397 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
crates/ec-av1/src/encoder.rsmodified+48 -31
@@ -536,10 +536,11 @@ pub struct Av1Encoder {
536 dpb: [Option<DpbSlot>; 8],536 dpb: [Option<DpbSlot>; 8],
537 /// Pictures held back waiting for their mini-GOP's hidden frame.537 /// Pictures held back waiting for their mini-GOP's hidden frame.
538 pending: Vec<(u64, Picture)>,538 pending: Vec<(u64, Picture)>,
539- /// The flat path's one-picture delay queue: the picture whose packet the539+ /// The flat path's delay queue: pictures whose packets later calls
540- /// NEXT call returns, coded with that call's picture as its lookahead540+ /// return, each coded with the ones behind it as its lookahead window
541- /// (lane-av1facade). Unused in pyramid mode, which buffers in `pending`.541+ /// (lane-av1facade, deepened to [`crate::encode::tpl_depth`] - 1 on
542- held: Option<Picture>,542+ /// lane-av1tpl2). Unused in pyramid mode, which buffers in `pending`.
543+ held: std::collections::VecDeque<Picture>,
543 /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its544 /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its
544 /// anchor.545 /// anchor.
545 anchor: usize,546 anchor: usize,
@@ -607,7 +608,7 @@ impl Av1Encoder {
607 pyramid: None,608 pyramid: None,
608 dpb: [const { None }; 8],609 dpb: [const { None }; 8],
609 pending: Vec::new(),610 pending: Vec::new(),
610- held: None,611+ held: std::collections::VecDeque::new(),
611 anchor: 0,612 anchor: 0,
612 next_dts: 0,613 next_dts: 0,
613 })614 })
@@ -741,13 +742,17 @@ impl Av1Encoder {
741 ));742 ));
742 }743 }
743 let Some(pyramid) = self.pyramid else {744 let Some(pyramid) = self.pyramid else {
744- // The one-picture delay queue: this picture is the lookahead the745+ // The delay queue: the pictures behind this one are the
745- // previous one is coded with, which is what makes the facade's746+ // lookahead window the one at its head is coded with, which is
746- // bytes identical to `encode_sequence`'s (lane-av1facade).747+ // what makes the facade's bytes identical to
747- return Ok(match self.held.replace(picture.clone()) {748+ // `encode_sequence`'s (lane-av1facade, lane-av1tpl2).
748- None => Vec::new(),749+ self.held.push_back(picture.clone());
749- Some(previous) => vec![self.encode_flat(&previous, Some(picture))?],750+ if self.held.len() <= crate::encode::tpl_depth() - 1 {
750- });751+ return Ok(Vec::new());
752+ }
753+ let previous = self.held.pop_front().expect("queue is over depth");
754+ let window: Vec<Picture> = self.held.iter().cloned().collect();
755+ return Ok(vec![self.encode_flat(&previous, &window)?]);
751 };756 };
752 let order = self.next_index;757 let order = self.next_index;
753 self.next_index += 1;758 self.next_index += 1;
@@ -778,8 +783,13 @@ impl Av1Encoder {
778 /// As [`Av1Encoder::encode_frames`].783 /// As [`Av1Encoder::encode_frames`].
779 pub fn flush(&mut self) -> Result<Vec<Packet>> {784 pub fn flush(&mut self) -> Result<Vec<Packet>> {
780 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);785 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
781- if let Some(previous) = self.held.take() {786+ if !self.held.is_empty() {
782- return Ok(vec![self.encode_flat(&previous, None)?]);787+ let mut packets = Vec::with_capacity(self.held.len());
788+ while let Some(previous) = self.held.pop_front() {
789+ let window: Vec<Picture> = self.held.iter().cloned().collect();
790+ packets.push(self.encode_flat(&previous, &window)?);
791+ }
792+ return Ok(packets);
783 }793 }
784 self.drain_pending()794 self.drain_pending()
785 }795 }
@@ -788,7 +798,7 @@ impl Av1Encoder {
788 /// `None` at the end of the stream) in, one packet out — the same inputs798 /// `None` at the end of the stream) in, one packet out — the same inputs
789 /// [`crate::encode::encode_sequence`] gives each of its inter frames, so799 /// [`crate::encode::encode_sequence`] gives each of its inter frames, so
790 /// the bytes are identical.800 /// the bytes are identical.
791- fn encode_flat(&mut self, picture: &Picture, lookahead: Option<&Picture>) -> Result<Packet> {801+ fn encode_flat(&mut self, picture: &Picture, lookahead: &[Picture]) -> Result<Packet> {
792 let render = (self.config.width, self.config.height);802 let render = (self.config.width, self.config.height);
793 let padded = picture.padded_to(SUPERBLOCK);803 let padded = picture.padded_to(SUPERBLOCK);
794 let is_key = self.next_index.is_multiple_of(self.config.gop as u64);804 let is_key = self.next_index.is_multiple_of(self.config.gop as u64);
@@ -836,7 +846,7 @@ impl Av1Encoder {
836 self.prev2.as_ref(),846 self.prev2.as_ref(),
837 &self.fctx,847 &self.fctx,
838 None,848 None,
839- lookahead.map(|n| n.padded_to(SUPERBLOCK)).as_ref(),849+ &lookahead.iter().map(|n| n.padded_to(SUPERBLOCK)).collect::<Vec<_>>(),
840 )?850 )?
841 };851 };
842 852
@@ -993,9 +1003,10 @@ impl Av1Encoder {
993 show_frame,1003 show_frame,
994 sign_bias,1004 sign_bias,
995 }),1005 }),
996- // The streaming facade holds no lookahead buffer, so the1006+ // The pyramid path reorders pictures, so its own buffer is not
997- // temporal lambda weighting is off on this path (lane-av1tpl).1007+ // a lookahead window: the temporal lambda weighting is off on
998- None,1008+ // this path (lane-av1tpl).
1009+ &[],
999 ) }();1010 ) }();
1000 // Name the pyramid position in any failure: an error out of the tile1011 // Name the pyramid position in any failure: an error out of the tile
1001 // writer or the filter search is otherwise indistinguishable between1012 // writer or the filter search is otherwise indistinguishable between
@@ -1150,13 +1161,14 @@ mod tests {
1150 packets.iter().flat_map(|p| p.data.clone()).collect()1161 packets.iter().flat_map(|p| p.data.clone()).collect()
1151 }1162 }
1152 1163
1153- /// The facade's latency contract (lane-av1facade): the first1164+ /// The facade's latency contract (lane-av1facade, deepened on
1154- /// [`Av1Encoder::encode`] call returns an empty packet, every later call1165+ /// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold
1155- /// returns the PREVIOUS picture's packet, and [`Av1Encoder::flush`]1166+ /// their picture back and return an empty packet, every later call
1156- /// yields the last one — so a caller still gets exactly one non-empty1167+ /// returns the packet of the picture that many frames earlier, and
1157- /// packet per picture, one call later.1168+ /// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets
1169+ /// exactly one non-empty packet per picture, `depth - 1` calls later.
1158 #[test]1170 #[test]
1159- fn one_in_one_out_delayed_by_a_frame() {1171+ fn one_in_one_out_delayed_by_the_lookahead_depth() {
1160 let config = EncoderConfig {1172 let config = EncoderConfig {
1161 width: 64,1173 width: 64,
1162 height: 64,1174 height: 64,
@@ -1166,19 +1178,24 @@ mod tests {
1166 tile_cols_log2: 0,1178 tile_cols_log2: 0,
1167 tile_rows_log2: 0,1179 tile_rows_log2: 0,
1168 };1180 };
1181+ let delay = crate::encode::tpl_depth() as u64 - 1;
1182+ let pictures = delay + 5;
1169 let mut enc = Av1Encoder::new(config).unwrap();1183 let mut enc = Av1Encoder::new(config).unwrap();
1170- for t in 0..5u64 {1184+ for t in 0..pictures {
1171 let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();1185 let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
1172- if t == 0 {1186+ if t < delay {
1173- assert!(packet.data.is_empty(), "the first call holds its picture back");1187+ assert!(packet.data.is_empty(), "call {t} holds its picture back");
1174 continue;1188 continue;
1175 }1189 }
1176 assert!(!packet.data.is_empty(), "picture {t}: empty packet");1190 assert!(!packet.data.is_empty(), "picture {t}: empty packet");
1177- assert_eq!(packet.order, t - 1, "picture {t}: order");1191+ assert_eq!(packet.order, t - delay, "picture {t}: order");
1178 }1192 }
1179 let tail = enc.flush().unwrap();1193 let tail = enc.flush().unwrap();
1180- assert_eq!(tail.len(), 1, "flush yields the last picture");1194+ assert_eq!(tail.len() as u64, delay, "flush yields the whole queue");
1181- assert_eq!(tail[0].order, 4);1195+ for (i, p) in tail.iter().enumerate() {
1196+ assert_eq!(p.order, pictures - delay + i as u64, "flushed packet {i}: order");
1197+ assert!(!p.data.is_empty(), "flushed packet {i}: empty");
1198+ }
1182 assert!(enc.flush().unwrap().is_empty(), "nothing is held twice");1199 assert!(enc.flush().unwrap().is_empty(), "nothing is held twice");
1183 }1200 }
1184 1201
lanes/tpl2-sweep.logadded+28 -0
@@ -0,0 +1,28 @@
1+=== k=0.25 d=4 ===
2+ Finished `release` profile [optimized] target(s) in 0.01s
3+ Running unittests src/lib.rs (/home/user/.cache/cargo-target-av1tpl2/release/deps/ec_av1-8fef0196ab10338d)
4+
5+running 1 test
6+
7+native crop, 12 frames, gop=12; tiles (0, 0), tile threads 1, intrabc false, palette maxcolors 128
8+| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |
9+|---|---|---|---|---|
10+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 553, 225, 622, 6280, 0, 0, 0], range 0.250..1.111, 58 within 0.9..1.1, lookahead wall 5.7 ms cumulative
11+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 529, 240, 624, 6287, 0, 0, 0], range 0.250..1.109, 61 within 0.9..1.1, lookahead wall 11.5 ms cumulative
12+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 526, 255, 628, 6271, 0, 0, 0], range 0.250..1.110, 44 within 0.9..1.1, lookahead wall 17.2 ms cumulative
13+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 550, 257, 632, 6241, 0, 0, 0], range 0.250..1.113, 64 within 0.9..1.1, lookahead wall 23.0 ms cumulative
14+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 570, 250, 643, 6217, 0, 0, 0], range 0.250..1.117, 62 within 0.9..1.1, lookahead wall 28.8 ms cumulative
15+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 544, 256, 624, 6256, 0, 0, 0], range 0.250..1.112, 73 within 0.9..1.1, lookahead wall 34.6 ms cumulative
16+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 531, 263, 595, 6291, 0, 0, 0], range 0.250..1.110, 49 within 0.9..1.1, lookahead wall 40.3 ms cumulative
17+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 515, 280, 617, 6268, 0, 0, 0], range 0.250..1.108, 58 within 0.9..1.1, lookahead wall 46.0 ms cumulative
18+tpl k=0.25 d=3: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 351, 267, 657, 6405, 0, 0, 0], range 0.250..1.077, 6615 within 0.9..1.1, lookahead wall 49.8 ms cumulative
19+tpl k=0.25 d=2: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 157, 56, 872, 6595, 0, 0, 0], range 0.250..1.039, 7133 within 0.9..1.1, lookahead wall 51.9 ms cumulative
20+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 553, 225, 622, 6280, 0, 0, 0], range 0.250..1.111, 58 within 0.9..1.1, lookahead wall 57.7 ms cumulative
21+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 529, 240, 624, 6287, 0, 0, 0], range 0.250..1.109, 61 within 0.9..1.1, lookahead wall 63.5 ms cumulative
22+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 526, 255, 628, 6271, 0, 0, 0], range 0.250..1.110, 44 within 0.9..1.1, lookahead wall 69.2 ms cumulative
23+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 550, 257, 632, 6241, 0, 0, 0], range 0.250..1.113, 64 within 0.9..1.1, lookahead wall 74.9 ms cumulative
24+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 570, 250, 643, 6217, 0, 0, 0], range 0.250..1.117, 62 within 0.9..1.1, lookahead wall 80.7 ms cumulative
25+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 544, 256, 624, 6256, 0, 0, 0], range 0.250..1.112, 73 within 0.9..1.1, lookahead wall 86.6 ms cumulative
26+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 531, 263, 595, 6291, 0, 0, 0], range 0.250..1.110, 49 within 0.9..1.1, lookahead wall 92.4 ms cumulative
27+tpl k=0.25 d=4: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 515, 280, 617, 6268, 0, 0, 0], range 0.250..1.108, 58 within 0.9..1.1, lookahead wall 98.2 ms cumulative
28+tpl k=0.25 d=3: 7680 cells, factor hist (0-.25,.25-.5,..,>1.75) [0, 351, 267, 657, 6405, 0, 0, 0], range 0.250..1.077, 6615 within 0.9..1.1, lookahead wall 102.0 ms cumulative
lanes/tpl2-sweep.shadded+13 -0
@@ -0,0 +1,13 @@
1+#!/bin/bash
2+cd $HOME/Documents/Code/Rust/edith_codecs-av1tpl2 || exit 1
3+export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-av1tpl2
4+L=lanes/tpl2-sweep.log
5+for d in 4 8; do
6+ for k in 0.25 0.5 1 2; do
7+ echo "=== k=$k d=$d ===" >> $L
8+ timeout 900 env EC_COMP_MISMATCH=1 EC_AV1_TPL=$k EC_AV1_TPL_D=$d EC_AV1_TPL_HIST=1 \
9+ cargo test -p ec-av1 --release --lib -- --ignored bd_rate_screen_native --nocapture >> $L 2>&1
10+ echo "RC=$? k=$k d=$d" >> $L
11+ done
12+done
13+echo SWEEPDONE >> $L