diff --git a/crates/ec-h264/tests/it/encode.rs b/crates/ec-h264/tests/it/encode.rs index 9a3ee3e4..c46d9a31 100644 --- a/crates/ec-h264/tests/it/encode.rs +++ b/crates/ec-h264/tests/it/encode.rs @@ -58,48 +58,6 @@ impl Clip { } } - /// Frame `t` without the per-sample noise field: smooth gradients, a - /// band of sinusoidal texture and a box translating by whole and - /// sub-sample amounts. `render`'s noise is incompressible, which makes a - /// rate-quality comparison read mostly as how willing each encoder is to - /// throw residual away; this one is content where prediction matters, the - /// half a rate-quality comparison is about. - fn render_smooth(&mut self, t: usize) { - let (w, h) = (self.w, self.h); - let ft = t as f64; - for y in 0..h { - for x in 0..w { - let (fx, fy) = (x as f64, y as f64); - // A slow diagonal ramp that drifts by 1.5 samples a frame, so - // motion is not always on the sample grid. - let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35; - // A textured band, the part a search has to actually find. - let texture = if y > h / 3 && y < 2 * h / 3 { - 18.0 * ((fx * 0.19 + ft * 0.9).sin() + (fy * 0.11).cos()) - } else { - 0.0 - }; - let box_x = ((ft * 2.7) as usize) % (w.saturating_sub(48).max(1)); - let inside = x >= box_x && x < box_x + 48 && y >= h / 5 && y < h / 5 + 36; - let v = if inside { - 196.0 - texture * 0.5 - } else { - 40.0 + (ramp % 90.0).abs() + texture - }; - self.y[y * w + x] = v.clamp(0.0, 255.0) as u8; - } - } - for y in 0..h / 2 { - for x in 0..w / 2 { - let (fx, fy) = (x as f64, y as f64); - self.u[y * (w / 2) + x] = - (118.0 + 12.0 * ((fx * 0.05 + ft * 0.3).sin())).clamp(0.0, 255.0) as u8; - self.v[y * (w / 2) + x] = - (134.0 + 10.0 * ((fy * 0.04 - ft * 0.25).cos())).clamp(0.0, 255.0) as u8; - } - } - } - fn view(&self) -> PictureView<'_> { PictureView::i420(self.w as u32, self.h as u32, &self.y, &self.u, &self.v) } @@ -147,35 +105,6 @@ fn planes_of(frame: &ec_core::frame::VideoFrame) -> Planes { (y, u, v) } -/// Mean squared error between two equal-length planes. -fn plane_mse(a: &[u8], b: &[u8]) -> f64 { - a.iter() - .zip(b) - .map(|(&x, &y)| { - let d = f64::from(x) - f64::from(y); - d * d - }) - .sum::() - / a.len() as f64 -} - -/// PSNR over all three planes, pooled by sample count the way x264 reports it: -/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number -/// rewards an encoder for throwing chroma away — a chroma decision measured -/// against it will always say "code less" — so any decision that can move -/// chroma bits is read here instead. -fn psnr_yuv(a: &(Vec, Vec, Vec), b: &(Vec, Vec, Vec)) -> f64 { - let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64); - let sse = - plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c; - let mse = sse / (n_y + 2.0 * n_c); - if mse == 0.0 { - 99.0 - } else { - 10.0 * (255.0 * 255.0 / mse).log10() - } -} - fn psnr(a: &[u8], b: &[u8]) -> f64 { let mse: f64 = a .iter() @@ -193,82 +122,6 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { } } -fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { - let mut a = [[0.0; 5]; 4]; - for i in 0..4 { - a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; - } - for col in 0..4 { - let mut pivot = col; - for row in col + 1..4 { - if a[row][col].abs() > a[pivot][col].abs() { - pivot = row; - } - } - a.swap(col, pivot); - let div = a[col][col]; - assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); - for v in a[col][col..].iter_mut() { - *v /= div; - } - for row in 0..4 { - if row == col { - continue; - } - let f = a[row][col]; - let pivot_row = a[col]; - for (dst, src) in a[row][col..].iter_mut().zip(&pivot_row[col..]) { - *dst -= f * src; - } - } - } - [a[0][4], a[1][4], a[2][4], a[3][4]] -} - -fn cubic_integral(c: [f64; 4], x: f64) -> f64 { - c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 -} - -/// A sample window with nothing in it (a film's black head, a fade) codes to -/// almost no bits and decodes back to the source exactly, so every point on -/// both curves sits at the PSNR cap and the BD number is a flat +0.000 that -/// reads like a measurement. Refuse such a window by name. -fn refuse_flat_window(psnrs: impl IntoIterator, skip_var: &str) { - const FLAT_WINDOW_DB: f64 = 90.0; - let ps: Vec = psnrs.into_iter().collect(); - assert!( - ps.iter().any(|&p| p < FLAT_WINDOW_DB), - "the sample window is flat — every point reaches the PSNR cap ({ps:?}); \ - this is a black head or a fade, not content: pass {skip_var} to sample \ - past it" - ); -} - -fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 { - let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); - let ys_candidate = std::array::from_fn(|i| candidate[i].1); - let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); - let ys_anchor = std::array::from_fn(|i| anchor[i].1); - let lo = xs_candidate - .iter() - .copied() - .fold(f64::INFINITY, f64::min) - .max(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); - let hi = xs_candidate - .iter() - .copied() - .fold(f64::NEG_INFINITY, f64::max) - .min(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); - assert!(hi > lo, "BD-PSNR curves do not overlap in bitrate"); - let c_candidate = cubic_fit(xs_candidate, ys_candidate); - let c_anchor = cubic_fit(xs_anchor, ys_anchor); - (cubic_integral(c_candidate, hi) - - cubic_integral(c_candidate, lo) - - cubic_integral(c_anchor, hi) - + cubic_integral(c_anchor, lo)) - / (hi - lo) -} - /// The encoder's reconstruction and a decode of its bitstream agree sample for /// sample, over a QP sweep, both presets, single and multi threaded. #[test] @@ -427,167 +280,6 @@ fn all_intra_when_the_gop_is_one() { // absent, exactly like the conformance suite's ffmpeg cross-check. // --------------------------------------------------------------------------- -/// Write `bytes` to `path` and PROVE the file on disk is exactly that long. -/// -/// lane-h26xpinloud: every write below used `std::fs::write(..).ok()?` and then -/// handed `path` to ffmpeg, which closes only the ERROR path. An Ok-but-short -/// write -- a filesystem that reports success and stores fewer bytes (ENOSPC on -/// a full mount, EFBIG under a size cap, a quota, a failed final flush) -- left -/// ffmpeg decoding a truncated stream, and the failure surfaced as a -/// plausible-looking wrong pixel or a shifted PSNR number, not as a write -/// failure. MEASURED: 1234 bytes written through a path that LOOKS like a -/// stream file in a scratch directory but whose filesystem accepts every byte -/// and stores none returns `Ok`, and the file on disk is 0 bytes. So the length -/// is checked here once, from the same `bytes.len()` the writer used, and any -/// shortfall carries the path, both counts, and the OS error -- or, for the -/// write that reported success and left a short file, the plain statement that -/// there was no OS error, which is exactly the case that used to print nothing. -/// -/// Returns the failure LINE rather than a bare bool, so the bail callers and any -/// panic caller all end on one format that cannot drift apart. The success path -/// is byte-identical to the old `fs::write`: same bytes, same path, truncate -/// then write. -fn pin_loud(site: &str, path: &std::path::Path, bytes: &[u8]) -> Result<(), String> { - let expected = bytes.len(); - if let Err(e) = std::fs::write(path, bytes) { - // The count here is the file's REAL length, not what the writer had - // confirmed in hand: under a size cap the kernel stores everything up - // to the cap and only THEN returns the error, and `fs::write` confirms - // none of it. - let on_disk = std::fs::metadata(path) - .map(|m| m.len() as usize) - .unwrap_or(0); - return Err(short_line( - site, - path, - on_disk, - expected, - &format!("the write failed: {e}"), - )); - } - match std::fs::metadata(path) { - Ok(m) if m.len() as usize == expected => Ok(()), - Ok(m) => Err(short_line( - site, - path, - m.len() as usize, - expected, - "the write reported success and the file on disk is still not that long (no OS error)", - )), - Err(e) => Err(short_line( - site, - path, - 0, - expected, - &format!("the written file could not be stat'ed: {e}"), - )), - } -} - -/// The one failure line every short pin ends on: site, path, the bytes the file -/// holds vs the bytes owed, and the reason. -fn short_line( - site: &str, - path: &std::path::Path, - on_disk: usize, - expected: usize, - why: &str, -) -> String { - format!( - "ec-h264 encode pin SHORT [{}] {}: file holds {on_disk} of {expected} bytes: {why}", - site, - path.display() - ) -} - -/// A pin whose shortfall is reported and then BAILED on, for a caller that -/// returns `None` today. Prints the same line [`pin_loud`] returns, so `None` -/// from here never reads as a plain "ffmpeg said no". -fn pin_or_bail(site: &str, path: &std::path::Path, bytes: &[u8]) -> Option<()> { - pin_loud(site, path, bytes) - .map_err(|why| eprintln!("{why}")) - .ok() -} - -#[cfg(unix)] -#[test] -fn pin_loud_reds_on_an_ok_but_short_write() { - // The shape the four sites left open: a write that reports success and - // leaves a file of a different length. A symlink to /dev/null accepts every - // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes -- - // a stream path, silently empty. - let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let path = dir.join("ok-but-short.264"); - let _ = std::fs::remove_file(&path); - std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null"); - let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err(); - assert!(why.contains(&path.display().to_string()), "{why}"); - assert!(why.contains("file holds 0 of 1234 bytes"), "{why}"); - std::fs::remove_file(&path).ok(); - - // The control: the same call on a real file succeeds and leaves every byte. - let good = dir.join("whole.264"); - let bytes = vec![7u8; 1234]; - pin_loud("control", &good, &bytes).expect("a whole write is not short"); - assert_eq!(std::fs::read(&good).expect("read back"), bytes); - std::fs::remove_file(&good).ok(); - std::fs::remove_dir_all(&dir).ok(); -} - -#[cfg(unix)] -#[test] -fn pin_loud_reports_what_landed_under_a_size_cap() { - // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores - // everything up to the cap and only then returns EFBIG. The line must carry - // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count - // the writer confirmed, which is zero. - use std::process::Command; - let Ok(exe) = std::env::current_exe() else { - return; - }; - // SIGXFSZ's default action would kill the child before it can print; - // `trap '' XFSZ` sets SIG_IGN, which survives the exec. - let script = format!( - "ulimit -f 1; trap '' XFSZ; exec {} --exact encode::pin_loud_cap_child --nocapture", - exe.display() - ); - let out = Command::new("sh") - .args(["-c", &script]) - .env("EC_PINLOUD_CHILD", "1") - .output() - .expect("run the capped child"); - let text = format!( - "{}{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - assert!(!out.status.success(), "the capped write must fail: {text}"); - assert!(text.contains("file holds 512 of 4096 bytes"), "{text}"); - assert!( - text.contains("EFBIG") || text.contains("File too large"), - "{text}" - ); -} - -/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under -/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails -/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`. -#[test] -fn pin_loud_cap_child() { - if std::env::var_os("EC_PINLOUD_CHILD").is_none() { - return; - } - let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-cap-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let path = dir.join("capped.264"); - let why = - pin_loud("capped", &path, &[7u8; 4096]).expect_err("4096 bytes cannot fit a 1 KiB cap"); - std::fs::remove_file(&path).ok(); - std::fs::remove_dir_all(&dir).ok(); - panic!("{why}"); -} - /// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture. fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option> { // Distinct per call, not per process: several #[test]s in this binary @@ -601,7 +293,7 @@ fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option> 7; - let stem = (2..5).contains(&cx); - let bar = (10..13).contains(&cy) && cx < 12 && hash & 1 == 1; - let foot = cy >= 19 && (2..13).contains(&cx) && hash & 2 == 2; - let glyph = y > h / 3 && (3..22).contains(&cy) && (stem || bar || foot); - clip.y[y * w + x] = if glyph { 24 } else { shade.min(235.0) as u8 }; - } - } - clip.u.fill(128); - clip.v.fill(128); - }; - let run = |t8x8: bool, qp: i32, cabac: bool| { - let mut cfg = EncoderConfig::new(w as u32, h as u32); - cfg.qp = qp; - cfg.gop_size = 10; - cfg.transform_8x8 = t8x8; - cfg.cabac = cabac; - let mut enc = Encoder::new(cfg).expect("encoder"); - let mut clip = Clip::new(w, h); - let (mut bits, mut sum_psnr) = (0usize, 0.0); - let mut share = 0.0; - for t in 0..10 { - render(t, &mut clip); - bits += enc.encode(&clip.view()).expect("encode").au.len() * 8; - let rec = enc.reconstruction().expect("reconstruction"); - sum_psnr += psnr(&clip.y, &rec.0); - } - if t8x8 { - let (i, p) = enc.transform_8x8_mbs(); - eprintln!("8x8 MBs: intra {i} inter {p}"); - share = (i + p) as f64 / (10.0 * (w / 16 * h / 16) as f64); - } - (bits as f64, sum_psnr / 10.0, share) - }; - let qps = [22, 26, 30, 34]; - let on: Vec<_> = qps.iter().map(|&q| run(true, q, true)).collect(); - let off: Vec<_> = qps.iter().map(|&q| run(false, q, true)).collect(); - refuse_flat_window(off.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP"); - let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); - let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); - let bd = bd_psnr_delta(&on_curve, &off_curve); - let share = on.iter().map(|&(_, _, share)| share).sum::() / on.len() as f64; - // What the flag buys, not what the encoder is worth: both arms move when - // the paths under them change. It was re-pinned from 0.255 when the 4x4 - // luma path gained its coded_block_pattern group test, which is in the - // flag-off arm and improved it -- the same change moves the absolute - // synthetic comparison against x264 from -4.060 to -3.969 dB, and the - // flag-on arm barely at all, because a transform_8x8 macroblock does not - // go through that path. - const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.230; - eprintln!( - "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", - share * 100.0 - ); - assert!(share > 0.0, "no 8x8 macroblocks were coded"); - assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off"); - assert!( - bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB, - "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate" - ); -} - /// ffmpeg's decode of our stream is our reconstruction, sample for sample, /// across a QP sweep and at a size that is not a multiple of a macroblock. #[test] @@ -968,423 +576,12 @@ fn open_h264_source( panic!("{}: no video track found", path.to_string_lossy()); } -/// The first `want` pictures a second apart from one of the user's media -/// files: demuxed by [`open_h264_source`] (MP4 or Matroska), decoded by this -/// crate, every Nth frame with N the source frame rate. Returns the -/// luma/chroma size and the pictures. -fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec) { - use ec_core::registry::Decoder as _; - - let (params, mut demux, index) = open_h264_source(path); - let video = match ¶ms.media { - ec_core::registry::MediaParameters::Video(v) => v, - _ => panic!("the H.264 track carries no video parameters"), - }; - let (w, h) = (video.width as usize, video.height as usize); - // Consecutive pictures by default. This used to take one picture a second, - // which measured an encoder on content it never sees: at a second apart - // nothing is predictable from the previous picture, so P slices went 93% - // intra on film and the inter path was never really under test. - // `EC_H264_CLIP_STRIDE` restores a wider spacing (`fps` takes one a - // second) for the deliberately-uncorrelated case. - let stride = match std::env::var("EC_H264_CLIP_STRIDE").as_deref() { - Ok("fps") => video - .frame_rate - .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1)), - Ok(n) => n.parse().unwrap_or(1usize).max(1), - Err(_) => 1, - }; - let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); - // Pictures to pass over before sampling: the head of a film is titles and - // fades, which are not what a codec is measured on. - let skip: usize = std::env::var("EC_H264_CLIP_SKIP") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(0); - let mut sources: Vec = Vec::new(); - let mut seen = 0usize; - while sources.len() < want { - let Ok(packet) = demux.next_packet() else { - break; - }; - if packet.stream != index { - continue; - } - dec.send_packet(&packet).expect("decode"); - while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { - if seen >= skip && sources.len() < want && (seen - skip).is_multiple_of(stride) { - sources.push(planes_of(&f)); - } - seen += 1; - } - } - assert!( - sources.len() >= 10, - "only {} pictures decoded from {}", - sources.len(), - path.to_string_lossy() - ); - eprintln!( - "{}: {}x{}, {} pictures, every {stride}th of {seen}", - path.to_string_lossy(), - w, - h, - sources.len() - ); - (w, h, sources) -} - -/// BD-PSNR of the `transform_8x8` flag (on by default) against flag-off on one real -/// clip from the library, full size, over a QP sweep: the number the synthetic -/// gate above cannot give, because the synthetic clip is content the flag wins -/// on. Prints the per-QP points, the BD-PSNR and the 8x8 macroblock share; -/// asserts nothing, so a regressing clip fails a gate, not the test run. -/// -/// EC_H264_CLIP= cargo test --release -p ec-h264 --test encode \ -/// real_clip_t8x8_bd_psnr -- --ignored --nocapture -#[test] -#[ignore = "slow measurement on the open 480p trailer"] -fn real_clip_t8x8_bd_psnr() { - let path = ec_testkit::fixture("open/sintel_trailer-480p.mp4"); - let (w, h, sources) = clip_sources(path.as_os_str(), 30); - - let run = |t8x8: bool, qp: i32| { - let mut cfg = EncoderConfig::new(w as u32, h as u32); - cfg.qp = qp; - cfg.gop_size = 10; - cfg.cabac = true; - cfg.transform_8x8 = t8x8; - cfg.framerate = 1.0; // the kept pictures are a second apart - cfg.threads = 0; - let mut enc = Encoder::new(cfg).expect("encoder"); - let (mut bits, mut sum_psnr) = (0usize, 0.0); - for (y, u, v) in &sources { - let view = PictureView::i420(w as u32, h as u32, y, u, v); - bits += enc.encode(&view).expect("encode").au.len() * 8; - let rec = enc.reconstruction().expect("reconstruction"); - sum_psnr += psnr(y, &rec.0); - } - let (i8x8, p8x8) = enc.transform_8x8_mbs(); - let share = (i8x8 + p8x8) as f64 / (sources.len() * (w / 16) * (h / 16)) as f64; - (bits as f64, sum_psnr / sources.len() as f64, share) - }; - let qps = [22, 26, 30, 34]; - let off: Vec<_> = qps.iter().map(|&q| run(false, q)).collect(); - let on: Vec<_> = qps.iter().map(|&q| run(true, q)).collect(); - for (i, &qp) in qps.iter().enumerate() { - let (ob, op, _) = off[i]; - let (nb, np, share) = on[i]; - eprintln!( - "qp {qp}: flag-off {ob:.0} bits {op:.2} dB | flag-on {nb:.0} bits {np:.2} dB, 8x8 share {:.1}%", - share * 100.0 - ); - } - let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); - let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); - let bd = bd_psnr_delta(&on_curve, &off_curve); - let share = on.iter().map(|&(_, _, s)| s).sum::() / on.len() as f64; - eprintln!( - "BD-PSNR flag-on vs flag-off over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", - share * 100.0 - ); -} - // --------------------------------------------------------------------------- // The encoder's rate-quality distance from x264: the survey's rank-1 gap, // because until this test existed the repo could measure our decoder against // every reference and our encoder against nothing but itself. // --------------------------------------------------------------------------- -/// Floor for [`bd_psnr_vs_x264`] on the synthetic clip. Our encoder measures -/// -4.523 dB against x264 there (352x288, 24 pictures of -/// `Clip::render_smooth`, both encoders at their own default effort: our -/// `Preset::Fast`, x264's `-preset medium`). The floor is that number with -/// room for platform noise, so the distance can shrink but not grow -/// unnoticed; it is not a claim that -4.5 dB is fine. On a 3840x1608 clip -/// from the library the same measurement reads -0.728 dB and on a 2560x1440 -/// screen capture -0.500, so this synthetic number is the pessimistic end of -/// the range and not the typical one. -/// -/// It moved -4.449 -> -4.523 when the intra-versus-inter decision started -/// coding both branches for real. That change is worth 0.315 dB on the film -/// clip and 0.564 on the screen capture, and takes fewer bits at every QP -/// while doing it. This clip prefers a heavier rate term in that decision -/// (see the sweep in `enc/mb.rs`), which the two real clips do not. -/// -/// It moved -4.523 -> -4.073 when inter luma levels started being chosen -/// against the CABAC coder's own price for them (0.100 dB on the film clip, -/// 0.029 on the screen capture). -const BD_PSNR_VS_X264_FLOOR: f64 = -4.15; - -fn have_x264() -> bool { - ec_testkit::ffmpeg() - .args(["-v", "error", "-hide_banner", "-encoders"]) - .output() - .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx264")) -} - -/// Encode raw I420 pictures with x264 at constant QP, matched to what our -/// encoder actually does: Main profile (CABAC, no 8x8 transform), one -/// reference, no B pictures, the same GOP, and adaptive quantisation and psy -/// off so both encoders spend bits by the same rule. Returns the Annex B -/// stream. -fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) -> Option> { - // Distinct per call, not per process: two #[test]s in this binary call - // this on parallel threads with overlapping qp values, and a path keyed - // only on qp lets one call's cleanup delete another's still-in-use file. - static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!("ec-h264-x264-{}", std::process::id())); - std::fs::create_dir_all(&dir).ok()?; - let raw = dir.join(format!("in-q{qp}-{seq}.yuv")); - let out = dir.join(format!("out-q{qp}-{seq}.264")); - let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); - for (y, u, v) in sources { - buf.extend_from_slice(y); - buf.extend_from_slice(u); - buf.extend_from_slice(v); - } - pin_or_bail("x264_encode_qp", &raw, &buf)?; - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y"]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .args(["-s", &format!("{w}x{h}"), "-r", "1"]) - .arg("-i") - .arg(&raw) - // EC_H264_X264_PRESET selects the reference preset; the DONE.md target is - // measured against `veryfast`, the default stays `medium` for the older gates. - .args([ - "-c:v", - "libx264", - "-preset", - &std::env::var("EC_H264_X264_PRESET").unwrap_or_else(|_| "medium".into()), - ]) - .args(["-profile:v", "main", "-qp", &qp.to_string()]) - .args(["-g", &gop.to_string(), "-bf", "0", "-refs", "1"]) - // ipratio/pbratio 1.0 matter: x264's constant-QP mode otherwise codes - // I pictures at a lower QP than the one asked for, which reads as a - // rate-quality win that is really a different quantiser. - // EC_H264_X264_PARAMS appends to this list, which is how a single - // reference feature gets attributed: running the sweep again with - // `trellis=0` says how much of x264's lead is its rate-distortion - // quantisation rather than its prediction. - .args([ - "-x264-params", - &format!( - "scenecut=0:aq-mode=0:psy=0:8x8dct=0:ipratio=1.0:pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}", - match std::env::var("EC_H264_X264_PARAMS") { - // The value may or may not carry its own leading colon; - // both spell the same thing. Passing it through would not: - // ffmpeg drops the token after an empty one, so "::subme=1" - // silently encodes at the preset's subme and the sweep - // reads as "the feature does nothing". - Ok(extra) if !extra.trim().trim_matches(':').is_empty() => - format!(":{}", extra.trim().trim_matches(':')), - _ => String::new(), - } - ), - ]) - .args(["-f", "h264"]) - .arg(&out) - .output() - .ok()?; - let _ = std::fs::remove_file(&raw); - if !status.status.success() { - eprintln!("x264 failed: {}", String::from_utf8_lossy(&status.stderr)); - return None; - } - let stream = std::fs::read(&out).ok()?; - let _ = std::fs::remove_file(&out); - Some(stream) -} - -/// BD-PSNR of our encoder against x264 at matched features over QP -/// 22/26/30/34. Runs on the synthetic clip by default, so the number cannot -/// rot behind an `#[ignore]`; point `EC_H264_CLIP` at a media file to measure -/// the same thing on real content. -/// -/// Both curves are (bits, luma PSNR against the same source pictures), and -/// both are measured on ffmpeg's decode of the stream rather than on an -/// encoder's own reconstruction, so the two halves are read the same way. -/// -/// `EC_H264_GOP` sets the GOP of both encoders; 1 makes the comparison -/// all-intra, which splits the gap between the intra path and the P pictures. -/// -/// `EC_H264_PRESET_BALANCED` runs our half of the comparison at -/// `Preset::Balanced` instead of the default `Preset::Fast`, which separates -/// what search effort buys from what the coder itself costs. -/// -/// `EC_H264_CLIP_SKIP` passes over that many pictures before sampling (film -/// heads are titles and fades), and `EC_H264_CLIP_STRIDE` widens the spacing -/// between the sampled pictures; both default to consecutive pictures from the -/// start of the file. The measurements quoted through this crate that predate -/// those two knobs were taken one picture a second, where nothing is -/// predictable from the previous picture -- they are not comparable with the -/// numbers taken since. -/// -/// cargo test --release -p ec-h264 --test encode bd_psnr_vs_x264 -- --nocapture -/// EC_H264_CLIP= cargo test --release -p ec-h264 --test encode \ -/// bd_psnr_vs_x264 -- --nocapture -#[test] -fn bd_psnr_vs_x264() { - assert!(have_x264(), "the pinned ffmpeg has no libx264"); - let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") { - Some(path) => clip_sources(&path, 24), - None => { - let (w, h, frames) = (352, 288, 24); - let mut clip = Clip::new(w, h); - let mut sources = Vec::with_capacity(frames); - for t in 0..frames { - clip.render_smooth(t); - sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); - } - eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); - (w, h, sources) - } - }; - - let gop: u32 = std::env::var("EC_H264_GOP") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(10); - let ours = |qp: i32| { - let mut cfg = EncoderConfig::new(w as u32, h as u32); - cfg.qp = qp; - cfg.gop_size = gop; - if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() { - cfg.preset = ec_h264::Preset::Balanced; - } - cfg.cabac = true; - cfg.framerate = 1.0; - cfg.threads = 0; - let mut enc = Encoder::new(cfg).expect("encoder"); - let (mut stream, mut sum_recon) = (Vec::new(), 0.0); - for (y, u, v) in &sources { - let view = PictureView::i420(w as u32, h as u32, y, u, v); - stream.extend_from_slice(&enc.encode(&view).expect("encode").au); - sum_recon += psnr(y, &enc.reconstruction().expect("reconstruction").0); - } - // Measured the same way x264 is: on what a decoder shows, not on the - // encoder's own reconstruction. The two are printed together because a - // gap between them is a bug in one of the halves, not a rate-quality - // result. - let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); - assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); - let sum: f64 = sources - .iter() - .zip(&decoded) - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) - .sum(); - let sum_yuv: f64 = sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr_yuv(s, d)) - .sum(); - let (sum_u, sum_v) = ( - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.1, &d.1)) - .sum::(), - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.2, &d.2)) - .sum::(), - ); - eprintln!( - " ours qp {qp}: u {:.2} dB v {:.2} dB", - sum_u / sources.len() as f64, - sum_v / sources.len() as f64 - ); - let (decoded_psnr, recon_psnr) = - (sum / sources.len() as f64, sum_recon / sources.len() as f64); - assert!( - (decoded_psnr - recon_psnr).abs() < 0.05, - "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ - stream decodes to {decoded_psnr:.2} dB" - ); - ( - (stream.len() * 8) as f64, - decoded_psnr, - sum_yuv / sources.len() as f64, - ) - }; - let x264 = |qp: i32| { - let stream = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes"); - let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes x264's own stream"); - assert_eq!( - decoded.len(), - sources.len(), - "x264 returned {} pictures for {} sources", - decoded.len(), - sources.len() - ); - let sum: f64 = sources - .iter() - .zip(&decoded) - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) - .sum(); - let sum_yuv: f64 = sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr_yuv(s, d)) - .sum(); - let n = sources.len() as f64; - eprintln!( - " x264 qp {qp}: u {:.2} dB v {:.2} dB", - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.1, &d.1)) - .sum::() - / n, - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.2, &d.2)) - .sum::() - / n - ); - ((stream.len() * 8) as f64, sum / n, sum_yuv / n) - }; - - let qps = [22, 26, 30, 34]; - let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect(); - let theirs: Vec<_> = qps.iter().map(|&q| x264(q)).collect(); - for (i, &qp) in qps.iter().enumerate() { - let (ob, op, oy) = mine[i]; - let (xb, xp, xy) = theirs[i]; - eprintln!( - "qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv) | x264 {xb:.0} bits {xp:.2} dB \ - ({xy:.2} yuv) ({:+.1}% bits, {:+.2} dB, {:+.2} yuv)", - (ob / xb - 1.0) * 100.0, - op - xp, - oy - xy - ); - } - refuse_flat_window(theirs.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP"); - let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { - v.iter() - .map(|&(b, p, y)| (b, if luma { p } else { y })) - .collect() - }; - let bd = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); - let bd_yuv = bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); - eprintln!("BD-PSNR ours vs x264 over q22/26/30/34: {bd:+.3} dB"); - eprintln!("BD-PSNR-YUV ours vs x264 over q22/26/30/34: {bd_yuv:+.3} dB"); - - // The floor is calibrated on the synthetic clip; a clip of the user's is a - // measurement, not a gate, because its content is not pinned. - if std::env::var_os("EC_H264_CLIP").is_none() && gop == 10 { - assert!( - bd > BD_PSNR_VS_X264_FLOOR, - "BD-PSNR against x264 fell to {bd:+.3} dB, past the \ - {BD_PSNR_VS_X264_FLOOR:+.3} dB floor" - ); - } -} - /// The partitions only `Preset::Balanced` searches, decoded by ffmpeg. /// /// The default preset codes every P macroblock as one 16x16 partition, so the