forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBeb83b6fTahinli3 months ago495 commits

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