forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB552edc4Tahinli2 months ago2048 commits

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