forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-arfpred' (bad02229): the top ARF is coded from a temporally filtered source (strength 3, off below anchor qindex 16); long-GOP film B +85.3/+6.7 to +79.0/+2.7; ARF prediction census; pins re-taken 8218 / 33017

Browse files at this commit

7c94ff1704e46efb10d61a8cac907765f637c311Ahmet Kaan GümüşParent: c200039cbb5336
crates/ec-av1/examples/syntax_census.rsmodified+10 -4
@@ -294,7 +294,7 @@ fn main() {
294 // the frames above are coded in (a pyramid codes a hidden ARF ahead of the294 // the frames above are coded in (a pyramid codes a hidden ARF ahead of the
295 // leaves that predict from it, and re-outputs it later with295 // leaves that predict from it, and re-outputs it later with
296 // `show_existing_frame`) -- so it is its own table rather than a column.296 // `show_existing_frame`) -- so it is its own table rather than a column.
297- let mut psnrs: Vec<f64> = Vec::new();297+ let mut psnrs: Vec<(f64, f64, f64)> = Vec::new();
298 if let Some(src) = args.get(1).map(|p| std::fs::read(p).expect("source")) {298 if let Some(src) = args.get(1).map(|p| std::fs::read(p).expect("source")) {
299 let mut sum = 0.0;299 let mut sum = 0.0;
300 let mut rows = Vec::new();300 let mut rows = Vec::new();
@@ -303,8 +303,13 @@ fn main() {
303 let frame_len = luma + 2 * chroma;303 let frame_len = luma + 2 * chroma;
304 let Some(b) = src.get(i * frame_len..(i + 1) * frame_len) else { break };304 let Some(b) = src.get(i * frame_len..(i + 1) * frame_len) else { break };
305 let want: Vec<u16> = b[..luma].iter().map(|&v| u16::from(v)).collect();305 let want: Vec<u16> = b[..luma].iter().map(|&v| u16::from(v)).collect();
306+ // lane-arfpred: the chroma planes too -- an anchor's byte gap can
307+ // sit in a plane the luma-only line cannot see (class
308+ // `metric blind to a plane`).
309+ let wu: Vec<u16> = b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect();
310+ let wv: Vec<u16> = b[luma + chroma..frame_len].iter().map(|&v| u16::from(v)).collect();
306 let p = psnr(&pic.y, &want);311 let p = psnr(&pic.y, &want);
307- psnrs.push(p);312+ psnrs.push((p, psnr(&pic.u, &wu), psnr(&pic.v, &wv)));
308 sum += p;313 sum += p;
309 rows.push(format!("{i}:{p:.2}"));314 rows.push(format!("{i}:{p:.2}"));
310 }315 }
@@ -321,7 +326,8 @@ fn main() {
321 // put next to the reference encoder's ARF at the same display position.326 // put next to the reference encoder's ARF at the same display position.
322 if std::env::var("EC_CENSUS_PERFRAME").as_deref() == Ok("1") {327 if std::env::var("EC_CENSUS_PERFRAME").as_deref() == Ok("1") {
323 for f in &frames {328 for f in &frames {
324- let p = psnrs.get(f.order_hint as usize).copied().unwrap_or(f64::NAN);329+ let (p, pu, pv) =
330+ psnrs.get(f.order_hint as usize).copied().unwrap_or((f64::NAN, f64::NAN, f64::NAN));
325 let refs: Vec<String> = (0..7)331 let refs: Vec<String> = (0..7)
326 .filter(|i| f.refs[i + 1] > 0)332 .filter(|i| f.refs[i + 1] > 0)
327 .map(|i| {333 .map(|i| {
@@ -334,7 +340,7 @@ fn main() {
334 .collect();340 .collect();
335 report(341 report(
336 &format!(342 &format!(
337- "frame {} {} hint {} q {} PSNR-Y {p:.2} dB refs [{}]",343+ "frame {} {} hint {} q {} PSNR-Y {p:.2} U {pu:.2} V {pv:.2} dB refs [{}]",
338 f.idx,344 f.idx,
339 f.kind,345 f.kind,
340 f.order_hint,346 f.order_hint,
crates/ec-av1/src/encode.rsmodified+315 -1
@@ -11334,6 +11334,149 @@ pub(crate) struct PyramidFrame {
11334 pub sign_bias: crate::mvstack::SignBiasTable,11334 pub sign_bias: crate::mvstack::SignBiasTable,
11335 }11335 }
11336 11336
11337+/// lane-arfpred: the temporal filter of a top ARF's SOURCE picture, libaom's
11338+/// `temporal_filter` in the small: every 16x16 luma block of `src` is
11339+/// motion-compensated from each picture of `window` (the group's own display
11340+/// neighbours, nearest first) and averaged in with weight
11341+/// `exp(-mse / strength)`, so a neighbour that matches badly contributes
11342+/// nothing and one that matches well cancels the grain the block's residual
11343+/// would otherwise have to code.
11344+///
11345+/// `strength` is [`crate::speed::ARF_TF`]; `0` never reaches here. Chroma
11346+/// rides the luma block's own vector (halved), which is what libaom does at
11347+/// this block size. The picture is the SUPERBLOCK-padded one, so the 16x16
11348+/// grid tiles it exactly.
11349+///
11350+/// Priced before it was built by `encode::tests::arf_pred_census`: on film B
11351+/// the filtered ARF's prediction SAD at lag 8 is 11.7% below the unfiltered
11352+/// one's (film A 5.9%) with the two past neighbours at strength 30, and the
11353+/// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the
11354+/// quality the ARF is coded at, so the substitution itself costs little.
11355+pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture {
11356+ const SIDE: usize = 16;
11357+ let neighbours: Vec<&Picture> = window
11358+ .iter()
11359+ .filter(|p| p.width == src.width && p.height == src.height)
11360+ .take(2)
11361+ .collect();
11362+ if neighbours.is_empty() || strength <= 0.0 {
11363+ return src.clone();
11364+ }
11365+ let mut out = src.clone();
11366+ // SAD of `src`'s block at `(bx, by)` against `r` displaced by `mv`, or
11367+ // `None` when the displaced block leaves the picture.
11368+ let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
11369+ let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
11370+ if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width {
11371+ return None;
11372+ }
11373+ let (sy, sx) = (sy as usize, sx as usize);
11374+ let mut acc = 0u64;
11375+ for row in 0..SIDE {
11376+ let c = &src.y[(by + row) * src.width + bx..][..SIDE];
11377+ let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
11378+ acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
11379+ }
11380+ Some((acc, (sy, sx)))
11381+ };
11382+ // The log-step diamond `arf_pred_census` priced this with.
11383+ let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> {
11384+ let mut best = sad(r, bx, by, (0, 0))?;
11385+ let mut centre = (0isize, 0isize);
11386+ let mut step = 16isize;
11387+ while step >= 1 {
11388+ let from = centre;
11389+ for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
11390+ let mv = (from.0 + dy * step, from.1 + dx * step);
11391+ if let Some(s) = sad(r, bx, by, mv) {
11392+ if s.0 < best.0 {
11393+ best = s;
11394+ centre = mv;
11395+ }
11396+ }
11397+ }
11398+ step /= 2;
11399+ }
11400+ Some(best.1)
11401+ };
11402+ let (cw, ch) = (src.width / 2, src.height / 2);
11403+ for by in (0..src.height).step_by(SIDE) {
11404+ for bx in (0..src.width).step_by(SIDE) {
11405+ if by + SIDE > src.height || bx + SIDE > src.width {
11406+ continue;
11407+ }
11408+ let mut y_acc = vec![0f64; SIDE * SIDE];
11409+ let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]];
11410+ let mut wsum = 1.0f64;
11411+ // Chroma keeps its OWN weight sum: an edge block whose halved
11412+ // vector leaves the chroma plane contributes to luma only, and
11413+ // dividing chroma by the luma sum would darken it (class
11414+ // `metric blind to a plane`, on the encoder side).
11415+ let mut cwsum = 1.0f64;
11416+ for row in 0..SIDE {
11417+ for col in 0..SIDE {
11418+ y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]);
11419+ }
11420+ }
11421+ for row in 0..SIDE / 2 {
11422+ for col in 0..SIDE / 2 {
11423+ let i = (by / 2 + row) * cw + bx / 2 + col;
11424+ c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]);
11425+ c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]);
11426+ }
11427+ }
11428+ for r in &neighbours {
11429+ let Some((sy, sx)) = search(r, bx, by) else { continue };
11430+ let mut sse = 0f64;
11431+ for row in 0..SIDE {
11432+ for col in 0..SIDE {
11433+ let d = f64::from(src.y[(by + row) * src.width + bx + col])
11434+ - f64::from(r.y[(sy + row) * r.width + sx + col]);
11435+ sse += d * d;
11436+ }
11437+ }
11438+ let w = (-sse / (SIDE * SIDE) as f64 / strength).exp();
11439+ for row in 0..SIDE {
11440+ for col in 0..SIDE {
11441+ y_acc[row * SIDE + col] +=
11442+ w * f64::from(r.y[(sy + row) * r.width + sx + col]);
11443+ }
11444+ }
11445+ // Chroma reads the luma vector halved; a block on the picture
11446+ // edge whose halved vector would leave the chroma plane is
11447+ // left to luma alone rather than clamped to a different
11448+ // displacement than the luma it must stay registered with.
11449+ let (cy, cx) = (sy / 2, sx / 2);
11450+ if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw {
11451+ for row in 0..SIDE / 2 {
11452+ for col in 0..SIDE / 2 {
11453+ let i = (cy + row) * cw + cx + col;
11454+ c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]);
11455+ c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]);
11456+ }
11457+ }
11458+ cwsum += w;
11459+ }
11460+ wsum += w;
11461+ }
11462+ for row in 0..SIDE {
11463+ for col in 0..SIDE {
11464+ out.y[(by + row) * src.width + bx + col] =
11465+ (y_acc[row * SIDE + col] / wsum).round() as u16;
11466+ }
11467+ }
11468+ for row in 0..SIDE / 2 {
11469+ for col in 0..SIDE / 2 {
11470+ let i = (by / 2 + row) * cw + bx / 2 + col;
11471+ out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16;
11472+ out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16;
11473+ }
11474+ }
11475+ }
11476+ }
11477+ out
11478+}
11479+
11337 /// Encodes one picture as an inter frame predicting from `reference`'s11480 /// Encodes one picture as an inter frame predicting from `reference`'s
11338 /// reconstruction, which the caller decoded (or, for the frame right after11481 /// reconstruction, which the caller decoded (or, for the frame right after
11339 /// the key frame, is the key frame's own reconstruction).11482 /// the key frame, is the key frame's own reconstruction).
@@ -16929,7 +17072,11 @@ mod tests {
16929 // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer17072 // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
16930 // grids -- and every decision priced against them -- moved:17073 // grids -- and every decision priced against them -- moved:
16931 // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.17074 // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
16932- let pins: [(u8, usize, u64); 2] = [(150, 8269, 0xf0a10bafe7b45fe2), (60, 33044, 0x077e9c22ff6f41fb)];17075+ // Re-taken on lane-arfpred: the top ARF is coded from a temporally
17076+ // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
17077+ // pixels -- and the leaves that predict from them -- moved:
17078+ // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
17079+ let pins: [(u8, usize, u64); 2] = [(150, 8218, 0xd533_c8ea_14ca_ae6e), (60, 33017, 0xbced_b694_dcfe_9146)];
16933 let coded: Vec<(u8, usize, u64)> = pins17080 let coded: Vec<(u8, usize, u64)> = pins
16934 .iter()17081 .iter()
16935 .map(|&(q, _, _)| {17082 .map(|&(q, _, _)| {
@@ -18660,6 +18807,173 @@ mod tests {
18660 }18807 }
18661 }18808 }
18662 18809
18810+ /// lane-arfpred: WHAT THE TOP ARF'S PREDICTION IS WORTH, and what a
18811+ /// temporal filter of its SOURCE would take off it, priced before any
18812+ /// encoder change (class `gate-blind-to-feature`).
18813+ ///
18814+ /// The stream census says our top ARF costs 6992 B a frame against
18815+ /// rav1e's 3872 at a COARSER quantizer (118 vs 104) for the same picture
18816+ /// quality, and that 61% of the gap is residual, not syntax. Two
18817+ /// explanations are separable here without an encoder: our anchor
18818+ /// predicts across 8 pictures where rav1e's predicts across 4 (lag), and
18819+ /// the residual it codes at that lag is dominated by film grain, which no
18820+ /// motion search can predict (source noise). So, per ARF position of the
18821+ /// gate's own 48-picture window:
18822+ ///
18823+ /// * mean full-pel SAD per pixel at lag 8 (ours) and lag 4 (rav1e's),
18824+ /// * the same at lag 8 with the CURRENT picture temporally filtered --
18825+ /// a libaom-shaped motion-compensated average of the +-2 display
18826+ /// neighbours, weights `exp(-mse / strength)` -- which is the residual
18827+ /// energy an ARF temporal filter would remove, and
18828+ /// * PSNR of that filtered picture against the unfiltered one, the
18829+ /// CEILING the filtered ARF's own PSNR is then measured under (the
18830+ /// BD gate scores against the unfiltered source).
18831+ ///
18832+ /// EC_ARF_TF_S=<strength> cargo test -p ec-av1 --release --lib -- \
18833+ /// --ignored arf_pred_census --nocapture
18834+ #[test]
18835+ #[ignore = "reads the real films"]
18836+ fn arf_pred_census() {
18837+ if !have_ffmpeg() {
18838+ eprintln!("SKIP arf_pred_census: no ffmpeg");
18839+ return;
18840+ }
18841+ const SIDE: usize = 16;
18842+ let strength: f64 = std::env::var("EC_ARF_TF_S")
18843+ .ok()
18844+ .and_then(|v| v.parse().ok())
18845+ .unwrap_or(30.0);
18846+ let past = std::env::var("EC_ARF_TF_PAST").as_deref() == Ok("1");
18847+ // SAD and the matching block of `r` at full-pel `(dy, dx)`, or `None`
18848+ // when the displaced block leaves the picture.
18849+ let at = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
18850+ let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
18851+ if sy < 0 || sx < 0 {
18852+ return None;
18853+ }
18854+ let (sy, sx) = (sy as usize, sx as usize);
18855+ if sy + SIDE > r.height || sx + SIDE > r.width {
18856+ return None;
18857+ }
18858+ let mut acc = 0u64;
18859+ for row in 0..SIDE {
18860+ let c = &cur[row * cw..][..SIDE];
18861+ let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
18862+ acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
18863+ }
18864+ Some((acc, (sy, sx)))
18865+ };
18866+ // The same log-step diamond `last2_census` uses, so the two censuses'
18867+ // SADs are comparable.
18868+ let search = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize| {
18869+ let mut best = match at(cur, cw, r, bx, by, (0, 0)) {
18870+ Some(v) => v,
18871+ None => return (u64::MAX, (by, bx)),
18872+ };
18873+ let mut centre = (0isize, 0isize);
18874+ let mut step = 16isize;
18875+ while step >= 1 {
18876+ let from = centre;
18877+ for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
18878+ let mv = (from.0 + dy * step, from.1 + dx * step);
18879+ if let Some(s) = at(cur, cw, r, bx, by, mv) {
18880+ if s.0 < best.0 {
18881+ best = s;
18882+ centre = mv;
18883+ }
18884+ }
18885+ }
18886+ step /= 2;
18887+ }
18888+ best
18889+ };
18890+ println!(
18891+ "| clip | ARFs | strength {strength} past {past} | lag8 SAD/px | lag4 SAD/px | tf lag8 SAD/px | tf removes | tf PSNR ceiling |"
18892+ );
18893+ println!("|---|---|---|---|---|---|---|");
18894+ for (name, path, seek) in native_gate_clips() {
18895+ if !name.starts_with("film ") {
18896+ continue;
18897+ }
18898+ let (vf, cw, ch) = crate::probe::gate_crop(&path);
18899+ let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 48);
18900+ let (mut n8, mut n4, mut ntf, mut px, mut arfs) = (0u64, 0u64, 0u64, 0u64, 0usize);
18901+ let (mut tf_sse, mut tf_px) = (0f64, 0u64);
18902+ for i in (8..pictures.len()).step_by(8) {
18903+ arfs += 1;
18904+ let cur = &pictures[i];
18905+ for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
18906+ for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
18907+ let block: Vec<u16> = (0..SIDE)
18908+ .flat_map(|row| cur.y[(by + row) * cur.width + bx..][..SIDE].to_vec())
18909+ .collect();
18910+ n8 += search(&block, SIDE, &pictures[i - 8], bx, by).0;
18911+ n4 += search(&block, SIDE, &pictures[i - 4], bx, by).0;
18912+ // The temporal filter: each +-2 display neighbour is
18913+ // motion-compensated onto this block and averaged in
18914+ // with libaom's shape, a weight that falls with the
18915+ // match's own mean squared error.
18916+ let mut acc: Vec<f64> = block.iter().map(|&v| f64::from(v)).collect();
18917+ let mut wsum = 1.0f64;
18918+ // `EC_ARF_TF_PAST=1` restricts the filter to the
18919+ // DISPLAY-PAST neighbours -- the only ones the
18920+ // encoder's own group buffer holds when it codes its
18921+ // top ARF (the group's future is not buffered yet).
18922+ let offs: &[isize] = match past {
18923+ true => &[-2, -1],
18924+ false => &[-2, -1, 1, 2],
18925+ };
18926+ for &d in offs {
18927+ let j = i as isize + d;
18928+ let Some(nb) = usize::try_from(j).ok().and_then(|j| pictures.get(j))
18929+ else {
18930+ continue;
18931+ };
18932+ let (_, (sy, sx)) = search(&block, SIDE, nb, bx, by);
18933+ let mut sse = 0f64;
18934+ for row in 0..SIDE {
18935+ for col in 0..SIDE {
18936+ let d = f64::from(block[row * SIDE + col])
18937+ - f64::from(nb.y[(sy + row) * nb.width + sx + col]);
18938+ sse += d * d;
18939+ }
18940+ }
18941+ let w = (-sse / ((SIDE * SIDE) as f64) / strength).exp();
18942+ for row in 0..SIDE {
18943+ for col in 0..SIDE {
18944+ acc[row * SIDE + col] +=
18945+ w * f64::from(nb.y[(sy + row) * nb.width + sx + col]);
18946+ }
18947+ }
18948+ wsum += w;
18949+ }
18950+ let filtered: Vec<u16> = acc
18951+ .iter()
18952+ .map(|v| (v / wsum).round().clamp(0.0, 1023.0) as u16)
18953+ .collect();
18954+ for (a, b) in filtered.iter().zip(&block) {
18955+ let d = f64::from(*a) - f64::from(*b);
18956+ tf_sse += d * d;
18957+ }
18958+ tf_px += (SIDE * SIDE) as u64;
18959+ ntf += search(&filtered, SIDE, &pictures[i - 8], bx, by).0;
18960+ px += (SIDE * SIDE) as u64;
18961+ }
18962+ }
18963+ }
18964+ let per = |v: u64| v as f64 / px.max(1) as f64;
18965+ let mse = tf_sse / tf_px.max(1) as f64;
18966+ println!(
18967+ "| {name} | {arfs} | s{strength} p{past} | {:.3} | {:.3} | {:.3} | {:.1}% | {:.2} dB |",
18968+ per(n8),
18969+ per(n4),
18970+ per(ntf),
18971+ 100.0 * (n8 - ntf) as f64 / n8.max(1) as f64,
18972+ 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(),
18973+ );
18974+ }
18975+ }
18976+
18663 /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to18977 /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
18664 /// hardwire the REGULAR kernel, so the encoder could not have coded a18978 /// hardwire the REGULAR kernel, so the encoder could not have coded a
18665 /// SMOOTH or SHARP frame even if the header had said so -- the search,18979 /// SMOOTH or SHARP frame even if the header had said so -- the search,
crates/ec-av1/src/encoder.rsmodified+29 -1
@@ -1067,6 +1067,16 @@ const KEY_DEFAULT: i16 = -48;
1067 /// shipped on the flat path -- was inert on every frame of every pyramid1067 /// shipped on the flat path -- was inert on every frame of every pyramid
1068 /// stream, including the ARFs that carry 54% of a long-GOP stream's bytes1068 /// stream, including the ARFs that carry 54% of a long-GOP stream's bytes
1069 /// (class `tool disabled in every gate recipe`).1069 /// (class `tool disabled in every gate recipe`).
1070+/// lane-arfpred: the top ARF source temporal filter's strength
1071+/// ([`crate::speed::ARF_TF`]), `EC_AV1_ARF_TF=<strength>` overriding it;
1072+/// `0` is off.
1073+fn arf_tf_strength() -> f64 {
1074+ std::env::var("EC_AV1_ARF_TF")
1075+ .ok()
1076+ .and_then(|v| v.parse().ok())
1077+ .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF))
1078+}
1079+
1070 fn tpl_pyramid() -> bool {1080 fn tpl_pyramid() -> bool {
1071 match std::env::var("EC_AV1_TPL_PYRAMID").ok() {1081 match std::env::var("EC_AV1_TPL_PYRAMID").ok() {
1072 Some(v) => v != "0",1082 Some(v) => v != "0",
@@ -1782,8 +1792,26 @@ impl Av1Encoder {
1782 .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone()))1792 .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone()))
1783 .flatten();1793 .flatten();
1784 let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone());1794 let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone());
1795+ // lane-arfpred: the top ARF is coded from a TEMPORALLY FILTERED
1796+ // source when `speed::ARF_TF` is non-zero -- the grain it would
1797+ // otherwise spend its residual on is averaged out against the
1798+ // group's own display neighbours (`lookahead`, already padded).
1799+ let source = picture.padded_to(SUPERBLOCK);
1800+ // ... and never at the very top of the quality range, where the
1801+ // anchor's own quantizer has hit the rate loop's floor
1802+ // ([`crate::speed::ARF_TF_QMIN`]).
1803+ let tf = match base_q_idx >= crate::speed::ARF_TF_QMIN {
1804+ true => arf_tf_strength(),
1805+ false => 0.0,
1806+ };
1807+ let source = match (tf > 0.0, dq_level) {
1808+ (true, crate::encode::DqLevel::TopArf) => {
1809+ crate::encode::arf_temporal_filter(&source, lookahead, tf)
1810+ }
1811+ _ => source,
1812+ };
1785 let encoded = || -> Result<Encoded> { encode_inter_frame(1813 let encoded = || -> Result<Encoded> { encode_inter_frame(
1786- &picture.padded_to(SUPERBLOCK),1814+ &source,
1787 &reference,1815 &reference,
1788 base_q_idx,1816 base_q_idx,
1789 DEADZONE,1817 DEADZONE,
crates/ec-av1/src/speed.rsmodified+43 -0
@@ -366,6 +366,49 @@ pub(crate) const DQ_TPL_K: [f64; 11] = [0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
366 /// `lanes/arfq.report.md`.366 /// `lanes/arfq.report.md`.
367 pub(crate) const DQ_LEVEL_K: [f64; 3] = [1.5, 1.0, 1.0];367 pub(crate) const DQ_LEVEL_K: [f64; 3] = [1.5, 1.0, 1.0];
368 368
369+/// lane-arfpred: the strength of the top ARF's SOURCE temporal filter
370+/// ([`crate::encode::arf_temporal_filter`]) -- `0` is off, higher filters
371+/// harder (the weight of a motion-compensated neighbour is
372+/// `exp(-mse / strength)`). `EC_AV1_ARF_TF=<strength>` overrides it.
373+///
374+/// The top ARF carries 55% of a 48-picture film B stream at 6992 B a frame
375+/// against rav1e's 3872 at a FINER quantizer, and the per-frame census says
376+/// 61% of that gap is residual, not syntax -- while `arf_pred_census` says
377+/// the anchor's own lag is worth only 7% of its prediction SAD (lag 8 1.199
378+/// vs lag 4 1.114 per pixel), so what the residual codes is mostly source
379+/// grain. Filtering it out of the picture the anchor is coded from is the
380+/// mechanism libaom uses (`arnr`) and rav1e 0.8.1 does not have at all.
381+/// Long-GOP gate (48 pictures, BD vs libaom / rav1e), strength 3 against the
382+/// control: film A +23.5/-8.0 -> **+22.7/-7.9**, film B +85.3/+6.7 ->
383+/// **+79.0/+2.7**. Film B takes 6.3 and 4.0 points off; film A takes 0.8 off
384+/// the libaom column and hands back 0.1 on the rav1e one, which is the
385+/// keep rule's "one column >=0.5 down, the other flat" clause. It is also
386+/// FASTER (film B two-point probe 167 s -> 147 s): the anchor has fewer
387+/// coefficients to code. Uniform over the presets -- above preset 6
388+/// [`TPL_DEPTH`] leaves the group window empty and the filter is inert by
389+/// construction.
390+///
391+/// Strength is single-peaked and SHARP: the film B two-point probe reads
392+/// -1.4% bytes at equal PSNR at 3, +3.4% at 8, +6.9% at 15 and +15.8% at 30
393+/// (`lanes/arfpred.report.md` section 3). Hard filtering does remove 6-7% of
394+/// the stream's bytes and gives all of it back in quality, because the leaves
395+/// still carry the grain the anchor no longer has.
396+pub(crate) const ARF_TF: [f64; 11] = [3.0; 11];
397+
398+/// lane-arfpred: the qindex below which the ARF temporal filter is OFF --
399+/// libaom scales `arnr` strength with the quantizer and stops filtering at
400+/// the high-quality end for the same reason: a picture we are about to
401+/// reproduce almost exactly should not have detail averaged out of it first.
402+///
403+/// 16 is under the gate's own finest anchor (its `q = 60` ladder point codes
404+/// the top ARF at qindex 28) and over the rate-loop floor a high bitrate
405+/// target drives the anchor to. `encoder::tests::bitrate_target_lands_within_5/// _percent_over_48_frames` is what named the floor: at 2 Mbps on the 640x384
406+/// fixture the loop codes IDENTICAL 22237-byte anchors as at 1536 kbps, i.e.
407+/// the anchor's `base_q_idx + arf_q_offset` has clamped to 1 and the loop
408+/// cannot spend the target's remaining bytes -- and a cheaper (filtered)
409+/// anchor there makes the miss worse, not better.
410+pub(crate) const ARF_TF_QMIN: u8 = 16;
411+
369 /// `encode::SPLIT_RD_THRESHOLD`: how cheap a block has to be before its split412 /// `encode::SPLIT_RD_THRESHOLD`: how cheap a block has to be before its split
370 /// trial is withheld. The single biggest wall lever in the tile search.413 /// trial is withheld. The single biggest wall lever in the tile search.
371 pub(crate) const SPLIT_RD: [f64; 11] = [414 pub(crate) const SPLIT_RD: [f64; 11] = [
lanes/arfpred.report.mdadded+183 -0
@@ -0,0 +1,183 @@
1+# lane-arfpred — the top ARF's PREDICTION, and a temporal filter of its source
2+
3+Worktree `edith_codecs-arfpred`, branch `lane-arfpred` off main `35874aef`.
4+Deciding gate `encode::tests::bd_rate_film_long_gop` (48 pictures, both film
5+rows, BD vs libaom `cpu-used 6` / rav1e `speed 6`). **The control was RUN, not
6+quoted: film A +23.5 / −8.0, film B +85.3 / +6.7 — the charter's numbers to
7+the digit.**
8+
9+## 0. The matched-rate point (film B, 48 pictures, the gate's own window)
10+
11+| stream | bytes | PSNR-Y |
12+|---|---|---|
13+| ours `q150` (this HEAD) | 76409 | 45.564 |
14+| rav1e `speed 6 quantizer 110` | 75452 | 45.751 |
15+| libaom `cpu-used 6 crf 34` | 70345 | 46.539 |
16+
17+Ours is +1.3% bytes for −0.19 dB against rav1e; every table below is read by
18+OUR decoder (`EC_AV1_BITCENSUS=1 EC_CENSUS_PERFRAME=1 syntax_census`), so all
19+three streams are measured by the same reader. `syntax_census` now prints
20+per-plane PSNR (`PSNR-Y ... U ... V`) per coded frame.
21+
22+## 1. Per-level census — bytes per FAMILY per frame (B/frame)
23+
24+| level | n | q | B/frame | PSNR-Y | U | V | intra% | comp% | skip% | NEW% | blocks/f | coeff | literal | mode | mv | part |
25+|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26+| **ours top ARF** | 6 | 118 | **6992** | 45.88 | 51.60 | 51.91 | 4.7 | 20.4 | 61.4 | 38.7 | 2196 | 3483 | 1151 | 1323 | 700 | 281 |
27+| **rav1e L1 ARF** | 11 | 104 | **3872** | 45.97 | 51.61 | 52.01 | 0.5 | 0.0 | 80.7 | 26.0 | 1507 | 1996 | 730 | 608 | 410 | 125 |
28+| ours mid ARF | 6 | 142 | 1354 | 45.74 | 51.69 | 51.96 | 0.4 | 58.1 | 88.9 | 41.0 | 954 | 343 | 104 | 450 | 356 | 92 |
29+| rav1e L2 | 12 | 122 | 537 | 45.48 | 51.60 | 52.02 | 0.1 | 52.7 | 98.7 | 21.1 | 732 | 60 | 20 | 228 | 186 | 41 |
30+| ours leaf | 35 | 162 | 267 | 45.43 | 51.60 | 51.96 | 0.0 | 56.5 | 98.0 | 27.5 | 552 | 24 | 6 | 142 | 73 | 18 |
31+| rav1e leaf | 24 | 139 | 179 | 45.69 | 51.55 | 52.06 | 0.0 | 62.5 | 99.8 | 16.7 | 528 | 6 | 1 | 103 | 55 | 11 |
32+| ours key | 1 | 102 | 15827 | 47.34 | 51.94 | 52.26 | 100 | 0 | 0 | — | 1479 | 10666 | 3788 | 1046 | 0 | 148 |
33+| rav1e key | 1 | 80 | 20763 | 47.95 | 51.94 | 52.45 | 100 | 0 | 0 | — | 1266 | 14646 | 5102 | 828 | 0 | 140 |
34+
35+**WHERE THE +3120 B/frame GOES** (top ARF, ours − rav1e): residual
36+(coeff+literal) **+1908 B = 61%**, mode+partition **+871 B = 28%**, mv
37+**+290 B = 9%**.
38+
39+Three readings the charter asked for, in one line each:
40+
41+* **NOT the quantizer.** rav1e codes its anchor at a FINER qindex than ours
42+ (104 vs 118) and still spends 45% of our bytes for +0.09 dB. Nothing on the
43+ q axis explains this (and lane-arfq refuted the offsets twice).
44+* **NOT chroma.** Per-plane PSNR at the anchor is 51.60/51.91 ours against
45+ 51.61/52.01 rav1e's — matched to a hundredth. The whole deficit is luma.
46+* **NOT intra fallback.** Our anchor codes 4.7% of its AREA intra where
47+ rav1e codes 0.5% (lane-arfcen read 8-10% before the merges since), so the
48+ ceiling of an intra-decision lever at this level is a few percent of one
49+ level — the same order as its own noise.
50+
51+What is left is the residual, and its two possible causes are the anchor's
52+LAG (we predict across 8 pictures, rav1e across 4) and the SOURCE the
53+residual is coding.
54+
55+## 2. `arf_pred_census` — pricing lag against source grain (new instrument)
56+
57+`encode::tests::arf_pred_census` (`--ignored`, 6 s, no encoder change): every
58+16x16 luma block of every ARF position of the gate's own 48-picture window
59+gets the SAME log-step diamond search (`last2_census`'s) against the picture
60+8 back, the picture 4 back, and — with the block temporally filtered first —
61+the picture 8 back again.
62+
63+| clip | ARFs | lag 8 SAD/px | lag 4 SAD/px | tf lag 8 SAD/px | tf removes | filtered-vs-source PSNR |
64+|---|---|---|---|---|---|---|
65+| film A | 5 | 2.484 | 2.369 | 2.337 | 5.9% | 48.30 dB |
66+| film B | 5 | 1.199 | 1.114 | 1.059 | 11.7% | 50.14 dB |
67+
68+(strength 30, the two DISPLAY-PAST neighbours — the only ones the encoder's
69+own group buffer holds when it codes its top ARF. With ±2 both sides it is
70+6.8% / 14.3% at 47.74 / 49.54 dB; strengths 10/30/60/120 are in
71+`$HOME/.cache/arfpred/predsweep.log`.)
72+
73+**THE LAG IS NOT THE CAUSE.** Halving the anchor's prediction distance —
74+rav1e's whole structural advantage at this level — is worth 7.1% of the
75+prediction SAD on film B and 4.6% on film A, where the byte gap is 81%. What
76+our anchor's residual codes is mostly SOURCE GRAIN, which no motion search at
77+any lag can predict; a motion-compensated average of the neighbours removes
78+1.6x more of it than the lag does.
79+
80+## 3. The lever: `arf_temporal_filter` (libaom's `arnr` in the small)
81+
82+Built (`encode::arf_temporal_filter`, `speed::ARF_TF`,
83+`EC_AV1_ARF_TF=<strength>`): the top ARF's source picture is replaced by a
84+motion-compensated average of itself and its two group-buffered display
85+neighbours, weight `exp(-mse / strength)` per 16x16 block, chroma on the
86+halved luma vector with its own weight sum. **rav1e 0.8.1 has NO temporal
87+filter at all** (`grep -rn "temporal_filter\|arnr" rav1e-0.8.1/src` — empty),
88+so this is a libaom-only mechanism, not the thing rav1e beats us with.
89+
90+Probe ladder, film B 48 pictures, `q150` and `q90`, each arm judged at the
91+CONTROL's own PSNR through the arm's own two-point slope (arfcen's rule):
92+
93+| strength | q150 B / dB | q90 B / dB | slope dB/doubling | bytes at 45.564 dB | vs control |
94+|---|---|---|---|---|---|
95+| 0 (control) | 76409 / 45.564 | 346678 / 47.838 | 1.042 | 76409 | — |
96+| **3** | 72278 / 45.498 | 308172 / 47.759 | 1.081 | **75378** | **−1.35%** |
97+| 8 | 71636 / 45.413 | 308366 / 47.669 | 1.071 | 78996 | +3.4% |
98+| 15 | 70975 / 45.351 | 312607 / 47.606 | 1.054 | 81657 | +6.9% |
99+| 30 | 71814 / 45.246 | 321413 / 47.533 | 1.058 | 88453 | +15.8% |
100+| 60 | 73252 / 45.158 | 331390 / 47.470 | — | — | worse still |
101+
102+The filter does exactly what the census said it would — 6-7% of the stream's
103+bytes come off at strength 15-30 — and the BD metric takes it straight back,
104+because the gate scores PSNR against the UNFILTERED source and the leaves
105+still carry the grain the anchor no longer has. Note the non-monotone byte
106+column: past strength 15 the stream gets BIGGER again, which is the leaves
107+paying for a reference that no longer resembles their own sources.
108+
109+## 4. The gate — the lever SHIPS at strength 3
110+
111+`encode::tests::bd_rate_film_long_gop`, 48 pictures, BD vs libaom `cpu-used 6`
112+/ rav1e `speed 6` (lower is better):
113+
114+| arm | film A | film B |
115+|---|---|---|
116+| control (`EC_AV1_ARF_TF=0`) | +23.5 / −8.0 | +85.3 / +6.7 |
117+| **`ARF_TF = 3` (ships)** | **+22.7 / −7.9** | **+79.0 / +2.7** |
118+
119+Film B takes **6.3 points off the libaom column and 4.0 off rav1e's** — the
120+biggest single move any lane has made on that row since the pyramid itself —
121+and film A takes 0.8 off the libaom column while handing back 0.1 on rav1e's,
122+which is the keep rule's "one column ≥0.5 down, the other flat ±0.3" clause.
123+It is also FASTER (film B two-point probe 167 s → 147 s).
124+
125+Guard gate `bd_rate_screen_native` (12 pictures, all five rows), against the
126+charter's controls:
127+
128+| clip | control | `ARF_TF = 3` | Δ |
129+|---|---|---|---|
130+| bars 1080p | −3.1 / −18.7 | −2.9 / −18.6 | +0.2 / +0.1 |
131+| bars 2160p | +9.1 / −13.3 | +9.1 / −13.3 | 0.0 / 0.0 |
132+| film A | +20.3 / −4.9 | **+18.3 / −6.0** | **−2.0 / −1.1** |
133+| film B | +24.7 / −1.8 | **+24.6 / −2.1** | −0.1 / −0.3 |
134+| screen capture | +14.6 / −33.2 | +14.6 / −33.2 | byte-identical |
135+
136+Every real-content row improves; the two colour-bar rows move 0.2 and 0.0
137+(inside the 0.3 bound), and the screen capture is byte-identical — its
138+sequence codes no pyramid ARF at all, so the filter never runs there.
139+
140+## 5. Where the filter is OFF — `ARF_TF_QMIN`
141+
142+The filter runs on the top ARF of every preset (above preset 6 `TPL_DEPTH`
143+leaves the group window empty and it is inert by construction) **except when
144+the anchor's own `base_q_idx` is below 16** (`speed::ARF_TF_QMIN`), which is
145+libaom's own rule for `arnr` and is what a red test named:
146+
147+`encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames` codes
148+its 2 Mbps pyramid arm with IDENTICAL 22358-byte anchors to its 1536 kbps arm
149+— the rate loop has clamped `base_q_idx + arf_q_offset` to 1 and cannot spend
150+the target's remaining bytes at all, so that arm sits at −4.8% of target
151+BEFORE this lane touches anything (measured: `EC_AV1_ARF_TF=0`, −4.8%). A
152+cheaper anchor there made the miss −5.1%, outside the test's ±5% bound. With
153+`ARF_TF_QMIN = 16` the arm reads **−4.8%, the control's own number**, and the
154+gate is untouched: its finest ladder point (`q = 60`) codes the top ARF at
155+qindex 28, and both byte pins are unchanged by the threshold.
156+
157+## 6. Invariants
158+
159+* Byte pins re-taken (the hidden frames' pixels move by construction):
160+ `(150, 8269 → 8218)`, `(60, 33044 → 33017)`; green at the default AND at
161+ `EC_AV1_SPEED=6`, and unchanged again after `ARF_TF_QMIN` landed.
162+* Split suite on the shipped default: `--skip stream::` **342 passed / 0 failed**, `stream::
163+ --skip 10bit` **201 passed / 0 failed**, `10bit` **42 passed / 0 failed** (585 in all).
164+* `cargo check --workspace --all-targets -j4`: 0 errors, 0 `ec-av1` warnings
165+ (the 25 warnings are `ec-opus`/`ec-vorbis`, pre-existing).
166+* `--ignored --exact encoder::tests::every_speed_preset_decodes_sample_exact_through_both_decoders`
167+ 1 passed.
168+
169+## 7. What this lane did NOT do
170+
171+* `deferred: a strength sweep ON THE GATE — only 3 was taken to the deciding
172+ gate; 8/15/30/60 were refuted on the two-point probe, which mispredicted
173+ the SIGN of 3's gate result (probe −1.4% bytes, gate −6.3 BD points), so the
174+ probe is a weak proxy for this lever — unblocked by a lane that can afford
175+ three more 30-minute long-GOP arms (1, 2, 5).`
176+* `deferred: the filter window — the encoder's group buffer holds only the two
177+ DISPLAY-PAST neighbours when it codes its top ARF; the census says ±2 both
178+ sides removes 14.3% of the prediction SAD against past-only's 11.7%, so a
179+ one-group lookahead is worth a lane — unblocked by a lane that reorders the
180+ encoder's picture buffer.`
181+* `deferred: the ARF's mode/partition gap (+871 B a frame, 2196 blocks against
182+ rav1e's 1507) — this lane's lever is the residual half of the census —
183+ unblocked by the 128-root lane (parked) or a partition lane at the anchor.`