diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index ec154ec0..ee667e15 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -7295,7 +7295,7 @@ fn search_inter_block( } /// lane-av1tpl: the strength `k` of the temporal lambda weighting -/// ([`tpl_sb_factors`]). 0 keeps every block at the frame's own lambda, which +/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which /// is what every measurement before this lane was taken on. Swept by /// `EC_AV1_TPL=`. /// @@ -7325,28 +7325,42 @@ fn tpl_strength() -> f64 { .unwrap_or(TPL_STRENGTH) } -/// Nanoseconds the lookahead pass ([`tpl_reference_map`]) has spent this +/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting +/// the frame being coded: 1 turns the weighting off (nothing to propagate +/// from), 2 is lane-av1tpl's one-frame map. Swept by `EC_AV1_TPL_D=`. +/// +/// The streaming facade holds `depth - 1` pictures back so it feeds +/// `encode_inter_frame` the same window `encode_sequence` does; both read +/// THIS function, so the two paths cannot disagree about the window. +const TPL_DEPTH: usize = 4; + +pub(crate) fn tpl_depth() -> usize { + std::env::var("EC_AV1_TPL_D") + .ok() + .and_then(|v| v.parse::().ok()) + .filter(|d| *d >= 1) + .unwrap_or(TPL_DEPTH) + .max(1) +} + +/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this /// process, so the gate can price it against the encode it rides on. static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -/// How much of THIS frame the next one will predict from, per 16x16 cell: one -/// coarse full-pel motion pass of the next SOURCE frame against this one -/// (libaom's `tpl` lookahead in its cheapest possible shape -- no transform, -/// no propagation chain, just referenced area). A cell's value is the area of -/// it that the next frame's blocks land on, in units of its own area, so 1.0 -/// is "referenced exactly once". +/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell, +/// the winning displacement and its SAD. /// /// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at -/// the left/above winners, first-best tie-break. The map is built once on the -/// frame's own thread and read-only afterwards, so it cannot make a tile's -/// bytes depend on the thread count. -fn tpl_reference_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec { - let start = std::time::Instant::now(); +/// the left/above winners, first-best tie-break. Built once on the frame's +/// own thread and read-only afterwards, so it cannot make a tile's bytes +/// depend on the thread count. +fn tpl_coarse_pass( + cur: &[u8], + next: &[u8], + width: usize, + height: usize, +) -> Vec<((i32, i32), u32)> { let (cells_x, cells_y) = (width / 16, height / 16); - let mut area = vec![0.0f64; cells_x * cells_y]; - // SAD of the next frame's 16x16 block at (bx, by) against this frame at - // that block displaced by (mx, my); a displacement that leaves the frame - // is not a candidate at all. let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 { let (sx, sy) = (bx as i32 + mx, by as i32 + my); 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 } sum }; + let mut out = Vec::with_capacity(cells_x * cells_y); let mut above = vec![(0i32, 0i32); cells_x]; for cy in 0..cells_y { let mut left = (0i32, 0i32); @@ -7388,61 +7403,118 @@ fn tpl_reference_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Ve } } } - let (mv, _) = (best.1, best.0); - left = mv; - above[cx] = mv; - // The 16x16 window of THIS frame that block referenced, spread - // over the (at most four) cells it overlaps. - let (x0, y0) = ((bx as i32 + mv.0) as usize, (by as i32 + mv.1) as usize); - for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) { - let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16); - for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) { - let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16); - area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0; + left = best.1; + above[cx] = best.1; + out.push((best.1, best.0)); + } + } + out +} + +/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a +/// transform: here, the mean absolute deviation of the cell from its own DC. +/// It is the denominator every propagated cost is read against, so only its +/// SHAPE across the frame matters, not its scale. +fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec { + let (cells_x, cells_y) = (width / 16, height / 16); + let mut out = Vec::with_capacity(cells_x * cells_y); + for cy in 0..cells_y { + for cx in 0..cells_x { + let (bx, by) = (cx * 16, cy * 16); + let mut sum = 0u32; + for r in 0..16 { + sum += frame[(by + r) * width + bx..][..16].iter().map(|&p| u32::from(p)).sum::(); + } + let dc = ((sum + 128) / 256) as u8; + let mut cost = 0u32; + for r in 0..16 { + cost += frame[(by + r) * width + bx..][..16] + .iter() + .map(|&p| u32::from(p.abs_diff(dc))) + .sum::(); + } + out.push(cost); + } + } + out +} + +/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda +/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how +/// much of the WHOLE lookahead window leans on that cell. +/// +/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the +/// coarse pass gives a displacement and an inter cost; a cell's own +/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that +/// cell well saves the frames that predict from it -- and it is splatted, +/// area-weighted, onto the (at most four) cells of `frames[f-1]` its +/// displacement lands on. Walking `f` from the far end of the window back to +/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame +/// area map could not do at all. +/// +/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean +/// factor over the frame is exactly 1: a cell the window leans on is coded +/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda +/// scale only moves around, never up or down -- a global move is what +/// lane-av1lambda already measured inert. +fn tpl_lambda_factors(frames: &[&[u8]], width: usize, height: usize, k: f64) -> Vec { + let start = std::time::Instant::now(); + let (cells_x, cells_y) = (width / 16, height / 16); + let cells = cells_x * cells_y; + let levels = frames.len(); + let intra: Vec> = frames.iter().map(|f| tpl_intra_costs(f, width, height)).collect(); + let passes: Vec> = (1..levels) + .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height)) + .collect(); + let mut mc_dep = vec![vec![0.0f64; cells]; levels]; + for f in (1..levels).rev() { + for cy in 0..cells_y { + for cx in 0..cells_x { + let ci = cy * cells_x + cx; + let (mv, inter) = passes[f - 1][ci]; + let saved = f64::from(intra[f][ci].saturating_sub(inter)); + let propagate = saved + mc_dep[f][ci]; + if propagate <= 0.0 { + continue; + } + // The 16x16 window of the PREVIOUS frame this cell predicted + // from, spread over the cells it overlaps. + let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1); + let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); + for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) { + let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16); + for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) { + let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16); + mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0; + } } } } } + let mut out: Vec = (0..cells) + .map(|c| { + let r = mc_dep[0][c] / f64::from(intra[0][c].max(1)); + 1.0 / (1.0 + k * r) + }) + .collect(); + let mean = (out.iter().sum::() / cells.max(1) as f64).max(1e-9); + for f in &mut out { + *f = (*f / mean).clamp(0.25, 4.0); + } TPL_NANOS.fetch_add( start.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed, ); - area -} - -/// [`tpl_reference_map`]'s per-cell referenced-ness turned into one lambda -/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where -/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean. -/// Decreasing in referenced-ness (a block the next frame leans on is coded -/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's -/// total lambda scale is only redistributed, never moved -- a global move is -/// the thing lane-av1lambda already measured inert. -fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec { - let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4); - let mean = (map.iter().sum::() / map.len().max(1) as f64).max(1e-6); - let mut out = Vec::with_capacity(sb_cols * sb_rows); - for sr in 0..sb_rows { - for sc in 0..sb_cols { - let mut sum = 0.0; - for r in 0..4 { - for c in 0..4 { - sum += map[(sr * 4 + r) * cells_x + sc * 4 + c]; - } - } - let w_rel = sum / 16.0 / mean; - out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0)); - } - } if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") { let mut hist = [0usize; 8]; - for w in map { - hist[((w / mean * 2.0) as usize).min(7)] += 1; + for &f in &out { + hist[((f * 4.0) as usize).min(7)] += 1; } let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f))); + let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count(); eprintln!( - "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \ - sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative", - map.len(), + "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \ + range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative", TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6, ); } @@ -7508,11 +7580,11 @@ pub(crate) fn encode_inter_frame( // Where this frame sits in the coding-order pyramid; `None` is the flat // one-shown-frame-per-picture stream this encoder wrote before. pyramid: Option, - // lane-av1tpl: the NEXT picture's source, padded like this one. Present, - // it buys the one-frame lookahead the per-superblock lambda weighting - // reads ([`tpl_reference_map`]); `None` (every streaming caller, which - // has no lookahead buffer) codes the frame at one lambda, as before. - lookahead: Option<&Picture>, + // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of + // them), padded like this one -- the lookahead window the per-block + // lambda weighting propagates back through ([`tpl_lambda_factors`]). An + // EMPTY slice codes the frame at one lambda, as before. + lookahead: &[Picture], ) -> Result { picture.check()?; if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { @@ -7675,15 +7747,18 @@ pub(crate) fn encode_inter_frame( // this frame the NEXT one predicts from. Off (`None`) without a // lookahead picture or at strength 0. let tpl_k = tpl_strength(); - let tpl_factors: Option> = lookahead - .filter(|_| tpl_k > 0.0) - .filter(|n| n.width == picture.width && n.height == picture.height) - .map(|n| { - let next_y8: Vec = n.y.iter().map(|&v| v as u8).collect(); - let map = tpl_reference_map(&picture_y8, &next_y8, picture.width, picture.height); - tpl_sb_factors(&map, picture.width / 16, picture.height / 16, tpl_k) - }); - let tpl_sb_cols = picture.width / SUPERBLOCK; + let window: Vec<&Picture> = lookahead + .iter() + .take_while(|n| n.width == picture.width && n.height == picture.height) + .collect(); + let tpl_sources: Vec> = + window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect(); + let tpl_factors: Option> = (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| { + let mut frames: Vec<&[u8]> = vec![&picture_y8]; + frames.extend(tpl_sources.iter().map(Vec::as_slice)); + tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k) + }); + let tpl_cells_x = picture.width / 16; // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded // coding surface's: `blocks` carries one entry per 32x32 block the tile @@ -7752,18 +7827,25 @@ pub(crate) fn encode_inter_frame( let mut blocks: Vec<(usize, Quadrant)> = Vec::new(); for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize { for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize { - // lane-av1tpl: this superblock's own lambda -- every RD decision - // under it (partition, mode, tx, motion) reads `search.lambda`, - // so scaling the one field here scales all of them. - let search = match &tpl_factors { - Some(f) => Search { - lambda: search.lambda * f[sb_r * tpl_sb_cols + sb_c], - ..search - }, - None => search, - }; for quadrant in 0..4 { let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); + // lane-av1tpl2: this 32x32 block's own lambda -- every RD + // decision under it (partition, mode, tx, motion) reads + // `search.lambda`, so scaling the one field here scales all + // of them. 32x32 and not the 16x16 the map is built at + // because the whole-vs-split comparison right below weighs + // one 32x32 cost against four 16x16 ones: a per-leaf lambda + // would make those two numbers incomparable. + let search = match &tpl_factors { + Some(f) => { + let mean = (0..4) + .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2]) + .sum::() + / 4.0; + Search { lambda: search.lambda * mean, ..search } + } + None => search, + }; // Same filter as the tile writer's: a quadrant whose own mi // origin is not inside the true frame is never coded. if r32 >= rows || c32 >= cols { @@ -8473,10 +8555,15 @@ pub(crate) fn encode_sequence_with_ctx( let mut frames = vec![crop_encoded(&key, render.0, render.1)]; for (i, picture) in rest.iter().enumerate() { picture.check_even()?; - // lane-av1tpl: the one-frame lookahead the per-superblock lambda - // weighting reads -- the NEXT picture's source at this frame's coded - // (padded) size. The last frame of the sequence has none. - let lookahead = rest.get(i + 1).map(|n| n.padded_to(SUPERBLOCK)); + // lane-av1tpl2: the lookahead window the per-block lambda weighting + // propagates back through -- the next [`tpl_depth`] - 1 pictures' + // sources at this frame's coded (padded) size. The tail of the + // sequence gets a shorter window, and the last frame none at all. + let lookahead: Vec = rest[(i + 1).min(rest.len())..] + .iter() + .take(tpl_depth() - 1) + .map(|n| n.padded_to(SUPERBLOCK)) + .collect(); if (picture.width, picture.height) != render { return Err(Error::unsupported( "AV1 encode", @@ -8496,7 +8583,7 @@ pub(crate) fn encode_sequence_with_ctx( Some(&golden), prev2.as_ref(), fctx, None, - lookahead.as_ref(), + &lookahead, )?; stream.extend_from_slice(&inter.stream); carried = inter.next_cdfs.clone(); @@ -8512,38 +8599,37 @@ pub(crate) fn encode_sequence_with_ctx( #[cfg(test)] mod tests { - /// lane-av1tpl's map and its lambda factors, on the two properties every - /// decision under them rests on: a frame the next one repeats exactly is - /// referenced once per cell (w = 1 everywhere, so every factor is 1 and - /// the weighting is a no-op), and the factor DECREASES in - /// referenced-ness -- a block the next frame leans on twice as hard as - /// the frame's mean is coded at a smaller lambda (more distortion-averse) - /// than one nothing points at. + /// lane-av1tpl2's propagated map, on the two properties every decision + /// under it rests on: a frame the whole lookahead window repeats exactly + /// (uniform texture) leans on every cell alike, so every factor is 1 and + /// the weighting is a no-op; and where the window really does save bits + /// by predicting -- the textured half of a frame whose other half is + /// flat -- the factor FALLS below 1, i.e. that half is coded more + /// distortion-averse than the half nothing gains from. #[test] - fn tpl_map_is_flat_on_a_repeated_frame_and_its_factor_falls_with_referencedness() { + fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() { let (w, h) = (64usize, 64usize); - let frame: Vec = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect(); - let map = super::tpl_reference_map(&frame, &frame, w, h); - assert_eq!(map.len(), 16, "4x4 cells of 16x16"); - for (i, &v) in map.iter().enumerate() { - assert!((v - 1.0).abs() < 1e-9, "cell {i} referenced {v} times, want exactly 1"); - } - let factors = super::tpl_sb_factors(&map, 4, 4, 1.0); - assert_eq!(factors.len(), 1); - assert!((factors[0] - 1.0).abs() < 1e-9, "a flat map must not move any lambda"); - - // Two superblocks of cells side by side, 8 cells wide and 4 tall: - // superblock 0 covers columns 0..4 and is referenced four times as - // much as superblock 1 in columns 4..8, so its factor must be the - // smaller of the two and the frame mean must sit between them. - let by_col: Vec = (0..32) - .map(|i| if (i % 8) < 4 { 2.0 } else { 0.5 }) + let uniform: Vec = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect(); + let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform]; + let f = super::tpl_lambda_factors(&frames, w, h, 1.0); + assert_eq!(f.len(), 16, "4x4 cells of 16x16"); + for (i, &v) in f.iter().enumerate() { + assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda"); + } + + // Left half textured, right half constant: the window saves bits + // predicting the left half and nothing at all on the right. + let split: Vec = (0..w * h) + .map(|i| if i % w < 32 { ((i * 37) % 251) as u8 } else { 128 }) .collect(); + let frames: Vec<&[u8]> = vec![&split, &split, &split]; for k in [0.25f64, 0.5, 1.0, 2.0] { - let f = super::tpl_sb_factors(&by_col, 8, 4, k); - assert_eq!(f.len(), 2); - assert!(f[0] < 1.0 && f[1] > 1.0, "k={k}: factors {f:?} must straddle 1"); - assert!(f[0] < f[1], "k={k}: the referenced half must get the smaller lambda"); + let f = super::tpl_lambda_factors(&frames, w, h, k); + for r in 0..4 { + let (lean, idle) = (f[r * 4], f[r * 4 + 3]); + assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1"); + assert!(idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1"); + } } } @@ -11011,7 +11097,7 @@ mod tests { let padded_pic = picture.padded_to(SUPERBLOCK); let t = Instant::now(); let inter = - 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(); + 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(); let inter_t = t.elapsed(); eprintln!( "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ @@ -11109,7 +11195,7 @@ mod tests { stage_reset(); let t = Instant::now(); let inter = - 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(); + 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(); let total_t = t.elapsed(); let [motion_search, interpolation, transform_quant, entropy] = stage_read(); let accounted = motion_search + transform_quant + entropy; @@ -11287,7 +11373,7 @@ mod tests { 0.5, 1, flat_order_hints(1, 0, false), - (width, height), None, None, None, fctx, None, None, + (width, height), None, None, None, fctx, None, &[], ) .unwrap(); let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); @@ -11305,7 +11391,7 @@ mod tests { 0.5, 1, flat_order_hints(1, 0, false), - (width, height), None, None, None, fctx, None, None, + (width, height), None, None, None, fctx, None, &[], ) .unwrap(); let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 1a3fc9ac..098d6d4c 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -536,10 +536,11 @@ pub struct Av1Encoder { dpb: [Option; 8], /// Pictures held back waiting for their mini-GOP's hidden frame. pending: Vec<(u64, Picture)>, - /// The flat path's one-picture delay queue: the picture whose packet the - /// NEXT call returns, coded with that call's picture as its lookahead - /// (lane-av1facade). Unused in pyramid mode, which buffers in `pending`. - held: Option, + /// The flat path's delay queue: pictures whose packets later calls + /// return, each coded with the ones behind it as its lookahead window + /// (lane-av1facade, deepened to [`crate::encode::tpl_depth`] - 1 on + /// lane-av1tpl2). Unused in pyramid mode, which buffers in `pending`. + held: std::collections::VecDeque, /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its /// anchor. anchor: usize, @@ -607,7 +608,7 @@ impl Av1Encoder { pyramid: None, dpb: [const { None }; 8], pending: Vec::new(), - held: None, + held: std::collections::VecDeque::new(), anchor: 0, next_dts: 0, }) @@ -741,13 +742,17 @@ impl Av1Encoder { )); } let Some(pyramid) = self.pyramid else { - // The one-picture delay queue: this picture is the lookahead the - // previous one is coded with, which is what makes the facade's - // bytes identical to `encode_sequence`'s (lane-av1facade). - return Ok(match self.held.replace(picture.clone()) { - None => Vec::new(), - Some(previous) => vec![self.encode_flat(&previous, Some(picture))?], - }); + // The delay queue: the pictures behind this one are the + // lookahead window the one at its head is coded with, which is + // what makes the facade's bytes identical to + // `encode_sequence`'s (lane-av1facade, lane-av1tpl2). + self.held.push_back(picture.clone()); + if self.held.len() <= crate::encode::tpl_depth() - 1 { + return Ok(Vec::new()); + } + let previous = self.held.pop_front().expect("queue is over depth"); + let window: Vec = self.held.iter().cloned().collect(); + return Ok(vec![self.encode_flat(&previous, &window)?]); }; let order = self.next_index; self.next_index += 1; @@ -778,8 +783,13 @@ impl Av1Encoder { /// As [`Av1Encoder::encode_frames`]. pub fn flush(&mut self) -> Result> { crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); - if let Some(previous) = self.held.take() { - return Ok(vec![self.encode_flat(&previous, None)?]); + if !self.held.is_empty() { + let mut packets = Vec::with_capacity(self.held.len()); + while let Some(previous) = self.held.pop_front() { + let window: Vec = self.held.iter().cloned().collect(); + packets.push(self.encode_flat(&previous, &window)?); + } + return Ok(packets); } self.drain_pending() } @@ -788,7 +798,7 @@ impl Av1Encoder { /// `None` at the end of the stream) in, one packet out — the same inputs /// [`crate::encode::encode_sequence`] gives each of its inter frames, so /// the bytes are identical. - fn encode_flat(&mut self, picture: &Picture, lookahead: Option<&Picture>) -> Result { + fn encode_flat(&mut self, picture: &Picture, lookahead: &[Picture]) -> Result { let render = (self.config.width, self.config.height); let padded = picture.padded_to(SUPERBLOCK); let is_key = self.next_index.is_multiple_of(self.config.gop as u64); @@ -836,7 +846,7 @@ impl Av1Encoder { self.prev2.as_ref(), &self.fctx, None, - lookahead.map(|n| n.padded_to(SUPERBLOCK)).as_ref(), + &lookahead.iter().map(|n| n.padded_to(SUPERBLOCK)).collect::>(), )? }; @@ -993,9 +1003,10 @@ impl Av1Encoder { show_frame, sign_bias, }), - // The streaming facade holds no lookahead buffer, so the - // temporal lambda weighting is off on this path (lane-av1tpl). - None, + // The pyramid path reorders pictures, so its own buffer is not + // a lookahead window: the temporal lambda weighting is off on + // this path (lane-av1tpl). + &[], ) }(); // Name the pyramid position in any failure: an error out of the tile // writer or the filter search is otherwise indistinguishable between @@ -1150,13 +1161,14 @@ mod tests { packets.iter().flat_map(|p| p.data.clone()).collect() } - /// The facade's latency contract (lane-av1facade): the first - /// [`Av1Encoder::encode`] call returns an empty packet, every later call - /// returns the PREVIOUS picture's packet, and [`Av1Encoder::flush`] - /// yields the last one — so a caller still gets exactly one non-empty - /// packet per picture, one call later. + /// The facade's latency contract (lane-av1facade, deepened on + /// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold + /// their picture back and return an empty packet, every later call + /// returns the packet of the picture that many frames earlier, and + /// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets + /// exactly one non-empty packet per picture, `depth - 1` calls later. #[test] - fn one_in_one_out_delayed_by_a_frame() { + fn one_in_one_out_delayed_by_the_lookahead_depth() { let config = EncoderConfig { width: 64, height: 64, @@ -1166,19 +1178,24 @@ mod tests { tile_cols_log2: 0, tile_rows_log2: 0, }; + let delay = crate::encode::tpl_depth() as u64 - 1; + let pictures = delay + 5; let mut enc = Av1Encoder::new(config).unwrap(); - for t in 0..5u64 { + for t in 0..pictures { let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); - if t == 0 { - assert!(packet.data.is_empty(), "the first call holds its picture back"); + if t < delay { + assert!(packet.data.is_empty(), "call {t} holds its picture back"); continue; } assert!(!packet.data.is_empty(), "picture {t}: empty packet"); - assert_eq!(packet.order, t - 1, "picture {t}: order"); + assert_eq!(packet.order, t - delay, "picture {t}: order"); } let tail = enc.flush().unwrap(); - assert_eq!(tail.len(), 1, "flush yields the last picture"); - assert_eq!(tail[0].order, 4); + assert_eq!(tail.len() as u64, delay, "flush yields the whole queue"); + for (i, p) in tail.iter().enumerate() { + assert_eq!(p.order, pictures - delay + i as u64, "flushed packet {i}: order"); + assert!(!p.data.is_empty(), "flushed packet {i}: empty"); + } assert!(enc.flush().unwrap().is_empty(), "nothing is held twice"); } diff --git a/lanes/tpl2-sweep.log b/lanes/tpl2-sweep.log new file mode 100644 index 00000000..4cee0d3c --- /dev/null +++ b/lanes/tpl2-sweep.log @@ -0,0 +1,28 @@ +=== k=0.25 d=4 === + Finished `release` profile [optimized] target(s) in 0.01s + Running unittests src/lib.rs (/home/user/.cache/cargo-target-av1tpl2/release/deps/ec_av1-8fef0196ab10338d) + +running 1 test + +native crop, 12 frames, gop=12; tiles (0, 0), tile threads 1, intrabc false, palette maxcolors 128 +| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) | +|---|---|---|---|---| +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 diff --git a/lanes/tpl2-sweep.sh b/lanes/tpl2-sweep.sh new file mode 100755 index 00000000..445db464 --- /dev/null +++ b/lanes/tpl2-sweep.sh @@ -0,0 +1,13 @@ +#!/bin/bash +cd $HOME/Documents/Code/Rust/edith_codecs-av1tpl2 || exit 1 +export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-av1tpl2 +L=lanes/tpl2-sweep.log +for d in 4 8; do + for k in 0.25 0.5 1 2; do + echo "=== k=$k d=$d ===" >> $L + timeout 900 env EC_COMP_MISMATCH=1 EC_AV1_TPL=$k EC_AV1_TPL_D=$d EC_AV1_TPL_HIST=1 \ + cargo test -p ec-av1 --release --lib -- --ignored bd_rate_screen_native --nocapture >> $L 2>&1 + echo "RC=$? k=$k d=$d" >> $L + done +done +echo SWEEPDONE >> $L