diff --git a/crates/ec-av1/examples/syntax_census.rs b/crates/ec-av1/examples/syntax_census.rs index 86ebe6ae..fc018240 100644 --- a/crates/ec-av1/examples/syntax_census.rs +++ b/crates/ec-av1/examples/syntax_census.rs @@ -294,7 +294,7 @@ fn main() { // the frames above are coded in (a pyramid codes a hidden ARF ahead of the // leaves that predict from it, and re-outputs it later with // `show_existing_frame`) -- so it is its own table rather than a column. - let mut psnrs: Vec = Vec::new(); + let mut psnrs: Vec<(f64, f64, f64)> = Vec::new(); if let Some(src) = args.get(1).map(|p| std::fs::read(p).expect("source")) { let mut sum = 0.0; let mut rows = Vec::new(); @@ -303,8 +303,13 @@ fn main() { let frame_len = luma + 2 * chroma; let Some(b) = src.get(i * frame_len..(i + 1) * frame_len) else { break }; let want: Vec = b[..luma].iter().map(|&v| u16::from(v)).collect(); + // lane-arfpred: the chroma planes too -- an anchor's byte gap can + // sit in a plane the luma-only line cannot see (class + // `metric blind to a plane`). + let wu: Vec = b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(); + let wv: Vec = b[luma + chroma..frame_len].iter().map(|&v| u16::from(v)).collect(); let p = psnr(&pic.y, &want); - psnrs.push(p); + psnrs.push((p, psnr(&pic.u, &wu), psnr(&pic.v, &wv))); sum += p; rows.push(format!("{i}:{p:.2}")); } @@ -321,7 +326,8 @@ fn main() { // put next to the reference encoder's ARF at the same display position. if std::env::var("EC_CENSUS_PERFRAME").as_deref() == Ok("1") { for f in &frames { - let p = psnrs.get(f.order_hint as usize).copied().unwrap_or(f64::NAN); + let (p, pu, pv) = + psnrs.get(f.order_hint as usize).copied().unwrap_or((f64::NAN, f64::NAN, f64::NAN)); let refs: Vec = (0..7) .filter(|i| f.refs[i + 1] > 0) .map(|i| { @@ -334,7 +340,7 @@ fn main() { .collect(); report( &format!( - "frame {} {} hint {} q {} PSNR-Y {p:.2} dB refs [{}]", + "frame {} {} hint {} q {} PSNR-Y {p:.2} U {pu:.2} V {pv:.2} dB refs [{}]", f.idx, f.kind, f.order_hint, diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 889dc2ff..8bb6ab73 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -11334,6 +11334,149 @@ pub(crate) struct PyramidFrame { pub sign_bias: crate::mvstack::SignBiasTable, } +/// lane-arfpred: the temporal filter of a top ARF's SOURCE picture, libaom's +/// `temporal_filter` in the small: every 16x16 luma block of `src` is +/// motion-compensated from each picture of `window` (the group's own display +/// neighbours, nearest first) and averaged in with weight +/// `exp(-mse / strength)`, so a neighbour that matches badly contributes +/// nothing and one that matches well cancels the grain the block's residual +/// would otherwise have to code. +/// +/// `strength` is [`crate::speed::ARF_TF`]; `0` never reaches here. Chroma +/// rides the luma block's own vector (halved), which is what libaom does at +/// this block size. The picture is the SUPERBLOCK-padded one, so the 16x16 +/// grid tiles it exactly. +/// +/// Priced before it was built by `encode::tests::arf_pred_census`: on film B +/// the filtered ARF's prediction SAD at lag 8 is 11.7% below the unfiltered +/// one's (film A 5.9%) with the two past neighbours at strength 30, and the +/// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the +/// quality the ARF is coded at, so the substitution itself costs little. +pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture { + const SIDE: usize = 16; + let neighbours: Vec<&Picture> = window + .iter() + .filter(|p| p.width == src.width && p.height == src.height) + .take(2) + .collect(); + if neighbours.is_empty() || strength <= 0.0 { + return src.clone(); + } + let mut out = src.clone(); + // SAD of `src`'s block at `(bx, by)` against `r` displaced by `mv`, or + // `None` when the displaced block leaves the picture. + let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| { + let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1); + if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width { + return None; + } + let (sy, sx) = (sy as usize, sx as usize); + let mut acc = 0u64; + for row in 0..SIDE { + let c = &src.y[(by + row) * src.width + bx..][..SIDE]; + let p = &r.y[(sy + row) * r.width + sx..][..SIDE]; + acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::(); + } + Some((acc, (sy, sx))) + }; + // The log-step diamond `arf_pred_census` priced this with. + let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> { + let mut best = sad(r, bx, by, (0, 0))?; + let mut centre = (0isize, 0isize); + let mut step = 16isize; + while step >= 1 { + let from = centre; + for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] { + let mv = (from.0 + dy * step, from.1 + dx * step); + if let Some(s) = sad(r, bx, by, mv) { + if s.0 < best.0 { + best = s; + centre = mv; + } + } + } + step /= 2; + } + Some(best.1) + }; + let (cw, ch) = (src.width / 2, src.height / 2); + for by in (0..src.height).step_by(SIDE) { + for bx in (0..src.width).step_by(SIDE) { + if by + SIDE > src.height || bx + SIDE > src.width { + continue; + } + let mut y_acc = vec![0f64; SIDE * SIDE]; + let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]]; + let mut wsum = 1.0f64; + // Chroma keeps its OWN weight sum: an edge block whose halved + // vector leaves the chroma plane contributes to luma only, and + // dividing chroma by the luma sum would darken it (class + // `metric blind to a plane`, on the encoder side). + let mut cwsum = 1.0f64; + for row in 0..SIDE { + for col in 0..SIDE { + y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]); + } + } + for row in 0..SIDE / 2 { + for col in 0..SIDE / 2 { + let i = (by / 2 + row) * cw + bx / 2 + col; + c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]); + c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]); + } + } + for r in &neighbours { + let Some((sy, sx)) = search(r, bx, by) else { continue }; + let mut sse = 0f64; + for row in 0..SIDE { + for col in 0..SIDE { + let d = f64::from(src.y[(by + row) * src.width + bx + col]) + - f64::from(r.y[(sy + row) * r.width + sx + col]); + sse += d * d; + } + } + let w = (-sse / (SIDE * SIDE) as f64 / strength).exp(); + for row in 0..SIDE { + for col in 0..SIDE { + y_acc[row * SIDE + col] += + w * f64::from(r.y[(sy + row) * r.width + sx + col]); + } + } + // Chroma reads the luma vector halved; a block on the picture + // edge whose halved vector would leave the chroma plane is + // left to luma alone rather than clamped to a different + // displacement than the luma it must stay registered with. + let (cy, cx) = (sy / 2, sx / 2); + if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw { + for row in 0..SIDE / 2 { + for col in 0..SIDE / 2 { + let i = (cy + row) * cw + cx + col; + c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]); + c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]); + } + } + cwsum += w; + } + wsum += w; + } + for row in 0..SIDE { + for col in 0..SIDE { + out.y[(by + row) * src.width + bx + col] = + (y_acc[row * SIDE + col] / wsum).round() as u16; + } + } + for row in 0..SIDE / 2 { + for col in 0..SIDE / 2 { + let i = (by / 2 + row) * cw + bx / 2 + col; + out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16; + out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16; + } + } + } + } + out +} + /// Encodes one picture as an inter frame predicting from `reference`'s /// reconstruction, which the caller decoded (or, for the frame right after /// the key frame, is the key frame's own reconstruction). @@ -16929,7 +17072,11 @@ mod tests { // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer // grids -- and every decision priced against them -- moved: // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60. - let pins: [(u8, usize, u64); 2] = [(150, 8269, 0xf0a10bafe7b45fe2), (60, 33044, 0x077e9c22ff6f41fb)]; + // Re-taken on lane-arfpred: the top ARF is coded from a temporally + // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's + // pixels -- and the leaves that predict from them -- moved: + // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60. + let pins: [(u8, usize, u64); 2] = [(150, 8218, 0xd533_c8ea_14ca_ae6e), (60, 33017, 0xbced_b694_dcfe_9146)]; let coded: Vec<(u8, usize, u64)> = pins .iter() .map(|&(q, _, _)| { @@ -18660,6 +18807,173 @@ mod tests { } } + /// lane-arfpred: WHAT THE TOP ARF'S PREDICTION IS WORTH, and what a + /// temporal filter of its SOURCE would take off it, priced before any + /// encoder change (class `gate-blind-to-feature`). + /// + /// The stream census says our top ARF costs 6992 B a frame against + /// rav1e's 3872 at a COARSER quantizer (118 vs 104) for the same picture + /// quality, and that 61% of the gap is residual, not syntax. Two + /// explanations are separable here without an encoder: our anchor + /// predicts across 8 pictures where rav1e's predicts across 4 (lag), and + /// the residual it codes at that lag is dominated by film grain, which no + /// motion search can predict (source noise). So, per ARF position of the + /// gate's own 48-picture window: + /// + /// * mean full-pel SAD per pixel at lag 8 (ours) and lag 4 (rav1e's), + /// * the same at lag 8 with the CURRENT picture temporally filtered -- + /// a libaom-shaped motion-compensated average of the +-2 display + /// neighbours, weights `exp(-mse / strength)` -- which is the residual + /// energy an ARF temporal filter would remove, and + /// * PSNR of that filtered picture against the unfiltered one, the + /// CEILING the filtered ARF's own PSNR is then measured under (the + /// BD gate scores against the unfiltered source). + /// + /// EC_ARF_TF_S= cargo test -p ec-av1 --release --lib -- \ + /// --ignored arf_pred_census --nocapture + #[test] + #[ignore = "reads the real films"] + fn arf_pred_census() { + if !have_ffmpeg() { + eprintln!("SKIP arf_pred_census: no ffmpeg"); + return; + } + const SIDE: usize = 16; + let strength: f64 = std::env::var("EC_ARF_TF_S") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(30.0); + let past = std::env::var("EC_ARF_TF_PAST").as_deref() == Ok("1"); + // SAD and the matching block of `r` at full-pel `(dy, dx)`, or `None` + // when the displaced block leaves the picture. + let at = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| { + let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1); + if sy < 0 || sx < 0 { + return None; + } + let (sy, sx) = (sy as usize, sx as usize); + if sy + SIDE > r.height || sx + SIDE > r.width { + return None; + } + let mut acc = 0u64; + for row in 0..SIDE { + let c = &cur[row * cw..][..SIDE]; + let p = &r.y[(sy + row) * r.width + sx..][..SIDE]; + acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::(); + } + Some((acc, (sy, sx))) + }; + // The same log-step diamond `last2_census` uses, so the two censuses' + // SADs are comparable. + let search = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize| { + let mut best = match at(cur, cw, r, bx, by, (0, 0)) { + Some(v) => v, + None => return (u64::MAX, (by, bx)), + }; + let mut centre = (0isize, 0isize); + let mut step = 16isize; + while step >= 1 { + let from = centre; + for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] { + let mv = (from.0 + dy * step, from.1 + dx * step); + if let Some(s) = at(cur, cw, r, bx, by, mv) { + if s.0 < best.0 { + best = s; + centre = mv; + } + } + } + step /= 2; + } + best + }; + println!( + "| clip | ARFs | strength {strength} past {past} | lag8 SAD/px | lag4 SAD/px | tf lag8 SAD/px | tf removes | tf PSNR ceiling |" + ); + println!("|---|---|---|---|---|---|---|"); + for (name, path, seek) in native_gate_clips() { + if !name.starts_with("film ") { + continue; + } + let (vf, cw, ch) = crate::probe::gate_crop(&path); + let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 48); + let (mut n8, mut n4, mut ntf, mut px, mut arfs) = (0u64, 0u64, 0u64, 0u64, 0usize); + let (mut tf_sse, mut tf_px) = (0f64, 0u64); + for i in (8..pictures.len()).step_by(8) { + arfs += 1; + let cur = &pictures[i]; + for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) { + for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) { + let block: Vec = (0..SIDE) + .flat_map(|row| cur.y[(by + row) * cur.width + bx..][..SIDE].to_vec()) + .collect(); + n8 += search(&block, SIDE, &pictures[i - 8], bx, by).0; + n4 += search(&block, SIDE, &pictures[i - 4], bx, by).0; + // The temporal filter: each +-2 display neighbour is + // motion-compensated onto this block and averaged in + // with libaom's shape, a weight that falls with the + // match's own mean squared error. + let mut acc: Vec = block.iter().map(|&v| f64::from(v)).collect(); + let mut wsum = 1.0f64; + // `EC_ARF_TF_PAST=1` restricts the filter to the + // DISPLAY-PAST neighbours -- the only ones the + // encoder's own group buffer holds when it codes its + // top ARF (the group's future is not buffered yet). + let offs: &[isize] = match past { + true => &[-2, -1], + false => &[-2, -1, 1, 2], + }; + for &d in offs { + let j = i as isize + d; + let Some(nb) = usize::try_from(j).ok().and_then(|j| pictures.get(j)) + else { + continue; + }; + let (_, (sy, sx)) = search(&block, SIDE, nb, bx, by); + let mut sse = 0f64; + for row in 0..SIDE { + for col in 0..SIDE { + let d = f64::from(block[row * SIDE + col]) + - f64::from(nb.y[(sy + row) * nb.width + sx + col]); + sse += d * d; + } + } + let w = (-sse / ((SIDE * SIDE) as f64) / strength).exp(); + for row in 0..SIDE { + for col in 0..SIDE { + acc[row * SIDE + col] += + w * f64::from(nb.y[(sy + row) * nb.width + sx + col]); + } + } + wsum += w; + } + let filtered: Vec = acc + .iter() + .map(|v| (v / wsum).round().clamp(0.0, 1023.0) as u16) + .collect(); + for (a, b) in filtered.iter().zip(&block) { + let d = f64::from(*a) - f64::from(*b); + tf_sse += d * d; + } + tf_px += (SIDE * SIDE) as u64; + ntf += search(&filtered, SIDE, &pictures[i - 8], bx, by).0; + px += (SIDE * SIDE) as u64; + } + } + } + let per = |v: u64| v as f64 / px.max(1) as f64; + let mse = tf_sse / tf_px.max(1) as f64; + println!( + "| {name} | {arfs} | s{strength} p{past} | {:.3} | {:.3} | {:.3} | {:.1}% | {:.2} dB |", + per(n8), + per(n4), + per(ntf), + 100.0 * (n8 - ntf) as f64 / n8.max(1) as f64, + 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(), + ); + } + } + /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to /// hardwire the REGULAR kernel, so the encoder could not have coded a /// SMOOTH or SHARP frame even if the header had said so -- the search, diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 18414acb..6feab2d1 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -1067,6 +1067,16 @@ const KEY_DEFAULT: i16 = -48; /// shipped on the flat path -- was inert on every frame of every pyramid /// stream, including the ARFs that carry 54% of a long-GOP stream's bytes /// (class `tool disabled in every gate recipe`). +/// lane-arfpred: the top ARF source temporal filter's strength +/// ([`crate::speed::ARF_TF`]), `EC_AV1_ARF_TF=` overriding it; +/// `0` is off. +fn arf_tf_strength() -> f64 { + std::env::var("EC_AV1_ARF_TF") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF)) +} + fn tpl_pyramid() -> bool { match std::env::var("EC_AV1_TPL_PYRAMID").ok() { Some(v) => v != "0", @@ -1782,8 +1792,26 @@ impl Av1Encoder { .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone())) .flatten(); let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone()); + // lane-arfpred: the top ARF is coded from a TEMPORALLY FILTERED + // source when `speed::ARF_TF` is non-zero -- the grain it would + // otherwise spend its residual on is averaged out against the + // group's own display neighbours (`lookahead`, already padded). + let source = picture.padded_to(SUPERBLOCK); + // ... and never at the very top of the quality range, where the + // anchor's own quantizer has hit the rate loop's floor + // ([`crate::speed::ARF_TF_QMIN`]). + let tf = match base_q_idx >= crate::speed::ARF_TF_QMIN { + true => arf_tf_strength(), + false => 0.0, + }; + let source = match (tf > 0.0, dq_level) { + (true, crate::encode::DqLevel::TopArf) => { + crate::encode::arf_temporal_filter(&source, lookahead, tf) + } + _ => source, + }; let encoded = || -> Result { encode_inter_frame( - &picture.padded_to(SUPERBLOCK), + &source, &reference, base_q_idx, DEADZONE, diff --git a/crates/ec-av1/src/speed.rs b/crates/ec-av1/src/speed.rs index d59d0df3..5ed6f668 100644 --- a/crates/ec-av1/src/speed.rs +++ b/crates/ec-av1/src/speed.rs @@ -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, /// `lanes/arfq.report.md`. pub(crate) const DQ_LEVEL_K: [f64; 3] = [1.5, 1.0, 1.0]; +/// lane-arfpred: the strength of the top ARF's SOURCE temporal filter +/// ([`crate::encode::arf_temporal_filter`]) -- `0` is off, higher filters +/// harder (the weight of a motion-compensated neighbour is +/// `exp(-mse / strength)`). `EC_AV1_ARF_TF=` overrides it. +/// +/// The top ARF carries 55% of a 48-picture film B stream at 6992 B a frame +/// against rav1e's 3872 at a FINER quantizer, and the per-frame census says +/// 61% of that gap is residual, not syntax -- while `arf_pred_census` says +/// the anchor's own lag is worth only 7% of its prediction SAD (lag 8 1.199 +/// vs lag 4 1.114 per pixel), so what the residual codes is mostly source +/// grain. Filtering it out of the picture the anchor is coded from is the +/// mechanism libaom uses (`arnr`) and rav1e 0.8.1 does not have at all. +/// Long-GOP gate (48 pictures, BD vs libaom / rav1e), strength 3 against the +/// control: film A +23.5/-8.0 -> **+22.7/-7.9**, film B +85.3/+6.7 -> +/// **+79.0/+2.7**. Film B takes 6.3 and 4.0 points off; film A takes 0.8 off +/// the libaom column and hands back 0.1 on the rav1e one, which is the +/// keep rule's "one column >=0.5 down, the other flat" clause. It is also +/// FASTER (film B two-point probe 167 s -> 147 s): the anchor has fewer +/// coefficients to code. Uniform over the presets -- above preset 6 +/// [`TPL_DEPTH`] leaves the group window empty and the filter is inert by +/// construction. +/// +/// Strength is single-peaked and SHARP: the film B two-point probe reads +/// -1.4% bytes at equal PSNR at 3, +3.4% at 8, +6.9% at 15 and +15.8% at 30 +/// (`lanes/arfpred.report.md` section 3). Hard filtering does remove 6-7% of +/// the stream's bytes and gives all of it back in quality, because the leaves +/// still carry the grain the anchor no longer has. +pub(crate) const ARF_TF: [f64; 11] = [3.0; 11]; + +/// lane-arfpred: the qindex below which the ARF temporal filter is OFF -- +/// libaom scales `arnr` strength with the quantizer and stops filtering at +/// the high-quality end for the same reason: a picture we are about to +/// reproduce almost exactly should not have detail averaged out of it first. +/// +/// 16 is under the gate's own finest anchor (its `q = 60` ladder point codes +/// the top ARF at qindex 28) and over the rate-loop floor a high bitrate +/// 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 +/// fixture the loop codes IDENTICAL 22237-byte anchors as at 1536 kbps, i.e. +/// the anchor's `base_q_idx + arf_q_offset` has clamped to 1 and the loop +/// cannot spend the target's remaining bytes -- and a cheaper (filtered) +/// anchor there makes the miss worse, not better. +pub(crate) const ARF_TF_QMIN: u8 = 16; + /// `encode::SPLIT_RD_THRESHOLD`: how cheap a block has to be before its split /// trial is withheld. The single biggest wall lever in the tile search. pub(crate) const SPLIT_RD: [f64; 11] = [ diff --git a/lanes/arfpred.report.md b/lanes/arfpred.report.md new file mode 100644 index 00000000..2937f055 --- /dev/null +++ b/lanes/arfpred.report.md @@ -0,0 +1,183 @@ +# lane-arfpred — the top ARF's PREDICTION, and a temporal filter of its source + +Worktree `edith_codecs-arfpred`, branch `lane-arfpred` off main `35874aef`. +Deciding gate `encode::tests::bd_rate_film_long_gop` (48 pictures, both film +rows, BD vs libaom `cpu-used 6` / rav1e `speed 6`). **The control was RUN, not +quoted: film A +23.5 / −8.0, film B +85.3 / +6.7 — the charter's numbers to +the digit.** + +## 0. The matched-rate point (film B, 48 pictures, the gate's own window) + +| stream | bytes | PSNR-Y | +|---|---|---| +| ours `q150` (this HEAD) | 76409 | 45.564 | +| rav1e `speed 6 quantizer 110` | 75452 | 45.751 | +| libaom `cpu-used 6 crf 34` | 70345 | 46.539 | + +Ours is +1.3% bytes for −0.19 dB against rav1e; every table below is read by +OUR decoder (`EC_AV1_BITCENSUS=1 EC_CENSUS_PERFRAME=1 syntax_census`), so all +three streams are measured by the same reader. `syntax_census` now prints +per-plane PSNR (`PSNR-Y ... U ... V`) per coded frame. + +## 1. Per-level census — bytes per FAMILY per frame (B/frame) + +| level | n | q | B/frame | PSNR-Y | U | V | intra% | comp% | skip% | NEW% | blocks/f | coeff | literal | mode | mv | part | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| **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 | +| **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 | +| 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 | +| 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 | +| 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 | +| 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 | +| ours key | 1 | 102 | 15827 | 47.34 | 51.94 | 52.26 | 100 | 0 | 0 | — | 1479 | 10666 | 3788 | 1046 | 0 | 148 | +| rav1e key | 1 | 80 | 20763 | 47.95 | 51.94 | 52.45 | 100 | 0 | 0 | — | 1266 | 14646 | 5102 | 828 | 0 | 140 | + +**WHERE THE +3120 B/frame GOES** (top ARF, ours − rav1e): residual +(coeff+literal) **+1908 B = 61%**, mode+partition **+871 B = 28%**, mv +**+290 B = 9%**. + +Three readings the charter asked for, in one line each: + +* **NOT the quantizer.** rav1e codes its anchor at a FINER qindex than ours + (104 vs 118) and still spends 45% of our bytes for +0.09 dB. Nothing on the + q axis explains this (and lane-arfq refuted the offsets twice). +* **NOT chroma.** Per-plane PSNR at the anchor is 51.60/51.91 ours against + 51.61/52.01 rav1e's — matched to a hundredth. The whole deficit is luma. +* **NOT intra fallback.** Our anchor codes 4.7% of its AREA intra where + rav1e codes 0.5% (lane-arfcen read 8-10% before the merges since), so the + ceiling of an intra-decision lever at this level is a few percent of one + level — the same order as its own noise. + +What is left is the residual, and its two possible causes are the anchor's +LAG (we predict across 8 pictures, rav1e across 4) and the SOURCE the +residual is coding. + +## 2. `arf_pred_census` — pricing lag against source grain (new instrument) + +`encode::tests::arf_pred_census` (`--ignored`, 6 s, no encoder change): every +16x16 luma block of every ARF position of the gate's own 48-picture window +gets the SAME log-step diamond search (`last2_census`'s) against the picture +8 back, the picture 4 back, and — with the block temporally filtered first — +the picture 8 back again. + +| clip | ARFs | lag 8 SAD/px | lag 4 SAD/px | tf lag 8 SAD/px | tf removes | filtered-vs-source PSNR | +|---|---|---|---|---|---|---| +| film A | 5 | 2.484 | 2.369 | 2.337 | 5.9% | 48.30 dB | +| film B | 5 | 1.199 | 1.114 | 1.059 | 11.7% | 50.14 dB | + +(strength 30, the two DISPLAY-PAST neighbours — the only ones the encoder's +own group buffer holds when it codes its top ARF. With ±2 both sides it is +6.8% / 14.3% at 47.74 / 49.54 dB; strengths 10/30/60/120 are in +`$HOME/.cache/arfpred/predsweep.log`.) + +**THE LAG IS NOT THE CAUSE.** Halving the anchor's prediction distance — +rav1e's whole structural advantage at this level — is worth 7.1% of the +prediction SAD on film B and 4.6% on film A, where the byte gap is 81%. What +our anchor's residual codes is mostly SOURCE GRAIN, which no motion search at +any lag can predict; a motion-compensated average of the neighbours removes +1.6x more of it than the lag does. + +## 3. The lever: `arf_temporal_filter` (libaom's `arnr` in the small) + +Built (`encode::arf_temporal_filter`, `speed::ARF_TF`, +`EC_AV1_ARF_TF=`): the top ARF's source picture is replaced by a +motion-compensated average of itself and its two group-buffered display +neighbours, weight `exp(-mse / strength)` per 16x16 block, chroma on the +halved luma vector with its own weight sum. **rav1e 0.8.1 has NO temporal +filter at all** (`grep -rn "temporal_filter\|arnr" rav1e-0.8.1/src` — empty), +so this is a libaom-only mechanism, not the thing rav1e beats us with. + +Probe ladder, film B 48 pictures, `q150` and `q90`, each arm judged at the +CONTROL's own PSNR through the arm's own two-point slope (arfcen's rule): + +| strength | q150 B / dB | q90 B / dB | slope dB/doubling | bytes at 45.564 dB | vs control | +|---|---|---|---|---|---| +| 0 (control) | 76409 / 45.564 | 346678 / 47.838 | 1.042 | 76409 | — | +| **3** | 72278 / 45.498 | 308172 / 47.759 | 1.081 | **75378** | **−1.35%** | +| 8 | 71636 / 45.413 | 308366 / 47.669 | 1.071 | 78996 | +3.4% | +| 15 | 70975 / 45.351 | 312607 / 47.606 | 1.054 | 81657 | +6.9% | +| 30 | 71814 / 45.246 | 321413 / 47.533 | 1.058 | 88453 | +15.8% | +| 60 | 73252 / 45.158 | 331390 / 47.470 | — | — | worse still | + +The filter does exactly what the census said it would — 6-7% of the stream's +bytes come off at strength 15-30 — and the BD metric takes it straight back, +because the gate scores PSNR against the UNFILTERED source and the leaves +still carry the grain the anchor no longer has. Note the non-monotone byte +column: past strength 15 the stream gets BIGGER again, which is the leaves +paying for a reference that no longer resembles their own sources. + +## 4. The gate — the lever SHIPS at strength 3 + +`encode::tests::bd_rate_film_long_gop`, 48 pictures, BD vs libaom `cpu-used 6` +/ rav1e `speed 6` (lower is better): + +| arm | film A | film B | +|---|---|---| +| control (`EC_AV1_ARF_TF=0`) | +23.5 / −8.0 | +85.3 / +6.7 | +| **`ARF_TF = 3` (ships)** | **+22.7 / −7.9** | **+79.0 / +2.7** | + +Film B takes **6.3 points off the libaom column and 4.0 off rav1e's** — the +biggest single move any lane has made on that row since the pyramid itself — +and film A takes 0.8 off the libaom column while handing back 0.1 on rav1e's, +which is the keep rule's "one column ≥0.5 down, the other flat ±0.3" clause. +It is also FASTER (film B two-point probe 167 s → 147 s). + +Guard gate `bd_rate_screen_native` (12 pictures, all five rows), against the +charter's controls: + +| clip | control | `ARF_TF = 3` | Δ | +|---|---|---|---| +| bars 1080p | −3.1 / −18.7 | −2.9 / −18.6 | +0.2 / +0.1 | +| bars 2160p | +9.1 / −13.3 | +9.1 / −13.3 | 0.0 / 0.0 | +| film A | +20.3 / −4.9 | **+18.3 / −6.0** | **−2.0 / −1.1** | +| film B | +24.7 / −1.8 | **+24.6 / −2.1** | −0.1 / −0.3 | +| screen capture | +14.6 / −33.2 | +14.6 / −33.2 | byte-identical | + +Every real-content row improves; the two colour-bar rows move 0.2 and 0.0 +(inside the 0.3 bound), and the screen capture is byte-identical — its +sequence codes no pyramid ARF at all, so the filter never runs there. + +## 5. Where the filter is OFF — `ARF_TF_QMIN` + +The filter runs on the top ARF of every preset (above preset 6 `TPL_DEPTH` +leaves the group window empty and it is inert by construction) **except when +the anchor's own `base_q_idx` is below 16** (`speed::ARF_TF_QMIN`), which is +libaom's own rule for `arnr` and is what a red test named: + +`encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames` codes +its 2 Mbps pyramid arm with IDENTICAL 22358-byte anchors to its 1536 kbps arm +— the rate loop has clamped `base_q_idx + arf_q_offset` to 1 and cannot spend +the target's remaining bytes at all, so that arm sits at −4.8% of target +BEFORE this lane touches anything (measured: `EC_AV1_ARF_TF=0`, −4.8%). A +cheaper anchor there made the miss −5.1%, outside the test's ±5% bound. With +`ARF_TF_QMIN = 16` the arm reads **−4.8%, the control's own number**, and the +gate is untouched: its finest ladder point (`q = 60`) codes the top ARF at +qindex 28, and both byte pins are unchanged by the threshold. + +## 6. Invariants + +* Byte pins re-taken (the hidden frames' pixels move by construction): + `(150, 8269 → 8218)`, `(60, 33044 → 33017)`; green at the default AND at + `EC_AV1_SPEED=6`, and unchanged again after `ARF_TF_QMIN` landed. +* Split suite on the shipped default: `--skip stream::` **342 passed / 0 failed**, `stream:: + --skip 10bit` **201 passed / 0 failed**, `10bit` **42 passed / 0 failed** (585 in all). +* `cargo check --workspace --all-targets -j4`: 0 errors, 0 `ec-av1` warnings + (the 25 warnings are `ec-opus`/`ec-vorbis`, pre-existing). +* `--ignored --exact encoder::tests::every_speed_preset_decodes_sample_exact_through_both_decoders` + 1 passed. + +## 7. What this lane did NOT do + +* `deferred: a strength sweep ON THE GATE — only 3 was taken to the deciding + gate; 8/15/30/60 were refuted on the two-point probe, which mispredicted + the SIGN of 3's gate result (probe −1.4% bytes, gate −6.3 BD points), so the + probe is a weak proxy for this lever — unblocked by a lane that can afford + three more 30-minute long-GOP arms (1, 2, 5).` +* `deferred: the filter window — the encoder's group buffer holds only the two + DISPLAY-PAST neighbours when it codes its top ARF; the census says ±2 both + sides removes 14.3% of the prediction SAD against past-only's 11.7%, so a + one-group lookahead is worth a lane — unblocked by a lane that reorders the + encoder's picture buffer.` +* `deferred: the ARF's mode/partition gap (+871 B a frame, 2196 blocks against + rav1e's 1507) — this lane's lever is the residual half of the census — + unblocked by the 128-root lane (parked) or a partition lane at the anchor.`