From f025ec8e87a4a7b89ac40aa08b12a6221c2d10ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 09:07:49 +0300 Subject: [PATCH] test(av1): pyramid round trip through both decoders, per-reference hit counter, pyramid arm in the BD gate --- crates/ec-av1/src/encode.rs | 117 ++++++++++++++++++++++++++++++++++- crates/ec-av1/src/encoder.rs | 99 +++++++++++++++++++++++++++++ 2 files changed, 215 insertions(+), 1 deletion(-) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index d398ef8d..cd6b0aeb 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1908,6 +1908,20 @@ pub(crate) fn take_tx_depth_hits() -> [usize; 3] { static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 2] = [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; +/// How many 32x32-and-below inter blocks each reference frame won, indexed by +/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the +/// fire count a gate prints to see an extra reference reach a block at all +/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never +/// chosen is a pyramid that costs bytes and buys nothing). +static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; + +/// Reads [`REF_FRAME_HITS`] and zeroes it. +#[cfg(test)] +pub(crate) fn take_ref_frame_hits() -> [usize; 8] { + std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + /// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it. #[cfg(test)] pub(crate) fn take_inter_tx_split_hits() -> [usize; 2] { @@ -4555,6 +4569,12 @@ pub(crate) fn encode_inter_frame( .filter(|b| b.inter.is_some()) .count() as f64 / modes.len() as f64; + for block in blocks.iter().flat_map(Quadrant::blocks) { + if let Some(info) = block.inter { + let r = (info.ref_frame as usize).min(7); + REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } #[cfg(test)] record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); // This frame's header leaves `disable_frame_end_update_cdf` off, so it @@ -7524,6 +7544,88 @@ mod tests { (ladder, wall) } + /// The [`crate::encoder::Pyramid`] this run's ladder is coded under, from + /// `EC_AV1_PYRAMID=[::]`. Unset + /// keeps the flat one-key-then-all-inter ladder the baseline was measured + /// on, so the gate's default recipe is unchanged. + fn pyramid_from_env() -> Option { + let spec = std::env::var("EC_AV1_PYRAMID").ok()?; + let mut f = spec.split(':'); + let mini_gop = f.next()?.parse().ok()?; + let d = crate::encoder::Pyramid::default(); + Some(crate::encoder::Pyramid { + mini_gop, + arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset), + leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset), + }) + } + + /// [`our_ladder`] through the streaming facade with a coding pyramid: the + /// four points are the same `base_q_idx` ladder, but each stream is + /// reordered (hidden `ALTREF` first, `show_existing_frame` last per + /// group) and each level is coded at its own quantizer offset. Returns + /// the ladder, the wall, and — per pyramid level over the whole ladder — + /// how many frames and how many bytes it spent. + fn our_ladder_pyramid( + source: &[Picture], + width: usize, + height: usize, + pyramid: crate::encoder::Pyramid, + ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4]) { + use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level}; + let slot = |l: Level| match l { + Level::Key => 0, + Level::Arf => 1, + Level::Leaf => 2, + Level::ShowExisting => 3, + }; + let mut ladder = Vec::new(); + let mut wall = 0.0; + let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]); + for &q in &[150u8, 120, 90, 60] { + let config = EncoderConfig { + width, + height, + base_q_idx: q, + gop: source.len(), + colour: Colour::Unspecified, + }; + let start = std::time::Instant::now(); + let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); + let mut packets = Vec::new(); + for picture in source { + packets.extend(enc.encode_frames(picture).unwrap()); + } + packets.extend(enc.flush().unwrap()); + wall += start.elapsed().as_secs_f64(); + let mut stream = Vec::new(); + for p in &packets { + counts[slot(p.level)] += 1; + bytes[slot(p.level)] += p.data.len(); + stream.extend_from_slice(&p.data); + } + // [[gate-blind-to-hidden-frames]]: a reordered stream is only + // correct if the DISPLAY-order output still has one frame per + // source picture, in the right order -- checked against our own + // decoder as well as ffmpeg's, both below. + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), source.len(), "q={q}: our display-order count"); + let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); + for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() { + assert!(d.y == o.y, "q={q} display frame {i}: ffmpeg differs from our decoder"); + } + let mean: f64 = decoded + .iter() + .zip(source) + .map(|(d, s)| psnr_all(d, s)) + .sum::() + / source.len() as f64; + ladder.push((mean, (stream.len() as f64).log10())); + } + ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); + (ladder, wall, counts, bytes) + } + /// Byte-exactness gate for encoder work that is meant to change only /// how long the encoder takes. /// @@ -7726,7 +7828,20 @@ mod tests { let _ = crate::tile::take_inter_mode_hits(); let _ = crate::tile::take_drl_hits(); let _ = crate::tile::take_ref_hits(); - let (ours, ours_wall) = our_ladder(&source, width, height, fctx); + let (ours, ours_wall) = match pyramid_from_env() { + None => our_ladder(&source, width, height, fctx), + Some(pyramid) => { + let (ladder, wall, counts, bytes) = + our_ladder_pyramid(&source, width, height, pyramid); + eprintln!( + "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \ + show_existing {}; bytes key {} arf {} leaf {} show_existing {}", + counts[0], counts[1], counts[2], counts[3], + bytes[0], bytes[1], bytes[2], bytes[3], + ); + (ladder, wall) + } + }; // How often the inter split actually fired over this clip's four // encodes, against the whole 32x32 that was the only outcome // before (gate-blind-to-feature). diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index c107e808..efcc07e1 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -1336,6 +1336,105 @@ mod tests { .collect() } + /// A pyramid stream reorders pictures: the hidden `ALTREF` of each + /// mini-GOP is coded before the leaves that precede it in display order, + /// and a `show_existing_frame` header puts it back. This pins the shape + /// (one packet per source picture plus one `show_existing_frame` per + /// group, `dts` monotone, `order` NOT monotone) and then decodes the + /// whole stream through OUR decoder and through ffmpeg/dav1d and requires + /// the two display-order outputs to agree sample for sample — the + /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never + /// output, or output twice, or output in the wrong position, changes the + /// display-order list and fails here. + #[test] + fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { + let (width, height) = (128usize, 64usize); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 32, + colour: Colour::Bt709Limited, + }; + let pyramid = Pyramid { + mini_gop: 4, + ..Pyramid::default() + }; + let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); + let sources: Vec = (0..9).map(|t| test_card(width, height, t * 3)).collect(); + let _ = crate::encode::take_ref_frame_hits(); + let mut packets = Vec::new(); + for picture in &sources { + packets.extend(enc.encode_frames(picture).unwrap()); + } + packets.extend(enc.flush().unwrap()); + + // Shape: every source picture is coded exactly once, and each closed + // group adds one `show_existing_frame` packet. + let coded: Vec = packets + .iter() + .filter(|p| p.level != Level::ShowExisting) + .map(|p| p.order) + .collect(); + let mut sorted = coded.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, (0..9).collect::>(), "one packet per picture"); + assert_ne!(coded, sorted, "the pyramid never reordered anything"); + let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count(); + assert_eq!(shown, 2, "one show_existing_frame per closed mini-GOP"); + for (i, p) in packets.iter().enumerate() { + assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position"); + } + let hist = |l: Level| packets.iter().filter(|p| p.level == l).count(); + eprintln!( + "pyramid levels: key {} arf {} leaf {} show_existing {}", + hist(Level::Key), + hist(Level::Arf), + hist(Level::Leaf), + hist(Level::ShowExisting), + ); + assert_eq!(hist(Level::Arf), 2, "two hidden frames"); + let refs = crate::encode::take_ref_frame_hits(); + eprintln!( + "blocks per reference: LAST {} GOLDEN {} ALTREF {}", + refs[crate::mvstack::LAST_FRAME as usize], + refs[crate::mvstack::GOLDEN_FRAME as usize], + refs[crate::mvstack::ALTREF_FRAME as usize], + ); + // [[gate-blind-to-feature]]: the whole point of the hidden frame is + // that the leaves predict BACKWARD off it, which is also the only + // thing that exercises `ref_frame_sign_bias` in the MV stack. A green + // round trip in which `ALTREF_FRAME` never won a block would prove + // only that a hidden frame can be written and re-output. + assert!( + refs[crate::mvstack::ALTREF_FRAME as usize] > 0, + "no block predicted off the hidden ALTREF" + ); + + let stream = concat(&packets); + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's display-order count"); + if !have_ffmpeg() { + eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg"); + return; + } + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert_eq!(got.len(), b.len(), "frame {i}: luma size"); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { + panic!( + "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + b[at], + ); + } + } + } + /// [`RateTarget::Quality`] is monotone: a higher quality dial never /// produces a smaller stream or a worse mean PSNR than a lower one, on /// the same real clip.