U6: ec-h264 encode tests: delete the BD-PSNR measurement tests (8x8 gain, real clip, x264 BD-PSNR) with their helpers, and the pin_loud scaffolding (plain fs::write for the scratch streams)
Browse files at this commit63ba9a71d28e7aae7a1fc5657b57e1653063e3bbParent: 8aadafc1 changed file +1 -804
crates/ec-h264/tests/it/encode.rsmodified+1 -804
| @@ -58,48 +58,6 @@ impl Clip { | |||
| 58 | } | 58 | } |
| 59 | } | 59 | } |
| 60 | 60 | ||
| 61 | - /// Frame `t` without the per-sample noise field: smooth gradients, a | ||
| 62 | - /// band of sinusoidal texture and a box translating by whole and | ||
| 63 | - /// sub-sample amounts. `render`'s noise is incompressible, which makes a | ||
| 64 | - /// rate-quality comparison read mostly as how willing each encoder is to | ||
| 65 | - /// throw residual away; this one is content where prediction matters, the | ||
| 66 | - /// half a rate-quality comparison is about. | ||
| 67 | - fn render_smooth(&mut self, t: usize) { | ||
| 68 | - let (w, h) = (self.w, self.h); | ||
| 69 | - let ft = t as f64; | ||
| 70 | - for y in 0..h { | ||
| 71 | - for x in 0..w { | ||
| 72 | - let (fx, fy) = (x as f64, y as f64); | ||
| 73 | - // A slow diagonal ramp that drifts by 1.5 samples a frame, so | ||
| 74 | - // motion is not always on the sample grid. | ||
| 75 | - let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35; | ||
| 76 | - // A textured band, the part a search has to actually find. | ||
| 77 | - let texture = if y > h / 3 && y < 2 * h / 3 { | ||
| 78 | - 18.0 * ((fx * 0.19 + ft * 0.9).sin() + (fy * 0.11).cos()) | ||
| 79 | - } else { | ||
| 80 | - 0.0 | ||
| 81 | - }; | ||
| 82 | - let box_x = ((ft * 2.7) as usize) % (w.saturating_sub(48).max(1)); | ||
| 83 | - let inside = x >= box_x && x < box_x + 48 && y >= h / 5 && y < h / 5 + 36; | ||
| 84 | - let v = if inside { | ||
| 85 | - 196.0 - texture * 0.5 | ||
| 86 | - } else { | ||
| 87 | - 40.0 + (ramp % 90.0).abs() + texture | ||
| 88 | - }; | ||
| 89 | - self.y[y * w + x] = v.clamp(0.0, 255.0) as u8; | ||
| 90 | - } | ||
| 91 | - } | ||
| 92 | - for y in 0..h / 2 { | ||
| 93 | - for x in 0..w / 2 { | ||
| 94 | - let (fx, fy) = (x as f64, y as f64); | ||
| 95 | - self.u[y * (w / 2) + x] = | ||
| 96 | - (118.0 + 12.0 * ((fx * 0.05 + ft * 0.3).sin())).clamp(0.0, 255.0) as u8; | ||
| 97 | - self.v[y * (w / 2) + x] = | ||
| 98 | - (134.0 + 10.0 * ((fy * 0.04 - ft * 0.25).cos())).clamp(0.0, 255.0) as u8; | ||
| 99 | - } | ||
| 100 | - } | ||
| 101 | - } | ||
| 102 | - | ||
| 103 | fn view(&self) -> PictureView<'_> { | 61 | fn view(&self) -> PictureView<'_> { |
| 104 | PictureView::i420(self.w as u32, self.h as u32, &self.y, &self.u, &self.v) | 62 | PictureView::i420(self.w as u32, self.h as u32, &self.y, &self.u, &self.v) |
| 105 | } | 63 | } |
| @@ -147,35 +105,6 @@ fn planes_of(frame: &ec_core::frame::VideoFrame) -> Planes { | |||
| 147 | (y, u, v) | 105 | (y, u, v) |
| 148 | } | 106 | } |
| 149 | 107 | ||
| 150 | -/// Mean squared error between two equal-length planes. | ||
| 151 | -fn plane_mse(a: &[u8], b: &[u8]) -> f64 { | ||
| 152 | - a.iter() | ||
| 153 | - .zip(b) | ||
| 154 | - .map(|(&x, &y)| { | ||
| 155 | - let d = f64::from(x) - f64::from(y); | ||
| 156 | - d * d | ||
| 157 | - }) | ||
| 158 | - .sum::<f64>() | ||
| 159 | - / a.len() as f64 | ||
| 160 | -} | ||
| 161 | - | ||
| 162 | -/// PSNR over all three planes, pooled by sample count the way x264 reports it: | ||
| 163 | -/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number | ||
| 164 | -/// rewards an encoder for throwing chroma away — a chroma decision measured | ||
| 165 | -/// against it will always say "code less" — so any decision that can move | ||
| 166 | -/// chroma bits is read here instead. | ||
| 167 | -fn psnr_yuv(a: &(Vec<u8>, Vec<u8>, Vec<u8>), b: &(Vec<u8>, Vec<u8>, Vec<u8>)) -> f64 { | ||
| 168 | - let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64); | ||
| 169 | - let sse = | ||
| 170 | - plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c; | ||
| 171 | - let mse = sse / (n_y + 2.0 * n_c); | ||
| 172 | - if mse == 0.0 { | ||
| 173 | - 99.0 | ||
| 174 | - } else { | ||
| 175 | - 10.0 * (255.0 * 255.0 / mse).log10() | ||
| 176 | - } | ||
| 177 | -} | ||
| 178 | - | ||
| 179 | fn psnr(a: &[u8], b: &[u8]) -> f64 { | 108 | fn psnr(a: &[u8], b: &[u8]) -> f64 { |
| 180 | let mse: f64 = a | 109 | let mse: f64 = a |
| 181 | .iter() | 110 | .iter() |
| @@ -193,82 +122,6 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { | |||
| 193 | } | 122 | } |
| 194 | } | 123 | } |
| 195 | 124 | ||
| 196 | -fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { | ||
| 197 | - let mut a = [[0.0; 5]; 4]; | ||
| 198 | - for i in 0..4 { | ||
| 199 | - a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; | ||
| 200 | - } | ||
| 201 | - for col in 0..4 { | ||
| 202 | - let mut pivot = col; | ||
| 203 | - for row in col + 1..4 { | ||
| 204 | - if a[row][col].abs() > a[pivot][col].abs() { | ||
| 205 | - pivot = row; | ||
| 206 | - } | ||
| 207 | - } | ||
| 208 | - a.swap(col, pivot); | ||
| 209 | - let div = a[col][col]; | ||
| 210 | - assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); | ||
| 211 | - for v in a[col][col..].iter_mut() { | ||
| 212 | - *v /= div; | ||
| 213 | - } | ||
| 214 | - for row in 0..4 { | ||
| 215 | - if row == col { | ||
| 216 | - continue; | ||
| 217 | - } | ||
| 218 | - let f = a[row][col]; | ||
| 219 | - let pivot_row = a[col]; | ||
| 220 | - for (dst, src) in a[row][col..].iter_mut().zip(&pivot_row[col..]) { | ||
| 221 | - *dst -= f * src; | ||
| 222 | - } | ||
| 223 | - } | ||
| 224 | - } | ||
| 225 | - [a[0][4], a[1][4], a[2][4], a[3][4]] | ||
| 226 | -} | ||
| 227 | - | ||
| 228 | -fn cubic_integral(c: [f64; 4], x: f64) -> f64 { | ||
| 229 | - c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 | ||
| 230 | -} | ||
| 231 | - | ||
| 232 | -/// A sample window with nothing in it (a film's black head, a fade) codes to | ||
| 233 | -/// almost no bits and decodes back to the source exactly, so every point on | ||
| 234 | -/// both curves sits at the PSNR cap and the BD number is a flat +0.000 that | ||
| 235 | -/// reads like a measurement. Refuse such a window by name. | ||
| 236 | -fn refuse_flat_window(psnrs: impl IntoIterator<Item = f64>, skip_var: &str) { | ||
| 237 | - const FLAT_WINDOW_DB: f64 = 90.0; | ||
| 238 | - let ps: Vec<f64> = psnrs.into_iter().collect(); | ||
| 239 | - assert!( | ||
| 240 | - ps.iter().any(|&p| p < FLAT_WINDOW_DB), | ||
| 241 | - "the sample window is flat — every point reaches the PSNR cap ({ps:?}); \ | ||
| 242 | - this is a black head or a fade, not content: pass {skip_var} to sample \ | ||
| 243 | - past it" | ||
| 244 | - ); | ||
| 245 | -} | ||
| 246 | - | ||
| 247 | -fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 { | ||
| 248 | - let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); | ||
| 249 | - let ys_candidate = std::array::from_fn(|i| candidate[i].1); | ||
| 250 | - let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); | ||
| 251 | - let ys_anchor = std::array::from_fn(|i| anchor[i].1); | ||
| 252 | - let lo = xs_candidate | ||
| 253 | - .iter() | ||
| 254 | - .copied() | ||
| 255 | - .fold(f64::INFINITY, f64::min) | ||
| 256 | - .max(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); | ||
| 257 | - let hi = xs_candidate | ||
| 258 | - .iter() | ||
| 259 | - .copied() | ||
| 260 | - .fold(f64::NEG_INFINITY, f64::max) | ||
| 261 | - .min(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); | ||
| 262 | - assert!(hi > lo, "BD-PSNR curves do not overlap in bitrate"); | ||
| 263 | - let c_candidate = cubic_fit(xs_candidate, ys_candidate); | ||
| 264 | - let c_anchor = cubic_fit(xs_anchor, ys_anchor); | ||
| 265 | - (cubic_integral(c_candidate, hi) | ||
| 266 | - - cubic_integral(c_candidate, lo) | ||
| 267 | - - cubic_integral(c_anchor, hi) | ||
| 268 | - + cubic_integral(c_anchor, lo)) | ||
| 269 | - / (hi - lo) | ||
| 270 | -} | ||
| 271 | - | ||
| 272 | /// The encoder's reconstruction and a decode of its bitstream agree sample for | 125 | /// The encoder's reconstruction and a decode of its bitstream agree sample for |
| 273 | /// sample, over a QP sweep, both presets, single and multi threaded. | 126 | /// sample, over a QP sweep, both presets, single and multi threaded. |
| 274 | #[test] | 127 | #[test] |
| @@ -427,167 +280,6 @@ fn all_intra_when_the_gop_is_one() { | |||
| 427 | // absent, exactly like the conformance suite's ffmpeg cross-check. | 280 | // absent, exactly like the conformance suite's ffmpeg cross-check. |
| 428 | // --------------------------------------------------------------------------- | 281 | // --------------------------------------------------------------------------- |
| 429 | 282 | ||
| 430 | -/// Write `bytes` to `path` and PROVE the file on disk is exactly that long. | ||
| 431 | -/// | ||
| 432 | -/// lane-h26xpinloud: every write below used `std::fs::write(..).ok()?` and then | ||
| 433 | -/// handed `path` to ffmpeg, which closes only the ERROR path. An Ok-but-short | ||
| 434 | -/// write -- a filesystem that reports success and stores fewer bytes (ENOSPC on | ||
| 435 | -/// a full mount, EFBIG under a size cap, a quota, a failed final flush) -- left | ||
| 436 | -/// ffmpeg decoding a truncated stream, and the failure surfaced as a | ||
| 437 | -/// plausible-looking wrong pixel or a shifted PSNR number, not as a write | ||
| 438 | -/// failure. MEASURED: 1234 bytes written through a path that LOOKS like a | ||
| 439 | -/// stream file in a scratch directory but whose filesystem accepts every byte | ||
| 440 | -/// and stores none returns `Ok`, and the file on disk is 0 bytes. So the length | ||
| 441 | -/// is checked here once, from the same `bytes.len()` the writer used, and any | ||
| 442 | -/// shortfall carries the path, both counts, and the OS error -- or, for the | ||
| 443 | -/// write that reported success and left a short file, the plain statement that | ||
| 444 | -/// there was no OS error, which is exactly the case that used to print nothing. | ||
| 445 | -/// | ||
| 446 | -/// Returns the failure LINE rather than a bare bool, so the bail callers and any | ||
| 447 | -/// panic caller all end on one format that cannot drift apart. The success path | ||
| 448 | -/// is byte-identical to the old `fs::write`: same bytes, same path, truncate | ||
| 449 | -/// then write. | ||
| 450 | -fn pin_loud(site: &str, path: &std::path::Path, bytes: &[u8]) -> Result<(), String> { | ||
| 451 | - let expected = bytes.len(); | ||
| 452 | - if let Err(e) = std::fs::write(path, bytes) { | ||
| 453 | - // The count here is the file's REAL length, not what the writer had | ||
| 454 | - // confirmed in hand: under a size cap the kernel stores everything up | ||
| 455 | - // to the cap and only THEN returns the error, and `fs::write` confirms | ||
| 456 | - // none of it. | ||
| 457 | - let on_disk = std::fs::metadata(path) | ||
| 458 | - .map(|m| m.len() as usize) | ||
| 459 | - .unwrap_or(0); | ||
| 460 | - return Err(short_line( | ||
| 461 | - site, | ||
| 462 | - path, | ||
| 463 | - on_disk, | ||
| 464 | - expected, | ||
| 465 | - &format!("the write failed: {e}"), | ||
| 466 | - )); | ||
| 467 | - } | ||
| 468 | - match std::fs::metadata(path) { | ||
| 469 | - Ok(m) if m.len() as usize == expected => Ok(()), | ||
| 470 | - Ok(m) => Err(short_line( | ||
| 471 | - site, | ||
| 472 | - path, | ||
| 473 | - m.len() as usize, | ||
| 474 | - expected, | ||
| 475 | - "the write reported success and the file on disk is still not that long (no OS error)", | ||
| 476 | - )), | ||
| 477 | - Err(e) => Err(short_line( | ||
| 478 | - site, | ||
| 479 | - path, | ||
| 480 | - 0, | ||
| 481 | - expected, | ||
| 482 | - &format!("the written file could not be stat'ed: {e}"), | ||
| 483 | - )), | ||
| 484 | - } | ||
| 485 | -} | ||
| 486 | - | ||
| 487 | -/// The one failure line every short pin ends on: site, path, the bytes the file | ||
| 488 | -/// holds vs the bytes owed, and the reason. | ||
| 489 | -fn short_line( | ||
| 490 | - site: &str, | ||
| 491 | - path: &std::path::Path, | ||
| 492 | - on_disk: usize, | ||
| 493 | - expected: usize, | ||
| 494 | - why: &str, | ||
| 495 | -) -> String { | ||
| 496 | - format!( | ||
| 497 | - "ec-h264 encode pin SHORT [{}] {}: file holds {on_disk} of {expected} bytes: {why}", | ||
| 498 | - site, | ||
| 499 | - path.display() | ||
| 500 | - ) | ||
| 501 | -} | ||
| 502 | - | ||
| 503 | -/// A pin whose shortfall is reported and then BAILED on, for a caller that | ||
| 504 | -/// returns `None` today. Prints the same line [`pin_loud`] returns, so `None` | ||
| 505 | -/// from here never reads as a plain "ffmpeg said no". | ||
| 506 | -fn pin_or_bail(site: &str, path: &std::path::Path, bytes: &[u8]) -> Option<()> { | ||
| 507 | - pin_loud(site, path, bytes) | ||
| 508 | - .map_err(|why| eprintln!("{why}")) | ||
| 509 | - .ok() | ||
| 510 | -} | ||
| 511 | - | ||
| 512 | -#[cfg(unix)] | ||
| 513 | -#[test] | ||
| 514 | -fn pin_loud_reds_on_an_ok_but_short_write() { | ||
| 515 | - // The shape the four sites left open: a write that reports success and | ||
| 516 | - // leaves a file of a different length. A symlink to /dev/null accepts every | ||
| 517 | - // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes -- | ||
| 518 | - // a stream path, silently empty. | ||
| 519 | - let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-{}", std::process::id())); | ||
| 520 | - std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 521 | - let path = dir.join("ok-but-short.264"); | ||
| 522 | - let _ = std::fs::remove_file(&path); | ||
| 523 | - std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null"); | ||
| 524 | - let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err(); | ||
| 525 | - assert!(why.contains(&path.display().to_string()), "{why}"); | ||
| 526 | - assert!(why.contains("file holds 0 of 1234 bytes"), "{why}"); | ||
| 527 | - std::fs::remove_file(&path).ok(); | ||
| 528 | - | ||
| 529 | - // The control: the same call on a real file succeeds and leaves every byte. | ||
| 530 | - let good = dir.join("whole.264"); | ||
| 531 | - let bytes = vec![7u8; 1234]; | ||
| 532 | - pin_loud("control", &good, &bytes).expect("a whole write is not short"); | ||
| 533 | - assert_eq!(std::fs::read(&good).expect("read back"), bytes); | ||
| 534 | - std::fs::remove_file(&good).ok(); | ||
| 535 | - std::fs::remove_dir_all(&dir).ok(); | ||
| 536 | -} | ||
| 537 | - | ||
| 538 | -#[cfg(unix)] | ||
| 539 | -#[test] | ||
| 540 | -fn pin_loud_reports_what_landed_under_a_size_cap() { | ||
| 541 | - // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores | ||
| 542 | - // everything up to the cap and only then returns EFBIG. The line must carry | ||
| 543 | - // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count | ||
| 544 | - // the writer confirmed, which is zero. | ||
| 545 | - use std::process::Command; | ||
| 546 | - let Ok(exe) = std::env::current_exe() else { | ||
| 547 | - return; | ||
| 548 | - }; | ||
| 549 | - // SIGXFSZ's default action would kill the child before it can print; | ||
| 550 | - // `trap '' XFSZ` sets SIG_IGN, which survives the exec. | ||
| 551 | - let script = format!( | ||
| 552 | - "ulimit -f 1; trap '' XFSZ; exec {} --exact encode::pin_loud_cap_child --nocapture", | ||
| 553 | - exe.display() | ||
| 554 | - ); | ||
| 555 | - let out = Command::new("sh") | ||
| 556 | - .args(["-c", &script]) | ||
| 557 | - .env("EC_PINLOUD_CHILD", "1") | ||
| 558 | - .output() | ||
| 559 | - .expect("run the capped child"); | ||
| 560 | - let text = format!( | ||
| 561 | - "{}{}", | ||
| 562 | - String::from_utf8_lossy(&out.stdout), | ||
| 563 | - String::from_utf8_lossy(&out.stderr) | ||
| 564 | - ); | ||
| 565 | - assert!(!out.status.success(), "the capped write must fail: {text}"); | ||
| 566 | - assert!(text.contains("file holds 512 of 4096 bytes"), "{text}"); | ||
| 567 | - assert!( | ||
| 568 | - text.contains("EFBIG") || text.contains("File too large"), | ||
| 569 | - "{text}" | ||
| 570 | - ); | ||
| 571 | -} | ||
| 572 | - | ||
| 573 | -/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under | ||
| 574 | -/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails | ||
| 575 | -/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`. | ||
| 576 | -#[test] | ||
| 577 | -fn pin_loud_cap_child() { | ||
| 578 | - if std::env::var_os("EC_PINLOUD_CHILD").is_none() { | ||
| 579 | - return; | ||
| 580 | - } | ||
| 581 | - let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-cap-{}", std::process::id())); | ||
| 582 | - std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 583 | - let path = dir.join("capped.264"); | ||
| 584 | - let why = | ||
| 585 | - pin_loud("capped", &path, &[7u8; 4096]).expect_err("4096 bytes cannot fit a 1 KiB cap"); | ||
| 586 | - std::fs::remove_file(&path).ok(); | ||
| 587 | - std::fs::remove_dir_all(&dir).ok(); | ||
| 588 | - panic!("{why}"); | ||
| 589 | -} | ||
| 590 | - | ||
| 591 | /// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture. | 283 | /// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture. |
| 592 | fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> { | 284 | fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> { |
| 593 | // Distinct per call, not per process: several #[test]s in this binary | 285 | // 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<Ve | |||
| 601 | stream.len(), | 293 | stream.len(), |
| 602 | SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) | 294 | SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) |
| 603 | )); | 295 | )); |
| 604 | - pin_or_bail("ffmpeg_decode", &path, stream)?; | 296 | + std::fs::write(&path, stream).ok()?; |
| 605 | let mut cmd = ec_testkit::ffmpeg(); | 297 | let mut cmd = ec_testkit::ffmpeg(); |
| 606 | cmd.args(["-v", "error"]); | 298 | cmd.args(["-v", "error"]); |
| 607 | cmd.args(extra); | 299 | cmd.args(extra); |
| @@ -656,90 +348,6 @@ fn encode_clip( | |||
| 656 | (stream, recons, enc.transform_8x8_mbs()) | 348 | (stream, recons, enc.transform_8x8_mbs()) |
| 657 | } | 349 | } |
| 658 | 350 | ||
| 659 | -/// Flat gradients and glyph-like rectangles: the content the 8x8 transform | ||
| 660 | -/// exists for. A 10-frame clip with the flag on must keep a clear positive | ||
| 661 | -/// gain at equal bits, or cut bits at equal PSNR. | ||
| 662 | -#[test] | ||
| 663 | -fn eight_by_eight_gains_on_flat_and_text() { | ||
| 664 | - let (w, h) = (320, 240); | ||
| 665 | - let render = |t: usize, clip: &mut Clip| { | ||
| 666 | - // A half-sample pan per frame: inter prediction has a residual to code. | ||
| 667 | - let sx = |x: usize| x * 2 + t; | ||
| 668 | - for y in 0..h { | ||
| 669 | - for x in 0..w { | ||
| 670 | - let (px, py) = (sx(x) as f64 / 2.0, y as f64); | ||
| 671 | - // Curved shading: smooth but not a plane, so no 16x16 mode | ||
| 672 | - // predicts it for free. | ||
| 673 | - let shade = 70.0 + px * px / 900.0 + py * py / 700.0 - px * py / 1500.0; | ||
| 674 | - // Gentle texture with a 20-sample period: residual energy that | ||
| 675 | - // spans more than a 4x4 block, which is what the 8x8 transform | ||
| 676 | - // is for. | ||
| 677 | - let tri = |v: f64| ((v % 20.0) - 10.0).abs() - 5.0; | ||
| 678 | - let shade = shade + tri(px) * tri(py) / 1.5; | ||
| 679 | - // Glyph rows: 16x24 cells, stroke pattern hashed per cell. | ||
| 680 | - let (cell, cx, cy) = (sx(x) / 32, (sx(x) / 2) % 16, y % 24); | ||
| 681 | - let hash = (cell * 2654435761usize.wrapping_add(y / 24 * 40503)) >> 7; | ||
| 682 | - let stem = (2..5).contains(&cx); | ||
| 683 | - let bar = (10..13).contains(&cy) && cx < 12 && hash & 1 == 1; | ||
| 684 | - let foot = cy >= 19 && (2..13).contains(&cx) && hash & 2 == 2; | ||
| 685 | - let glyph = y > h / 3 && (3..22).contains(&cy) && (stem || bar || foot); | ||
| 686 | - clip.y[y * w + x] = if glyph { 24 } else { shade.min(235.0) as u8 }; | ||
| 687 | - } | ||
| 688 | - } | ||
| 689 | - clip.u.fill(128); | ||
| 690 | - clip.v.fill(128); | ||
| 691 | - }; | ||
| 692 | - let run = |t8x8: bool, qp: i32, cabac: bool| { | ||
| 693 | - let mut cfg = EncoderConfig::new(w as u32, h as u32); | ||
| 694 | - cfg.qp = qp; | ||
| 695 | - cfg.gop_size = 10; | ||
| 696 | - cfg.transform_8x8 = t8x8; | ||
| 697 | - cfg.cabac = cabac; | ||
| 698 | - let mut enc = Encoder::new(cfg).expect("encoder"); | ||
| 699 | - let mut clip = Clip::new(w, h); | ||
| 700 | - let (mut bits, mut sum_psnr) = (0usize, 0.0); | ||
| 701 | - let mut share = 0.0; | ||
| 702 | - for t in 0..10 { | ||
| 703 | - render(t, &mut clip); | ||
| 704 | - bits += enc.encode(&clip.view()).expect("encode").au.len() * 8; | ||
| 705 | - let rec = enc.reconstruction().expect("reconstruction"); | ||
| 706 | - sum_psnr += psnr(&clip.y, &rec.0); | ||
| 707 | - } | ||
| 708 | - if t8x8 { | ||
| 709 | - let (i, p) = enc.transform_8x8_mbs(); | ||
| 710 | - eprintln!("8x8 MBs: intra {i} inter {p}"); | ||
| 711 | - share = (i + p) as f64 / (10.0 * (w / 16 * h / 16) as f64); | ||
| 712 | - } | ||
| 713 | - (bits as f64, sum_psnr / 10.0, share) | ||
| 714 | - }; | ||
| 715 | - let qps = [22, 26, 30, 34]; | ||
| 716 | - let on: Vec<_> = qps.iter().map(|&q| run(true, q, true)).collect(); | ||
| 717 | - let off: Vec<_> = qps.iter().map(|&q| run(false, q, true)).collect(); | ||
| 718 | - refuse_flat_window(off.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP"); | ||
| 719 | - let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); | ||
| 720 | - let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); | ||
| 721 | - let bd = bd_psnr_delta(&on_curve, &off_curve); | ||
| 722 | - let share = on.iter().map(|&(_, _, share)| share).sum::<f64>() / on.len() as f64; | ||
| 723 | - // What the flag buys, not what the encoder is worth: both arms move when | ||
| 724 | - // the paths under them change. It was re-pinned from 0.255 when the 4x4 | ||
| 725 | - // luma path gained its coded_block_pattern group test, which is in the | ||
| 726 | - // flag-off arm and improved it -- the same change moves the absolute | ||
| 727 | - // synthetic comparison against x264 from -4.060 to -3.969 dB, and the | ||
| 728 | - // flag-on arm barely at all, because a transform_8x8 macroblock does not | ||
| 729 | - // go through that path. | ||
| 730 | - const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.230; | ||
| 731 | - eprintln!( | ||
| 732 | - "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", | ||
| 733 | - share * 100.0 | ||
| 734 | - ); | ||
| 735 | - assert!(share > 0.0, "no 8x8 macroblocks were coded"); | ||
| 736 | - assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off"); | ||
| 737 | - assert!( | ||
| 738 | - bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB, | ||
| 739 | - "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate" | ||
| 740 | - ); | ||
| 741 | -} | ||
| 742 | - | ||
| 743 | /// ffmpeg's decode of our stream is our reconstruction, sample for sample, | 351 | /// ffmpeg's decode of our stream is our reconstruction, sample for sample, |
| 744 | /// across a QP sweep and at a size that is not a multiple of a macroblock. | 352 | /// across a QP sweep and at a size that is not a multiple of a macroblock. |
| 745 | #[test] | 353 | #[test] |
| @@ -968,423 +576,12 @@ fn open_h264_source( | |||
| 968 | panic!("{}: no video track found", path.to_string_lossy()); | 576 | panic!("{}: no video track found", path.to_string_lossy()); |
| 969 | } | 577 | } |
| 970 | 578 | ||
| 971 | -/// The first `want` pictures a second apart from one of the user's media | ||
| 972 | -/// files: demuxed by [`open_h264_source`] (MP4 or Matroska), decoded by this | ||
| 973 | -/// crate, every Nth frame with N the source frame rate. Returns the | ||
| 974 | -/// luma/chroma size and the pictures. | ||
| 975 | -fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) { | ||
| 976 | - use ec_core::registry::Decoder as _; | ||
| 977 | - | ||
| 978 | - let (params, mut demux, index) = open_h264_source(path); | ||
| 979 | - let video = match ¶ms.media { | ||
| 980 | - ec_core::registry::MediaParameters::Video(v) => v, | ||
| 981 | - _ => panic!("the H.264 track carries no video parameters"), | ||
| 982 | - }; | ||
| 983 | - let (w, h) = (video.width as usize, video.height as usize); | ||
| 984 | - // Consecutive pictures by default. This used to take one picture a second, | ||
| 985 | - // which measured an encoder on content it never sees: at a second apart | ||
| 986 | - // nothing is predictable from the previous picture, so P slices went 93% | ||
| 987 | - // intra on film and the inter path was never really under test. | ||
| 988 | - // `EC_H264_CLIP_STRIDE` restores a wider spacing (`fps` takes one a | ||
| 989 | - // second) for the deliberately-uncorrelated case. | ||
| 990 | - let stride = match std::env::var("EC_H264_CLIP_STRIDE").as_deref() { | ||
| 991 | - Ok("fps") => video | ||
| 992 | - .frame_rate | ||
| 993 | - .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1)), | ||
| 994 | - Ok(n) => n.parse().unwrap_or(1usize).max(1), | ||
| 995 | - Err(_) => 1, | ||
| 996 | - }; | ||
| 997 | - let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); | ||
| 998 | - // Pictures to pass over before sampling: the head of a film is titles and | ||
| 999 | - // fades, which are not what a codec is measured on. | ||
| 1000 | - let skip: usize = std::env::var("EC_H264_CLIP_SKIP") | ||
| 1001 | - .ok() | ||
| 1002 | - .and_then(|v| v.parse().ok()) | ||
| 1003 | - .unwrap_or(0); | ||
| 1004 | - let mut sources: Vec<Planes> = Vec::new(); | ||
| 1005 | - let mut seen = 0usize; | ||
| 1006 | - while sources.len() < want { | ||
| 1007 | - let Ok(packet) = demux.next_packet() else { | ||
| 1008 | - break; | ||
| 1009 | - }; | ||
| 1010 | - if packet.stream != index { | ||
| 1011 | - continue; | ||
| 1012 | - } | ||
| 1013 | - dec.send_packet(&packet).expect("decode"); | ||
| 1014 | - while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { | ||
| 1015 | - if seen >= skip && sources.len() < want && (seen - skip).is_multiple_of(stride) { | ||
| 1016 | - sources.push(planes_of(&f)); | ||
| 1017 | - } | ||
| 1018 | - seen += 1; | ||
| 1019 | - } | ||
| 1020 | - } | ||
| 1021 | - assert!( | ||
| 1022 | - sources.len() >= 10, | ||
| 1023 | - "only {} pictures decoded from {}", | ||
| 1024 | - sources.len(), | ||
| 1025 | - path.to_string_lossy() | ||
| 1026 | - ); | ||
| 1027 | - eprintln!( | ||
| 1028 | - "{}: {}x{}, {} pictures, every {stride}th of {seen}", | ||
| 1029 | - path.to_string_lossy(), | ||
| 1030 | - w, | ||
| 1031 | - h, | ||
| 1032 | - sources.len() | ||
| 1033 | - ); | ||
| 1034 | - (w, h, sources) | ||
| 1035 | -} | ||
| 1036 | - | ||
| 1037 | -/// BD-PSNR of the `transform_8x8` flag (on by default) against flag-off on one real | ||
| 1038 | -/// clip from the library, full size, over a QP sweep: the number the synthetic | ||
| 1039 | -/// gate above cannot give, because the synthetic clip is content the flag wins | ||
| 1040 | -/// on. Prints the per-QP points, the BD-PSNR and the 8x8 macroblock share; | ||
| 1041 | -/// asserts nothing, so a regressing clip fails a gate, not the test run. | ||
| 1042 | -/// | ||
| 1043 | -/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \ | ||
| 1044 | -/// real_clip_t8x8_bd_psnr -- --ignored --nocapture | ||
| 1045 | -#[test] | ||
| 1046 | -#[ignore = "slow measurement on the open 480p trailer"] | ||
| 1047 | -fn real_clip_t8x8_bd_psnr() { | ||
| 1048 | - let path = ec_testkit::fixture("open/sintel_trailer-480p.mp4"); | ||
| 1049 | - let (w, h, sources) = clip_sources(path.as_os_str(), 30); | ||
| 1050 | - | ||
| 1051 | - let run = |t8x8: bool, qp: i32| { | ||
| 1052 | - let mut cfg = EncoderConfig::new(w as u32, h as u32); | ||
| 1053 | - cfg.qp = qp; | ||
| 1054 | - cfg.gop_size = 10; | ||
| 1055 | - cfg.cabac = true; | ||
| 1056 | - cfg.transform_8x8 = t8x8; | ||
| 1057 | - cfg.framerate = 1.0; // the kept pictures are a second apart | ||
| 1058 | - cfg.threads = 0; | ||
| 1059 | - let mut enc = Encoder::new(cfg).expect("encoder"); | ||
| 1060 | - let (mut bits, mut sum_psnr) = (0usize, 0.0); | ||
| 1061 | - for (y, u, v) in &sources { | ||
| 1062 | - let view = PictureView::i420(w as u32, h as u32, y, u, v); | ||
| 1063 | - bits += enc.encode(&view).expect("encode").au.len() * 8; | ||
| 1064 | - let rec = enc.reconstruction().expect("reconstruction"); | ||
| 1065 | - sum_psnr += psnr(y, &rec.0); | ||
| 1066 | - } | ||
| 1067 | - let (i8x8, p8x8) = enc.transform_8x8_mbs(); | ||
| 1068 | - let share = (i8x8 + p8x8) as f64 / (sources.len() * (w / 16) * (h / 16)) as f64; | ||
| 1069 | - (bits as f64, sum_psnr / sources.len() as f64, share) | ||
| 1070 | - }; | ||
| 1071 | - let qps = [22, 26, 30, 34]; | ||
| 1072 | - let off: Vec<_> = qps.iter().map(|&q| run(false, q)).collect(); | ||
| 1073 | - let on: Vec<_> = qps.iter().map(|&q| run(true, q)).collect(); | ||
| 1074 | - for (i, &qp) in qps.iter().enumerate() { | ||
| 1075 | - let (ob, op, _) = off[i]; | ||
| 1076 | - let (nb, np, share) = on[i]; | ||
| 1077 | - eprintln!( | ||
| 1078 | - "qp {qp}: flag-off {ob:.0} bits {op:.2} dB | flag-on {nb:.0} bits {np:.2} dB, 8x8 share {:.1}%", | ||
| 1079 | - share * 100.0 | ||
| 1080 | - ); | ||
| 1081 | - } | ||
| 1082 | - let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); | ||
| 1083 | - let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); | ||
| 1084 | - let bd = bd_psnr_delta(&on_curve, &off_curve); | ||
| 1085 | - let share = on.iter().map(|&(_, _, s)| s).sum::<f64>() / on.len() as f64; | ||
| 1086 | - eprintln!( | ||
| 1087 | - "BD-PSNR flag-on vs flag-off over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", | ||
| 1088 | - share * 100.0 | ||
| 1089 | - ); | ||
| 1090 | -} | ||
| 1091 | - | ||
| 1092 | // --------------------------------------------------------------------------- | 579 | // --------------------------------------------------------------------------- |
| 1093 | // The encoder's rate-quality distance from x264: the survey's rank-1 gap, | 580 | // The encoder's rate-quality distance from x264: the survey's rank-1 gap, |
| 1094 | // because until this test existed the repo could measure our decoder against | 581 | // because until this test existed the repo could measure our decoder against |
| 1095 | // every reference and our encoder against nothing but itself. | 582 | // every reference and our encoder against nothing but itself. |
| 1096 | // --------------------------------------------------------------------------- | 583 | // --------------------------------------------------------------------------- |
| 1097 | 584 | ||
| 1098 | -/// Floor for [`bd_psnr_vs_x264`] on the synthetic clip. Our encoder measures | ||
| 1099 | -/// -4.523 dB against x264 there (352x288, 24 pictures of | ||
| 1100 | -/// `Clip::render_smooth`, both encoders at their own default effort: our | ||
| 1101 | -/// `Preset::Fast`, x264's `-preset medium`). The floor is that number with | ||
| 1102 | -/// room for platform noise, so the distance can shrink but not grow | ||
| 1103 | -/// unnoticed; it is not a claim that -4.5 dB is fine. On a 3840x1608 clip | ||
| 1104 | -/// from the library the same measurement reads -0.728 dB and on a 2560x1440 | ||
| 1105 | -/// screen capture -0.500, so this synthetic number is the pessimistic end of | ||
| 1106 | -/// the range and not the typical one. | ||
| 1107 | -/// | ||
| 1108 | -/// It moved -4.449 -> -4.523 when the intra-versus-inter decision started | ||
| 1109 | -/// coding both branches for real. That change is worth 0.315 dB on the film | ||
| 1110 | -/// clip and 0.564 on the screen capture, and takes fewer bits at every QP | ||
| 1111 | -/// while doing it. This clip prefers a heavier rate term in that decision | ||
| 1112 | -/// (see the sweep in `enc/mb.rs`), which the two real clips do not. | ||
| 1113 | -/// | ||
| 1114 | -/// It moved -4.523 -> -4.073 when inter luma levels started being chosen | ||
| 1115 | -/// against the CABAC coder's own price for them (0.100 dB on the film clip, | ||
| 1116 | -/// 0.029 on the screen capture). | ||
| 1117 | -const BD_PSNR_VS_X264_FLOOR: f64 = -4.15; | ||
| 1118 | - | ||
| 1119 | -fn have_x264() -> bool { | ||
| 1120 | - ec_testkit::ffmpeg() | ||
| 1121 | - .args(["-v", "error", "-hide_banner", "-encoders"]) | ||
| 1122 | - .output() | ||
| 1123 | - .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx264")) | ||
| 1124 | -} | ||
| 1125 | - | ||
| 1126 | -/// Encode raw I420 pictures with x264 at constant QP, matched to what our | ||
| 1127 | -/// encoder actually does: Main profile (CABAC, no 8x8 transform), one | ||
| 1128 | -/// reference, no B pictures, the same GOP, and adaptive quantisation and psy | ||
| 1129 | -/// off so both encoders spend bits by the same rule. Returns the Annex B | ||
| 1130 | -/// stream. | ||
| 1131 | -fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) -> Option<Vec<u8>> { | ||
| 1132 | - // Distinct per call, not per process: two #[test]s in this binary call | ||
| 1133 | - // this on parallel threads with overlapping qp values, and a path keyed | ||
| 1134 | - // only on qp lets one call's cleanup delete another's still-in-use file. | ||
| 1135 | - static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); | ||
| 1136 | - let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 1137 | - let dir = std::env::temp_dir().join(format!("ec-h264-x264-{}", std::process::id())); | ||
| 1138 | - std::fs::create_dir_all(&dir).ok()?; | ||
| 1139 | - let raw = dir.join(format!("in-q{qp}-{seq}.yuv")); | ||
| 1140 | - let out = dir.join(format!("out-q{qp}-{seq}.264")); | ||
| 1141 | - let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); | ||
| 1142 | - for (y, u, v) in sources { | ||
| 1143 | - buf.extend_from_slice(y); | ||
| 1144 | - buf.extend_from_slice(u); | ||
| 1145 | - buf.extend_from_slice(v); | ||
| 1146 | - } | ||
| 1147 | - pin_or_bail("x264_encode_qp", &raw, &buf)?; | ||
| 1148 | - let status = ec_testkit::ffmpeg() | ||
| 1149 | - .args(["-v", "error", "-y"]) | ||
| 1150 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) | ||
| 1151 | - .args(["-s", &format!("{w}x{h}"), "-r", "1"]) | ||
| 1152 | - .arg("-i") | ||
| 1153 | - .arg(&raw) | ||
| 1154 | - // EC_H264_X264_PRESET selects the reference preset; the DONE.md target is | ||
| 1155 | - // measured against `veryfast`, the default stays `medium` for the older gates. | ||
| 1156 | - .args([ | ||
| 1157 | - "-c:v", | ||
| 1158 | - "libx264", | ||
| 1159 | - "-preset", | ||
| 1160 | - &std::env::var("EC_H264_X264_PRESET").unwrap_or_else(|_| "medium".into()), | ||
| 1161 | - ]) | ||
| 1162 | - .args(["-profile:v", "main", "-qp", &qp.to_string()]) | ||
| 1163 | - .args(["-g", &gop.to_string(), "-bf", "0", "-refs", "1"]) | ||
| 1164 | - // ipratio/pbratio 1.0 matter: x264's constant-QP mode otherwise codes | ||
| 1165 | - // I pictures at a lower QP than the one asked for, which reads as a | ||
| 1166 | - // rate-quality win that is really a different quantiser. | ||
| 1167 | - // EC_H264_X264_PARAMS appends to this list, which is how a single | ||
| 1168 | - // reference feature gets attributed: running the sweep again with | ||
| 1169 | - // `trellis=0` says how much of x264's lead is its rate-distortion | ||
| 1170 | - // quantisation rather than its prediction. | ||
| 1171 | - .args([ | ||
| 1172 | - "-x264-params", | ||
| 1173 | - &format!( | ||
| 1174 | - "scenecut=0:aq-mode=0:psy=0:8x8dct=0:ipratio=1.0:pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}", | ||
| 1175 | - match std::env::var("EC_H264_X264_PARAMS") { | ||
| 1176 | - // The value may or may not carry its own leading colon; | ||
| 1177 | - // both spell the same thing. Passing it through would not: | ||
| 1178 | - // ffmpeg drops the token after an empty one, so "::subme=1" | ||
| 1179 | - // silently encodes at the preset's subme and the sweep | ||
| 1180 | - // reads as "the feature does nothing". | ||
| 1181 | - Ok(extra) if !extra.trim().trim_matches(':').is_empty() => | ||
| 1182 | - format!(":{}", extra.trim().trim_matches(':')), | ||
| 1183 | - _ => String::new(), | ||
| 1184 | - } | ||
| 1185 | - ), | ||
| 1186 | - ]) | ||
| 1187 | - .args(["-f", "h264"]) | ||
| 1188 | - .arg(&out) | ||
| 1189 | - .output() | ||
| 1190 | - .ok()?; | ||
| 1191 | - let _ = std::fs::remove_file(&raw); | ||
| 1192 | - if !status.status.success() { | ||
| 1193 | - eprintln!("x264 failed: {}", String::from_utf8_lossy(&status.stderr)); | ||
| 1194 | - return None; | ||
| 1195 | - } | ||
| 1196 | - let stream = std::fs::read(&out).ok()?; | ||
| 1197 | - let _ = std::fs::remove_file(&out); | ||
| 1198 | - Some(stream) | ||
| 1199 | -} | ||
| 1200 | - | ||
| 1201 | -/// BD-PSNR of our encoder against x264 at matched features over QP | ||
| 1202 | -/// 22/26/30/34. Runs on the synthetic clip by default, so the number cannot | ||
| 1203 | -/// rot behind an `#[ignore]`; point `EC_H264_CLIP` at a media file to measure | ||
| 1204 | -/// the same thing on real content. | ||
| 1205 | -/// | ||
| 1206 | -/// Both curves are (bits, luma PSNR against the same source pictures), and | ||
| 1207 | -/// both are measured on ffmpeg's decode of the stream rather than on an | ||
| 1208 | -/// encoder's own reconstruction, so the two halves are read the same way. | ||
| 1209 | -/// | ||
| 1210 | -/// `EC_H264_GOP` sets the GOP of both encoders; 1 makes the comparison | ||
| 1211 | -/// all-intra, which splits the gap between the intra path and the P pictures. | ||
| 1212 | -/// | ||
| 1213 | -/// `EC_H264_PRESET_BALANCED` runs our half of the comparison at | ||
| 1214 | -/// `Preset::Balanced` instead of the default `Preset::Fast`, which separates | ||
| 1215 | -/// what search effort buys from what the coder itself costs. | ||
| 1216 | -/// | ||
| 1217 | -/// `EC_H264_CLIP_SKIP` passes over that many pictures before sampling (film | ||
| 1218 | -/// heads are titles and fades), and `EC_H264_CLIP_STRIDE` widens the spacing | ||
| 1219 | -/// between the sampled pictures; both default to consecutive pictures from the | ||
| 1220 | -/// start of the file. The measurements quoted through this crate that predate | ||
| 1221 | -/// those two knobs were taken one picture a second, where nothing is | ||
| 1222 | -/// predictable from the previous picture -- they are not comparable with the | ||
| 1223 | -/// numbers taken since. | ||
| 1224 | -/// | ||
| 1225 | -/// cargo test --release -p ec-h264 --test encode bd_psnr_vs_x264 -- --nocapture | ||
| 1226 | -/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \ | ||
| 1227 | -/// bd_psnr_vs_x264 -- --nocapture | ||
| 1228 | -#[test] | ||
| 1229 | -fn bd_psnr_vs_x264() { | ||
| 1230 | - assert!(have_x264(), "the pinned ffmpeg has no libx264"); | ||
| 1231 | - let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") { | ||
| 1232 | - Some(path) => clip_sources(&path, 24), | ||
| 1233 | - None => { | ||
| 1234 | - let (w, h, frames) = (352, 288, 24); | ||
| 1235 | - let mut clip = Clip::new(w, h); | ||
| 1236 | - let mut sources = Vec::with_capacity(frames); | ||
| 1237 | - for t in 0..frames { | ||
| 1238 | - clip.render_smooth(t); | ||
| 1239 | - sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); | ||
| 1240 | - } | ||
| 1241 | - eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); | ||
| 1242 | - (w, h, sources) | ||
| 1243 | - } | ||
| 1244 | - }; | ||
| 1245 | - | ||
| 1246 | - let gop: u32 = std::env::var("EC_H264_GOP") | ||
| 1247 | - .ok() | ||
| 1248 | - .and_then(|v| v.parse().ok()) | ||
| 1249 | - .unwrap_or(10); | ||
| 1250 | - let ours = |qp: i32| { | ||
| 1251 | - let mut cfg = EncoderConfig::new(w as u32, h as u32); | ||
| 1252 | - cfg.qp = qp; | ||
| 1253 | - cfg.gop_size = gop; | ||
| 1254 | - if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() { | ||
| 1255 | - cfg.preset = ec_h264::Preset::Balanced; | ||
| 1256 | - } | ||
| 1257 | - cfg.cabac = true; | ||
| 1258 | - cfg.framerate = 1.0; | ||
| 1259 | - cfg.threads = 0; | ||
| 1260 | - let mut enc = Encoder::new(cfg).expect("encoder"); | ||
| 1261 | - let (mut stream, mut sum_recon) = (Vec::new(), 0.0); | ||
| 1262 | - for (y, u, v) in &sources { | ||
| 1263 | - let view = PictureView::i420(w as u32, h as u32, y, u, v); | ||
| 1264 | - stream.extend_from_slice(&enc.encode(&view).expect("encode").au); | ||
| 1265 | - sum_recon += psnr(y, &enc.reconstruction().expect("reconstruction").0); | ||
| 1266 | - } | ||
| 1267 | - // Measured the same way x264 is: on what a decoder shows, not on the | ||
| 1268 | - // encoder's own reconstruction. The two are printed together because a | ||
| 1269 | - // gap between them is a bug in one of the halves, not a rate-quality | ||
| 1270 | - // result. | ||
| 1271 | - let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); | ||
| 1272 | - assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); | ||
| 1273 | - let sum: f64 = sources | ||
| 1274 | - .iter() | ||
| 1275 | - .zip(&decoded) | ||
| 1276 | - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) | ||
| 1277 | - .sum(); | ||
| 1278 | - let sum_yuv: f64 = sources | ||
| 1279 | - .iter() | ||
| 1280 | - .zip(&decoded) | ||
| 1281 | - .map(|(s, d)| psnr_yuv(s, d)) | ||
| 1282 | - .sum(); | ||
| 1283 | - let (sum_u, sum_v) = ( | ||
| 1284 | - sources | ||
| 1285 | - .iter() | ||
| 1286 | - .zip(&decoded) | ||
| 1287 | - .map(|(s, d)| psnr(&s.1, &d.1)) | ||
| 1288 | - .sum::<f64>(), | ||
| 1289 | - sources | ||
| 1290 | - .iter() | ||
| 1291 | - .zip(&decoded) | ||
| 1292 | - .map(|(s, d)| psnr(&s.2, &d.2)) | ||
| 1293 | - .sum::<f64>(), | ||
| 1294 | - ); | ||
| 1295 | - eprintln!( | ||
| 1296 | - " ours qp {qp}: u {:.2} dB v {:.2} dB", | ||
| 1297 | - sum_u / sources.len() as f64, | ||
| 1298 | - sum_v / sources.len() as f64 | ||
| 1299 | - ); | ||
| 1300 | - let (decoded_psnr, recon_psnr) = | ||
| 1301 | - (sum / sources.len() as f64, sum_recon / sources.len() as f64); | ||
| 1302 | - assert!( | ||
| 1303 | - (decoded_psnr - recon_psnr).abs() < 0.05, | ||
| 1304 | - "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ | ||
| 1305 | - stream decodes to {decoded_psnr:.2} dB" | ||
| 1306 | - ); | ||
| 1307 | - ( | ||
| 1308 | - (stream.len() * 8) as f64, | ||
| 1309 | - decoded_psnr, | ||
| 1310 | - sum_yuv / sources.len() as f64, | ||
| 1311 | - ) | ||
| 1312 | - }; | ||
| 1313 | - let x264 = |qp: i32| { | ||
| 1314 | - let stream = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes"); | ||
| 1315 | - let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes x264's own stream"); | ||
| 1316 | - assert_eq!( | ||
| 1317 | - decoded.len(), | ||
| 1318 | - sources.len(), | ||
| 1319 | - "x264 returned {} pictures for {} sources", | ||
| 1320 | - decoded.len(), | ||
| 1321 | - sources.len() | ||
| 1322 | - ); | ||
| 1323 | - let sum: f64 = sources | ||
| 1324 | - .iter() | ||
| 1325 | - .zip(&decoded) | ||
| 1326 | - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) | ||
| 1327 | - .sum(); | ||
| 1328 | - let sum_yuv: f64 = sources | ||
| 1329 | - .iter() | ||
| 1330 | - .zip(&decoded) | ||
| 1331 | - .map(|(s, d)| psnr_yuv(s, d)) | ||
| 1332 | - .sum(); | ||
| 1333 | - let n = sources.len() as f64; | ||
| 1334 | - eprintln!( | ||
| 1335 | - " x264 qp {qp}: u {:.2} dB v {:.2} dB", | ||
| 1336 | - sources | ||
| 1337 | - .iter() | ||
| 1338 | - .zip(&decoded) | ||
| 1339 | - .map(|(s, d)| psnr(&s.1, &d.1)) | ||
| 1340 | - .sum::<f64>() | ||
| 1341 | - / n, | ||
| 1342 | - sources | ||
| 1343 | - .iter() | ||
| 1344 | - .zip(&decoded) | ||
| 1345 | - .map(|(s, d)| psnr(&s.2, &d.2)) | ||
| 1346 | - .sum::<f64>() | ||
| 1347 | - / n | ||
| 1348 | - ); | ||
| 1349 | - ((stream.len() * 8) as f64, sum / n, sum_yuv / n) | ||
| 1350 | - }; | ||
| 1351 | - | ||
| 1352 | - let qps = [22, 26, 30, 34]; | ||
| 1353 | - let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect(); | ||
| 1354 | - let theirs: Vec<_> = qps.iter().map(|&q| x264(q)).collect(); | ||
| 1355 | - for (i, &qp) in qps.iter().enumerate() { | ||
| 1356 | - let (ob, op, oy) = mine[i]; | ||
| 1357 | - let (xb, xp, xy) = theirs[i]; | ||
| 1358 | - eprintln!( | ||
| 1359 | - "qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv) | x264 {xb:.0} bits {xp:.2} dB \ | ||
| 1360 | - ({xy:.2} yuv) ({:+.1}% bits, {:+.2} dB, {:+.2} yuv)", | ||
| 1361 | - (ob / xb - 1.0) * 100.0, | ||
| 1362 | - op - xp, | ||
| 1363 | - oy - xy | ||
| 1364 | - ); | ||
| 1365 | - } | ||
| 1366 | - refuse_flat_window(theirs.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP"); | ||
| 1367 | - let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { | ||
| 1368 | - v.iter() | ||
| 1369 | - .map(|&(b, p, y)| (b, if luma { p } else { y })) | ||
| 1370 | - .collect() | ||
| 1371 | - }; | ||
| 1372 | - let bd = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); | ||
| 1373 | - let bd_yuv = bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); | ||
| 1374 | - eprintln!("BD-PSNR ours vs x264 over q22/26/30/34: {bd:+.3} dB"); | ||
| 1375 | - eprintln!("BD-PSNR-YUV ours vs x264 over q22/26/30/34: {bd_yuv:+.3} dB"); | ||
| 1376 | - | ||
| 1377 | - // The floor is calibrated on the synthetic clip; a clip of the user's is a | ||
| 1378 | - // measurement, not a gate, because its content is not pinned. | ||
| 1379 | - if std::env::var_os("EC_H264_CLIP").is_none() && gop == 10 { | ||
| 1380 | - assert!( | ||
| 1381 | - bd > BD_PSNR_VS_X264_FLOOR, | ||
| 1382 | - "BD-PSNR against x264 fell to {bd:+.3} dB, past the \ | ||
| 1383 | - {BD_PSNR_VS_X264_FLOOR:+.3} dB floor" | ||
| 1384 | - ); | ||
| 1385 | - } | ||
| 1386 | -} | ||
| 1387 | - | ||
| 1388 | /// The partitions only `Preset::Balanced` searches, decoded by ffmpeg. | 585 | /// The partitions only `Preset::Balanced` searches, decoded by ffmpeg. |
| 1389 | /// | 586 | /// |
| 1390 | /// The default preset codes every P macroblock as one 16x16 partition, so the | 587 | /// The default preset codes every P macroblock as one 16x16 partition, so the |