forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.5 MiB7eb6d34Tahinli8 hours ago4054 commits

encode.rs1546 lines, 61.5 KiBHistoryRawDownload
1//! Encoder conformance: what this encoder writes is what this decoder — and,
2//! in the ffmpeg-driven half of the suite, what ffmpeg — reconstructs.
3//!
4//! The load-bearing property is that the encoder's own reconstruction is
5//! *bit-identical* to a decode of its bitstream. Both sides share the
6//! prediction, transform and deblocking code, so a mismatch means the syntax
7//! written does not describe the picture reconstructed, which is the one class
8//! of encoder bug that quality metrics cannot see.
9
10use ec_h264::{Decoder, Encoder, EncoderConfig, NalOutcome, OutputOrder, PictureView, Preset};
11
12/// One decoded picture: Y, Cb and Cr planes, cropped and tightly packed.
13type Planes = (Vec<u8>, Vec<u8>, Vec<u8>);
14
15/// A synthetic source with real structure: moving edges, a gradient and a
16/// noisy patch, so intra, inter and skip all get exercised.
17struct Clip {
18 w: usize,
19 h: usize,
20 y: Vec<u8>,
21 u: Vec<u8>,
22 v: Vec<u8>,
23}
24
25impl Clip {
26 fn new(w: usize, h: usize) -> Clip {
27 Clip {
28 w,
29 h,
30 y: vec![0; w * h],
31 u: vec![0; w / 2 * h / 2],
32 v: vec![0; w / 2 * h / 2],
33 }
34 }
35
36 /// Frame `t`: a diagonal gradient, a moving box and a deterministic noise
37 /// field that keeps the residual from vanishing.
38 fn render(&mut self, t: usize) {
39 let (w, h) = (self.w, self.h);
40 for y in 0..h {
41 for x in 0..w {
42 let grad = ((x + y * 2 + t * 3) % 256) as u8;
43 let noise = ((x * 37 + y * 17 + t * 11) % 23) as u8;
44 let box_x = (t * 5) % (w.saturating_sub(40).max(1));
45 let inside = x >= box_x && x < box_x + 40 && y >= h / 4 && y < h / 4 + 30;
46 self.y[y * w + x] = if inside {
47 200u8.saturating_sub(noise)
48 } else {
49 grad / 2 + noise
50 };
51 }
52 }
53 for y in 0..h / 2 {
54 for x in 0..w / 2 {
55 self.u[y * (w / 2) + x] = (100 + ((x + t) % 40)) as u8;
56 self.v[y * (w / 2) + x] = (140 + ((y + t * 2) % 30)) as u8;
57 }
58 }
59 }
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<'_> {
104 PictureView::i420(self.w as u32, self.h as u32, &self.y, &self.u, &self.v)
105 }
106}
107
108/// Decode a whole stream with this crate's decoder, returning one I420 triple
109/// per picture.
110fn decode_all(stream: &[u8]) -> Vec<Planes> {
111 let mut dec = Decoder::new();
112 dec.set_output_order(OutputOrder::Decode);
113 let mut out = Vec::new();
114 for nal in ec_h264_syntax::AnnexBIter::new(stream) {
115 if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
116 dec.end_picture().expect("end of picture");
117 dec.push_nal(nal).expect("decoder accepts the NAL");
118 }
119 while let Some(frame) = dec.next_frame() {
120 out.push(planes_of(&frame));
121 }
122 }
123 dec.flush().expect("flush");
124 while let Some(frame) = dec.next_frame() {
125 out.push(planes_of(&frame));
126 }
127 out
128}
129
130fn planes_of(frame: &ec_core::frame::VideoFrame) -> Planes {
131 let (w, h) = (frame.width as usize, frame.height as usize);
132 let mut planes = Vec::new();
133 for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)]
134 .into_iter()
135 .enumerate()
136 {
137 let plane = &frame.planes[i];
138 let mut out = Vec::with_capacity(pw * ph);
139 for row in 0..ph {
140 out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]);
141 }
142 planes.push(out);
143 }
144 let v = planes.pop().unwrap();
145 let u = planes.pop().unwrap();
146 let y = planes.pop().unwrap();
147 (y, u, v)
148}
149
150/// Mean squared error between two equal-length planes.
151fn 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.
167fn 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
179fn psnr(a: &[u8], b: &[u8]) -> f64 {
180 let mse: f64 = a
181 .iter()
182 .zip(b)
183 .map(|(&x, &y)| {
184 let d = f64::from(x) - f64::from(y);
185 d * d
186 })
187 .sum::<f64>()
188 / a.len() as f64;
189 if mse == 0.0 {
190 99.0
191 } else {
192 10.0 * (255.0 * 255.0 / mse).log10()
193 }
194}
195
196fn 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
228fn 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.
236fn 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
247fn 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
273/// sample, over a QP sweep, both presets, single and multi threaded.
274#[test]
275fn reconstruction_matches_the_decoder() {
276 let mut t8x8_mbs = (0, 0);
277 for (w, h) in [(176, 144), (208, 122), (64, 48)] {
278 let mut clip = Clip::new(w, h);
279 for qp in [12, 24, 33, 44] {
280 for (threads, preset, cabac, t8x8) in [
281 (1usize, Preset::Fast, true, false),
282 (4, Preset::Balanced, true, false),
283 (1, Preset::Fast, false, false),
284 (3, Preset::Balanced, false, false),
285 (2, Preset::Balanced, true, true),
286 (2, Preset::Balanced, false, true),
287 ] {
288 let mut cfg = EncoderConfig::new(w as u32, h as u32);
289 cfg.qp = qp;
290 cfg.gop_size = 5;
291 cfg.threads = threads;
292 cfg.preset = preset;
293 cfg.cabac = cabac;
294 cfg.transform_8x8 = t8x8;
295 let mut enc = Encoder::new(cfg).expect("encoder");
296 let mut stream = Vec::new();
297 let mut recons = Vec::new();
298 for t in 0..8 {
299 clip.render(t);
300 let picture = enc.encode(&clip.view()).expect("encode");
301 stream.extend_from_slice(&picture.au);
302 recons.push(enc.reconstruction().expect("a reconstruction"));
303 }
304 if t8x8 {
305 let (intra, inter) = enc.transform_8x8_mbs();
306 t8x8_mbs.0 += intra;
307 t8x8_mbs.1 += inter;
308 }
309 let decoded = decode_all(&stream);
310 assert_eq!(
311 decoded.len(),
312 recons.len(),
313 "{w}x{h} qp {qp}: picture count"
314 );
315 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
316 assert_eq!(
317 dec.0, rec.0,
318 "{w}x{h} qp {qp} t{threads}: luma of picture {i}"
319 );
320 assert_eq!(
321 dec.1, rec.1,
322 "{w}x{h} qp {qp} t{threads}: Cb of picture {i}"
323 );
324 assert_eq!(
325 dec.2, rec.2,
326 "{w}x{h} qp {qp} t{threads}: Cr of picture {i}"
327 );
328 }
329 }
330 }
331 }
332 // The flag-on streams above really carried 8x8 macroblocks of both kinds.
333 assert!(
334 t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0,
335 "8x8 MBs across the sweep: intra {} inter {}",
336 t8x8_mbs.0,
337 t8x8_mbs.1
338 );
339}
340
341/// Quality tracks the quantiser, and a low QP is close to lossless: a stream
342/// that decodes bit-exactly could still be encoding garbage, and this is what
343/// says it is not.
344#[test]
345fn quality_follows_the_quantiser() {
346 let (w, h) = (176, 144);
347 let mut clip = Clip::new(w, h);
348 let mut last = 0.0;
349 for qp in [40, 30, 20, 10] {
350 let mut cfg = EncoderConfig::new(w as u32, h as u32);
351 cfg.qp = qp;
352 cfg.gop_size = 4;
353 cfg.threads = 1;
354 let mut enc = Encoder::new(cfg).expect("encoder");
355 let mut total = 0.0;
356 for t in 0..6 {
357 clip.render(t);
358 enc.encode(&clip.view()).expect("encode");
359 let (y, _, _) = enc.reconstruction().unwrap();
360 total += psnr(&clip.y, &y);
361 }
362 let avg = total / 6.0;
363 assert!(
364 avg > last,
365 "qp {qp}: PSNR {avg:.2} did not improve on {last:.2}"
366 );
367 if qp == 10 {
368 assert!(avg > 45.0, "qp 10 should be near lossless, got {avg:.2}");
369 }
370 last = avg;
371 }
372}
373
374/// Constant bitrate lands within a quarter of the target over a short clip,
375/// and every GOP boundary is an IDR the decoder can start from.
376#[test]
377fn rate_control_hits_its_target() {
378 let (w, h) = (352, 288);
379 let mut clip = Clip::new(w, h);
380 let bitrate = 1_500_000u32;
381 let mut cfg = EncoderConfig::new(w as u32, h as u32);
382 cfg.bitrate = bitrate;
383 cfg.framerate = 25.0;
384 cfg.gop_size = 25;
385 cfg.threads = 2;
386 let mut enc = Encoder::new(cfg).expect("encoder");
387 let mut bits = 0u64;
388 let frames = 50;
389 let mut keys = 0;
390 for t in 0..frames {
391 clip.render(t);
392 let p = enc.encode(&clip.view()).expect("encode");
393 bits += p.au.len() as u64 * 8;
394 keys += u32::from(p.key_frame);
395 }
396 assert_eq!(keys, 2, "one IDR per GOP");
397 let actual = bits as f64 / (frames as f64 / 25.0);
398 let ratio = actual / f64::from(bitrate);
399 assert!(
400 (0.7..1.35).contains(&ratio),
401 "bitrate {actual:.0} against target {bitrate} (ratio {ratio:.2})"
402 );
403}
404
405/// Every picture of a `gop_size` 1 stream is an IDR, which is what an
406/// intraframe master asks for.
407#[test]
408fn all_intra_when_the_gop_is_one() {
409 let (w, h) = (64, 64);
410 let mut clip = Clip::new(w, h);
411 let mut cfg = EncoderConfig::new(w as u32, h as u32);
412 cfg.gop_size = 1;
413 cfg.qp = 26;
414 let mut enc = Encoder::new(cfg).expect("encoder");
415 let mut stream = Vec::new();
416 for t in 0..4 {
417 clip.render(t);
418 let p = enc.encode(&clip.view()).expect("encode");
419 assert!(p.key_frame, "picture {t} is not a key frame");
420 stream.extend_from_slice(&p.au);
421 }
422 assert_eq!(decode_all(&stream).len(), 4);
423}
424
425// ---------------------------------------------------------------------------
426// ffmpeg-driven half: the third-party oracle. Skipped loudly when ffmpeg is
427// absent, exactly like the conformance suite's ffmpeg cross-check.
428// ---------------------------------------------------------------------------
429
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.
450fn 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.
489fn 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".
506fn 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]
514fn 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]
540fn 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]
577fn 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.
592fn 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
594 // call this on parallel threads, and a path keyed only on stream length
595 // lets one call's cleanup delete another's still-being-read file.
596 static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
597 let dir = std::env::temp_dir().join(format!("ec-h264-enc-{}", std::process::id()));
598 std::fs::create_dir_all(&dir).ok()?;
599 let path = dir.join(format!(
600 "s{}-{}.264",
601 stream.len(),
602 SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
603 ));
604 pin_or_bail("ffmpeg_decode", &path, stream)?;
605 let mut cmd = ec_testkit::ffmpeg();
606 cmd.args(["-v", "error"]);
607 cmd.args(extra);
608 cmd.arg("-i").arg(&path);
609 cmd.args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]);
610 let out = cmd.output().ok()?;
611 let _ = std::fs::remove_file(&path);
612 if !out.status.success() {
613 eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
614 return None;
615 }
616 let frame = w * h * 3 / 2;
617 if frame == 0 || out.stdout.len() % frame != 0 {
618 eprintln!(
619 "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames",
620 out.stdout.len()
621 );
622 return None;
623 }
624 Some(
625 out.stdout
626 .chunks(frame)
627 .map(|f| {
628 let (y, rest) = f.split_at(w * h);
629 let (u, v) = rest.split_at(w / 2 * h / 2);
630 (y.to_vec(), u.to_vec(), v.to_vec())
631 })
632 .collect(),
633 )
634}
635
636/// Encode a clip and hand back the stream with the encoder's reconstructions.
637fn encode_clip(
638 w: usize,
639 h: usize,
640 frames: usize,
641 configure: impl FnOnce(&mut EncoderConfig),
642) -> (Vec<u8>, Vec<Planes>, (u64, u64)) {
643 let mut cfg = EncoderConfig::new(w as u32, h as u32);
644 cfg.gop_size = 10;
645 cfg.threads = 3;
646 configure(&mut cfg);
647 let mut enc = Encoder::new(cfg).expect("encoder");
648 let mut clip = Clip::new(w, h);
649 let mut stream = Vec::new();
650 let mut recons = Vec::new();
651 for t in 0..frames {
652 clip.render(t);
653 stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au);
654 recons.push(enc.reconstruction().expect("reconstruction"));
655 }
656 (stream, recons, enc.transform_8x8_mbs())
657}
658
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]
663fn 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,
744/// across a QP sweep and at a size that is not a multiple of a macroblock.
745#[test]
746fn ffmpeg_decodes_bit_exactly() {
747 let mut t8x8_mbs = (0, 0);
748 for (w, h) in [(176, 144), (322, 242)] {
749 for qp in [10, 20, 28, 37, 47] {
750 let cavlc = qp % 2 == 0; // both entropy coders across the sweep
751 let t8x8 = qp % 3 == 1; // High-profile PPS with the per-MB flag
752 let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| {
753 cfg.qp = qp;
754 cfg.cabac = !cavlc;
755 cfg.transform_8x8 = t8x8;
756 });
757 t8x8_mbs.0 += intra;
758 t8x8_mbs.1 += inter;
759 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
760 assert_eq!(decoded.len(), recons.len(), "{w}x{h} qp {qp}: frame count");
761 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
762 assert_eq!(dec.0, rec.0, "{w}x{h} qp {qp}: luma of frame {i}");
763 assert_eq!(dec.1, rec.1, "{w}x{h} qp {qp}: Cb of frame {i}");
764 assert_eq!(dec.2, rec.2, "{w}x{h} qp {qp}: Cr of frame {i}");
765 }
766 }
767 }
768 assert!(
769 t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0,
770 "8x8 MBs across the sweep: intra {} inter {}",
771 t8x8_mbs.0,
772 t8x8_mbs.1
773 );
774}
775
776/// The same stream under constant bitrate, which is the mode edith exports in.
777#[test]
778fn ffmpeg_decodes_a_cbr_stream_bit_exactly() {
779 let (w, h) = (352, 288);
780 let (stream, recons, _) = encode_clip(w, h, 12, |cfg| {
781 cfg.bitrate = 2_000_000;
782 cfg.framerate = 25.0;
783 });
784 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
785 assert_eq!(decoded.len(), recons.len());
786 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
787 assert_eq!(dec.0, rec.0, "luma of frame {i}");
788 assert_eq!(
789 (dec.1.clone(), dec.2.clone()),
790 (rec.1.clone(), rec.2.clone()),
791 "chroma of frame {i}"
792 );
793 }
794}
795
796/// The VA-API hardware decoder on this machine accepts the same stream: a
797/// bitstream a driver refuses is not a bitstream edith can ship, whatever a
798/// software decoder says about it.
799#[test]
800fn vaapi_decodes_our_stream() {
801 if !std::path::Path::new("/dev/dri/renderD128").exists() {
802 eprintln!("SKIP vaapi_decodes_our_stream: no render node");
803 return;
804 }
805 let (w, h) = (352, 288);
806 let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| {
807 cfg.qp = 26;
808 cfg.transform_8x8 = true;
809 });
810 assert!(intra + inter > 0, "no 8x8 macroblocks in the VA-API stream");
811 let Some(decoded) = ffmpeg_decode(
812 &stream,
813 w,
814 h,
815 &[
816 "-hwaccel",
817 "vaapi",
818 "-hwaccel_device",
819 "/dev/dri/renderD128",
820 ],
821 ) else {
822 eprintln!("SKIP vaapi_decodes_our_stream: VA-API decode unavailable here");
823 return;
824 };
825 assert_eq!(decoded.len(), recons.len(), "VA-API frame count");
826 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
827 let p = psnr(&dec.0, &rec.0);
828 assert!(p > 60.0, "VA-API luma of frame {i} differs: PSNR {p:.1} dB");
829 }
830}
831
832/// Real 1080p pictures from this machine's library, demuxed by `ec-mp4` and
833/// decoded by this crate, are re-encoded and handed back to ffmpeg.
834///
835/// Synthetic clips do not have film grain, hard cuts, or the residual
836/// statistics an encoder actually meets; a stream that survives a gradient and
837/// a moving box says nothing about one. Every picture must decode to exactly
838/// the encoder's own reconstruction, and the run reports the rate it landed on
839/// against the rate it was asked for.
840#[test]
841fn real_library_frames_encode_and_decode_exactly() {
842 use ec_core::registry::Decoder as _;
843
844 let path = ec_testkit::fixture("open/sintel_trailer-720p.mp4");
845 let (w, h) = (1280, 720);
846
847 let (params, mut demux, index) = open_h264_source(path.as_os_str());
848 let mut dec = ec_h264::H264Decoder::new(params).expect("decoder");
849 let mut sources: Vec<Planes> = Vec::new();
850 while sources.len() < 12 {
851 let Ok(packet) = demux.next_packet() else {
852 break;
853 };
854 if packet.stream != index {
855 continue;
856 }
857 dec.send_packet(&packet).expect("decode");
858 while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() {
859 if sources.len() < 12 {
860 sources.push(planes_of(&f));
861 }
862 }
863 }
864 assert!(
865 sources.len() >= 6,
866 "only {} pictures decoded from the library file",
867 sources.len()
868 );
869
870 let bitrate = 8_000_000u32;
871 let mut cfg = EncoderConfig::new(w as u32, h as u32);
872 cfg.bitrate = bitrate;
873 cfg.framerate = 25.0;
874 cfg.gop_size = 25;
875 cfg.threads = 0;
876 let mut enc = Encoder::new(cfg).expect("encoder");
877 let mut stream = Vec::new();
878 let mut recons = Vec::new();
879 let mut bits = 0u64;
880 for (y, u, v) in &sources {
881 let view = PictureView::i420(w as u32, h as u32, y, u, v);
882 let p = enc.encode(&view).expect("encode");
883 bits += p.au.len() as u64 * 8;
884 stream.extend_from_slice(&p.au);
885 recons.push(enc.reconstruction().expect("reconstruction"));
886 }
887 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
888 assert_eq!(decoded.len(), recons.len(), "picture count");
889 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
890 assert_eq!(dec.0, rec.0, "luma of picture {i} from the library clip");
891 assert_eq!(dec.1, rec.1, "Cb of picture {i}");
892 assert_eq!(dec.2, rec.2, "Cr of picture {i}");
893 }
894 let quality: f64 = sources
895 .iter()
896 .zip(&recons)
897 .map(|((y, ..), (ry, ..))| psnr(y, ry))
898 .sum::<f64>()
899 / sources.len() as f64;
900 let rate = bits as f64 / (sources.len() as f64 / 25.0);
901 eprintln!(
902 "library clip {w}x{h}: {} pictures, {:.0} kbit/s asked {:.0}, luma PSNR {quality:.2} dB",
903 sources.len(),
904 rate / 1000.0,
905 f64::from(bitrate) / 1000.0
906 );
907 assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s");
908}
909
910/// Opens `path` by probing its bytes — MP4 carries an `ftyp` box at offset 4,
911/// Matroska starts with EBML magic `1A 45 DF A3` — never by extension. Returns
912/// the first H.264 video track's codec parameters (whose `extradata` is the
913/// avcC or CodecPrivate) and a boxed demuxer plus the track's stream index.
914///
915/// A video track that is not H.264 (AV1, HEVC, …) is refused with a message
916/// naming the codec, never a panic inside the demuxer.
917fn open_h264_source(
918 path: &std::ffi::OsStr,
919) -> (
920 ec_core::registry::CodecParameters,
921 Box<dyn ec_core::registry::Demuxer>,
922 u32,
923) {
924 use std::io::{Read, Seek, SeekFrom};
925
926 let file = std::fs::File::open(path).expect("source opens");
927 let mut reader = std::io::BufReader::new(file);
928 // corner-cut: a 12-byte probe reads only the two magics this gate opens
929 // — 'ftyp' at 4 for MP4, EBML at 0 for Matroska. A third container this
930 // crate grows to support would need its own magic here; upgrade by
931 // extending the if-chain.
932 let mut head = [0u8; 12];
933 let n = reader.read(&mut head).expect("read container head");
934 reader.seek(SeekFrom::Start(0)).expect("rewind");
935
936 let demux: Box<dyn ec_core::registry::Demuxer> = if ec_matroska::is_matroska(&head[..n]) {
937 Box::new(ec_matroska::MatroskaDemuxer::new(reader).expect("ec-matroska opens the file"))
938 } else if n >= 8 && &head[4..8] == b"ftyp" {
939 Box::new(ec_mp4::Mp4Demuxer::new(reader).expect("ec-mp4 opens the file"))
940 } else {
941 panic!(
942 "{}: not an MP4 or Matroska container",
943 path.to_string_lossy()
944 )
945 };
946
947 let streams = demux.streams();
948 if let Some((params, index)) = streams
949 .iter()
950 .find(|s| s.params.codec == ec_core::registry::CodecId::H264)
951 .map(|s| (s.params.clone(), s.index))
952 {
953 return (params, demux, index);
954 }
955 // No H.264 track: name what the video track actually is, so an AV1 or
956 // HEVC file is refused clearly rather than panicking inside a find.
957 if let Some(codec) = streams
958 .iter()
959 .find(|s| matches!(s.params.media, ec_core::registry::MediaParameters::Video(_)))
960 .map(|s| s.params.codec)
961 {
962 panic!(
963 "{}: video track is {:?}, not H.264 — this gate measures H.264 only",
964 path.to_string_lossy(),
965 codec
966 );
967 }
968 panic!("{}: no video track found", path.to_string_lossy());
969}
970
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.
975fn 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 &params.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"]
1047fn 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// ---------------------------------------------------------------------------
1093// 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
1095// every reference and our encoder against nothing but itself.
1096// ---------------------------------------------------------------------------
1097
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).
1117const BD_PSNR_VS_X264_FLOOR: f64 = -4.15;
1118
1119fn 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.
1131fn 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]
1229fn 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/// Where our bits go against where x264's go, class by class, on the same
1389/// sources at the same QP. Both streams are parsed by this crate's decoder, so
1390/// the two accounts are the same measurement; the BD-PSNR gate says how much
1391/// we overspend, this says on what.
1392///
1393/// cargo test --release -p ec-h264 --test encode bit_account_vs_x264 -- --nocapture
1394/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
1395/// bit_account_vs_x264 -- --nocapture
1396#[test]
1397fn bit_account_vs_x264() {
1398 assert!(have_x264(), "the pinned ffmpeg has no libx264");
1399 let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") {
1400 Some(path) => clip_sources(&path, 12),
1401 None => {
1402 let (w, h, frames) = (352, 288, 12);
1403 let mut clip = Clip::new(w, h);
1404 let mut sources = Vec::with_capacity(frames);
1405 for t in 0..frames {
1406 clip.render_smooth(t);
1407 sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone()));
1408 }
1409 eprintln!("synthetic clip: {w}x{h}, {frames} pictures");
1410 (w, h, sources)
1411 }
1412 };
1413 let gop: u32 = 10;
1414 let account = |stream: &[u8]| {
1415 let mut dec = Decoder::new();
1416 dec.set_output_order(OutputOrder::Decode);
1417 for nal in ec_h264_syntax::AnnexBIter::new(stream) {
1418 if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
1419 dec.end_picture().expect("end of picture");
1420 dec.push_nal(nal).expect("decoder accepts the NAL");
1421 }
1422 while dec.next_frame().is_some() {}
1423 }
1424 dec.flush().expect("flush");
1425 while dec.next_frame().is_some() {}
1426 (dec.bit_account(), dec.mb_shapes())
1427 };
1428 for qp in [26, 34] {
1429 let mut cfg = EncoderConfig::new(w as u32, h as u32);
1430 cfg.qp = qp;
1431 cfg.gop_size = gop;
1432 cfg.cabac = true;
1433 cfg.framerate = 1.0;
1434 cfg.threads = 0;
1435 if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() {
1436 cfg.preset = ec_h264::Preset::Balanced;
1437 }
1438 let mut enc = Encoder::new(cfg).expect("encoder");
1439 let mut ours = Vec::new();
1440 for (y, u, v) in &sources {
1441 let view = PictureView::i420(w as u32, h as u32, y, u, v);
1442 ours.extend_from_slice(&enc.encode(&view).expect("encode").au);
1443 }
1444 let theirs = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes");
1445 let ((a, sa), (b, sb)) = (account(&ours), account(&theirs));
1446 eprintln!(
1447 "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes",
1448 sources.len(),
1449 ours.len(),
1450 theirs.len()
1451 );
1452 let row = |name: &str, ours: u64, theirs: u64| {
1453 let (o, t) = (ours as f64 / 256.0, theirs as f64 / 256.0);
1454 let delta = if t > 0.0 {
1455 format!("{:+.1}%", (o - t) / t * 100.0)
1456 } else {
1457 "--".to_string()
1458 };
1459 eprintln!(" {name:<16} ours {o:>12.0} bits | x264 {t:>12.0} bits {delta:>8}");
1460 };
1461 row("skip", a.skip, b.skip);
1462 row("mb_type", a.mb_type, b.mb_type);
1463 row("mv", a.mv, b.mv);
1464 row("ref_idx", a.ref_idx, b.ref_idx);
1465 row("cbp+qp", a.cbp_qp, b.cbp_qp);
1466 row("intra modes", a.intra_mode, b.intra_mode);
1467 row("residual luma", a.residual_luma, b.residual_luma);
1468 row("residual chroma", a.residual_chroma, b.residual_chroma);
1469 row("total accounted", a.total(), b.total());
1470 let mix = |n: &str, s: &ec_h264::MbShapes| {
1471 eprintln!(
1472 " {n:<16} skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}",
1473 s.skip, s.p16x16, s.p16x8, s.p8x16, s.p8x8, s.intra
1474 );
1475 };
1476 mix("shapes ours", &sa);
1477 mix("shapes x264", &sb);
1478 }
1479}
1480
1481/// The partitions only `Preset::Balanced` searches, decoded by ffmpeg.
1482///
1483/// The default preset codes every P macroblock as one 16x16 partition, so the
1484/// bit-exactness sweeps above never put a 16x8, an 8x16 or a P_8x8 -- and so
1485/// never a `sub_mb_type` -- in front of another decoder. This does.
1486#[test]
1487fn balanced_partitions_decode_bit_exactly() {
1488 let (w, h) = (176, 144);
1489 let mut shapes = ec_h264::MbShapes::default();
1490 for qp in [16, 26, 36] {
1491 let cavlc = qp == 26; // both entropy coders write sub_mb_type
1492 let (stream, recons, _) = encode_clip(w, h, 8, |cfg| {
1493 cfg.qp = qp;
1494 cfg.cabac = !cavlc;
1495 cfg.preset = ec_h264::Preset::Balanced;
1496 });
1497 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
1498 assert_eq!(decoded.len(), recons.len(), "qp {qp}: frame count");
1499 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
1500 assert_eq!(dec.0, rec.0, "qp {qp}: luma of frame {i}");
1501 assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}");
1502 assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}");
1503 }
1504 let mut dec = Decoder::new();
1505 dec.set_output_order(OutputOrder::Decode);
1506 for nal in ec_h264_syntax::AnnexBIter::new(&stream) {
1507 if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
1508 dec.end_picture().expect("end of picture");
1509 dec.push_nal(nal).expect("decoder accepts the NAL");
1510 }
1511 while dec.next_frame().is_some() {}
1512 }
1513 dec.flush().expect("flush");
1514 while dec.next_frame().is_some() {}
1515 shapes.add_public(&dec.mb_shapes());
1516 }
1517 eprintln!(
1518 "balanced shapes: skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}",
1519 shapes.skip, shapes.p16x16, shapes.p16x8, shapes.p8x16, shapes.p8x8, shapes.intra
1520 );
1521 assert!(
1522 shapes.p16x8 + shapes.p8x16 > 0 && shapes.p8x8 > 0,
1523 "the sweep has to code every shape, or it proves nothing about them"
1524 );
1525}
1526
1527#[test]
1528fn force_keyframe_restarts_the_gop() {
1529 let (w, h) = (64, 64);
1530 let mut clip = Clip::new(w, h);
1531 let mut cfg = EncoderConfig::new(w as u32, h as u32);
1532 cfg.gop_size = 4;
1533 cfg.threads = 1;
1534 let mut enc = Encoder::new(cfg).expect("encoder");
1535 let mut stream = Vec::new();
1536 let keys: Vec<bool> = (0..8)
1537 .map(|t| {
1538 clip.render(t);
1539 let pic = enc.encode_with(&clip.view(), t == 2).expect("encode");
1540 stream.extend_from_slice(&pic.au);
1541 pic.key_frame
1542 })
1543 .collect();
1544 assert_eq!(keys, [true, false, true, false, false, false, true, false]);
1545 assert_eq!(decode_all(&stream).len(), 8);
1546}