forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB6828b15Tahinli3 months ago393 commits

encode.rs701 lines, 25.5 KiBHistoryRawDownload
1//! Encoder conformance: what this encoder writes is what this decoder — and,
2//! in the ffmpeg-driven half of the suite, what ffmpeg — reconstructs.
3//!
4//! The load-bearing property is that the encoder's own reconstruction is
5//! *bit-identical* to a decode of its bitstream. Both sides share the
6//! prediction, transform and deblocking code, so a mismatch means the syntax
7//! written does not describe the picture reconstructed, which is the one class
8//! of encoder bug that quality metrics cannot see.
9
10use ec_h264::{Decoder, Encoder, EncoderConfig, NalOutcome, OutputOrder, PictureView, Preset};
11
12/// One decoded picture: Y, Cb and Cr planes, cropped and tightly packed.
13type Planes = (Vec<u8>, Vec<u8>, Vec<u8>);
14
15/// A synthetic source with real structure: moving edges, a gradient and a
16/// noisy patch, so intra, inter and skip all get exercised.
17struct Clip {
18 w: usize,
19 h: usize,
20 y: Vec<u8>,
21 u: Vec<u8>,
22 v: Vec<u8>,
23}
24
25impl Clip {
26 fn new(w: usize, h: usize) -> Clip {
27 Clip {
28 w,
29 h,
30 y: vec![0; w * h],
31 u: vec![0; w / 2 * h / 2],
32 v: vec![0; w / 2 * h / 2],
33 }
34 }
35
36 /// Frame `t`: a diagonal gradient, a moving box and a deterministic noise
37 /// field that keeps the residual from vanishing.
38 fn render(&mut self, t: usize) {
39 let (w, h) = (self.w, self.h);
40 for y in 0..h {
41 for x in 0..w {
42 let grad = ((x + y * 2 + t * 3) % 256) as u8;
43 let noise = ((x * 37 + y * 17 + t * 11) % 23) as u8;
44 let box_x = (t * 5) % (w.saturating_sub(40).max(1));
45 let inside = x >= box_x && x < box_x + 40 && y >= h / 4 && y < h / 4 + 30;
46 self.y[y * w + x] = if inside {
47 200u8.saturating_sub(noise)
48 } else {
49 grad / 2 + noise
50 };
51 }
52 }
53 for y in 0..h / 2 {
54 for x in 0..w / 2 {
55 self.u[y * (w / 2) + x] = (100 + ((x + t) % 40)) as u8;
56 self.v[y * (w / 2) + x] = (140 + ((y + t * 2) % 30)) as u8;
57 }
58 }
59 }
60
61 fn view(&self) -> PictureView<'_> {
62 PictureView::i420(self.w as u32, self.h as u32, &self.y, &self.u, &self.v)
63 }
64}
65
66/// Decode a whole stream with this crate's decoder, returning one I420 triple
67/// per picture.
68fn decode_all(stream: &[u8]) -> Vec<Planes> {
69 let mut dec = Decoder::new();
70 dec.set_output_order(OutputOrder::Decode);
71 let mut out = Vec::new();
72 for nal in ec_h264_syntax::AnnexBIter::new(stream) {
73 if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary {
74 dec.end_picture().expect("end of picture");
75 dec.push_nal(nal).expect("decoder accepts the NAL");
76 }
77 while let Some(frame) = dec.next_frame() {
78 out.push(planes_of(&frame));
79 }
80 }
81 dec.flush().expect("flush");
82 while let Some(frame) = dec.next_frame() {
83 out.push(planes_of(&frame));
84 }
85 out
86}
87
88fn planes_of(frame: &ec_core::frame::VideoFrame) -> Planes {
89 let (w, h) = (frame.width as usize, frame.height as usize);
90 let mut planes = Vec::new();
91 for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)]
92 .into_iter()
93 .enumerate()
94 {
95 let plane = &frame.planes[i];
96 let mut out = Vec::with_capacity(pw * ph);
97 for row in 0..ph {
98 out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]);
99 }
100 planes.push(out);
101 }
102 let v = planes.pop().unwrap();
103 let u = planes.pop().unwrap();
104 let y = planes.pop().unwrap();
105 (y, u, v)
106}
107
108fn psnr(a: &[u8], b: &[u8]) -> f64 {
109 let mse: f64 = a
110 .iter()
111 .zip(b)
112 .map(|(&x, &y)| {
113 let d = f64::from(x) - f64::from(y);
114 d * d
115 })
116 .sum::<f64>()
117 / a.len() as f64;
118 if mse == 0.0 {
119 99.0
120 } else {
121 10.0 * (255.0 * 255.0 / mse).log10()
122 }
123}
124
125fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] {
126 let mut a = [[0.0; 5]; 4];
127 for i in 0..4 {
128 a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]];
129 }
130 for col in 0..4 {
131 let mut pivot = col;
132 for row in col + 1..4 {
133 if a[row][col].abs() > a[pivot][col].abs() {
134 pivot = row;
135 }
136 }
137 a.swap(col, pivot);
138 let div = a[col][col];
139 assert!(div.abs() > 1e-12, "singular BD-PSNR fit");
140 for j in col..5 {
141 a[col][j] /= div;
142 }
143 for row in 0..4 {
144 if row == col {
145 continue;
146 }
147 let f = a[row][col];
148 for j in col..5 {
149 a[row][j] -= f * a[col][j];
150 }
151 }
152 }
153 [a[0][4], a[1][4], a[2][4], a[3][4]]
154}
155
156fn cubic_integral(c: [f64; 4], x: f64) -> f64 {
157 c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0
158}
159
160fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 {
161 let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln());
162 let ys_candidate = std::array::from_fn(|i| candidate[i].1);
163 let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln());
164 let ys_anchor = std::array::from_fn(|i| anchor[i].1);
165 let lo = xs_candidate
166 .iter()
167 .copied()
168 .fold(f64::INFINITY, f64::min)
169 .max(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min));
170 let hi = xs_candidate
171 .iter()
172 .copied()
173 .fold(f64::NEG_INFINITY, f64::max)
174 .min(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max));
175 assert!(hi > lo, "BD-PSNR curves do not overlap in bitrate");
176 let c_candidate = cubic_fit(xs_candidate, ys_candidate);
177 let c_anchor = cubic_fit(xs_anchor, ys_anchor);
178 (cubic_integral(c_candidate, hi)
179 - cubic_integral(c_candidate, lo)
180 - cubic_integral(c_anchor, hi)
181 + cubic_integral(c_anchor, lo))
182 / (hi - lo)
183}
184
185/// The encoder's reconstruction and a decode of its bitstream agree sample for
186/// sample, over a QP sweep, both presets, single and multi threaded.
187#[test]
188fn reconstruction_matches_the_decoder() {
189 let mut t8x8_mbs = (0, 0);
190 for (w, h) in [(176, 144), (208, 122), (64, 48)] {
191 let mut clip = Clip::new(w, h);
192 for qp in [12, 24, 33, 44] {
193 for (threads, preset, cabac, t8x8) in [
194 (1usize, Preset::Fast, true, false),
195 (4, Preset::Balanced, true, false),
196 (1, Preset::Fast, false, false),
197 (3, Preset::Balanced, false, false),
198 (2, Preset::Balanced, true, true),
199 (2, Preset::Balanced, false, true),
200 ] {
201 let mut cfg = EncoderConfig::new(w as u32, h as u32);
202 cfg.qp = qp;
203 cfg.gop_size = 5;
204 cfg.threads = threads;
205 cfg.preset = preset;
206 cfg.cabac = cabac;
207 cfg.transform_8x8 = t8x8;
208 let mut enc = Encoder::new(cfg).expect("encoder");
209 let mut stream = Vec::new();
210 let mut recons = Vec::new();
211 for t in 0..8 {
212 clip.render(t);
213 let picture = enc.encode(&clip.view()).expect("encode");
214 stream.extend_from_slice(&picture.au);
215 recons.push(enc.reconstruction().expect("a reconstruction"));
216 }
217 if t8x8 {
218 let (intra, inter) = enc.transform_8x8_mbs();
219 t8x8_mbs.0 += intra;
220 t8x8_mbs.1 += inter;
221 }
222 let decoded = decode_all(&stream);
223 assert_eq!(
224 decoded.len(),
225 recons.len(),
226 "{w}x{h} qp {qp}: picture count"
227 );
228 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
229 assert_eq!(
230 dec.0, rec.0,
231 "{w}x{h} qp {qp} t{threads}: luma of picture {i}"
232 );
233 assert_eq!(
234 dec.1, rec.1,
235 "{w}x{h} qp {qp} t{threads}: Cb of picture {i}"
236 );
237 assert_eq!(
238 dec.2, rec.2,
239 "{w}x{h} qp {qp} t{threads}: Cr of picture {i}"
240 );
241 }
242 }
243 }
244 }
245 // The flag-on streams above really carried 8x8 macroblocks of both kinds.
246 assert!(
247 t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0,
248 "8x8 MBs across the sweep: intra {} inter {}",
249 t8x8_mbs.0,
250 t8x8_mbs.1
251 );
252}
253
254/// Quality tracks the quantiser, and a low QP is close to lossless: a stream
255/// that decodes bit-exactly could still be encoding garbage, and this is what
256/// says it is not.
257#[test]
258fn quality_follows_the_quantiser() {
259 let (w, h) = (176, 144);
260 let mut clip = Clip::new(w, h);
261 let mut last = 0.0;
262 for qp in [40, 30, 20, 10] {
263 let mut cfg = EncoderConfig::new(w as u32, h as u32);
264 cfg.qp = qp;
265 cfg.gop_size = 4;
266 cfg.threads = 1;
267 let mut enc = Encoder::new(cfg).expect("encoder");
268 let mut total = 0.0;
269 for t in 0..6 {
270 clip.render(t);
271 enc.encode(&clip.view()).expect("encode");
272 let (y, _, _) = enc.reconstruction().unwrap();
273 total += psnr(&clip.y, &y);
274 }
275 let avg = total / 6.0;
276 assert!(
277 avg > last,
278 "qp {qp}: PSNR {avg:.2} did not improve on {last:.2}"
279 );
280 if qp == 10 {
281 assert!(avg > 45.0, "qp 10 should be near lossless, got {avg:.2}");
282 }
283 last = avg;
284 }
285}
286
287/// Constant bitrate lands within a quarter of the target over a short clip,
288/// and every GOP boundary is an IDR the decoder can start from.
289#[test]
290fn rate_control_hits_its_target() {
291 let (w, h) = (352, 288);
292 let mut clip = Clip::new(w, h);
293 let bitrate = 1_500_000u32;
294 let mut cfg = EncoderConfig::new(w as u32, h as u32);
295 cfg.bitrate = bitrate;
296 cfg.framerate = 25.0;
297 cfg.gop_size = 25;
298 cfg.threads = 2;
299 let mut enc = Encoder::new(cfg).expect("encoder");
300 let mut bits = 0u64;
301 let frames = 50;
302 let mut keys = 0;
303 for t in 0..frames {
304 clip.render(t);
305 let p = enc.encode(&clip.view()).expect("encode");
306 bits += p.au.len() as u64 * 8;
307 keys += u32::from(p.key_frame);
308 }
309 assert_eq!(keys, 2, "one IDR per GOP");
310 let actual = bits as f64 / (frames as f64 / 25.0);
311 let ratio = actual / f64::from(bitrate);
312 assert!(
313 (0.7..1.35).contains(&ratio),
314 "bitrate {actual:.0} against target {bitrate} (ratio {ratio:.2})"
315 );
316}
317
318/// Every picture of a `gop_size` 1 stream is an IDR, which is what an
319/// intraframe master asks for.
320#[test]
321fn all_intra_when_the_gop_is_one() {
322 let (w, h) = (64, 64);
323 let mut clip = Clip::new(w, h);
324 let mut cfg = EncoderConfig::new(w as u32, h as u32);
325 cfg.gop_size = 1;
326 cfg.qp = 26;
327 let mut enc = Encoder::new(cfg).expect("encoder");
328 let mut stream = Vec::new();
329 for t in 0..4 {
330 clip.render(t);
331 let p = enc.encode(&clip.view()).expect("encode");
332 assert!(p.key_frame, "picture {t} is not a key frame");
333 stream.extend_from_slice(&p.au);
334 }
335 assert_eq!(decode_all(&stream).len(), 4);
336}
337
338// ---------------------------------------------------------------------------
339// ffmpeg-driven half: the third-party oracle. Skipped loudly when ffmpeg is
340// absent, exactly like the conformance suite's ffmpeg cross-check.
341// ---------------------------------------------------------------------------
342
343fn have_ffmpeg() -> bool {
344 std::process::Command::new("ffmpeg")
345 .arg("-version")
346 .stdout(std::process::Stdio::null())
347 .stderr(std::process::Stdio::null())
348 .status()
349 .is_ok_and(|s| s.success())
350}
351
352/// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture.
353fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> {
354 let dir = std::env::temp_dir().join(format!("ec-h264-enc-{}", std::process::id()));
355 std::fs::create_dir_all(&dir).ok()?;
356 let path = dir.join(format!("s{}.264", stream.len()));
357 std::fs::write(&path, stream).ok()?;
358 let mut cmd = std::process::Command::new("ffmpeg");
359 cmd.args(["-v", "error"]);
360 cmd.args(extra);
361 cmd.arg("-i").arg(&path);
362 cmd.args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]);
363 let out = cmd.output().ok()?;
364 let _ = std::fs::remove_file(&path);
365 if !out.status.success() {
366 eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
367 return None;
368 }
369 let frame = w * h * 3 / 2;
370 if frame == 0 || out.stdout.len() % frame != 0 {
371 eprintln!(
372 "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames",
373 out.stdout.len()
374 );
375 return None;
376 }
377 Some(
378 out.stdout
379 .chunks(frame)
380 .map(|f| {
381 let (y, rest) = f.split_at(w * h);
382 let (u, v) = rest.split_at(w / 2 * h / 2);
383 (y.to_vec(), u.to_vec(), v.to_vec())
384 })
385 .collect(),
386 )
387}
388
389/// Encode a clip and hand back the stream with the encoder's reconstructions.
390fn encode_clip(
391 w: usize,
392 h: usize,
393 frames: usize,
394 configure: impl FnOnce(&mut EncoderConfig),
395) -> (Vec<u8>, Vec<Planes>, (u64, u64)) {
396 let mut cfg = EncoderConfig::new(w as u32, h as u32);
397 cfg.gop_size = 10;
398 cfg.threads = 3;
399 configure(&mut cfg);
400 let mut enc = Encoder::new(cfg).expect("encoder");
401 let mut clip = Clip::new(w, h);
402 let mut stream = Vec::new();
403 let mut recons = Vec::new();
404 for t in 0..frames {
405 clip.render(t);
406 stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au);
407 recons.push(enc.reconstruction().expect("reconstruction"));
408 }
409 (stream, recons, enc.transform_8x8_mbs())
410}
411
412/// Flat gradients and glyph-like rectangles: the content the 8x8 transform
413/// exists for. A 10-frame clip with the flag on must keep a clear positive
414/// gain at equal bits, or cut bits at equal PSNR.
415#[test]
416fn eight_by_eight_gains_on_flat_and_text() {
417 let (w, h) = (320, 240);
418 let render = |t: usize, clip: &mut Clip| {
419 // A half-sample pan per frame: inter prediction has a residual to code.
420 let sx = |x: usize| x * 2 + t;
421 for y in 0..h {
422 for x in 0..w {
423 let (px, py) = (sx(x) as f64 / 2.0, y as f64);
424 // Curved shading: smooth but not a plane, so no 16x16 mode
425 // predicts it for free.
426 let shade = 70.0 + px * px / 900.0 + py * py / 700.0 - px * py / 1500.0;
427 // Gentle texture with a 20-sample period: residual energy that
428 // spans more than a 4x4 block, which is what the 8x8 transform
429 // is for.
430 let tri = |v: f64| ((v % 20.0) - 10.0).abs() - 5.0;
431 let shade = shade + tri(px) * tri(py) / 1.5;
432 // Glyph rows: 16x24 cells, stroke pattern hashed per cell.
433 let (cell, cx, cy) = (sx(x) / 32, (sx(x) / 2) % 16, y % 24);
434 let hash = (cell * 2654435761usize.wrapping_add(y / 24 * 40503)) >> 7;
435 let stem = (2..5).contains(&cx);
436 let bar = (10..13).contains(&cy) && cx < 12 && hash & 1 == 1;
437 let foot = cy >= 19 && (2..13).contains(&cx) && hash & 2 == 2;
438 let glyph = y > h / 3 && (3..22).contains(&cy) && (stem || bar || foot);
439 clip.y[y * w + x] = if glyph { 24 } else { shade.min(235.0) as u8 };
440 }
441 }
442 clip.u.fill(128);
443 clip.v.fill(128);
444 };
445 let run = |t8x8: bool, qp: i32, cabac: bool| {
446 let mut cfg = EncoderConfig::new(w as u32, h as u32);
447 cfg.qp = qp;
448 cfg.gop_size = 10;
449 cfg.transform_8x8 = t8x8;
450 cfg.cabac = cabac;
451 let mut enc = Encoder::new(cfg).expect("encoder");
452 let mut clip = Clip::new(w, h);
453 let (mut bits, mut sum_psnr) = (0usize, 0.0);
454 let mut share = 0.0;
455 for t in 0..10 {
456 render(t, &mut clip);
457 bits += enc.encode(&clip.view()).expect("encode").au.len() * 8;
458 let rec = enc.reconstruction().expect("reconstruction");
459 sum_psnr += psnr(&clip.y, &rec.0);
460 }
461 if t8x8 {
462 let (i, p) = enc.transform_8x8_mbs();
463 eprintln!("8x8 MBs: intra {i} inter {p}");
464 share = (i + p) as f64 / (10.0 * (w / 16 * h / 16) as f64);
465 }
466 (bits as f64, sum_psnr / 10.0, share)
467 };
468 let qps = [22, 26, 30, 34];
469 let on: Vec<_> = qps.iter().map(|&q| run(true, q, true)).collect();
470 let off: Vec<_> = qps.iter().map(|&q| run(false, q, true)).collect();
471 let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
472 let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
473 let bd = bd_psnr_delta(&on_curve, &off_curve);
474 let share = on.iter().map(|&(_, _, share)| share).sum::<f64>() / on.len() as f64;
475 const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.255_347;
476 eprintln!(
477 "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%",
478 share * 100.0
479 );
480 assert!(share > 0.0, "no 8x8 macroblocks were coded");
481 assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off");
482 assert!(
483 bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB,
484 "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate"
485 );
486}
487
488/// ffmpeg's decode of our stream is our reconstruction, sample for sample,
489/// across a QP sweep and at a size that is not a multiple of a macroblock.
490#[test]
491fn ffmpeg_decodes_bit_exactly() {
492 if !have_ffmpeg() {
493 eprintln!("SKIP ffmpeg_decodes_bit_exactly: no ffmpeg on PATH");
494 return;
495 }
496 let mut t8x8_mbs = (0, 0);
497 for (w, h) in [(176, 144), (322, 242)] {
498 for qp in [10, 20, 28, 37, 47] {
499 let cavlc = qp % 2 == 0; // both entropy coders across the sweep
500 let t8x8 = qp % 3 == 1; // High-profile PPS with the per-MB flag
501 let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| {
502 cfg.qp = qp;
503 cfg.cabac = !cavlc;
504 cfg.transform_8x8 = t8x8;
505 });
506 t8x8_mbs.0 += intra;
507 t8x8_mbs.1 += inter;
508 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
509 assert_eq!(decoded.len(), recons.len(), "{w}x{h} qp {qp}: frame count");
510 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
511 assert_eq!(dec.0, rec.0, "{w}x{h} qp {qp}: luma of frame {i}");
512 assert_eq!(dec.1, rec.1, "{w}x{h} qp {qp}: Cb of frame {i}");
513 assert_eq!(dec.2, rec.2, "{w}x{h} qp {qp}: Cr of frame {i}");
514 }
515 }
516 }
517 assert!(
518 t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0,
519 "8x8 MBs across the sweep: intra {} inter {}",
520 t8x8_mbs.0,
521 t8x8_mbs.1
522 );
523}
524
525/// The same stream under constant bitrate, which is the mode edith exports in.
526#[test]
527fn ffmpeg_decodes_a_cbr_stream_bit_exactly() {
528 if !have_ffmpeg() {
529 eprintln!("SKIP ffmpeg_decodes_a_cbr_stream_bit_exactly: no ffmpeg on PATH");
530 return;
531 }
532 let (w, h) = (352, 288);
533 let (stream, recons, _) = encode_clip(w, h, 12, |cfg| {
534 cfg.bitrate = 2_000_000;
535 cfg.framerate = 25.0;
536 });
537 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
538 assert_eq!(decoded.len(), recons.len());
539 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
540 assert_eq!(dec.0, rec.0, "luma of frame {i}");
541 assert_eq!(
542 (dec.1.clone(), dec.2.clone()),
543 (rec.1.clone(), rec.2.clone()),
544 "chroma of frame {i}"
545 );
546 }
547}
548
549/// The VA-API hardware decoder on this machine accepts the same stream: a
550/// bitstream a driver refuses is not a bitstream edith can ship, whatever a
551/// software decoder says about it.
552#[test]
553fn vaapi_decodes_our_stream() {
554 if !have_ffmpeg() || !std::path::Path::new("/dev/dri/renderD128").exists() {
555 eprintln!("SKIP vaapi_decodes_our_stream: no ffmpeg or no render node");
556 return;
557 }
558 let (w, h) = (352, 288);
559 let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| {
560 cfg.qp = 26;
561 cfg.transform_8x8 = true;
562 });
563 assert!(intra + inter > 0, "no 8x8 macroblocks in the VA-API stream");
564 let Some(decoded) = ffmpeg_decode(
565 &stream,
566 w,
567 h,
568 &[
569 "-hwaccel",
570 "vaapi",
571 "-hwaccel_device",
572 "/dev/dri/renderD128",
573 ],
574 ) else {
575 eprintln!("SKIP vaapi_decodes_our_stream: VA-API decode unavailable here");
576 return;
577 };
578 assert_eq!(decoded.len(), recons.len(), "VA-API frame count");
579 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
580 let p = psnr(&dec.0, &rec.0);
581 assert!(p > 60.0, "VA-API luma of frame {i} differs: PSNR {p:.1} dB");
582 }
583}
584
585/// Real 1080p pictures from this machine's library, demuxed by `ec-mp4` and
586/// decoded by this crate, are re-encoded and handed back to ffmpeg.
587///
588/// Synthetic clips do not have film grain, hard cuts, or the residual
589/// statistics an encoder actually meets; a stream that survives a gradient and
590/// a moving box says nothing about one. Every picture must decode to exactly
591/// the encoder's own reconstruction, and the run reports the rate it landed on
592/// against the rate it was asked for.
593#[test]
594fn real_library_frames_encode_and_decode_exactly() {
595 use ec_core::registry::{Decoder as _, Demuxer as _};
596
597 if !have_ffmpeg() {
598 eprintln!("SKIP real_library_frames: no ffmpeg on PATH");
599 return;
600 }
601 let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
602 .join("../../fixtures/real-library-manifest.tsv");
603 let Ok(text) = std::fs::read_to_string(&manifest) else {
604 eprintln!("SKIP real_library_frames: {} missing", manifest.display());
605 return;
606 };
607 // The first 8-bit 4:2:0 H.264 mp4 of at least 720p in the manifest.
608 let mut source = None;
609 for line in text.lines().skip(1) {
610 let f: Vec<&str> = line.split('\t').collect();
611 if f.len() < 7 || f[2] != "h264" || f[5] != "yuv420p" {
612 continue;
613 }
614 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
615 continue;
616 };
617 if w < 1280 || h < 720 || !w.is_multiple_of(2) || !h.is_multiple_of(2) {
618 continue;
619 }
620 if !f[1].contains("mp4") || !std::path::Path::new(f[0]).exists() {
621 continue;
622 }
623 source = Some((f[0].to_string(), w, h));
624 break;
625 }
626 let Some((path, w, h)) = source else {
627 eprintln!("SKIP real_library_frames: no H.264 4:2:0 mp4 in the manifest");
628 return;
629 };
630
631 // Decode a handful of real pictures.
632 let file = std::fs::File::open(&path).expect("source opens");
633 let mut demux =
634 ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)).expect("ec-mp4 opens the file");
635 let (index, params) = demux
636 .streams()
637 .iter()
638 .find(|s| s.params.codec == ec_core::registry::CodecId::H264)
639 .map(|s| (s.index, s.params.clone()))
640 .expect("an H.264 track");
641 let mut dec = ec_h264::H264Decoder::new(params).expect("decoder");
642 let mut sources: Vec<Planes> = Vec::new();
643 while sources.len() < 12 {
644 let Ok(packet) = demux.next_packet() else {
645 break;
646 };
647 if packet.stream != index {
648 continue;
649 }
650 dec.send_packet(&packet).expect("decode");
651 while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() {
652 if sources.len() < 12 {
653 sources.push(planes_of(&f));
654 }
655 }
656 }
657 assert!(
658 sources.len() >= 6,
659 "only {} pictures decoded from the library file",
660 sources.len()
661 );
662
663 let bitrate = 8_000_000u32;
664 let mut cfg = EncoderConfig::new(w as u32, h as u32);
665 cfg.bitrate = bitrate;
666 cfg.framerate = 25.0;
667 cfg.gop_size = 25;
668 cfg.threads = 0;
669 let mut enc = Encoder::new(cfg).expect("encoder");
670 let mut stream = Vec::new();
671 let mut recons = Vec::new();
672 let mut bits = 0u64;
673 for (y, u, v) in &sources {
674 let view = PictureView::i420(w as u32, h as u32, y, u, v);
675 let p = enc.encode(&view).expect("encode");
676 bits += p.au.len() as u64 * 8;
677 stream.extend_from_slice(&p.au);
678 recons.push(enc.reconstruction().expect("reconstruction"));
679 }
680 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
681 assert_eq!(decoded.len(), recons.len(), "picture count");
682 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
683 assert_eq!(dec.0, rec.0, "luma of picture {i} from the library clip");
684 assert_eq!(dec.1, rec.1, "Cb of picture {i}");
685 assert_eq!(dec.2, rec.2, "Cr of picture {i}");
686 }
687 let quality: f64 = sources
688 .iter()
689 .zip(&recons)
690 .map(|((y, ..), (ry, ..))| psnr(y, ry))
691 .sum::<f64>()
692 / sources.len() as f64;
693 let rate = bits as f64 / (sources.len() as f64 / 25.0);
694 eprintln!(
695 "library clip {w}x{h}: {} pictures, {:.0} kbit/s asked {:.0}, luma PSNR {quality:.2} dB",
696 sources.len(),
697 rate / 1000.0,
698 f64::from(bitrate) / 1000.0
699 );
700 assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s");
701}