forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB4c07cbcTahinli2 months ago3583 commits

encode.rs1453 lines, 57.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 j in col..5 {
212 a[col][j] /= div;
213 }
214 for row in 0..4 {
215 if row == col {
216 continue;
217 }
218 let f = a[row][col];
219 for j in col..5 {
220 a[row][j] -= f * a[col][j];
221 }
222 }
223 }
224 [a[0][4], a[1][4], a[2][4], a[3][4]]
225}
226
227fn cubic_integral(c: [f64; 4], x: f64) -> f64 {
228 c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0
229}
230
231/// A sample window with nothing in it (a film's black head, a fade) codes to
232/// almost no bits and decodes back to the source exactly, so every point on
233/// both curves sits at the PSNR cap and the BD number is a flat +0.000 that
234/// reads like a measurement. Refuse such a window by name.
235fn refuse_flat_window(psnrs: impl IntoIterator<Item = f64>, skip_var: &str) {
236 const FLAT_WINDOW_DB: f64 = 90.0;
237 let ps: Vec<f64> = psnrs.into_iter().collect();
238 assert!(
239 ps.iter().any(|&p| p < FLAT_WINDOW_DB),
240 "the sample window is flat — every point reaches the PSNR cap ({ps:?}); \
241 this is a black head or a fade, not content: pass {skip_var} to sample \
242 past it"
243 );
244}
245
246fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 {
247 let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln());
248 let ys_candidate = std::array::from_fn(|i| candidate[i].1);
249 let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln());
250 let ys_anchor = std::array::from_fn(|i| anchor[i].1);
251 let lo = xs_candidate
252 .iter()
253 .copied()
254 .fold(f64::INFINITY, f64::min)
255 .max(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min));
256 let hi = xs_candidate
257 .iter()
258 .copied()
259 .fold(f64::NEG_INFINITY, f64::max)
260 .min(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max));
261 assert!(hi > lo, "BD-PSNR curves do not overlap in bitrate");
262 let c_candidate = cubic_fit(xs_candidate, ys_candidate);
263 let c_anchor = cubic_fit(xs_anchor, ys_anchor);
264 (cubic_integral(c_candidate, hi)
265 - cubic_integral(c_candidate, lo)
266 - cubic_integral(c_anchor, hi)
267 + cubic_integral(c_anchor, lo))
268 / (hi - lo)
269}
270
271/// The encoder's reconstruction and a decode of its bitstream agree sample for
272/// sample, over a QP sweep, both presets, single and multi threaded.
273#[test]
274fn reconstruction_matches_the_decoder() {
275 let mut t8x8_mbs = (0, 0);
276 for (w, h) in [(176, 144), (208, 122), (64, 48)] {
277 let mut clip = Clip::new(w, h);
278 for qp in [12, 24, 33, 44] {
279 for (threads, preset, cabac, t8x8) in [
280 (1usize, Preset::Fast, true, false),
281 (4, Preset::Balanced, true, false),
282 (1, Preset::Fast, false, false),
283 (3, Preset::Balanced, false, false),
284 (2, Preset::Balanced, true, true),
285 (2, Preset::Balanced, false, true),
286 ] {
287 let mut cfg = EncoderConfig::new(w as u32, h as u32);
288 cfg.qp = qp;
289 cfg.gop_size = 5;
290 cfg.threads = threads;
291 cfg.preset = preset;
292 cfg.cabac = cabac;
293 cfg.transform_8x8 = t8x8;
294 let mut enc = Encoder::new(cfg).expect("encoder");
295 let mut stream = Vec::new();
296 let mut recons = Vec::new();
297 for t in 0..8 {
298 clip.render(t);
299 let picture = enc.encode(&clip.view()).expect("encode");
300 stream.extend_from_slice(&picture.au);
301 recons.push(enc.reconstruction().expect("a reconstruction"));
302 }
303 if t8x8 {
304 let (intra, inter) = enc.transform_8x8_mbs();
305 t8x8_mbs.0 += intra;
306 t8x8_mbs.1 += inter;
307 }
308 let decoded = decode_all(&stream);
309 assert_eq!(
310 decoded.len(),
311 recons.len(),
312 "{w}x{h} qp {qp}: picture count"
313 );
314 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
315 assert_eq!(
316 dec.0, rec.0,
317 "{w}x{h} qp {qp} t{threads}: luma of picture {i}"
318 );
319 assert_eq!(
320 dec.1, rec.1,
321 "{w}x{h} qp {qp} t{threads}: Cb of picture {i}"
322 );
323 assert_eq!(
324 dec.2, rec.2,
325 "{w}x{h} qp {qp} t{threads}: Cr of picture {i}"
326 );
327 }
328 }
329 }
330 }
331 // The flag-on streams above really carried 8x8 macroblocks of both kinds.
332 assert!(
333 t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0,
334 "8x8 MBs across the sweep: intra {} inter {}",
335 t8x8_mbs.0,
336 t8x8_mbs.1
337 );
338}
339
340/// Quality tracks the quantiser, and a low QP is close to lossless: a stream
341/// that decodes bit-exactly could still be encoding garbage, and this is what
342/// says it is not.
343#[test]
344fn quality_follows_the_quantiser() {
345 let (w, h) = (176, 144);
346 let mut clip = Clip::new(w, h);
347 let mut last = 0.0;
348 for qp in [40, 30, 20, 10] {
349 let mut cfg = EncoderConfig::new(w as u32, h as u32);
350 cfg.qp = qp;
351 cfg.gop_size = 4;
352 cfg.threads = 1;
353 let mut enc = Encoder::new(cfg).expect("encoder");
354 let mut total = 0.0;
355 for t in 0..6 {
356 clip.render(t);
357 enc.encode(&clip.view()).expect("encode");
358 let (y, _, _) = enc.reconstruction().unwrap();
359 total += psnr(&clip.y, &y);
360 }
361 let avg = total / 6.0;
362 assert!(
363 avg > last,
364 "qp {qp}: PSNR {avg:.2} did not improve on {last:.2}"
365 );
366 if qp == 10 {
367 assert!(avg > 45.0, "qp 10 should be near lossless, got {avg:.2}");
368 }
369 last = avg;
370 }
371}
372
373/// Constant bitrate lands within a quarter of the target over a short clip,
374/// and every GOP boundary is an IDR the decoder can start from.
375#[test]
376fn rate_control_hits_its_target() {
377 let (w, h) = (352, 288);
378 let mut clip = Clip::new(w, h);
379 let bitrate = 1_500_000u32;
380 let mut cfg = EncoderConfig::new(w as u32, h as u32);
381 cfg.bitrate = bitrate;
382 cfg.framerate = 25.0;
383 cfg.gop_size = 25;
384 cfg.threads = 2;
385 let mut enc = Encoder::new(cfg).expect("encoder");
386 let mut bits = 0u64;
387 let frames = 50;
388 let mut keys = 0;
389 for t in 0..frames {
390 clip.render(t);
391 let p = enc.encode(&clip.view()).expect("encode");
392 bits += p.au.len() as u64 * 8;
393 keys += u32::from(p.key_frame);
394 }
395 assert_eq!(keys, 2, "one IDR per GOP");
396 let actual = bits as f64 / (frames as f64 / 25.0);
397 let ratio = actual / f64::from(bitrate);
398 assert!(
399 (0.7..1.35).contains(&ratio),
400 "bitrate {actual:.0} against target {bitrate} (ratio {ratio:.2})"
401 );
402}
403
404/// Every picture of a `gop_size` 1 stream is an IDR, which is what an
405/// intraframe master asks for.
406#[test]
407fn all_intra_when_the_gop_is_one() {
408 let (w, h) = (64, 64);
409 let mut clip = Clip::new(w, h);
410 let mut cfg = EncoderConfig::new(w as u32, h as u32);
411 cfg.gop_size = 1;
412 cfg.qp = 26;
413 let mut enc = Encoder::new(cfg).expect("encoder");
414 let mut stream = Vec::new();
415 for t in 0..4 {
416 clip.render(t);
417 let p = enc.encode(&clip.view()).expect("encode");
418 assert!(p.key_frame, "picture {t} is not a key frame");
419 stream.extend_from_slice(&p.au);
420 }
421 assert_eq!(decode_all(&stream).len(), 4);
422}
423
424// ---------------------------------------------------------------------------
425// ffmpeg-driven half: the third-party oracle. Skipped loudly when ffmpeg is
426// absent, exactly like the conformance suite's ffmpeg cross-check.
427// ---------------------------------------------------------------------------
428
429fn have_ffmpeg() -> bool {
430 std::process::Command::new("ffmpeg")
431 .arg("-version")
432 .stdout(std::process::Stdio::null())
433 .stderr(std::process::Stdio::null())
434 .status()
435 .is_ok_and(|s| s.success())
436}
437
438/// Fixture-presence probe for `<what this test needs>`.
439/// Returns whether the fixture is present, but never silently: under
440/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path
441/// and the script that regenerates it, so a host whose fixture library drifted
442/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure;
443/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently
444/// short-circuited because the probe ran first in a compound `if`).
445///
446/// Order is load-bearing: probe, assert, return. Never merge the probe into
447/// the same `if` as the escape.
448fn require_fixture(path: &std::path::Path, generator: &str) -> bool {
449 let present = path.exists();
450 assert!(
451 present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
452 "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}",
453 path.display(),
454 generator
455 );
456 if !present {
457 eprintln!("SKIP: fixture {} absent", path.display());
458 }
459 present
460}
461
462/// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture.
463fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> {
464 // Distinct per call, not per process: several #[test]s in this binary
465 // call this on parallel threads, and a path keyed only on stream length
466 // lets one call's cleanup delete another's still-being-read file.
467 static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
468 let dir = std::env::temp_dir().join(format!("ec-h264-enc-{}", std::process::id()));
469 std::fs::create_dir_all(&dir).ok()?;
470 let path = dir.join(format!(
471 "s{}-{}.264",
472 stream.len(),
473 SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
474 ));
475 std::fs::write(&path, stream).ok()?;
476 let mut cmd = std::process::Command::new("ffmpeg");
477 cmd.args(["-v", "error"]);
478 cmd.args(extra);
479 cmd.arg("-i").arg(&path);
480 cmd.args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]);
481 let out = cmd.output().ok()?;
482 let _ = std::fs::remove_file(&path);
483 if !out.status.success() {
484 eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
485 return None;
486 }
487 let frame = w * h * 3 / 2;
488 if frame == 0 || out.stdout.len() % frame != 0 {
489 eprintln!(
490 "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames",
491 out.stdout.len()
492 );
493 return None;
494 }
495 Some(
496 out.stdout
497 .chunks(frame)
498 .map(|f| {
499 let (y, rest) = f.split_at(w * h);
500 let (u, v) = rest.split_at(w / 2 * h / 2);
501 (y.to_vec(), u.to_vec(), v.to_vec())
502 })
503 .collect(),
504 )
505}
506
507/// Encode a clip and hand back the stream with the encoder's reconstructions.
508fn encode_clip(
509 w: usize,
510 h: usize,
511 frames: usize,
512 configure: impl FnOnce(&mut EncoderConfig),
513) -> (Vec<u8>, Vec<Planes>, (u64, u64)) {
514 let mut cfg = EncoderConfig::new(w as u32, h as u32);
515 cfg.gop_size = 10;
516 cfg.threads = 3;
517 configure(&mut cfg);
518 let mut enc = Encoder::new(cfg).expect("encoder");
519 let mut clip = Clip::new(w, h);
520 let mut stream = Vec::new();
521 let mut recons = Vec::new();
522 for t in 0..frames {
523 clip.render(t);
524 stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au);
525 recons.push(enc.reconstruction().expect("reconstruction"));
526 }
527 (stream, recons, enc.transform_8x8_mbs())
528}
529
530/// Flat gradients and glyph-like rectangles: the content the 8x8 transform
531/// exists for. A 10-frame clip with the flag on must keep a clear positive
532/// gain at equal bits, or cut bits at equal PSNR.
533#[test]
534fn eight_by_eight_gains_on_flat_and_text() {
535 let (w, h) = (320, 240);
536 let render = |t: usize, clip: &mut Clip| {
537 // A half-sample pan per frame: inter prediction has a residual to code.
538 let sx = |x: usize| x * 2 + t;
539 for y in 0..h {
540 for x in 0..w {
541 let (px, py) = (sx(x) as f64 / 2.0, y as f64);
542 // Curved shading: smooth but not a plane, so no 16x16 mode
543 // predicts it for free.
544 let shade = 70.0 + px * px / 900.0 + py * py / 700.0 - px * py / 1500.0;
545 // Gentle texture with a 20-sample period: residual energy that
546 // spans more than a 4x4 block, which is what the 8x8 transform
547 // is for.
548 let tri = |v: f64| ((v % 20.0) - 10.0).abs() - 5.0;
549 let shade = shade + tri(px) * tri(py) / 1.5;
550 // Glyph rows: 16x24 cells, stroke pattern hashed per cell.
551 let (cell, cx, cy) = (sx(x) / 32, (sx(x) / 2) % 16, y % 24);
552 let hash = (cell * 2654435761usize.wrapping_add(y / 24 * 40503)) >> 7;
553 let stem = (2..5).contains(&cx);
554 let bar = (10..13).contains(&cy) && cx < 12 && hash & 1 == 1;
555 let foot = cy >= 19 && (2..13).contains(&cx) && hash & 2 == 2;
556 let glyph = y > h / 3 && (3..22).contains(&cy) && (stem || bar || foot);
557 clip.y[y * w + x] = if glyph { 24 } else { shade.min(235.0) as u8 };
558 }
559 }
560 clip.u.fill(128);
561 clip.v.fill(128);
562 };
563 let run = |t8x8: bool, qp: i32, cabac: bool| {
564 let mut cfg = EncoderConfig::new(w as u32, h as u32);
565 cfg.qp = qp;
566 cfg.gop_size = 10;
567 cfg.transform_8x8 = t8x8;
568 cfg.cabac = cabac;
569 let mut enc = Encoder::new(cfg).expect("encoder");
570 let mut clip = Clip::new(w, h);
571 let (mut bits, mut sum_psnr) = (0usize, 0.0);
572 let mut share = 0.0;
573 for t in 0..10 {
574 render(t, &mut clip);
575 bits += enc.encode(&clip.view()).expect("encode").au.len() * 8;
576 let rec = enc.reconstruction().expect("reconstruction");
577 sum_psnr += psnr(&clip.y, &rec.0);
578 }
579 if t8x8 {
580 let (i, p) = enc.transform_8x8_mbs();
581 eprintln!("8x8 MBs: intra {i} inter {p}");
582 share = (i + p) as f64 / (10.0 * (w / 16 * h / 16) as f64);
583 }
584 (bits as f64, sum_psnr / 10.0, share)
585 };
586 let qps = [22, 26, 30, 34];
587 let on: Vec<_> = qps.iter().map(|&q| run(true, q, true)).collect();
588 let off: Vec<_> = qps.iter().map(|&q| run(false, q, true)).collect();
589 refuse_flat_window(off.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP");
590 let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
591 let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
592 let bd = bd_psnr_delta(&on_curve, &off_curve);
593 let share = on.iter().map(|&(_, _, share)| share).sum::<f64>() / on.len() as f64;
594 // What the flag buys, not what the encoder is worth: both arms move when
595 // the paths under them change. It was re-pinned from 0.255 when the 4x4
596 // luma path gained its coded_block_pattern group test, which is in the
597 // flag-off arm and improved it -- the same change moves the absolute
598 // synthetic comparison against x264 from -4.060 to -3.969 dB, and the
599 // flag-on arm barely at all, because a transform_8x8 macroblock does not
600 // go through that path.
601 const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.230;
602 eprintln!(
603 "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%",
604 share * 100.0
605 );
606 assert!(share > 0.0, "no 8x8 macroblocks were coded");
607 assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off");
608 assert!(
609 bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB,
610 "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate"
611 );
612}
613
614/// ffmpeg's decode of our stream is our reconstruction, sample for sample,
615/// across a QP sweep and at a size that is not a multiple of a macroblock.
616#[test]
617fn ffmpeg_decodes_bit_exactly() {
618 if !have_ffmpeg() {
619 eprintln!("SKIP ffmpeg_decodes_bit_exactly: no ffmpeg on PATH");
620 return;
621 }
622 let mut t8x8_mbs = (0, 0);
623 for (w, h) in [(176, 144), (322, 242)] {
624 for qp in [10, 20, 28, 37, 47] {
625 let cavlc = qp % 2 == 0; // both entropy coders across the sweep
626 let t8x8 = qp % 3 == 1; // High-profile PPS with the per-MB flag
627 let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| {
628 cfg.qp = qp;
629 cfg.cabac = !cavlc;
630 cfg.transform_8x8 = t8x8;
631 });
632 t8x8_mbs.0 += intra;
633 t8x8_mbs.1 += inter;
634 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
635 assert_eq!(decoded.len(), recons.len(), "{w}x{h} qp {qp}: frame count");
636 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
637 assert_eq!(dec.0, rec.0, "{w}x{h} qp {qp}: luma of frame {i}");
638 assert_eq!(dec.1, rec.1, "{w}x{h} qp {qp}: Cb of frame {i}");
639 assert_eq!(dec.2, rec.2, "{w}x{h} qp {qp}: Cr of frame {i}");
640 }
641 }
642 }
643 assert!(
644 t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0,
645 "8x8 MBs across the sweep: intra {} inter {}",
646 t8x8_mbs.0,
647 t8x8_mbs.1
648 );
649}
650
651/// The same stream under constant bitrate, which is the mode edith exports in.
652#[test]
653fn ffmpeg_decodes_a_cbr_stream_bit_exactly() {
654 if !have_ffmpeg() {
655 eprintln!("SKIP ffmpeg_decodes_a_cbr_stream_bit_exactly: no ffmpeg on PATH");
656 return;
657 }
658 let (w, h) = (352, 288);
659 let (stream, recons, _) = encode_clip(w, h, 12, |cfg| {
660 cfg.bitrate = 2_000_000;
661 cfg.framerate = 25.0;
662 });
663 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
664 assert_eq!(decoded.len(), recons.len());
665 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
666 assert_eq!(dec.0, rec.0, "luma of frame {i}");
667 assert_eq!(
668 (dec.1.clone(), dec.2.clone()),
669 (rec.1.clone(), rec.2.clone()),
670 "chroma of frame {i}"
671 );
672 }
673}
674
675/// The VA-API hardware decoder on this machine accepts the same stream: a
676/// bitstream a driver refuses is not a bitstream edith can ship, whatever a
677/// software decoder says about it.
678#[test]
679fn vaapi_decodes_our_stream() {
680 if !have_ffmpeg() || !std::path::Path::new("/dev/dri/renderD128").exists() {
681 eprintln!("SKIP vaapi_decodes_our_stream: no ffmpeg or no render node");
682 return;
683 }
684 let (w, h) = (352, 288);
685 let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| {
686 cfg.qp = 26;
687 cfg.transform_8x8 = true;
688 });
689 assert!(intra + inter > 0, "no 8x8 macroblocks in the VA-API stream");
690 let Some(decoded) = ffmpeg_decode(
691 &stream,
692 w,
693 h,
694 &[
695 "-hwaccel",
696 "vaapi",
697 "-hwaccel_device",
698 "/dev/dri/renderD128",
699 ],
700 ) else {
701 eprintln!("SKIP vaapi_decodes_our_stream: VA-API decode unavailable here");
702 return;
703 };
704 assert_eq!(decoded.len(), recons.len(), "VA-API frame count");
705 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
706 let p = psnr(&dec.0, &rec.0);
707 assert!(p > 60.0, "VA-API luma of frame {i} differs: PSNR {p:.1} dB");
708 }
709}
710
711/// Real 1080p pictures from this machine's library, demuxed by `ec-mp4` and
712/// decoded by this crate, are re-encoded and handed back to ffmpeg.
713///
714/// Synthetic clips do not have film grain, hard cuts, or the residual
715/// statistics an encoder actually meets; a stream that survives a gradient and
716/// a moving box says nothing about one. Every picture must decode to exactly
717/// the encoder's own reconstruction, and the run reports the rate it landed on
718/// against the rate it was asked for.
719#[test]
720fn real_library_frames_encode_and_decode_exactly() {
721 use ec_core::registry::Decoder as _;
722
723 if !have_ffmpeg() {
724 eprintln!("SKIP real_library_frames: no ffmpeg on PATH");
725 return;
726 }
727 let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
728 .join("../../fixtures/real-library-manifest.tsv");
729 if !require_fixture(&manifest, "scripts/scan-real-library.sh") {
730 return;
731 }
732 let text = std::fs::read_to_string(&manifest).expect("manifest reads");
733 // The first 8-bit 4:2:0 H.264 mp4 of at least 720p in the manifest.
734 let mut source = None;
735 for line in text.lines().skip(1) {
736 let f: Vec<&str> = line.split('\t').collect();
737 if f.len() < 7 || f[2] != "h264" || f[5] != "yuv420p" {
738 continue;
739 }
740 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
741 continue;
742 };
743 if w < 1280 || h < 720 || !w.is_multiple_of(2) || !h.is_multiple_of(2) {
744 continue;
745 }
746 if !f[1].contains("mp4") || !std::path::Path::new(f[0]).exists() {
747 continue;
748 }
749 source = Some((f[0].to_string(), w, h));
750 break;
751 }
752 let Some((path, w, h)) = source else {
753 // A manifest with no qualifying row is a corpus that drifted, not a
754 // reason to report PASS for a sweep that never ran.
755 assert!(
756 std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
757 "EC_REQUIRE_FIXTURES=1 but {} lists no H.264 4:2:0 mp4 of at least \
758 720p -- regenerate with: scripts/scan-real-library.sh",
759 manifest.display()
760 );
761 eprintln!("SKIP real_library_frames: no H.264 4:2:0 mp4 in the manifest");
762 return;
763 };
764
765 // Decode a handful of real pictures.
766 let (params, mut demux, index) = open_h264_source(std::ffi::OsStr::new(&path));
767 let mut dec = ec_h264::H264Decoder::new(params).expect("decoder");
768 let mut sources: Vec<Planes> = Vec::new();
769 while sources.len() < 12 {
770 let Ok(packet) = demux.next_packet() else {
771 break;
772 };
773 if packet.stream != index {
774 continue;
775 }
776 dec.send_packet(&packet).expect("decode");
777 while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() {
778 if sources.len() < 12 {
779 sources.push(planes_of(&f));
780 }
781 }
782 }
783 assert!(
784 sources.len() >= 6,
785 "only {} pictures decoded from the library file",
786 sources.len()
787 );
788
789 let bitrate = 8_000_000u32;
790 let mut cfg = EncoderConfig::new(w as u32, h as u32);
791 cfg.bitrate = bitrate;
792 cfg.framerate = 25.0;
793 cfg.gop_size = 25;
794 cfg.threads = 0;
795 let mut enc = Encoder::new(cfg).expect("encoder");
796 let mut stream = Vec::new();
797 let mut recons = Vec::new();
798 let mut bits = 0u64;
799 for (y, u, v) in &sources {
800 let view = PictureView::i420(w as u32, h as u32, y, u, v);
801 let p = enc.encode(&view).expect("encode");
802 bits += p.au.len() as u64 * 8;
803 stream.extend_from_slice(&p.au);
804 recons.push(enc.reconstruction().expect("reconstruction"));
805 }
806 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
807 assert_eq!(decoded.len(), recons.len(), "picture count");
808 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
809 assert_eq!(dec.0, rec.0, "luma of picture {i} from the library clip");
810 assert_eq!(dec.1, rec.1, "Cb of picture {i}");
811 assert_eq!(dec.2, rec.2, "Cr of picture {i}");
812 }
813 let quality: f64 = sources
814 .iter()
815 .zip(&recons)
816 .map(|((y, ..), (ry, ..))| psnr(y, ry))
817 .sum::<f64>()
818 / sources.len() as f64;
819 let rate = bits as f64 / (sources.len() as f64 / 25.0);
820 eprintln!(
821 "library clip {w}x{h}: {} pictures, {:.0} kbit/s asked {:.0}, luma PSNR {quality:.2} dB",
822 sources.len(),
823 rate / 1000.0,
824 f64::from(bitrate) / 1000.0
825 );
826 assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s");
827}
828
829/// Opens `path` by probing its bytes — MP4 carries an `ftyp` box at offset 4,
830/// Matroska starts with EBML magic `1A 45 DF A3` — never by extension. Returns
831/// the first H.264 video track's codec parameters (whose `extradata` is the
832/// avcC or CodecPrivate) and a boxed demuxer plus the track's stream index.
833///
834/// A video track that is not H.264 (AV1, HEVC, …) is refused with a message
835/// naming the codec, never a panic inside the demuxer.
836fn open_h264_source(
837 path: &std::ffi::OsStr,
838) -> (
839 ec_core::registry::CodecParameters,
840 Box<dyn ec_core::registry::Demuxer>,
841 u32,
842) {
843 use std::io::{Read, Seek, SeekFrom};
844
845 let file = std::fs::File::open(path).expect("source opens");
846 let mut reader = std::io::BufReader::new(file);
847 // corner-cut: a 12-byte probe reads only the two magics this gate opens
848 // — 'ftyp' at 4 for MP4, EBML at 0 for Matroska. A third container this
849 // crate grows to support would need its own magic here; upgrade by
850 // extending the if-chain.
851 let mut head = [0u8; 12];
852 let n = reader.read(&mut head).expect("read container head");
853 reader.seek(SeekFrom::Start(0)).expect("rewind");
854
855 let demux: Box<dyn ec_core::registry::Demuxer> = if ec_matroska::is_matroska(&head[..n]) {
856 Box::new(ec_matroska::MatroskaDemuxer::new(reader).expect("ec-matroska opens the file"))
857 } else if n >= 8 && &head[4..8] == b"ftyp" {
858 Box::new(ec_mp4::Mp4Demuxer::new(reader).expect("ec-mp4 opens the file"))
859 } else {
860 panic!(
861 "{}: not an MP4 or Matroska container",
862 path.to_string_lossy()
863 )
864 };
865
866 let streams = demux.streams();
867 if let Some((params, index)) = streams
868 .iter()
869 .find(|s| s.params.codec == ec_core::registry::CodecId::H264)
870 .map(|s| (s.params.clone(), s.index))
871 {
872 return (params, demux, index);
873 }
874 // No H.264 track: name what the video track actually is, so an AV1 or
875 // HEVC file is refused clearly rather than panicking inside a find.
876 if let Some(codec) = streams
877 .iter()
878 .find(|s| matches!(s.params.media, ec_core::registry::MediaParameters::Video(_)))
879 .map(|s| s.params.codec)
880 {
881 panic!(
882 "{}: video track is {:?}, not H.264 — this gate measures H.264 only",
883 path.to_string_lossy(),
884 codec
885 );
886 }
887 panic!("{}: no video track found", path.to_string_lossy());
888}
889
890/// The first `want` pictures a second apart from one of the user's media
891/// files: demuxed by [`open_h264_source`] (MP4 or Matroska), decoded by this
892/// crate, every Nth frame with N the source frame rate. Returns the
893/// luma/chroma size and the pictures.
894fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) {
895 use ec_core::registry::Decoder as _;
896
897 let (params, mut demux, index) = open_h264_source(path);
898 let video = match &params.media {
899 ec_core::registry::MediaParameters::Video(v) => v,
900 _ => panic!("the H.264 track carries no video parameters"),
901 };
902 let (w, h) = (video.width as usize, video.height as usize);
903 // Consecutive pictures by default. This used to take one picture a second,
904 // which measured an encoder on content it never sees: at a second apart
905 // nothing is predictable from the previous picture, so P slices went 93%
906 // intra on film and the inter path was never really under test.
907 // `EC_H264_CLIP_STRIDE` restores a wider spacing (`fps` takes one a
908 // second) for the deliberately-uncorrelated case.
909 let stride = match std::env::var("EC_H264_CLIP_STRIDE").as_deref() {
910 Ok("fps") => video
911 .frame_rate
912 .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1)),
913 Ok(n) => n.parse().unwrap_or(1usize).max(1),
914 Err(_) => 1,
915 };
916 let mut dec = ec_h264::H264Decoder::new(params).expect("decoder");
917 // Pictures to pass over before sampling: the head of a film is titles and
918 // fades, which are not what a codec is measured on.
919 let skip: usize = std::env::var("EC_H264_CLIP_SKIP")
920 .ok()
921 .and_then(|v| v.parse().ok())
922 .unwrap_or(0);
923 let mut sources: Vec<Planes> = Vec::new();
924 let mut seen = 0usize;
925 while sources.len() < want {
926 let Ok(packet) = demux.next_packet() else {
927 break;
928 };
929 if packet.stream != index {
930 continue;
931 }
932 dec.send_packet(&packet).expect("decode");
933 while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() {
934 if seen >= skip && sources.len() < want && (seen - skip).is_multiple_of(stride) {
935 sources.push(planes_of(&f));
936 }
937 seen += 1;
938 }
939 }
940 assert!(
941 sources.len() >= 10,
942 "only {} pictures decoded from {}",
943 sources.len(),
944 path.to_string_lossy()
945 );
946 eprintln!(
947 "{}: {}x{}, {} pictures, every {stride}th of {seen}",
948 path.to_string_lossy(),
949 w,
950 h,
951 sources.len()
952 );
953 (w, h, sources)
954}
955
956/// BD-PSNR of the `transform_8x8` flag (on by default) against flag-off on one real
957/// clip from the library, full size, over a QP sweep: the number the synthetic
958/// gate above cannot give, because the synthetic clip is content the flag wins
959/// on. Prints the per-QP points, the BD-PSNR and the 8x8 macroblock share;
960/// asserts nothing, so a regressing clip fails a gate, not the test run.
961///
962/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
963/// real_clip_t8x8_bd_psnr -- --ignored --nocapture
964#[test]
965#[ignore = "set EC_H264_CLIP to a media file of yours"]
966fn real_clip_t8x8_bd_psnr() {
967 let Some(path) = std::env::var_os("EC_H264_CLIP") else {
968 panic!("EC_H264_CLIP must name a media file");
969 };
970 let (w, h, sources) = clip_sources(&path, 30);
971
972 let run = |t8x8: bool, qp: i32| {
973 let mut cfg = EncoderConfig::new(w as u32, h as u32);
974 cfg.qp = qp;
975 cfg.gop_size = 10;
976 cfg.cabac = true;
977 cfg.transform_8x8 = t8x8;
978 cfg.framerate = 1.0; // the kept pictures are a second apart
979 cfg.threads = 0;
980 let mut enc = Encoder::new(cfg).expect("encoder");
981 let (mut bits, mut sum_psnr) = (0usize, 0.0);
982 for (y, u, v) in &sources {
983 let view = PictureView::i420(w as u32, h as u32, y, u, v);
984 bits += enc.encode(&view).expect("encode").au.len() * 8;
985 let rec = enc.reconstruction().expect("reconstruction");
986 sum_psnr += psnr(y, &rec.0);
987 }
988 let (i8x8, p8x8) = enc.transform_8x8_mbs();
989 let share = (i8x8 + p8x8) as f64 / (sources.len() * (w / 16) * (h / 16)) as f64;
990 (bits as f64, sum_psnr / sources.len() as f64, share)
991 };
992 let qps = [22, 26, 30, 34];
993 let off: Vec<_> = qps.iter().map(|&q| run(false, q)).collect();
994 let on: Vec<_> = qps.iter().map(|&q| run(true, q)).collect();
995 for (i, &qp) in qps.iter().enumerate() {
996 let (ob, op, _) = off[i];
997 let (nb, np, share) = on[i];
998 eprintln!(
999 "qp {qp}: flag-off {ob:.0} bits {op:.2} dB | flag-on {nb:.0} bits {np:.2} dB, 8x8 share {:.1}%",
1000 share * 100.0
1001 );
1002 }
1003 let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
1004 let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
1005 let bd = bd_psnr_delta(&on_curve, &off_curve);
1006 let share = on.iter().map(|&(_, _, s)| s).sum::<f64>() / on.len() as f64;
1007 eprintln!(
1008 "BD-PSNR flag-on vs flag-off over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%",
1009 share * 100.0
1010 );
1011}
1012
1013// ---------------------------------------------------------------------------
1014// The encoder's rate-quality distance from x264: the survey's rank-1 gap,
1015// because until this test existed the repo could measure our decoder against
1016// every reference and our encoder against nothing but itself.
1017// ---------------------------------------------------------------------------
1018
1019/// Floor for [`bd_psnr_vs_x264`] on the synthetic clip. Our encoder measures
1020/// -4.523 dB against x264 there (352x288, 24 pictures of
1021/// `Clip::render_smooth`, both encoders at their own default effort: our
1022/// `Preset::Fast`, x264's `-preset medium`). The floor is that number with
1023/// room for platform noise, so the distance can shrink but not grow
1024/// unnoticed; it is not a claim that -4.5 dB is fine. On a 3840x1608 clip
1025/// from the library the same measurement reads -0.728 dB and on a 2560x1440
1026/// screen capture -0.500, so this synthetic number is the pessimistic end of
1027/// the range and not the typical one.
1028///
1029/// It moved -4.449 -> -4.523 when the intra-versus-inter decision started
1030/// coding both branches for real. That change is worth 0.315 dB on the film
1031/// clip and 0.564 on the screen capture, and takes fewer bits at every QP
1032/// while doing it. This clip prefers a heavier rate term in that decision
1033/// (see the sweep in `enc/mb.rs`), which the two real clips do not.
1034///
1035/// It moved -4.523 -> -4.073 when inter luma levels started being chosen
1036/// against the CABAC coder's own price for them (0.100 dB on the film clip,
1037/// 0.029 on the screen capture).
1038const BD_PSNR_VS_X264_FLOOR: f64 = -4.15;
1039
1040fn have_x264() -> bool {
1041 std::process::Command::new("ffmpeg")
1042 .args(["-v", "error", "-hide_banner", "-encoders"])
1043 .output()
1044 .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx264"))
1045}
1046
1047/// Encode raw I420 pictures with x264 at constant QP, matched to what our
1048/// encoder actually does: Main profile (CABAC, no 8x8 transform), one
1049/// reference, no B pictures, the same GOP, and adaptive quantisation and psy
1050/// off so both encoders spend bits by the same rule. Returns the Annex B
1051/// stream.
1052fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) -> Option<Vec<u8>> {
1053 // Distinct per call, not per process: two #[test]s in this binary call
1054 // this on parallel threads with overlapping qp values, and a path keyed
1055 // only on qp lets one call's cleanup delete another's still-in-use file.
1056 static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1057 let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1058 let dir = std::env::temp_dir().join(format!("ec-h264-x264-{}", std::process::id()));
1059 std::fs::create_dir_all(&dir).ok()?;
1060 let raw = dir.join(format!("in-q{qp}-{seq}.yuv"));
1061 let out = dir.join(format!("out-q{qp}-{seq}.264"));
1062 let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2);
1063 for (y, u, v) in sources {
1064 buf.extend_from_slice(y);
1065 buf.extend_from_slice(u);
1066 buf.extend_from_slice(v);
1067 }
1068 std::fs::write(&raw, &buf).ok()?;
1069 let status = std::process::Command::new("ffmpeg")
1070 .args(["-v", "error", "-y"])
1071 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
1072 .args(["-s", &format!("{w}x{h}"), "-r", "1"])
1073 .arg("-i")
1074 .arg(&raw)
1075 .args(["-c:v", "libx264", "-preset", "medium"])
1076 .args(["-profile:v", "main", "-qp", &qp.to_string()])
1077 .args(["-g", &gop.to_string(), "-bf", "0", "-refs", "1"])
1078 // ipratio/pbratio 1.0 matter: x264's constant-QP mode otherwise codes
1079 // I pictures at a lower QP than the one asked for, which reads as a
1080 // rate-quality win that is really a different quantiser.
1081 // EC_H264_X264_PARAMS appends to this list, which is how a single
1082 // reference feature gets attributed: running the sweep again with
1083 // `trellis=0` says how much of x264's lead is its rate-distortion
1084 // quantisation rather than its prediction.
1085 .args([
1086 "-x264-params",
1087 &format!(
1088 "scenecut=0:aq-mode=0:psy=0:8x8dct=0:ipratio=1.0:pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}",
1089 match std::env::var("EC_H264_X264_PARAMS") {
1090 // The value may or may not carry its own leading colon;
1091 // both spell the same thing. Passing it through would not:
1092 // ffmpeg drops the token after an empty one, so "::subme=1"
1093 // silently encodes at the preset's subme and the sweep
1094 // reads as "the feature does nothing".
1095 Ok(extra) if !extra.trim().trim_matches(':').is_empty() =>
1096 format!(":{}", extra.trim().trim_matches(':')),
1097 _ => String::new(),
1098 }
1099 ),
1100 ])
1101 .args(["-f", "h264"])
1102 .arg(&out)
1103 .output()
1104 .ok()?;
1105 let _ = std::fs::remove_file(&raw);
1106 if !status.status.success() {
1107 eprintln!("x264 failed: {}", String::from_utf8_lossy(&status.stderr));
1108 return None;
1109 }
1110 let stream = std::fs::read(&out).ok()?;
1111 let _ = std::fs::remove_file(&out);
1112 Some(stream)
1113}
1114
1115/// BD-PSNR of our encoder against x264 at matched features over QP
1116/// 22/26/30/34. Runs on the synthetic clip by default, so the number cannot
1117/// rot behind an `#[ignore]`; point `EC_H264_CLIP` at a media file to measure
1118/// the same thing on real content.
1119///
1120/// Both curves are (bits, luma PSNR against the same source pictures), and
1121/// both are measured on ffmpeg's decode of the stream rather than on an
1122/// encoder's own reconstruction, so the two halves are read the same way.
1123///
1124/// `EC_H264_GOP` sets the GOP of both encoders; 1 makes the comparison
1125/// all-intra, which splits the gap between the intra path and the P pictures.
1126///
1127/// `EC_H264_PRESET_BALANCED` runs our half of the comparison at
1128/// `Preset::Balanced` instead of the default `Preset::Fast`, which separates
1129/// what search effort buys from what the coder itself costs.
1130///
1131/// `EC_H264_CLIP_SKIP` passes over that many pictures before sampling (film
1132/// heads are titles and fades), and `EC_H264_CLIP_STRIDE` widens the spacing
1133/// between the sampled pictures; both default to consecutive pictures from the
1134/// start of the file. The measurements quoted through this crate that predate
1135/// those two knobs were taken one picture a second, where nothing is
1136/// predictable from the previous picture -- they are not comparable with the
1137/// numbers taken since.
1138///
1139/// cargo test --release -p ec-h264 --test encode bd_psnr_vs_x264 -- --nocapture
1140/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
1141/// bd_psnr_vs_x264 -- --nocapture
1142#[test]
1143fn bd_psnr_vs_x264() {
1144 if !have_ffmpeg() || !have_x264() {
1145 eprintln!(
1146 "SKIP bd_psnr_vs_x264: no ffmpeg with libx264 on PATH. \
1147 Install one, then: cargo test --release -p ec-h264 --test encode \
1148 bd_psnr_vs_x264 -- --nocapture"
1149 );
1150 return;
1151 }
1152 let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") {
1153 Some(path) => clip_sources(&path, 24),
1154 None => {
1155 let (w, h, frames) = (352, 288, 24);
1156 let mut clip = Clip::new(w, h);
1157 let mut sources = Vec::with_capacity(frames);
1158 for t in 0..frames {
1159 clip.render_smooth(t);
1160 sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone()));
1161 }
1162 eprintln!("synthetic clip: {w}x{h}, {frames} pictures");
1163 (w, h, sources)
1164 }
1165 };
1166
1167 let gop: u32 = std::env::var("EC_H264_GOP")
1168 .ok()
1169 .and_then(|v| v.parse().ok())
1170 .unwrap_or(10);
1171 let ours = |qp: i32| {
1172 let mut cfg = EncoderConfig::new(w as u32, h as u32);
1173 cfg.qp = qp;
1174 cfg.gop_size = gop;
1175 if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() {
1176 cfg.preset = ec_h264::Preset::Balanced;
1177 }
1178 cfg.cabac = true;
1179 cfg.framerate = 1.0;
1180 cfg.threads = 0;
1181 let mut enc = Encoder::new(cfg).expect("encoder");
1182 let (mut stream, mut sum_recon) = (Vec::new(), 0.0);
1183 for (y, u, v) in &sources {
1184 let view = PictureView::i420(w as u32, h as u32, y, u, v);
1185 stream.extend_from_slice(&enc.encode(&view).expect("encode").au);
1186 sum_recon += psnr(y, &enc.reconstruction().expect("reconstruction").0);
1187 }
1188 // Measured the same way x264 is: on what a decoder shows, not on the
1189 // encoder's own reconstruction. The two are printed together because a
1190 // gap between them is a bug in one of the halves, not a rate-quality
1191 // result.
1192 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
1193 assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures");
1194 let sum: f64 = sources
1195 .iter()
1196 .zip(&decoded)
1197 .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
1198 .sum();
1199 let sum_yuv: f64 = sources
1200 .iter()
1201 .zip(&decoded)
1202 .map(|(s, d)| psnr_yuv(s, d))
1203 .sum();
1204 let (sum_u, sum_v) = (
1205 sources
1206 .iter()
1207 .zip(&decoded)
1208 .map(|(s, d)| psnr(&s.1, &d.1))
1209 .sum::<f64>(),
1210 sources
1211 .iter()
1212 .zip(&decoded)
1213 .map(|(s, d)| psnr(&s.2, &d.2))
1214 .sum::<f64>(),
1215 );
1216 eprintln!(
1217 " ours qp {qp}: u {:.2} dB v {:.2} dB",
1218 sum_u / sources.len() as f64,
1219 sum_v / sources.len() as f64
1220 );
1221 let (decoded_psnr, recon_psnr) =
1222 (sum / sources.len() as f64, sum_recon / sources.len() as f64);
1223 assert!(
1224 (decoded_psnr - recon_psnr).abs() < 0.05,
1225 "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \
1226 stream decodes to {decoded_psnr:.2} dB"
1227 );
1228 (
1229 (stream.len() * 8) as f64,
1230 decoded_psnr,
1231 sum_yuv / sources.len() as f64,
1232 )
1233 };
1234 let x264 = |qp: i32| {
1235 let stream = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes");
1236 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes x264's own stream");
1237 assert_eq!(
1238 decoded.len(),
1239 sources.len(),
1240 "x264 returned {} pictures for {} sources",
1241 decoded.len(),
1242 sources.len()
1243 );
1244 let sum: f64 = sources
1245 .iter()
1246 .zip(&decoded)
1247 .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
1248 .sum();
1249 let sum_yuv: f64 = sources
1250 .iter()
1251 .zip(&decoded)
1252 .map(|(s, d)| psnr_yuv(s, d))
1253 .sum();
1254 let n = sources.len() as f64;
1255 eprintln!(
1256 " x264 qp {qp}: u {:.2} dB v {:.2} dB",
1257 sources
1258 .iter()
1259 .zip(&decoded)
1260 .map(|(s, d)| psnr(&s.1, &d.1))
1261 .sum::<f64>()
1262 / n,
1263 sources
1264 .iter()
1265 .zip(&decoded)
1266 .map(|(s, d)| psnr(&s.2, &d.2))
1267 .sum::<f64>()
1268 / n
1269 );
1270 ((stream.len() * 8) as f64, sum / n, sum_yuv / n)
1271 };
1272
1273 let qps = [22, 26, 30, 34];
1274 let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect();
1275 let theirs: Vec<_> = qps.iter().map(|&q| x264(q)).collect();
1276 for (i, &qp) in qps.iter().enumerate() {
1277 let (ob, op, oy) = mine[i];
1278 let (xb, xp, xy) = theirs[i];
1279 eprintln!(
1280 "qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv) | x264 {xb:.0} bits {xp:.2} dB \
1281 ({xy:.2} yuv) ({:+.1}% bits, {:+.2} dB, {:+.2} yuv)",
1282 (ob / xb - 1.0) * 100.0,
1283 op - xp,
1284 oy - xy
1285 );
1286 }
1287 refuse_flat_window(theirs.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP");
1288 let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> {
1289 v.iter()
1290 .map(|&(b, p, y)| (b, if luma { p } else { y }))
1291 .collect()
1292 };
1293 let bd = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true));
1294 let bd_yuv = bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false));
1295 eprintln!("BD-PSNR ours vs x264 over q22/26/30/34: {bd:+.3} dB");
1296 eprintln!("BD-PSNR-YUV ours vs x264 over q22/26/30/34: {bd_yuv:+.3} dB");
1297
1298 // The floor is calibrated on the synthetic clip; a clip of the user's is a
1299 // measurement, not a gate, because its content is not pinned.
1300 if std::env::var_os("EC_H264_CLIP").is_none() && gop == 10 {
1301 assert!(
1302 bd > BD_PSNR_VS_X264_FLOOR,
1303 "BD-PSNR against x264 fell to {bd:+.3} dB, past the \
1304 {BD_PSNR_VS_X264_FLOOR:+.3} dB floor"
1305 );
1306 }
1307}
1308
1309/// Where our bits go against where x264's go, class by class, on the same
1310/// sources at the same QP. Both streams are parsed by this crate's decoder, so
1311/// the two accounts are the same measurement; the BD-PSNR gate says how much
1312/// we overspend, this says on what.
1313///
1314/// cargo test --release -p ec-h264 --test encode bit_account_vs_x264 -- --nocapture
1315/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
1316/// bit_account_vs_x264 -- --nocapture
1317#[test]
1318fn bit_account_vs_x264() {
1319 if !have_ffmpeg() || !have_x264() {
1320 eprintln!("SKIP bit_account_vs_x264: no ffmpeg with libx264 on PATH");
1321 return;
1322 }
1323 let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") {
1324 Some(path) => clip_sources(&path, 12),
1325 None => {
1326 let (w, h, frames) = (352, 288, 12);
1327 let mut clip = Clip::new(w, h);
1328 let mut sources = Vec::with_capacity(frames);
1329 for t in 0..frames {
1330 clip.render_smooth(t);
1331 sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone()));
1332 }
1333 eprintln!("synthetic clip: {w}x{h}, {frames} pictures");
1334 (w, h, sources)
1335 }
1336 };
1337 let gop: u32 = 10;
1338 let account = |stream: &[u8]| {
1339 let mut dec = Decoder::new();
1340 dec.set_output_order(OutputOrder::Decode);
1341 for nal in ec_h264_syntax::AnnexBIter::new(stream) {
1342 if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
1343 dec.end_picture().expect("end of picture");
1344 dec.push_nal(nal).expect("decoder accepts the NAL");
1345 }
1346 while dec.next_frame().is_some() {}
1347 }
1348 dec.flush().expect("flush");
1349 while dec.next_frame().is_some() {}
1350 (dec.bit_account(), dec.mb_shapes())
1351 };
1352 for qp in [26, 34] {
1353 let mut cfg = EncoderConfig::new(w as u32, h as u32);
1354 cfg.qp = qp;
1355 cfg.gop_size = gop;
1356 cfg.cabac = true;
1357 cfg.framerate = 1.0;
1358 cfg.threads = 0;
1359 if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() {
1360 cfg.preset = ec_h264::Preset::Balanced;
1361 }
1362 let mut enc = Encoder::new(cfg).expect("encoder");
1363 let mut ours = Vec::new();
1364 for (y, u, v) in &sources {
1365 let view = PictureView::i420(w as u32, h as u32, y, u, v);
1366 ours.extend_from_slice(&enc.encode(&view).expect("encode").au);
1367 }
1368 let theirs = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes");
1369 let ((a, sa), (b, sb)) = (account(&ours), account(&theirs));
1370 eprintln!(
1371 "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes",
1372 sources.len(),
1373 ours.len(),
1374 theirs.len()
1375 );
1376 let row = |name: &str, ours: u64, theirs: u64| {
1377 let (o, t) = (ours as f64 / 256.0, theirs as f64 / 256.0);
1378 let delta = if t > 0.0 {
1379 format!("{:+.1}%", (o - t) / t * 100.0)
1380 } else {
1381 "--".to_string()
1382 };
1383 eprintln!(" {name:<16} ours {o:>12.0} bits | x264 {t:>12.0} bits {delta:>8}");
1384 };
1385 row("skip", a.skip, b.skip);
1386 row("mb_type", a.mb_type, b.mb_type);
1387 row("mv", a.mv, b.mv);
1388 row("ref_idx", a.ref_idx, b.ref_idx);
1389 row("cbp+qp", a.cbp_qp, b.cbp_qp);
1390 row("intra modes", a.intra_mode, b.intra_mode);
1391 row("residual luma", a.residual_luma, b.residual_luma);
1392 row("residual chroma", a.residual_chroma, b.residual_chroma);
1393 row("total accounted", a.total(), b.total());
1394 let mix = |n: &str, s: &ec_h264::MbShapes| {
1395 eprintln!(
1396 " {n:<16} skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}",
1397 s.skip, s.p16x16, s.p16x8, s.p8x16, s.p8x8, s.intra
1398 );
1399 };
1400 mix("shapes ours", &sa);
1401 mix("shapes x264", &sb);
1402 }
1403}
1404
1405/// The partitions only `Preset::Balanced` searches, decoded by ffmpeg.
1406///
1407/// The default preset codes every P macroblock as one 16x16 partition, so the
1408/// bit-exactness sweeps above never put a 16x8, an 8x16 or a P_8x8 -- and so
1409/// never a `sub_mb_type` -- in front of another decoder. This does.
1410#[test]
1411fn balanced_partitions_decode_bit_exactly() {
1412 if !have_ffmpeg() {
1413 eprintln!("SKIP balanced_partitions_decode_bit_exactly: no ffmpeg on PATH");
1414 return;
1415 }
1416 let (w, h) = (176, 144);
1417 let mut shapes = ec_h264::MbShapes::default();
1418 for qp in [16, 26, 36] {
1419 let cavlc = qp == 26; // both entropy coders write sub_mb_type
1420 let (stream, recons, _) = encode_clip(w, h, 8, |cfg| {
1421 cfg.qp = qp;
1422 cfg.cabac = !cavlc;
1423 cfg.preset = ec_h264::Preset::Balanced;
1424 });
1425 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
1426 assert_eq!(decoded.len(), recons.len(), "qp {qp}: frame count");
1427 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
1428 assert_eq!(dec.0, rec.0, "qp {qp}: luma of frame {i}");
1429 assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}");
1430 assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}");
1431 }
1432 let mut dec = Decoder::new();
1433 dec.set_output_order(OutputOrder::Decode);
1434 for nal in ec_h264_syntax::AnnexBIter::new(&stream) {
1435 if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
1436 dec.end_picture().expect("end of picture");
1437 dec.push_nal(nal).expect("decoder accepts the NAL");
1438 }
1439 while dec.next_frame().is_some() {}
1440 }
1441 dec.flush().expect("flush");
1442 while dec.next_frame().is_some() {}
1443 shapes.add_public(&dec.mb_shapes());
1444 }
1445 eprintln!(
1446 "balanced shapes: skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}",
1447 shapes.skip, shapes.p16x16, shapes.p16x8, shapes.p8x16, shapes.p8x8, shapes.intra
1448 );
1449 assert!(
1450 shapes.p16x8 + shapes.p8x16 > 0 && shapes.p8x8 > 0,
1451 "the sweep has to code every shape, or it proves nothing about them"
1452 );
1453}