forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

encode.rs536 lines, 18.8 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
125/// The encoder's reconstruction and a decode of its bitstream agree sample for
126/// sample, over a QP sweep, both presets, single and multi threaded.
127#[test]
128fn reconstruction_matches_the_decoder() {
129 for (w, h) in [(176, 144), (208, 122), (64, 48)] {
130 let mut clip = Clip::new(w, h);
131 for qp in [12, 24, 33, 44] {
132 for (threads, preset, cabac) in [
133 (1usize, Preset::Fast, true),
134 (4, Preset::Balanced, true),
135 (1, Preset::Fast, false),
136 (3, Preset::Balanced, false),
137 ] {
138 let mut cfg = EncoderConfig::new(w as u32, h as u32);
139 cfg.qp = qp;
140 cfg.gop_size = 5;
141 cfg.threads = threads;
142 cfg.preset = preset;
143 cfg.cabac = cabac;
144 let mut enc = Encoder::new(cfg).expect("encoder");
145 let mut stream = Vec::new();
146 let mut recons = Vec::new();
147 for t in 0..8 {
148 clip.render(t);
149 let picture = enc.encode(&clip.view()).expect("encode");
150 stream.extend_from_slice(&picture.au);
151 recons.push(enc.reconstruction().expect("a reconstruction"));
152 }
153 let decoded = decode_all(&stream);
154 assert_eq!(
155 decoded.len(),
156 recons.len(),
157 "{w}x{h} qp {qp}: picture count"
158 );
159 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
160 assert_eq!(
161 dec.0, rec.0,
162 "{w}x{h} qp {qp} t{threads}: luma of picture {i}"
163 );
164 assert_eq!(
165 dec.1, rec.1,
166 "{w}x{h} qp {qp} t{threads}: Cb of picture {i}"
167 );
168 assert_eq!(
169 dec.2, rec.2,
170 "{w}x{h} qp {qp} t{threads}: Cr of picture {i}"
171 );
172 }
173 }
174 }
175 }
176}
177
178/// Quality tracks the quantiser, and a low QP is close to lossless: a stream
179/// that decodes bit-exactly could still be encoding garbage, and this is what
180/// says it is not.
181#[test]
182fn quality_follows_the_quantiser() {
183 let (w, h) = (176, 144);
184 let mut clip = Clip::new(w, h);
185 let mut last = 0.0;
186 for qp in [40, 30, 20, 10] {
187 let mut cfg = EncoderConfig::new(w as u32, h as u32);
188 cfg.qp = qp;
189 cfg.gop_size = 4;
190 cfg.threads = 1;
191 let mut enc = Encoder::new(cfg).expect("encoder");
192 let mut total = 0.0;
193 for t in 0..6 {
194 clip.render(t);
195 enc.encode(&clip.view()).expect("encode");
196 let (y, _, _) = enc.reconstruction().unwrap();
197 total += psnr(&clip.y, &y);
198 }
199 let avg = total / 6.0;
200 assert!(
201 avg > last,
202 "qp {qp}: PSNR {avg:.2} did not improve on {last:.2}"
203 );
204 if qp == 10 {
205 assert!(avg > 45.0, "qp 10 should be near lossless, got {avg:.2}");
206 }
207 last = avg;
208 }
209}
210
211/// Constant bitrate lands within a quarter of the target over a short clip,
212/// and every GOP boundary is an IDR the decoder can start from.
213#[test]
214fn rate_control_hits_its_target() {
215 let (w, h) = (352, 288);
216 let mut clip = Clip::new(w, h);
217 let bitrate = 1_500_000u32;
218 let mut cfg = EncoderConfig::new(w as u32, h as u32);
219 cfg.bitrate = bitrate;
220 cfg.framerate = 25.0;
221 cfg.gop_size = 25;
222 cfg.threads = 2;
223 let mut enc = Encoder::new(cfg).expect("encoder");
224 let mut bits = 0u64;
225 let frames = 50;
226 let mut keys = 0;
227 for t in 0..frames {
228 clip.render(t);
229 let p = enc.encode(&clip.view()).expect("encode");
230 bits += p.au.len() as u64 * 8;
231 keys += u32::from(p.key_frame);
232 }
233 assert_eq!(keys, 2, "one IDR per GOP");
234 let actual = bits as f64 / (frames as f64 / 25.0);
235 let ratio = actual / f64::from(bitrate);
236 assert!(
237 (0.7..1.35).contains(&ratio),
238 "bitrate {actual:.0} against target {bitrate} (ratio {ratio:.2})"
239 );
240}
241
242/// Every picture of a `gop_size` 1 stream is an IDR, which is what an
243/// intraframe master asks for.
244#[test]
245fn all_intra_when_the_gop_is_one() {
246 let (w, h) = (64, 64);
247 let mut clip = Clip::new(w, h);
248 let mut cfg = EncoderConfig::new(w as u32, h as u32);
249 cfg.gop_size = 1;
250 cfg.qp = 26;
251 let mut enc = Encoder::new(cfg).expect("encoder");
252 let mut stream = Vec::new();
253 for t in 0..4 {
254 clip.render(t);
255 let p = enc.encode(&clip.view()).expect("encode");
256 assert!(p.key_frame, "picture {t} is not a key frame");
257 stream.extend_from_slice(&p.au);
258 }
259 assert_eq!(decode_all(&stream).len(), 4);
260}
261
262// ---------------------------------------------------------------------------
263// ffmpeg-driven half: the third-party oracle. Skipped loudly when ffmpeg is
264// absent, exactly like the conformance suite's ffmpeg cross-check.
265// ---------------------------------------------------------------------------
266
267fn have_ffmpeg() -> bool {
268 std::process::Command::new("ffmpeg")
269 .arg("-version")
270 .stdout(std::process::Stdio::null())
271 .stderr(std::process::Stdio::null())
272 .status()
273 .is_ok_and(|s| s.success())
274}
275
276/// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture.
277fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> {
278 let dir = std::env::temp_dir().join(format!("ec-h264-enc-{}", std::process::id()));
279 std::fs::create_dir_all(&dir).ok()?;
280 let path = dir.join(format!("s{}.264", stream.len()));
281 std::fs::write(&path, stream).ok()?;
282 let mut cmd = std::process::Command::new("ffmpeg");
283 cmd.args(["-v", "error"]);
284 cmd.args(extra);
285 cmd.arg("-i").arg(&path);
286 cmd.args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]);
287 let out = cmd.output().ok()?;
288 let _ = std::fs::remove_file(&path);
289 if !out.status.success() {
290 eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
291 return None;
292 }
293 let frame = w * h * 3 / 2;
294 if frame == 0 || out.stdout.len() % frame != 0 {
295 eprintln!(
296 "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames",
297 out.stdout.len()
298 );
299 return None;
300 }
301 Some(
302 out.stdout
303 .chunks(frame)
304 .map(|f| {
305 let (y, rest) = f.split_at(w * h);
306 let (u, v) = rest.split_at(w / 2 * h / 2);
307 (y.to_vec(), u.to_vec(), v.to_vec())
308 })
309 .collect(),
310 )
311}
312
313/// Encode a clip and hand back the stream with the encoder's reconstructions.
314fn encode_clip(
315 w: usize,
316 h: usize,
317 frames: usize,
318 configure: impl FnOnce(&mut EncoderConfig),
319) -> (Vec<u8>, Vec<Planes>) {
320 let mut cfg = EncoderConfig::new(w as u32, h as u32);
321 cfg.gop_size = 10;
322 cfg.threads = 3;
323 configure(&mut cfg);
324 let mut enc = Encoder::new(cfg).expect("encoder");
325 let mut clip = Clip::new(w, h);
326 let mut stream = Vec::new();
327 let mut recons = Vec::new();
328 for t in 0..frames {
329 clip.render(t);
330 stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au);
331 recons.push(enc.reconstruction().expect("reconstruction"));
332 }
333 (stream, recons)
334}
335
336/// ffmpeg's decode of our stream is our reconstruction, sample for sample,
337/// across a QP sweep and at a size that is not a multiple of a macroblock.
338#[test]
339fn ffmpeg_decodes_bit_exactly() {
340 if !have_ffmpeg() {
341 eprintln!("SKIP ffmpeg_decodes_bit_exactly: no ffmpeg on PATH");
342 return;
343 }
344 for (w, h) in [(176, 144), (322, 242)] {
345 for qp in [10, 20, 28, 37, 47] {
346 let cavlc = qp % 2 == 0; // both entropy coders across the sweep
347 let (stream, recons) = encode_clip(w, h, 6, |cfg| {
348 cfg.qp = qp;
349 cfg.cabac = !cavlc;
350 });
351 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
352 assert_eq!(decoded.len(), recons.len(), "{w}x{h} qp {qp}: frame count");
353 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
354 assert_eq!(dec.0, rec.0, "{w}x{h} qp {qp}: luma of frame {i}");
355 assert_eq!(dec.1, rec.1, "{w}x{h} qp {qp}: Cb of frame {i}");
356 assert_eq!(dec.2, rec.2, "{w}x{h} qp {qp}: Cr of frame {i}");
357 }
358 }
359 }
360}
361
362/// The same stream under constant bitrate, which is the mode edith exports in.
363#[test]
364fn ffmpeg_decodes_a_cbr_stream_bit_exactly() {
365 if !have_ffmpeg() {
366 eprintln!("SKIP ffmpeg_decodes_a_cbr_stream_bit_exactly: no ffmpeg on PATH");
367 return;
368 }
369 let (w, h) = (352, 288);
370 let (stream, recons) = encode_clip(w, h, 12, |cfg| {
371 cfg.bitrate = 2_000_000;
372 cfg.framerate = 25.0;
373 });
374 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
375 assert_eq!(decoded.len(), recons.len());
376 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
377 assert_eq!(dec.0, rec.0, "luma of frame {i}");
378 assert_eq!(
379 (dec.1.clone(), dec.2.clone()),
380 (rec.1.clone(), rec.2.clone()),
381 "chroma of frame {i}"
382 );
383 }
384}
385
386/// The VA-API hardware decoder on this machine accepts the same stream: a
387/// bitstream a driver refuses is not a bitstream edith can ship, whatever a
388/// software decoder says about it.
389#[test]
390fn vaapi_decodes_our_stream() {
391 if !have_ffmpeg() || !std::path::Path::new("/dev/dri/renderD128").exists() {
392 eprintln!("SKIP vaapi_decodes_our_stream: no ffmpeg or no render node");
393 return;
394 }
395 let (w, h) = (352, 288);
396 let (stream, recons) = encode_clip(w, h, 6, |cfg| {
397 cfg.qp = 26;
398 });
399 let Some(decoded) = ffmpeg_decode(
400 &stream,
401 w,
402 h,
403 &[
404 "-hwaccel",
405 "vaapi",
406 "-hwaccel_device",
407 "/dev/dri/renderD128",
408 ],
409 ) else {
410 eprintln!("SKIP vaapi_decodes_our_stream: VA-API decode unavailable here");
411 return;
412 };
413 assert_eq!(decoded.len(), recons.len(), "VA-API frame count");
414 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
415 let p = psnr(&dec.0, &rec.0);
416 assert!(p > 60.0, "VA-API luma of frame {i} differs: PSNR {p:.1} dB");
417 }
418}
419
420/// Real 1080p pictures from this machine's library, demuxed by `ec-mp4` and
421/// decoded by this crate, are re-encoded and handed back to ffmpeg.
422///
423/// Synthetic clips do not have film grain, hard cuts, or the residual
424/// statistics an encoder actually meets; a stream that survives a gradient and
425/// a moving box says nothing about one. Every picture must decode to exactly
426/// the encoder's own reconstruction, and the run reports the rate it landed on
427/// against the rate it was asked for.
428#[test]
429fn real_library_frames_encode_and_decode_exactly() {
430 use ec_core::registry::{Decoder as _, Demuxer as _};
431
432 if !have_ffmpeg() {
433 eprintln!("SKIP real_library_frames: no ffmpeg on PATH");
434 return;
435 }
436 let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
437 .join("../../fixtures/real-library-manifest.tsv");
438 let Ok(text) = std::fs::read_to_string(&manifest) else {
439 eprintln!("SKIP real_library_frames: {} missing", manifest.display());
440 return;
441 };
442 // The first 8-bit 4:2:0 H.264 mp4 of at least 720p in the manifest.
443 let mut source = None;
444 for line in text.lines().skip(1) {
445 let f: Vec<&str> = line.split('\t').collect();
446 if f.len() < 7 || f[2] != "h264" || f[5] != "yuv420p" {
447 continue;
448 }
449 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
450 continue;
451 };
452 if w < 1280 || h < 720 || !w.is_multiple_of(2) || !h.is_multiple_of(2) {
453 continue;
454 }
455 if !f[1].contains("mp4") || !std::path::Path::new(f[0]).exists() {
456 continue;
457 }
458 source = Some((f[0].to_string(), w, h));
459 break;
460 }
461 let Some((path, w, h)) = source else {
462 eprintln!("SKIP real_library_frames: no H.264 4:2:0 mp4 in the manifest");
463 return;
464 };
465
466 // Decode a handful of real pictures.
467 let file = std::fs::File::open(&path).expect("source opens");
468 let mut demux =
469 ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)).expect("ec-mp4 opens the file");
470 let (index, params) = demux
471 .streams()
472 .iter()
473 .find(|s| s.params.codec == ec_core::registry::CodecId::H264)
474 .map(|s| (s.index, s.params.clone()))
475 .expect("an H.264 track");
476 let mut dec = ec_h264::H264Decoder::new(params).expect("decoder");
477 let mut sources: Vec<Planes> = Vec::new();
478 while sources.len() < 12 {
479 let Ok(packet) = demux.next_packet() else {
480 break;
481 };
482 if packet.stream != index {
483 continue;
484 }
485 dec.send_packet(&packet).expect("decode");
486 while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() {
487 if sources.len() < 12 {
488 sources.push(planes_of(&f));
489 }
490 }
491 }
492 assert!(
493 sources.len() >= 6,
494 "only {} pictures decoded from the library file",
495 sources.len()
496 );
497
498 let bitrate = 8_000_000u32;
499 let mut cfg = EncoderConfig::new(w as u32, h as u32);
500 cfg.bitrate = bitrate;
501 cfg.framerate = 25.0;
502 cfg.gop_size = 25;
503 cfg.threads = 0;
504 let mut enc = Encoder::new(cfg).expect("encoder");
505 let mut stream = Vec::new();
506 let mut recons = Vec::new();
507 let mut bits = 0u64;
508 for (y, u, v) in &sources {
509 let view = PictureView::i420(w as u32, h as u32, y, u, v);
510 let p = enc.encode(&view).expect("encode");
511 bits += p.au.len() as u64 * 8;
512 stream.extend_from_slice(&p.au);
513 recons.push(enc.reconstruction().expect("reconstruction"));
514 }
515 let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream");
516 assert_eq!(decoded.len(), recons.len(), "picture count");
517 for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() {
518 assert_eq!(dec.0, rec.0, "luma of picture {i} from the library clip");
519 assert_eq!(dec.1, rec.1, "Cb of picture {i}");
520 assert_eq!(dec.2, rec.2, "Cr of picture {i}");
521 }
522 let quality: f64 = sources
523 .iter()
524 .zip(&recons)
525 .map(|((y, ..), (ry, ..))| psnr(y, ry))
526 .sum::<f64>()
527 / sources.len() as f64;
528 let rate = bits as f64 / (sources.len() as f64 / 25.0);
529 eprintln!(
530 "library clip {w}x{h}: {} pictures, {:.0} kbit/s asked {:.0}, luma PSNR {quality:.2} dB",
531 sources.len(),
532 rate / 1000.0,
533 f64::from(bitrate) / 1000.0
534 );
535 assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s");
536}