forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1bdgate' (5b132459): ignored gate bd_rate_vs_libaom_and_rav1e measures ec-av1 encoder BD-rate + wall vs ffmpeg libaom-av1 cpu-used 6 and librav1e speed 6 on ffmpeg-decoded pixels (baseline: +441..+504% rate vs libaom, +206..+401% vs rav1e); ec-bench AV1 encode row gains fps + bytes/frame; no encoder code changed

Browse files at this commit

f336d0c11e83c0b4f79625657838773a2e5d4f96Ahmet Kaan GümüşParent: 2426e3de1f8c49
crates/ec-av1/src/encode.rsmodified+262 -0
@@ -5799,4 +5799,266 @@ mod tests {
5799 }5799 }
5800 }5800 }
5801 }5801 }
5802+
5803+ // -----------------------------------------------------------------------
5804+ // The encoder's standing BD-rate baseline against libaom and rav1e.
5805+ // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
5806+ // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
5807+ // agreeing with our encoder proves nothing about the bitstream.
5808+ // -----------------------------------------------------------------------
5809+
5810+ /// All-plane PSNR of a decoded picture against its source, on the same
5811+ /// 8-bit scale [`psnr`] uses.
5812+ fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
5813+ let cat = |p: &Picture| {
5814+ let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
5815+ v.extend_from_slice(&p.y);
5816+ v.extend_from_slice(&p.u);
5817+ v.extend_from_slice(&p.v);
5818+ v
5819+ };
5820+ psnr(&cat(decoded), &cat(source))
5821+ }
5822+
5823+ /// The pictures back as the planar 8-bit bytes an encoder reads.
5824+ fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
5825+ let mut raw = Vec::new();
5826+ for p in source {
5827+ for plane in [&p.y, &p.u, &p.v] {
5828+ raw.extend(plane.iter().map(|&s| s as u8));
5829+ }
5830+ }
5831+ raw
5832+ }
5833+
5834+ /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
5835+ /// through ffmpeg: one point per entry of `points`, each a quality flag
5836+ /// set. Returns the ladder ordered by fidelity and the total encode wall
5837+ /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
5838+ /// so both curves are measured by the same decoder.
5839+ fn external_ladder(
5840+ source: &[Picture],
5841+ width: usize,
5842+ height: usize,
5843+ encoder: &str,
5844+ points: &[Vec<String>],
5845+ ) -> (Vec<(f64, f64)>, f64) {
5846+ // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
5847+ let dir = std::env::temp_dir();
5848+ let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
5849+ std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
5850+ let mut ladder = Vec::new();
5851+ let mut wall = 0.0;
5852+ for (i, params) in points.iter().enumerate() {
5853+ let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id()));
5854+ let start = std::time::Instant::now();
5855+ let out = Command::new("ffmpeg")
5856+ .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
5857+ .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
5858+ .arg(&raw_path)
5859+ .args(["-an", "-threads", "1"])
5860+ .args(["-g", &source.len().to_string(), "-c:v", encoder])
5861+ .args(params)
5862+ .args(["-f", "obu"])
5863+ .arg(&obu)
5864+ .output()
5865+ .expect("ffmpeg failed to run");
5866+ wall += start.elapsed().as_secs_f64();
5867+ assert!(
5868+ out.status.success(),
5869+ "{encoder} {params:?}: {}",
5870+ String::from_utf8_lossy(&out.stderr)
5871+ );
5872+ let stream = std::fs::read(&obu).expect("reference stream");
5873+ let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
5874+ let mean: f64 = decoded
5875+ .iter()
5876+ .zip(source)
5877+ .map(|(d, s)| psnr_all(d, s))
5878+ .sum::<f64>()
5879+ / source.len() as f64;
5880+ ladder.push((mean, (stream.len() as f64).log10()));
5881+ let _ = std::fs::remove_file(&obu);
5882+ }
5883+ let _ = std::fs::remove_file(&raw_path);
5884+ ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
5885+ (ladder, wall)
5886+ }
5887+
5888+ /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
5889+ /// comes from ffmpeg's decode of our own stream, and every frame of that
5890+ /// decode is asserted sample-exact against our reconstruction -- which is
5891+ /// itself a gate: it proves the bitstream says what the encoder thinks.
5892+ fn our_ladder(
5893+ source: &[Picture],
5894+ width: usize,
5895+ height: usize,
5896+ fctx: &crate::decode::FrameCtx,
5897+ ) -> (Vec<(f64, f64)>, f64) {
5898+ let mut ladder = Vec::new();
5899+ let mut wall = 0.0;
5900+ for &q in &[150u8, 120, 90, 60] {
5901+ let start = std::time::Instant::now();
5902+ let encoded = encode_sequence_with_ctx(source, q, 0.5, fctx).unwrap();
5903+ wall += start.elapsed().as_secs_f64();
5904+ let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
5905+ for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
5906+ assert!(
5907+ d.y == e.reconstruction.y
5908+ && d.u == e.reconstruction.u
5909+ && d.v == e.reconstruction.v,
5910+ "q={q} frame {i}: ffmpeg's decode differs from our reconstruction"
5911+ );
5912+ }
5913+ let mean: f64 = decoded
5914+ .iter()
5915+ .zip(source)
5916+ .map(|(d, s)| psnr_all(d, s))
5917+ .sum::<f64>()
5918+ / source.len() as f64;
5919+ ladder.push((mean, (encoded.stream.len() as f64).log10()));
5920+ }
5921+ ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
5922+ (ladder, wall)
5923+ }
5924+
5925+ /// A ladder is only a ladder if both axes rise together.
5926+ fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
5927+ assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
5928+ for w in ladder.windows(2) {
5929+ assert!(
5930+ w[1].0 > w[0].0 && w[1].1 > w[0].1,
5931+ "{name}: not monotone, {ladder:?}"
5932+ );
5933+ }
5934+ }
5935+
5936+ /// The missing instrument: what this encoder costs against libaom and
5937+ /// rav1e at matched fidelity, and how long it takes to get there.
5938+ ///
5939+ /// Recipe, identical on all three sides: 12 consecutive frames of each
5940+ /// clip scaled to 640x384 (a whole number of superblocks), one key frame
5941+ /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
5942+ /// tile, `-threads 1`, no film grain synthesis (neither reference enables
5943+ /// it by default), 4:2:0 8-bit in and out. Reference points:
5944+ /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
5945+ /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
5946+ /// tile_cols=1:tile_rows=1:threads=1`
5947+ /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
5948+ /// ffmpeg-decoded frames of each encoder's own stream.
5949+ ///
5950+ /// Measured baseline 2026-09-06, 12 frames, this box (wall = the four
5951+ /// encodes of that ladder together):
5952+ ///
5953+ /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
5954+ /// |---|---|---|---|---|
5955+ /// | 1080p fixture | 40.36 dB/26824 B .. 48.24 dB/120942 B | +501.4% | +364.4% | 5.1s:1.9s:3.8s |
5956+ /// | 2160p fixture | 41.36 dB/17608 B .. 49.27 dB/76978 B | +504.4% | +401.0% | 4.6s:1.5s:3.3s |
5957+ /// | screen capture | 37.32 dB/13053 B .. 45.39 dB/59744 B | +440.9% | +206.0% | 5.9s:1.7s:3.0s |
5958+ ///
5959+ /// So: roughly 5x libaom's rate and 3-4x rav1e's at matched fidelity,
5960+ /// while spending 2.7x libaom's and 1.4x rav1e's encode time. No
5961+ /// threshold is asserted yet -- this run sets the baseline; the gate
5962+ /// asserts only four monotone points per ladder and that ffmpeg decodes
5963+ /// our stream sample-exact against our reconstruction.
5964+ ///
5965+ /// Run:
5966+ /// cargo test -p ec-av1 --release --lib -- --ignored \
5967+ /// bd_rate_vs_libaom_and_rav1e --nocapture
5968+ #[test]
5969+ #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
5970+ fn bd_rate_vs_libaom_and_rav1e() {
5971+ if !have_ffmpeg() {
5972+ eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
5973+ return;
5974+ }
5975+ let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
5976+ let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
5977+ for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] {
5978+ let path = fixtures.join("video").join(name);
5979+ if path.exists() {
5980+ clips.push((name.to_string(), path));
5981+ } else {
5982+ eprintln!("SKIP clip {name}: missing");
5983+ }
5984+ }
5985+ // Screen capture: the repo carries no screen-capture fixture, so take
5986+ // the first OBS recording the real-library manifest names.
5987+ match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
5988+ Ok(manifest) => {
5989+ let screen = manifest
5990+ .lines()
5991+ .skip(1)
5992+ .filter_map(|l| l.split('\t').next())
5993+ .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists());
5994+ match screen {
5995+ Some(p) => clips.push((
5996+ format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
5997+ std::path::PathBuf::from(p),
5998+ )),
5999+ None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
6000+ }
6001+ }
6002+ Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
6003+ }
6004+ assert!(!clips.is_empty(), "no source clip available");
6005+
6006+ let (width, height, frames) = (640usize, 384usize, 12usize);
6007+ let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
6008+ .iter()
6009+ .map(|q| {
6010+ ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
6011+ .map(String::from)
6012+ .to_vec()
6013+ })
6014+ .collect();
6015+ let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
6016+ .iter()
6017+ .map(|q| {
6018+ vec![
6019+ "-rav1e-params".to_string(),
6020+ format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
6021+ ]
6022+ })
6023+ .collect();
6024+ println!(
6025+ "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
6026+ );
6027+ println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |");
6028+ println!("|---|---|---|---|---|");
6029+ for (name, path) in &clips {
6030+ let fctx = &crate::decode::FrameCtx::new();
6031+ let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
6032+ let (ours, ours_wall) = our_ladder(&source, width, height, fctx);
6033+ let (aom, aom_wall) =
6034+ external_ladder(&source, width, height, "libaom-av1", &aom_points);
6035+ let (rav1e, rav1e_wall) =
6036+ external_ladder(&source, width, height, "librav1e", &rav1e_points);
6037+ assert_monotone(&format!("{name}: ours"), &ours);
6038+ assert_monotone(&format!("{name}: libaom"), &aom);
6039+ assert_monotone(&format!("{name}: rav1e"), &rav1e);
6040+ let points = ours
6041+ .iter()
6042+ .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
6043+ .collect::<Vec<_>>()
6044+ .join(", ");
6045+ println!(
6046+ "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
6047+ bd_rate(&aom, &ours) * 100.0,
6048+ bd_rate(&rav1e, &ours) * 100.0,
6049+ );
6050+ println!(
6051+ "| references | libaom {} | rav1e {} | | |",
6052+ aom.iter()
6053+ .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
6054+ .collect::<Vec<_>>()
6055+ .join(", "),
6056+ rav1e
6057+ .iter()
6058+ .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
6059+ .collect::<Vec<_>>()
6060+ .join(", "),
6061+ );
6062+ }
6063+ }
5802 }6064 }
tools/ec-bench/src/main.rsmodified+5 -1
@@ -373,10 +373,14 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
373 }373 }
374 let wall = start.elapsed().as_secs_f64();374 let wall = start.elapsed().as_secs_f64();
375 let media_s = n as f64 / 30.0;375 let media_s = n as f64 / 30.0;
376+ let fps = if wall > 0.0 { f64::from(n) / wall } else { 0.0 };
377+ let bytes_per_frame = stream.len() as f64 / f64::from(n);
376 rows.push(Row {378 rows.push(Row {
377 component: "ec-av1",379 component: "ec-av1",
378 direction: "encode",380 direction: "encode",
379- content: format!("{w}x{h}, {n} frames, gop=10"),381+ content: format!(
382+ "{w}x{h}, {n} frames, gop=10, {fps:.1} fps, {bytes_per_frame:.0} B/frame"
383+ ),
380 media: format!("{media_s:.1}s"),384 media: format!("{media_s:.1}s"),
381 wall_ms: wall * 1000.0,385 wall_ms: wall * 1000.0,
382 rtf: (wall > 0.0).then_some(media_s / wall),386 rtf: (wall > 0.0).then_some(media_s / wall),