forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

encode.rs1643 lines, 65.1 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
430fn have_ffmpeg() -> bool {
431 std::process::Command::new("ffmpeg")
432 .arg("-version")
433 .stdout(std::process::Stdio::null())
434 .stderr(std::process::Stdio::null())
435 .status()
436 .is_ok_and(|s| s.success())
437}
438
439/// Fixture-presence probe for `<what this test needs>`.
440/// Returns whether the fixture is present, but never silently: under
441/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path
442/// and the script that regenerates it, so a host whose fixture library drifted
443/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure;
444/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently
445/// short-circuited because the probe ran first in a compound `if`).
446///
447/// Order is load-bearing: probe, assert, return. Never merge the probe into
448/// the same `if` as the escape.
449fn require_fixture(path: &std::path::Path, generator: &str) -> bool {
450 let present = path.exists();
451 assert!(
452 present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
453 "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}",
454 path.display(),
455 generator
456 );
457 if !present {
458 eprintln!("SKIP: fixture {} absent", path.display());
459 }
460 present
461}
462
463/// Write `bytes` to `path` and PROVE the file on disk is exactly that long.
464///
465/// lane-h26xpinloud: every write below used `std::fs::write(..).ok()?` and then
466/// handed `path` to ffmpeg, which closes only the ERROR path. An Ok-but-short
467/// write -- a filesystem that reports success and stores fewer bytes (ENOSPC on
468/// a full mount, EFBIG under a size cap, a quota, a failed final flush) -- left
469/// ffmpeg decoding a truncated stream, and the failure surfaced as a
470/// plausible-looking wrong pixel or a shifted PSNR number, not as a write
471/// failure. MEASURED: 1234 bytes written through a path that LOOKS like a
472/// stream file in a scratch directory but whose filesystem accepts every byte
473/// and stores none returns `Ok`, and the file on disk is 0 bytes. So the length
474/// is checked here once, from the same `bytes.len()` the writer used, and any
475/// shortfall carries the path, both counts, and the OS error -- or, for the
476/// write that reported success and left a short file, the plain statement that
477/// there was no OS error, which is exactly the case that used to print nothing.
478///
479/// Returns the failure LINE rather than a bare bool, so the bail callers and any
480/// panic caller all end on one format that cannot drift apart. The success path
481/// is byte-identical to the old `fs::write`: same bytes, same path, truncate
482/// then write.
483fn pin_loud(site: &str, path: &std::path::Path, bytes: &[u8]) -> Result<(), String> {
484 let expected = bytes.len();
485 if let Err(e) = std::fs::write(path, bytes) {
486 // The count here is the file's REAL length, not what the writer had
487 // confirmed in hand: under a size cap the kernel stores everything up
488 // to the cap and only THEN returns the error, and `fs::write` confirms
489 // none of it.
490 let on_disk = std::fs::metadata(path)
491 .map(|m| m.len() as usize)
492 .unwrap_or(0);
493 return Err(short_line(
494 site,
495 path,
496 on_disk,
497 expected,
498 &format!("the write failed: {e}"),
499 ));
500 }
501 match std::fs::metadata(path) {
502 Ok(m) if m.len() as usize == expected => Ok(()),
503 Ok(m) => Err(short_line(
504 site,
505 path,
506 m.len() as usize,
507 expected,
508 "the write reported success and the file on disk is still not that long (no OS error)",
509 )),
510 Err(e) => Err(short_line(
511 site,
512 path,
513 0,
514 expected,
515 &format!("the written file could not be stat'ed: {e}"),
516 )),
517 }
518}
519
520/// The one failure line every short pin ends on: site, path, the bytes the file
521/// holds vs the bytes owed, and the reason.
522fn short_line(
523 site: &str,
524 path: &std::path::Path,
525 on_disk: usize,
526 expected: usize,
527 why: &str,
528) -> String {
529 format!(
530 "ec-h264 encode pin SHORT [{}] {}: file holds {on_disk} of {expected} bytes: {why}",
531 site,
532 path.display()
533 )
534}
535
536/// A pin whose shortfall is reported and then BAILED on, for a caller that
537/// returns `None` today. Prints the same line [`pin_loud`] returns, so `None`
538/// from here never reads as a plain "ffmpeg said no".
539fn pin_or_bail(site: &str, path: &std::path::Path, bytes: &[u8]) -> Option<()> {
540 pin_loud(site, path, bytes)
541 .map_err(|why| eprintln!("{why}"))
542 .ok()
543}
544
545#[cfg(unix)]
546#[test]
547fn pin_loud_reds_on_an_ok_but_short_write() {
548 // The shape the four sites left open: a write that reports success and
549 // leaves a file of a different length. A symlink to /dev/null accepts every
550 // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes --
551 // a stream path, silently empty.
552 let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-{}", std::process::id()));
553 std::fs::create_dir_all(&dir).expect("scratch dir");
554 let path = dir.join("ok-but-short.264");
555 let _ = std::fs::remove_file(&path);
556 std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null");
557 let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err();
558 assert!(why.contains(&path.display().to_string()), "{why}");
559 assert!(why.contains("file holds 0 of 1234 bytes"), "{why}");
560 std::fs::remove_file(&path).ok();
561
562 // The control: the same call on a real file succeeds and leaves every byte.
563 let good = dir.join("whole.264");
564 let bytes = vec![7u8; 1234];
565 pin_loud("control", &good, &bytes).expect("a whole write is not short");
566 assert_eq!(std::fs::read(&good).expect("read back"), bytes);
567 std::fs::remove_file(&good).ok();
568 std::fs::remove_dir_all(&dir).ok();
569}
570
571#[cfg(unix)]
572#[test]
573fn pin_loud_reports_what_landed_under_a_size_cap() {
574 // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores
575 // everything up to the cap and only then returns EFBIG. The line must carry
576 // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count
577 // the writer confirmed, which is zero.
578 use std::process::Command;
579 let Ok(exe) = std::env::current_exe() else {
580 return;
581 };
582 // SIGXFSZ's default action would kill the child before it can print;
583 // `trap '' XFSZ` sets SIG_IGN, which survives the exec.
584 let script = format!(
585 "ulimit -f 1; trap '' XFSZ; exec {} --exact encode::pin_loud_cap_child --nocapture",
586 exe.display()
587 );
588 let out = Command::new("sh")
589 .args(["-c", &script])
590 .env("EC_PINLOUD_CHILD", "1")
591 .output()
592 .expect("run the capped child");
593 let text = format!(
594 "{}{}",
595 String::from_utf8_lossy(&out.stdout),
596 String::from_utf8_lossy(&out.stderr)
597 );
598 assert!(!out.status.success(), "the capped write must fail: {text}");
599 assert!(text.contains("file holds 512 of 4096 bytes"), "{text}");
600 assert!(
601 text.contains("EFBIG") || text.contains("File too large"),
602 "{text}"
603 );
604}
605
606/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under
607/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails
608/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`.
609#[test]
610fn pin_loud_cap_child() {
611 if std::env::var_os("EC_PINLOUD_CHILD").is_none() {
612 return;
613 }
614 let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-cap-{}", std::process::id()));
615 std::fs::create_dir_all(&dir).expect("scratch dir");
616 let path = dir.join("capped.264");
617 let why =
618 pin_loud("capped", &path, &[7u8; 4096]).expect_err("4096 bytes cannot fit a 1 KiB cap");
619 std::fs::remove_file(&path).ok();
620 std::fs::remove_dir_all(&dir).ok();
621 panic!("{why}");
622}
623
624/// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture.
625fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> {
626 // Distinct per call, not per process: several #[test]s in this binary
627 // call this on parallel threads, and a path keyed only on stream length
628 // lets one call's cleanup delete another's still-being-read file.
629 static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
630 let dir = std::env::temp_dir().join(format!("ec-h264-enc-{}", std::process::id()));
631 std::fs::create_dir_all(&dir).ok()?;
632 let path = dir.join(format!(
633 "s{}-{}.264",
634 stream.len(),
635 SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
636 ));
637 pin_or_bail("ffmpeg_decode", &path, stream)?;
638 let mut cmd = std::process::Command::new("ffmpeg");
639 cmd.args(["-v", "error"]);
640 cmd.args(extra);
641 cmd.arg("-i").arg(&path);
642 cmd.args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]);
643 let out = cmd.output().ok()?;
644 let _ = std::fs::remove_file(&path);
645 if !out.status.success() {
646 eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
647 return None;
648 }
649 let frame = w * h * 3 / 2;
650 if frame == 0 || out.stdout.len() % frame != 0 {
651 eprintln!(
652 "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames",
653 out.stdout.len()
654 );
655 return None;
656 }
657 Some(
658 out.stdout
659 .chunks(frame)
660 .map(|f| {
661 let (y, rest) = f.split_at(w * h);
662 let (u, v) = rest.split_at(w / 2 * h / 2);
663 (y.to_vec(), u.to_vec(), v.to_vec())
664 })
665 .collect(),
666 )
667}
668
669/// Encode a clip and hand back the stream with the encoder's reconstructions.
670fn encode_clip(
671 w: usize,
672 h: usize,
673 frames: usize,
674 configure: impl FnOnce(&mut EncoderConfig),
675) -> (Vec<u8>, Vec<Planes>, (u64, u64)) {
676 let mut cfg = EncoderConfig::new(w as u32, h as u32);
677 cfg.gop_size = 10;
678 cfg.threads = 3;
679 configure(&mut cfg);
680 let mut enc = Encoder::new(cfg).expect("encoder");
681 let mut clip = Clip::new(w, h);
682 let mut stream = Vec::new();
683 let mut recons = Vec::new();
684 for t in 0..frames {
685 clip.render(t);
686 stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au);
687 recons.push(enc.reconstruction().expect("reconstruction"));
688 }
689 (stream, recons, enc.transform_8x8_mbs())
690}
691
692/// Flat gradients and glyph-like rectangles: the content the 8x8 transform
693/// exists for. A 10-frame clip with the flag on must keep a clear positive
694/// gain at equal bits, or cut bits at equal PSNR.
695#[test]
696fn eight_by_eight_gains_on_flat_and_text() {
697 let (w, h) = (320, 240);
698 let render = |t: usize, clip: &mut Clip| {
699 // A half-sample pan per frame: inter prediction has a residual to code.
700 let sx = |x: usize| x * 2 + t;
701 for y in 0..h {
702 for x in 0..w {
703 let (px, py) = (sx(x) as f64 / 2.0, y as f64);
704 // Curved shading: smooth but not a plane, so no 16x16 mode
705 // predicts it for free.
706 let shade = 70.0 + px * px / 900.0 + py * py / 700.0 - px * py / 1500.0;
707 // Gentle texture with a 20-sample period: residual energy that
708 // spans more than a 4x4 block, which is what the 8x8 transform
709 // is for.
710 let tri = |v: f64| ((v % 20.0) - 10.0).abs() - 5.0;
711 let shade = shade + tri(px) * tri(py) / 1.5;
712 // Glyph rows: 16x24 cells, stroke pattern hashed per cell.
713 let (cell, cx, cy) = (sx(x) / 32, (sx(x) / 2) % 16, y % 24);
714 let hash = (cell * 2654435761usize.wrapping_add(y / 24 * 40503)) >> 7;
715 let stem = (2..5).contains(&cx);
716 let bar = (10..13).contains(&cy) && cx < 12 && hash & 1 == 1;
717 let foot = cy >= 19 && (2..13).contains(&cx) && hash & 2 == 2;
718 let glyph = y > h / 3 && (3..22).contains(&cy) && (stem || bar || foot);
719 clip.y[y * w + x] = if glyph { 24 } else { shade.min(235.0) as u8 };
720 }
721 }
722 clip.u.fill(128);
723 clip.v.fill(128);
724 };
725 let run = |t8x8: bool, qp: i32, cabac: bool| {
726 let mut cfg = EncoderConfig::new(w as u32, h as u32);
727 cfg.qp = qp;
728 cfg.gop_size = 10;
729 cfg.transform_8x8 = t8x8;
730 cfg.cabac = cabac;
731 let mut enc = Encoder::new(cfg).expect("encoder");
732 let mut clip = Clip::new(w, h);
733 let (mut bits, mut sum_psnr) = (0usize, 0.0);
734 let mut share = 0.0;
735 for t in 0..10 {
736 render(t, &mut clip);
737 bits += enc.encode(&clip.view()).expect("encode").au.len() * 8;
738 let rec = enc.reconstruction().expect("reconstruction");
739 sum_psnr += psnr(&clip.y, &rec.0);
740 }
741 if t8x8 {
742 let (i, p) = enc.transform_8x8_mbs();
743 eprintln!("8x8 MBs: intra {i} inter {p}");
744 share = (i + p) as f64 / (10.0 * (w / 16 * h / 16) as f64);
745 }
746 (bits as f64, sum_psnr / 10.0, share)
747 };
748 let qps = [22, 26, 30, 34];
749 let on: Vec<_> = qps.iter().map(|&q| run(true, q, true)).collect();
750 let off: Vec<_> = qps.iter().map(|&q| run(false, q, true)).collect();
751 refuse_flat_window(off.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP");
752 let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
753 let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
754 let bd = bd_psnr_delta(&on_curve, &off_curve);
755 let share = on.iter().map(|&(_, _, share)| share).sum::<f64>() / on.len() as f64;
756 // What the flag buys, not what the encoder is worth: both arms move when
757 // the paths under them change. It was re-pinned from 0.255 when the 4x4
758 // luma path gained its coded_block_pattern group test, which is in the
759 // flag-off arm and improved it -- the same change moves the absolute
760 // synthetic comparison against x264 from -4.060 to -3.969 dB, and the
761 // flag-on arm barely at all, because a transform_8x8 macroblock does not
762 // go through that path.
763 const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.230;
764 eprintln!(
765 "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%",
766 share * 100.0
767 );
768 assert!(share > 0.0, "no 8x8 macroblocks were coded");
769 assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off");
770 assert!(
771 bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB,
772 "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate"
773 );
774}
775
776/// ffmpeg's decode of our stream is our reconstruction, sample for sample,
777/// across a QP sweep and at a size that is not a multiple of a macroblock.
778#[test]
779fn ffmpeg_decodes_bit_exactly() {
780 if !have_ffmpeg() {
781 eprintln!("SKIP ffmpeg_decodes_bit_exactly: no ffmpeg on PATH");
782 return;
783 }
784 let mut t8x8_mbs = (0, 0);
785 for (w, h) in [(176, 144), (322, 242)] {
786 for qp in [10, 20, 28, 37, 47] {
787 let cavlc = qp % 2 == 0; // both entropy coders across the sweep
788 let t8x8 = qp % 3 == 1; // High-profile PPS with the per-MB flag
789 let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| {
790 cfg.qp = qp;
791 cfg.cabac = !cavlc;
792 cfg.transform_8x8 = t8x8;
793 });
794 t8x8_mbs.0 += intra;
795 t8x8_mbs.1 += inter;
796 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
797 assert_eq!(decoded.len(), recons.len(), "{w}x{h} qp {qp}: frame count");
798 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
799 assert_eq!(dec.0, rec.0, "{w}x{h} qp {qp}: luma of frame {i}");
800 assert_eq!(dec.1, rec.1, "{w}x{h} qp {qp}: Cb of frame {i}");
801 assert_eq!(dec.2, rec.2, "{w}x{h} qp {qp}: Cr of frame {i}");
802 }
803 }
804 }
805 assert!(
806 t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0,
807 "8x8 MBs across the sweep: intra {} inter {}",
808 t8x8_mbs.0,
809 t8x8_mbs.1
810 );
811}
812
813/// The same stream under constant bitrate, which is the mode edith exports in.
814#[test]
815fn ffmpeg_decodes_a_cbr_stream_bit_exactly() {
816 if !have_ffmpeg() {
817 eprintln!("SKIP ffmpeg_decodes_a_cbr_stream_bit_exactly: no ffmpeg on PATH");
818 return;
819 }
820 let (w, h) = (352, 288);
821 let (stream, recons, _) = encode_clip(w, h, 12, |cfg| {
822 cfg.bitrate = 2_000_000;
823 cfg.framerate = 25.0;
824 });
825 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
826 assert_eq!(decoded.len(), recons.len());
827 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
828 assert_eq!(dec.0, rec.0, "luma of frame {i}");
829 assert_eq!(
830 (dec.1.clone(), dec.2.clone()),
831 (rec.1.clone(), rec.2.clone()),
832 "chroma of frame {i}"
833 );
834 }
835}
836
837/// The VA-API hardware decoder on this machine accepts the same stream: a
838/// bitstream a driver refuses is not a bitstream edith can ship, whatever a
839/// software decoder says about it.
840#[test]
841fn vaapi_decodes_our_stream() {
842 if !have_ffmpeg() || !std::path::Path::new("/dev/dri/renderD128").exists() {
843 eprintln!("SKIP vaapi_decodes_our_stream: no ffmpeg or no render node");
844 return;
845 }
846 let (w, h) = (352, 288);
847 let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| {
848 cfg.qp = 26;
849 cfg.transform_8x8 = true;
850 });
851 assert!(intra + inter > 0, "no 8x8 macroblocks in the VA-API stream");
852 let Some(decoded) = ffmpeg_decode(
853 &stream,
854 w,
855 h,
856 &[
857 "-hwaccel",
858 "vaapi",
859 "-hwaccel_device",
860 "/dev/dri/renderD128",
861 ],
862 ) else {
863 eprintln!("SKIP vaapi_decodes_our_stream: VA-API decode unavailable here");
864 return;
865 };
866 assert_eq!(decoded.len(), recons.len(), "VA-API frame count");
867 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
868 let p = psnr(&dec.0, &rec.0);
869 assert!(p > 60.0, "VA-API luma of frame {i} differs: PSNR {p:.1} dB");
870 }
871}
872
873/// Real 1080p pictures from this machine's library, demuxed by `ec-mp4` and
874/// decoded by this crate, are re-encoded and handed back to ffmpeg.
875///
876/// Synthetic clips do not have film grain, hard cuts, or the residual
877/// statistics an encoder actually meets; a stream that survives a gradient and
878/// a moving box says nothing about one. Every picture must decode to exactly
879/// the encoder's own reconstruction, and the run reports the rate it landed on
880/// against the rate it was asked for.
881#[test]
882fn real_library_frames_encode_and_decode_exactly() {
883 use ec_core::registry::Decoder as _;
884
885 if !have_ffmpeg() {
886 eprintln!("SKIP real_library_frames: no ffmpeg on PATH");
887 return;
888 }
889 let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
890 .join("../../fixtures/real-library-manifest.tsv");
891 if !require_fixture(&manifest, "scripts/scan-real-library.sh") {
892 return;
893 }
894 let text = std::fs::read_to_string(&manifest).expect("manifest reads");
895 // The first 8-bit 4:2:0 H.264 mp4 of at least 720p in the manifest.
896 let mut source = None;
897 for line in text.lines().skip(1) {
898 let f: Vec<&str> = line.split('\t').collect();
899 if f.len() < 7 || f[2] != "h264" || f[5] != "yuv420p" {
900 continue;
901 }
902 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
903 continue;
904 };
905 if w < 1280 || h < 720 || !w.is_multiple_of(2) || !h.is_multiple_of(2) {
906 continue;
907 }
908 if !f[1].contains("mp4") || !std::path::Path::new(f[0]).exists() {
909 continue;
910 }
911 source = Some((f[0].to_string(), w, h));
912 break;
913 }
914 let Some((path, w, h)) = source else {
915 // A manifest with no qualifying row is a corpus that drifted, not a
916 // reason to report PASS for a sweep that never ran.
917 assert!(
918 std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
919 "EC_REQUIRE_FIXTURES=1 but {} lists no H.264 4:2:0 mp4 of at least \
920 720p -- regenerate with: scripts/scan-real-library.sh",
921 manifest.display()
922 );
923 eprintln!("SKIP real_library_frames: no H.264 4:2:0 mp4 in the manifest");
924 return;
925 };
926
927 // Decode a handful of real pictures.
928 let (params, mut demux, index) = open_h264_source(std::ffi::OsStr::new(&path));
929 let mut dec = ec_h264::H264Decoder::new(params).expect("decoder");
930 let mut sources: Vec<Planes> = Vec::new();
931 while sources.len() < 12 {
932 let Ok(packet) = demux.next_packet() else {
933 break;
934 };
935 if packet.stream != index {
936 continue;
937 }
938 dec.send_packet(&packet).expect("decode");
939 while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() {
940 if sources.len() < 12 {
941 sources.push(planes_of(&f));
942 }
943 }
944 }
945 assert!(
946 sources.len() >= 6,
947 "only {} pictures decoded from the library file",
948 sources.len()
949 );
950
951 let bitrate = 8_000_000u32;
952 let mut cfg = EncoderConfig::new(w as u32, h as u32);
953 cfg.bitrate = bitrate;
954 cfg.framerate = 25.0;
955 cfg.gop_size = 25;
956 cfg.threads = 0;
957 let mut enc = Encoder::new(cfg).expect("encoder");
958 let mut stream = Vec::new();
959 let mut recons = Vec::new();
960 let mut bits = 0u64;
961 for (y, u, v) in &sources {
962 let view = PictureView::i420(w as u32, h as u32, y, u, v);
963 let p = enc.encode(&view).expect("encode");
964 bits += p.au.len() as u64 * 8;
965 stream.extend_from_slice(&p.au);
966 recons.push(enc.reconstruction().expect("reconstruction"));
967 }
968 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
969 assert_eq!(decoded.len(), recons.len(), "picture count");
970 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
971 assert_eq!(dec.0, rec.0, "luma of picture {i} from the library clip");
972 assert_eq!(dec.1, rec.1, "Cb of picture {i}");
973 assert_eq!(dec.2, rec.2, "Cr of picture {i}");
974 }
975 let quality: f64 = sources
976 .iter()
977 .zip(&recons)
978 .map(|((y, ..), (ry, ..))| psnr(y, ry))
979 .sum::<f64>()
980 / sources.len() as f64;
981 let rate = bits as f64 / (sources.len() as f64 / 25.0);
982 eprintln!(
983 "library clip {w}x{h}: {} pictures, {:.0} kbit/s asked {:.0}, luma PSNR {quality:.2} dB",
984 sources.len(),
985 rate / 1000.0,
986 f64::from(bitrate) / 1000.0
987 );
988 assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s");
989}
990
991/// Opens `path` by probing its bytes — MP4 carries an `ftyp` box at offset 4,
992/// Matroska starts with EBML magic `1A 45 DF A3` — never by extension. Returns
993/// the first H.264 video track's codec parameters (whose `extradata` is the
994/// avcC or CodecPrivate) and a boxed demuxer plus the track's stream index.
995///
996/// A video track that is not H.264 (AV1, HEVC, …) is refused with a message
997/// naming the codec, never a panic inside the demuxer.
998fn open_h264_source(
999 path: &std::ffi::OsStr,
1000) -> (
1001 ec_core::registry::CodecParameters,
1002 Box<dyn ec_core::registry::Demuxer>,
1003 u32,
1004) {
1005 use std::io::{Read, Seek, SeekFrom};
1006
1007 let file = std::fs::File::open(path).expect("source opens");
1008 let mut reader = std::io::BufReader::new(file);
1009 // corner-cut: a 12-byte probe reads only the two magics this gate opens
1010 // — 'ftyp' at 4 for MP4, EBML at 0 for Matroska. A third container this
1011 // crate grows to support would need its own magic here; upgrade by
1012 // extending the if-chain.
1013 let mut head = [0u8; 12];
1014 let n = reader.read(&mut head).expect("read container head");
1015 reader.seek(SeekFrom::Start(0)).expect("rewind");
1016
1017 let demux: Box<dyn ec_core::registry::Demuxer> = if ec_matroska::is_matroska(&head[..n]) {
1018 Box::new(ec_matroska::MatroskaDemuxer::new(reader).expect("ec-matroska opens the file"))
1019 } else if n >= 8 && &head[4..8] == b"ftyp" {
1020 Box::new(ec_mp4::Mp4Demuxer::new(reader).expect("ec-mp4 opens the file"))
1021 } else {
1022 panic!(
1023 "{}: not an MP4 or Matroska container",
1024 path.to_string_lossy()
1025 )
1026 };
1027
1028 let streams = demux.streams();
1029 if let Some((params, index)) = streams
1030 .iter()
1031 .find(|s| s.params.codec == ec_core::registry::CodecId::H264)
1032 .map(|s| (s.params.clone(), s.index))
1033 {
1034 return (params, demux, index);
1035 }
1036 // No H.264 track: name what the video track actually is, so an AV1 or
1037 // HEVC file is refused clearly rather than panicking inside a find.
1038 if let Some(codec) = streams
1039 .iter()
1040 .find(|s| matches!(s.params.media, ec_core::registry::MediaParameters::Video(_)))
1041 .map(|s| s.params.codec)
1042 {
1043 panic!(
1044 "{}: video track is {:?}, not H.264 — this gate measures H.264 only",
1045 path.to_string_lossy(),
1046 codec
1047 );
1048 }
1049 panic!("{}: no video track found", path.to_string_lossy());
1050}
1051
1052/// The first `want` pictures a second apart from one of the user's media
1053/// files: demuxed by [`open_h264_source`] (MP4 or Matroska), decoded by this
1054/// crate, every Nth frame with N the source frame rate. Returns the
1055/// luma/chroma size and the pictures.
1056fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) {
1057 use ec_core::registry::Decoder as _;
1058
1059 let (params, mut demux, index) = open_h264_source(path);
1060 let video = match &params.media {
1061 ec_core::registry::MediaParameters::Video(v) => v,
1062 _ => panic!("the H.264 track carries no video parameters"),
1063 };
1064 let (w, h) = (video.width as usize, video.height as usize);
1065 // Consecutive pictures by default. This used to take one picture a second,
1066 // which measured an encoder on content it never sees: at a second apart
1067 // nothing is predictable from the previous picture, so P slices went 93%
1068 // intra on film and the inter path was never really under test.
1069 // `EC_H264_CLIP_STRIDE` restores a wider spacing (`fps` takes one a
1070 // second) for the deliberately-uncorrelated case.
1071 let stride = match std::env::var("EC_H264_CLIP_STRIDE").as_deref() {
1072 Ok("fps") => video
1073 .frame_rate
1074 .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1)),
1075 Ok(n) => n.parse().unwrap_or(1usize).max(1),
1076 Err(_) => 1,
1077 };
1078 let mut dec = ec_h264::H264Decoder::new(params).expect("decoder");
1079 // Pictures to pass over before sampling: the head of a film is titles and
1080 // fades, which are not what a codec is measured on.
1081 let skip: usize = std::env::var("EC_H264_CLIP_SKIP")
1082 .ok()
1083 .and_then(|v| v.parse().ok())
1084 .unwrap_or(0);
1085 let mut sources: Vec<Planes> = Vec::new();
1086 let mut seen = 0usize;
1087 while sources.len() < want {
1088 let Ok(packet) = demux.next_packet() else {
1089 break;
1090 };
1091 if packet.stream != index {
1092 continue;
1093 }
1094 dec.send_packet(&packet).expect("decode");
1095 while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() {
1096 if seen >= skip && sources.len() < want && (seen - skip).is_multiple_of(stride) {
1097 sources.push(planes_of(&f));
1098 }
1099 seen += 1;
1100 }
1101 }
1102 assert!(
1103 sources.len() >= 10,
1104 "only {} pictures decoded from {}",
1105 sources.len(),
1106 path.to_string_lossy()
1107 );
1108 eprintln!(
1109 "{}: {}x{}, {} pictures, every {stride}th of {seen}",
1110 path.to_string_lossy(),
1111 w,
1112 h,
1113 sources.len()
1114 );
1115 (w, h, sources)
1116}
1117
1118/// BD-PSNR of the `transform_8x8` flag (on by default) against flag-off on one real
1119/// clip from the library, full size, over a QP sweep: the number the synthetic
1120/// gate above cannot give, because the synthetic clip is content the flag wins
1121/// on. Prints the per-QP points, the BD-PSNR and the 8x8 macroblock share;
1122/// asserts nothing, so a regressing clip fails a gate, not the test run.
1123///
1124/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
1125/// real_clip_t8x8_bd_psnr -- --ignored --nocapture
1126#[test]
1127#[ignore = "set EC_H264_CLIP to a media file of yours"]
1128fn real_clip_t8x8_bd_psnr() {
1129 let Some(path) = std::env::var_os("EC_H264_CLIP") else {
1130 panic!("EC_H264_CLIP must name a media file");
1131 };
1132 let (w, h, sources) = clip_sources(&path, 30);
1133
1134 let run = |t8x8: bool, qp: i32| {
1135 let mut cfg = EncoderConfig::new(w as u32, h as u32);
1136 cfg.qp = qp;
1137 cfg.gop_size = 10;
1138 cfg.cabac = true;
1139 cfg.transform_8x8 = t8x8;
1140 cfg.framerate = 1.0; // the kept pictures are a second apart
1141 cfg.threads = 0;
1142 let mut enc = Encoder::new(cfg).expect("encoder");
1143 let (mut bits, mut sum_psnr) = (0usize, 0.0);
1144 for (y, u, v) in &sources {
1145 let view = PictureView::i420(w as u32, h as u32, y, u, v);
1146 bits += enc.encode(&view).expect("encode").au.len() * 8;
1147 let rec = enc.reconstruction().expect("reconstruction");
1148 sum_psnr += psnr(y, &rec.0);
1149 }
1150 let (i8x8, p8x8) = enc.transform_8x8_mbs();
1151 let share = (i8x8 + p8x8) as f64 / (sources.len() * (w / 16) * (h / 16)) as f64;
1152 (bits as f64, sum_psnr / sources.len() as f64, share)
1153 };
1154 let qps = [22, 26, 30, 34];
1155 let off: Vec<_> = qps.iter().map(|&q| run(false, q)).collect();
1156 let on: Vec<_> = qps.iter().map(|&q| run(true, q)).collect();
1157 for (i, &qp) in qps.iter().enumerate() {
1158 let (ob, op, _) = off[i];
1159 let (nb, np, share) = on[i];
1160 eprintln!(
1161 "qp {qp}: flag-off {ob:.0} bits {op:.2} dB | flag-on {nb:.0} bits {np:.2} dB, 8x8 share {:.1}%",
1162 share * 100.0
1163 );
1164 }
1165 let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
1166 let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
1167 let bd = bd_psnr_delta(&on_curve, &off_curve);
1168 let share = on.iter().map(|&(_, _, s)| s).sum::<f64>() / on.len() as f64;
1169 eprintln!(
1170 "BD-PSNR flag-on vs flag-off over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%",
1171 share * 100.0
1172 );
1173}
1174
1175// ---------------------------------------------------------------------------
1176// The encoder's rate-quality distance from x264: the survey's rank-1 gap,
1177// because until this test existed the repo could measure our decoder against
1178// every reference and our encoder against nothing but itself.
1179// ---------------------------------------------------------------------------
1180
1181/// Floor for [`bd_psnr_vs_x264`] on the synthetic clip. Our encoder measures
1182/// -4.523 dB against x264 there (352x288, 24 pictures of
1183/// `Clip::render_smooth`, both encoders at their own default effort: our
1184/// `Preset::Fast`, x264's `-preset medium`). The floor is that number with
1185/// room for platform noise, so the distance can shrink but not grow
1186/// unnoticed; it is not a claim that -4.5 dB is fine. On a 3840x1608 clip
1187/// from the library the same measurement reads -0.728 dB and on a 2560x1440
1188/// screen capture -0.500, so this synthetic number is the pessimistic end of
1189/// the range and not the typical one.
1190///
1191/// It moved -4.449 -> -4.523 when the intra-versus-inter decision started
1192/// coding both branches for real. That change is worth 0.315 dB on the film
1193/// clip and 0.564 on the screen capture, and takes fewer bits at every QP
1194/// while doing it. This clip prefers a heavier rate term in that decision
1195/// (see the sweep in `enc/mb.rs`), which the two real clips do not.
1196///
1197/// It moved -4.523 -> -4.073 when inter luma levels started being chosen
1198/// against the CABAC coder's own price for them (0.100 dB on the film clip,
1199/// 0.029 on the screen capture).
1200const BD_PSNR_VS_X264_FLOOR: f64 = -4.15;
1201
1202fn have_x264() -> bool {
1203 std::process::Command::new("ffmpeg")
1204 .args(["-v", "error", "-hide_banner", "-encoders"])
1205 .output()
1206 .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx264"))
1207}
1208
1209/// Encode raw I420 pictures with x264 at constant QP, matched to what our
1210/// encoder actually does: Main profile (CABAC, no 8x8 transform), one
1211/// reference, no B pictures, the same GOP, and adaptive quantisation and psy
1212/// off so both encoders spend bits by the same rule. Returns the Annex B
1213/// stream.
1214fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) -> Option<Vec<u8>> {
1215 // Distinct per call, not per process: two #[test]s in this binary call
1216 // this on parallel threads with overlapping qp values, and a path keyed
1217 // only on qp lets one call's cleanup delete another's still-in-use file.
1218 static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1219 let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1220 let dir = std::env::temp_dir().join(format!("ec-h264-x264-{}", std::process::id()));
1221 std::fs::create_dir_all(&dir).ok()?;
1222 let raw = dir.join(format!("in-q{qp}-{seq}.yuv"));
1223 let out = dir.join(format!("out-q{qp}-{seq}.264"));
1224 let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2);
1225 for (y, u, v) in sources {
1226 buf.extend_from_slice(y);
1227 buf.extend_from_slice(u);
1228 buf.extend_from_slice(v);
1229 }
1230 pin_or_bail("x264_encode_qp", &raw, &buf)?;
1231 let status = std::process::Command::new("ffmpeg")
1232 .args(["-v", "error", "-y"])
1233 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
1234 .args(["-s", &format!("{w}x{h}"), "-r", "1"])
1235 .arg("-i")
1236 .arg(&raw)
1237 // EC_H264_X264_PRESET selects the reference preset; the DONE.md target is
1238 // measured against `veryfast`, the default stays `medium` for the older gates.
1239 .args([
1240 "-c:v",
1241 "libx264",
1242 "-preset",
1243 &std::env::var("EC_H264_X264_PRESET").unwrap_or_else(|_| "medium".into()),
1244 ])
1245 .args(["-profile:v", "main", "-qp", &qp.to_string()])
1246 .args(["-g", &gop.to_string(), "-bf", "0", "-refs", "1"])
1247 // ipratio/pbratio 1.0 matter: x264's constant-QP mode otherwise codes
1248 // I pictures at a lower QP than the one asked for, which reads as a
1249 // rate-quality win that is really a different quantiser.
1250 // EC_H264_X264_PARAMS appends to this list, which is how a single
1251 // reference feature gets attributed: running the sweep again with
1252 // `trellis=0` says how much of x264's lead is its rate-distortion
1253 // quantisation rather than its prediction.
1254 .args([
1255 "-x264-params",
1256 &format!(
1257 "scenecut=0:aq-mode=0:psy=0:8x8dct=0:ipratio=1.0:pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}",
1258 match std::env::var("EC_H264_X264_PARAMS") {
1259 // The value may or may not carry its own leading colon;
1260 // both spell the same thing. Passing it through would not:
1261 // ffmpeg drops the token after an empty one, so "::subme=1"
1262 // silently encodes at the preset's subme and the sweep
1263 // reads as "the feature does nothing".
1264 Ok(extra) if !extra.trim().trim_matches(':').is_empty() =>
1265 format!(":{}", extra.trim().trim_matches(':')),
1266 _ => String::new(),
1267 }
1268 ),
1269 ])
1270 .args(["-f", "h264"])
1271 .arg(&out)
1272 .output()
1273 .ok()?;
1274 let _ = std::fs::remove_file(&raw);
1275 if !status.status.success() {
1276 eprintln!("x264 failed: {}", String::from_utf8_lossy(&status.stderr));
1277 return None;
1278 }
1279 let stream = std::fs::read(&out).ok()?;
1280 let _ = std::fs::remove_file(&out);
1281 Some(stream)
1282}
1283
1284/// BD-PSNR of our encoder against x264 at matched features over QP
1285/// 22/26/30/34. Runs on the synthetic clip by default, so the number cannot
1286/// rot behind an `#[ignore]`; point `EC_H264_CLIP` at a media file to measure
1287/// the same thing on real content.
1288///
1289/// Both curves are (bits, luma PSNR against the same source pictures), and
1290/// both are measured on ffmpeg's decode of the stream rather than on an
1291/// encoder's own reconstruction, so the two halves are read the same way.
1292///
1293/// `EC_H264_GOP` sets the GOP of both encoders; 1 makes the comparison
1294/// all-intra, which splits the gap between the intra path and the P pictures.
1295///
1296/// `EC_H264_PRESET_BALANCED` runs our half of the comparison at
1297/// `Preset::Balanced` instead of the default `Preset::Fast`, which separates
1298/// what search effort buys from what the coder itself costs.
1299///
1300/// `EC_H264_CLIP_SKIP` passes over that many pictures before sampling (film
1301/// heads are titles and fades), and `EC_H264_CLIP_STRIDE` widens the spacing
1302/// between the sampled pictures; both default to consecutive pictures from the
1303/// start of the file. The measurements quoted through this crate that predate
1304/// those two knobs were taken one picture a second, where nothing is
1305/// predictable from the previous picture -- they are not comparable with the
1306/// numbers taken since.
1307///
1308/// cargo test --release -p ec-h264 --test encode bd_psnr_vs_x264 -- --nocapture
1309/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
1310/// bd_psnr_vs_x264 -- --nocapture
1311#[test]
1312fn bd_psnr_vs_x264() {
1313 if !have_ffmpeg() || !have_x264() {
1314 eprintln!(
1315 "SKIP bd_psnr_vs_x264: no ffmpeg with libx264 on PATH. \
1316 Install one, then: cargo test --release -p ec-h264 --test encode \
1317 bd_psnr_vs_x264 -- --nocapture"
1318 );
1319 return;
1320 }
1321 let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") {
1322 Some(path) => clip_sources(&path, 24),
1323 None => {
1324 let (w, h, frames) = (352, 288, 24);
1325 let mut clip = Clip::new(w, h);
1326 let mut sources = Vec::with_capacity(frames);
1327 for t in 0..frames {
1328 clip.render_smooth(t);
1329 sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone()));
1330 }
1331 eprintln!("synthetic clip: {w}x{h}, {frames} pictures");
1332 (w, h, sources)
1333 }
1334 };
1335
1336 let gop: u32 = std::env::var("EC_H264_GOP")
1337 .ok()
1338 .and_then(|v| v.parse().ok())
1339 .unwrap_or(10);
1340 let ours = |qp: i32| {
1341 let mut cfg = EncoderConfig::new(w as u32, h as u32);
1342 cfg.qp = qp;
1343 cfg.gop_size = gop;
1344 if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() {
1345 cfg.preset = ec_h264::Preset::Balanced;
1346 }
1347 cfg.cabac = true;
1348 cfg.framerate = 1.0;
1349 cfg.threads = 0;
1350 let mut enc = Encoder::new(cfg).expect("encoder");
1351 let (mut stream, mut sum_recon) = (Vec::new(), 0.0);
1352 for (y, u, v) in &sources {
1353 let view = PictureView::i420(w as u32, h as u32, y, u, v);
1354 stream.extend_from_slice(&enc.encode(&view).expect("encode").au);
1355 sum_recon += psnr(y, &enc.reconstruction().expect("reconstruction").0);
1356 }
1357 // Measured the same way x264 is: on what a decoder shows, not on the
1358 // encoder's own reconstruction. The two are printed together because a
1359 // gap between them is a bug in one of the halves, not a rate-quality
1360 // result.
1361 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
1362 assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures");
1363 let sum: f64 = sources
1364 .iter()
1365 .zip(&decoded)
1366 .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
1367 .sum();
1368 let sum_yuv: f64 = sources
1369 .iter()
1370 .zip(&decoded)
1371 .map(|(s, d)| psnr_yuv(s, d))
1372 .sum();
1373 let (sum_u, sum_v) = (
1374 sources
1375 .iter()
1376 .zip(&decoded)
1377 .map(|(s, d)| psnr(&s.1, &d.1))
1378 .sum::<f64>(),
1379 sources
1380 .iter()
1381 .zip(&decoded)
1382 .map(|(s, d)| psnr(&s.2, &d.2))
1383 .sum::<f64>(),
1384 );
1385 eprintln!(
1386 " ours qp {qp}: u {:.2} dB v {:.2} dB",
1387 sum_u / sources.len() as f64,
1388 sum_v / sources.len() as f64
1389 );
1390 let (decoded_psnr, recon_psnr) =
1391 (sum / sources.len() as f64, sum_recon / sources.len() as f64);
1392 assert!(
1393 (decoded_psnr - recon_psnr).abs() < 0.05,
1394 "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \
1395 stream decodes to {decoded_psnr:.2} dB"
1396 );
1397 (
1398 (stream.len() * 8) as f64,
1399 decoded_psnr,
1400 sum_yuv / sources.len() as f64,
1401 )
1402 };
1403 let x264 = |qp: i32| {
1404 let stream = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes");
1405 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes x264's own stream");
1406 assert_eq!(
1407 decoded.len(),
1408 sources.len(),
1409 "x264 returned {} pictures for {} sources",
1410 decoded.len(),
1411 sources.len()
1412 );
1413 let sum: f64 = sources
1414 .iter()
1415 .zip(&decoded)
1416 .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
1417 .sum();
1418 let sum_yuv: f64 = sources
1419 .iter()
1420 .zip(&decoded)
1421 .map(|(s, d)| psnr_yuv(s, d))
1422 .sum();
1423 let n = sources.len() as f64;
1424 eprintln!(
1425 " x264 qp {qp}: u {:.2} dB v {:.2} dB",
1426 sources
1427 .iter()
1428 .zip(&decoded)
1429 .map(|(s, d)| psnr(&s.1, &d.1))
1430 .sum::<f64>()
1431 / n,
1432 sources
1433 .iter()
1434 .zip(&decoded)
1435 .map(|(s, d)| psnr(&s.2, &d.2))
1436 .sum::<f64>()
1437 / n
1438 );
1439 ((stream.len() * 8) as f64, sum / n, sum_yuv / n)
1440 };
1441
1442 let qps = [22, 26, 30, 34];
1443 let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect();
1444 let theirs: Vec<_> = qps.iter().map(|&q| x264(q)).collect();
1445 for (i, &qp) in qps.iter().enumerate() {
1446 let (ob, op, oy) = mine[i];
1447 let (xb, xp, xy) = theirs[i];
1448 eprintln!(
1449 "qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv) | x264 {xb:.0} bits {xp:.2} dB \
1450 ({xy:.2} yuv) ({:+.1}% bits, {:+.2} dB, {:+.2} yuv)",
1451 (ob / xb - 1.0) * 100.0,
1452 op - xp,
1453 oy - xy
1454 );
1455 }
1456 refuse_flat_window(theirs.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP");
1457 let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> {
1458 v.iter()
1459 .map(|&(b, p, y)| (b, if luma { p } else { y }))
1460 .collect()
1461 };
1462 let bd = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true));
1463 let bd_yuv = bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false));
1464 eprintln!("BD-PSNR ours vs x264 over q22/26/30/34: {bd:+.3} dB");
1465 eprintln!("BD-PSNR-YUV ours vs x264 over q22/26/30/34: {bd_yuv:+.3} dB");
1466
1467 // The floor is calibrated on the synthetic clip; a clip of the user's is a
1468 // measurement, not a gate, because its content is not pinned.
1469 if std::env::var_os("EC_H264_CLIP").is_none() && gop == 10 {
1470 assert!(
1471 bd > BD_PSNR_VS_X264_FLOOR,
1472 "BD-PSNR against x264 fell to {bd:+.3} dB, past the \
1473 {BD_PSNR_VS_X264_FLOOR:+.3} dB floor"
1474 );
1475 }
1476}
1477
1478/// Where our bits go against where x264's go, class by class, on the same
1479/// sources at the same QP. Both streams are parsed by this crate's decoder, so
1480/// the two accounts are the same measurement; the BD-PSNR gate says how much
1481/// we overspend, this says on what.
1482///
1483/// cargo test --release -p ec-h264 --test encode bit_account_vs_x264 -- --nocapture
1484/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
1485/// bit_account_vs_x264 -- --nocapture
1486#[test]
1487fn bit_account_vs_x264() {
1488 if !have_ffmpeg() || !have_x264() {
1489 eprintln!("SKIP bit_account_vs_x264: no ffmpeg with libx264 on PATH");
1490 return;
1491 }
1492 let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") {
1493 Some(path) => clip_sources(&path, 12),
1494 None => {
1495 let (w, h, frames) = (352, 288, 12);
1496 let mut clip = Clip::new(w, h);
1497 let mut sources = Vec::with_capacity(frames);
1498 for t in 0..frames {
1499 clip.render_smooth(t);
1500 sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone()));
1501 }
1502 eprintln!("synthetic clip: {w}x{h}, {frames} pictures");
1503 (w, h, sources)
1504 }
1505 };
1506 let gop: u32 = 10;
1507 let account = |stream: &[u8]| {
1508 let mut dec = Decoder::new();
1509 dec.set_output_order(OutputOrder::Decode);
1510 for nal in ec_h264_syntax::AnnexBIter::new(stream) {
1511 if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
1512 dec.end_picture().expect("end of picture");
1513 dec.push_nal(nal).expect("decoder accepts the NAL");
1514 }
1515 while dec.next_frame().is_some() {}
1516 }
1517 dec.flush().expect("flush");
1518 while dec.next_frame().is_some() {}
1519 (dec.bit_account(), dec.mb_shapes())
1520 };
1521 for qp in [26, 34] {
1522 let mut cfg = EncoderConfig::new(w as u32, h as u32);
1523 cfg.qp = qp;
1524 cfg.gop_size = gop;
1525 cfg.cabac = true;
1526 cfg.framerate = 1.0;
1527 cfg.threads = 0;
1528 if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() {
1529 cfg.preset = ec_h264::Preset::Balanced;
1530 }
1531 let mut enc = Encoder::new(cfg).expect("encoder");
1532 let mut ours = Vec::new();
1533 for (y, u, v) in &sources {
1534 let view = PictureView::i420(w as u32, h as u32, y, u, v);
1535 ours.extend_from_slice(&enc.encode(&view).expect("encode").au);
1536 }
1537 let theirs = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes");
1538 let ((a, sa), (b, sb)) = (account(&ours), account(&theirs));
1539 eprintln!(
1540 "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes",
1541 sources.len(),
1542 ours.len(),
1543 theirs.len()
1544 );
1545 let row = |name: &str, ours: u64, theirs: u64| {
1546 let (o, t) = (ours as f64 / 256.0, theirs as f64 / 256.0);
1547 let delta = if t > 0.0 {
1548 format!("{:+.1}%", (o - t) / t * 100.0)
1549 } else {
1550 "--".to_string()
1551 };
1552 eprintln!(" {name:<16} ours {o:>12.0} bits | x264 {t:>12.0} bits {delta:>8}");
1553 };
1554 row("skip", a.skip, b.skip);
1555 row("mb_type", a.mb_type, b.mb_type);
1556 row("mv", a.mv, b.mv);
1557 row("ref_idx", a.ref_idx, b.ref_idx);
1558 row("cbp+qp", a.cbp_qp, b.cbp_qp);
1559 row("intra modes", a.intra_mode, b.intra_mode);
1560 row("residual luma", a.residual_luma, b.residual_luma);
1561 row("residual chroma", a.residual_chroma, b.residual_chroma);
1562 row("total accounted", a.total(), b.total());
1563 let mix = |n: &str, s: &ec_h264::MbShapes| {
1564 eprintln!(
1565 " {n:<16} skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}",
1566 s.skip, s.p16x16, s.p16x8, s.p8x16, s.p8x8, s.intra
1567 );
1568 };
1569 mix("shapes ours", &sa);
1570 mix("shapes x264", &sb);
1571 }
1572}
1573
1574/// The partitions only `Preset::Balanced` searches, decoded by ffmpeg.
1575///
1576/// The default preset codes every P macroblock as one 16x16 partition, so the
1577/// bit-exactness sweeps above never put a 16x8, an 8x16 or a P_8x8 -- and so
1578/// never a `sub_mb_type` -- in front of another decoder. This does.
1579#[test]
1580fn balanced_partitions_decode_bit_exactly() {
1581 if !have_ffmpeg() {
1582 eprintln!("SKIP balanced_partitions_decode_bit_exactly: no ffmpeg on PATH");
1583 return;
1584 }
1585 let (w, h) = (176, 144);
1586 let mut shapes = ec_h264::MbShapes::default();
1587 for qp in [16, 26, 36] {
1588 let cavlc = qp == 26; // both entropy coders write sub_mb_type
1589 let (stream, recons, _) = encode_clip(w, h, 8, |cfg| {
1590 cfg.qp = qp;
1591 cfg.cabac = !cavlc;
1592 cfg.preset = ec_h264::Preset::Balanced;
1593 });
1594 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
1595 assert_eq!(decoded.len(), recons.len(), "qp {qp}: frame count");
1596 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
1597 assert_eq!(dec.0, rec.0, "qp {qp}: luma of frame {i}");
1598 assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}");
1599 assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}");
1600 }
1601 let mut dec = Decoder::new();
1602 dec.set_output_order(OutputOrder::Decode);
1603 for nal in ec_h264_syntax::AnnexBIter::new(&stream) {
1604 if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
1605 dec.end_picture().expect("end of picture");
1606 dec.push_nal(nal).expect("decoder accepts the NAL");
1607 }
1608 while dec.next_frame().is_some() {}
1609 }
1610 dec.flush().expect("flush");
1611 while dec.next_frame().is_some() {}
1612 shapes.add_public(&dec.mb_shapes());
1613 }
1614 eprintln!(
1615 "balanced shapes: skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}",
1616 shapes.skip, shapes.p16x16, shapes.p16x8, shapes.p8x16, shapes.p8x8, shapes.intra
1617 );
1618 assert!(
1619 shapes.p16x8 + shapes.p8x16 > 0 && shapes.p8x8 > 0,
1620 "the sweep has to code every shape, or it proves nothing about them"
1621 );
1622}
1623
1624#[test]
1625fn force_keyframe_restarts_the_gop() {
1626 let (w, h) = (64, 64);
1627 let mut clip = Clip::new(w, h);
1628 let mut cfg = EncoderConfig::new(w as u32, h as u32);
1629 cfg.gop_size = 4;
1630 cfg.threads = 1;
1631 let mut enc = Encoder::new(cfg).expect("encoder");
1632 let mut stream = Vec::new();
1633 let keys: Vec<bool> = (0..8)
1634 .map(|t| {
1635 clip.render(t);
1636 let pic = enc.encode_with(&clip.view(), t == 2).expect("encode");
1637 stream.extend_from_slice(&pic.au);
1638 pic.key_frame
1639 })
1640 .collect();
1641 assert_eq!(keys, [true, false, true, false, false, false, true, false]);
1642 assert_eq!(decode_all(&stream).len(), 8);
1643}