forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcef0239Tahinli3 months ago705 commits

main.rs589 lines, 20.1 KiBHistoryRawDownload
1//! Standing performance harness: real media in, each codec's own public
2//! one-shot API exercised, a ranked realtime-factor table out.
3//!
4//! Realtime factor = media-seconds decoded (or encoded) per wall-second;
5//! bigger is faster. ffmpeg/ffprobe are used only to extract elementary
6//! streams and raw planes and to read duration, exactly as the crates' own
7//! tests already do -- this binary never decodes anything itself.
8//!
9//! Run: `cargo run -p ec-bench --release`
10
11use std::path::{Path, PathBuf};
12use std::process::Command;
13use std::time::Instant;
14
15use ec_av1::encode::Picture as Av1Picture;
16use ec_av1::encoder::{Av1Encoder, Colour, EncoderConfig as Av1Config};
17use ec_core::frame::{PixelFormat, Plane, VideoFrame};
18use ec_core::registry::MediaType;
19use ec_h264::{
20 Decoder as H264Decoder, Encoder as H264Encoder, EncoderConfig as H264Config, NalOutcome,
21 PictureView,
22};
23use ec_h264_syntax::AnnexBIter;
24use ec_h265::encoder::{Encoder as H265Encoder, EncoderConfig as H265Config};
25use ec_probe::Reader;
26
27struct Row {
28 component: &'static str,
29 direction: &'static str,
30 content: String,
31 media: String,
32 wall_ms: f64,
33 rtf: Option<f64>,
34}
35
36fn main() {
37 let mut rows = Vec::new();
38
39 bench_h264(&mut rows);
40 bench_h265_encode(&mut rows);
41 bench_av1_encode(&mut rows);
42 bench_audio_decode(&mut rows);
43 bench_image_decode(&mut rows);
44 bench_inflate(&mut rows);
45
46 rows.sort_by(|a, b| {
47 a.rtf
48 .unwrap_or(f64::INFINITY)
49 .partial_cmp(&b.rtf.unwrap_or(f64::INFINITY))
50 .unwrap()
51 });
52
53 println!("| component | direction | content | media | wall ms | realtime factor |");
54 println!("|---|---|---|---|---|---|");
55 for r in &rows {
56 let rtf = r
57 .rtf
58 .map_or_else(|| "-".to_string(), |v| format!("{v:.2}x"));
59 println!(
60 "| {} | {} | {} | {} | {:.1} | {} |",
61 r.component, r.direction, r.content, r.media, r.wall_ms, rtf
62 );
63 }
64}
65
66// ---------------------------------------------------------------------------
67// media discovery
68// ---------------------------------------------------------------------------
69
70fn fixtures() -> PathBuf {
71 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
72}
73
74fn home() -> PathBuf {
75 PathBuf::from(std::env::var("HOME").expect("HOME"))
76}
77
78/// A handful of real-library candidates, largest-effort first, that ffprobe
79/// confirms carry the wanted video codec. Read-only: never touches the file
80/// beyond `ffprobe`/`ffmpeg -i ... -o <scratch>`.
81fn real_video(codec: &str) -> Option<PathBuf> {
82 let roots = [home().join("Videos"), home().join("Downloads")];
83 let mut found = Vec::new();
84 for root in roots {
85 let Ok(walker) = std::fs::read_dir(&root) else {
86 continue;
87 };
88 for entry in walker.flatten() {
89 let p = entry.path();
90 let Some(ext) = p.extension().and_then(|e| e.to_str()) else {
91 continue;
92 };
93 if !matches!(
94 ext.to_ascii_lowercase().as_str(),
95 "mp4" | "mkv" | "mov" | "avi"
96 ) {
97 continue;
98 }
99 found.push(p);
100 }
101 }
102 found.sort();
103 for p in found {
104 if ffprobe_field(&p, "v:0", "codec_name").as_deref() == Some(codec) {
105 return Some(p);
106 }
107 }
108 None
109}
110
111fn ffprobe_field(path: &Path, stream: &str, key: &str) -> Option<String> {
112 let out = Command::new("ffprobe")
113 .args(["-v", "error", "-select_streams", stream, "-show_entries"])
114 .arg(format!("stream={key}"))
115 .args(["-of", "default=nw=1:nk=1"])
116 .arg(path)
117 .output()
118 .ok()?;
119 if !out.status.success() {
120 return None;
121 }
122 let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
123 (!s.is_empty()).then_some(s)
124}
125
126// ---------------------------------------------------------------------------
127// h264: decode (real film, 10s) + encode (raw planes from the same clip)
128// ---------------------------------------------------------------------------
129
130fn bench_h264(rows: &mut Vec<Row>) {
131 let Some(src) = real_video("h264") else {
132 rows.push(missing("ec-h264", "decode"));
133 rows.push(missing("ec-h264", "encode"));
134 return;
135 };
136 let w: u32 = ffprobe_field(&src, "v:0", "width")
137 .and_then(|s| s.parse().ok())
138 .unwrap_or(0);
139 let h: u32 = ffprobe_field(&src, "v:0", "height")
140 .and_then(|s| s.parse().ok())
141 .unwrap_or(0);
142
143 // decode: 10s Annex-B extract, trimmed inside ffmpeg (never decode-then-trim).
144 let out = Command::new("ffmpeg")
145 .args(["-v", "error", "-t", "10", "-i"])
146 .arg(&src)
147 .args([
148 "-an",
149 "-c:v",
150 "copy",
151 "-bsf:v",
152 "h264_mp4toannexb",
153 "-f",
154 "h264",
155 "-",
156 ])
157 .output()
158 .expect("ffmpeg extract h264");
159 if out.status.success() && !out.stdout.is_empty() {
160 let bytes = out.stdout;
161 let start = Instant::now();
162 let mut dec = H264Decoder::new();
163 let mut frames = 0u64;
164 for nal in AnnexBIter::new(&bytes) {
165 if let Ok(NalOutcome::PictureBoundary) = dec.push_nal(nal) {
166 let _ = dec.end_picture();
167 let _ = dec.push_nal(nal);
168 }
169 while dec.next_frame().is_some() {
170 frames += 1;
171 }
172 }
173 let _ = dec.flush();
174 while dec.next_frame().is_some() {
175 frames += 1;
176 }
177 let wall = start.elapsed().as_secs_f64();
178 let fps = ffprobe_field(&src, "v:0", "r_frame_rate")
179 .and_then(|s| parse_ratio(&s))
180 .unwrap_or(25.0);
181 let media_s = frames as f64 / fps;
182 rows.push(Row {
183 component: "ec-h264",
184 direction: "decode",
185 content: format!("{w}x{h} film, {frames} frames"),
186 media: format!("{media_s:.1}s"),
187 wall_ms: wall * 1000.0,
188 rtf: (wall > 0.0).then_some(media_s / wall),
189 });
190 } else {
191 rows.push(missing("ec-h264", "decode"));
192 }
193
194 // encode: 30 raw yuv420p frames scaled to 640x360 from the same clip.
195 let (planes, ew, eh, n) = extract_yuv420p(&src, 640, 360, 30);
196 if n > 0 {
197 let mut cfg = H264Config::new(ew, eh);
198 cfg.threads = 1; // one worker: single-core cost, not a parallelism claim
199 let mut enc = H264Encoder::new(cfg).expect("h264 encoder");
200 let frame_len = (ew * eh + 2 * (ew.div_ceil(2) * eh.div_ceil(2))) as usize;
201 let start = Instant::now();
202 for frame in planes.chunks_exact(frame_len) {
203 let (y, rest) = frame.split_at((ew * eh) as usize);
204 let (u, v) = rest.split_at(rest.len() / 2);
205 let view = PictureView::i420(ew, eh, y, u, v);
206 enc.encode(&view).expect("h264 encode");
207 }
208 let wall = start.elapsed().as_secs_f64();
209 let media_s = n as f64 / 30.0;
210 rows.push(Row {
211 component: "ec-h264",
212 direction: "encode",
213 content: format!("{ew}x{eh}, {n} frames, 1 thread"),
214 media: format!("{media_s:.1}s"),
215 wall_ms: wall * 1000.0,
216 rtf: (wall > 0.0).then_some(media_s / wall),
217 });
218 } else {
219 rows.push(missing("ec-h264", "encode"));
220 }
221}
222
223/// `n` progressive frames of raw I420 at `w x h`, scaled and trimmed inside
224/// ffmpeg.
225fn extract_yuv420p(src: &Path, w: u32, h: u32, n: u32) -> (Vec<u8>, u32, u32, u32) {
226 let out = Command::new("ffmpeg")
227 .args(["-v", "error", "-i"])
228 .arg(src)
229 .args([
230 "-vf",
231 &format!("scale={w}:{h}"),
232 "-frames:v",
233 &n.to_string(),
234 "-pix_fmt",
235 "yuv420p",
236 "-f",
237 "rawvideo",
238 "-",
239 ])
240 .output()
241 .expect("ffmpeg extract yuv420p");
242 if !out.status.success() || out.stdout.is_empty() {
243 return (Vec::new(), w, h, 0);
244 }
245 let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
246 let frames = (out.stdout.len() / frame_len) as u32;
247 (out.stdout, w, h, frames)
248}
249
250fn parse_ratio(s: &str) -> Option<f64> {
251 let (n, d) = s.split_once('/')?;
252 let (n, d) = (n.parse::<f64>().ok()?, d.parse::<f64>().ok()?);
253 (d != 0.0).then_some(n / d)
254}
255
256// ---------------------------------------------------------------------------
257// h265: encode, then software-decode the encoded stream back.
258// ---------------------------------------------------------------------------
259
260fn bench_h265_encode(rows: &mut Vec<Row>) {
261 let Some(src) = real_video("h264").or_else(|| real_video("hevc")) else {
262 rows.push(missing("ec-h265", "decode"));
263 rows.push(missing("ec-h265", "encode"));
264 return;
265 };
266 let (planes, w, h, n) = extract_yuv420p(&src, 640, 360, 10);
267 if n == 0 {
268 rows.push(missing("ec-h265", "encode"));
269 rows.push(missing("ec-h265", "decode"));
270 return;
271 }
272 let cfg = H265Config::new(w, h);
273 let enc = H265Encoder::new(cfg).expect("h265 encoder");
274 let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
275 let cw = w.div_ceil(2);
276 let ch = h.div_ceil(2);
277 let mut aus = Vec::new();
278 let start = Instant::now();
279 for frame in planes.chunks_exact(frame_len) {
280 let (y, rest) = frame.split_at((w * h) as usize);
281 let (u, v) = rest.split_at(rest.len() / 2);
282 let vf = VideoFrame::try_new(
283 PixelFormat::I420,
284 w,
285 h,
286 vec![
287 Plane::new(y.to_vec(), w as usize),
288 Plane::new(u.to_vec(), cw as usize),
289 Plane::new(v.to_vec(), cw as usize),
290 ],
291 )
292 .expect("i420 frame");
293 let _ = ch; // silence unused if plane_geometry ignores it
294 aus.push(enc.encode_idr(&vf).expect("h265 encode").au);
295 }
296 let wall = start.elapsed().as_secs_f64();
297 let media_s = n as f64 / 30.0;
298 rows.push(Row {
299 component: "ec-h265",
300 direction: "encode",
301 content: format!("{w}x{h}, {n} frames, IDR-only"),
302 media: format!("{media_s:.1}s"),
303 wall_ms: wall * 1000.0,
304 rtf: (wall > 0.0).then_some(media_s / wall),
305 });
306
307 let start = Instant::now();
308 for au in &aus {
309 ec_h265::decode::decode_idr_au(au).expect("h265 decode");
310 }
311 let wall = start.elapsed().as_secs_f64();
312 rows.push(Row {
313 component: "ec-h265",
314 direction: "decode",
315 content: format!("{w}x{h}, {n} frames, own IDR stream"),
316 media: format!("{media_s:.1}s"),
317 wall_ms: wall * 1000.0,
318 rtf: (wall > 0.0).then_some(media_s / wall),
319 });
320}
321
322// ---------------------------------------------------------------------------
323// av1: encode only -- same shape as h265.
324// ---------------------------------------------------------------------------
325
326fn bench_av1_encode(rows: &mut Vec<Row>) {
327 let Some(src) = real_video("h264") else {
328 rows.push(missing("ec-av1", "encode"));
329 rows.push(missing("ec-av1", "decode"));
330 return;
331 };
332 // AV1's block grid is 32x32 superblocks: pick a size already a multiple of it.
333 let (planes, w, h, n) = extract_yuv420p(&src, 640, 384, 10);
334 if n == 0 {
335 rows.push(missing("ec-av1", "encode"));
336 rows.push(missing("ec-av1", "decode"));
337 return;
338 }
339 let cfg = Av1Config {
340 width: w as usize,
341 height: h as usize,
342 base_q_idx: 100,
343 gop: 10,
344 colour: Colour::default(),
345 };
346 let mut enc = Av1Encoder::new(cfg).expect("av1 encoder");
347 let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
348 let mut stream = Vec::new();
349 let start = Instant::now();
350 for frame in planes.chunks_exact(frame_len) {
351 let (y, rest) = frame.split_at((w * h) as usize);
352 let (u, v) = rest.split_at(rest.len() / 2);
353 let pic = Av1Picture {
354 width: w as usize,
355 height: h as usize,
356 y: y.to_vec(),
357 u: u.to_vec(),
358 v: v.to_vec(),
359 };
360 let packet = enc.encode(&pic).expect("av1 encode");
361 stream.extend_from_slice(&packet.data);
362 }
363 let wall = start.elapsed().as_secs_f64();
364 let media_s = n as f64 / 30.0;
365 rows.push(Row {
366 component: "ec-av1",
367 direction: "encode",
368 content: format!("{w}x{h}, {n} frames, gop=10"),
369 media: format!("{media_s:.1}s"),
370 wall_ms: wall * 1000.0,
371 rtf: (wall > 0.0).then_some(media_s / wall),
372 });
373
374 let start = Instant::now();
375 let pictures = ec_av1::stream::decode_stream(&stream).expect("av1 decode_stream");
376 let wall = start.elapsed().as_secs_f64();
377 assert_eq!(pictures.len(), n as usize, "decode_stream frame count");
378 rows.push(Row {
379 component: "ec-av1",
380 direction: "decode",
381 content: format!("{w}x{h}, {n} frames, gop=10"),
382 media: format!("{media_s:.1}s"),
383 wall_ms: wall * 1000.0,
384 rtf: (wall > 0.0).then_some(media_s / wall),
385 });
386}
387
388// ---------------------------------------------------------------------------
389// audio decode: one loop over ec-probe's unified reader covers every codec
390// it wraps (mp3/flac/aac/alac/ac3/truehd/opus/vorbis via ogg/mp4/matroska).
391// ---------------------------------------------------------------------------
392
393fn bench_audio_decode(rows: &mut Vec<Row>) {
394 let mut candidates: Vec<PathBuf> = Vec::new();
395 if let Ok(entries) = std::fs::read_dir(fixtures().join("audio")) {
396 candidates.extend(entries.flatten().map(|e| e.path()));
397 }
398 // Real-library samples: mp3 and wav are on disk; ac3 lives inside the
399 // ReelT mux (5.1 AC-3), extracted as its own elementary file.
400 for f in ["8a3b6d1d19.mp3", "test.wav"] {
401 let p = home().join("Downloads").join(f);
402 if p.exists() {
403 candidates.push(p);
404 }
405 }
406 if let Some(src) = real_video("h264") {
407 if ffprobe_field(&src, "a:0", "codec_name").as_deref() == Some("ac3") {
408 let out = Command::new("ffmpeg")
409 .args(["-v", "error", "-t", "10", "-i"])
410 .arg(&src)
411 .args(["-vn", "-c:a", "copy", "-f", "ac3"])
412 .arg(
413 Path::new(&std::env::var("HOME").unwrap())
414 .join(".cache/bench-media/sample.ac3"),
415 )
416 .output();
417 if let Ok(o) = out {
418 if o.status.success() {
419 candidates.push(home().join(".cache/bench-media/sample.ac3"));
420 }
421 }
422 }
423 }
424 candidates.sort();
425 candidates.dedup();
426
427 for path in candidates {
428 let Ok(mut reader) = Reader::open(&path) else {
429 continue;
430 };
431 let Some(stream) = reader.default_stream(MediaType::Audio).map(|s| s.index) else {
432 continue;
433 };
434 let Ok(mut dec) = reader.make_decoder(stream) else {
435 continue;
436 };
437 let codec = format!("{:?}", dec.codec());
438 let mut samples = 0u64;
439 let start = Instant::now();
440 let mut out = Vec::new();
441 loop {
442 match reader.next_packet() {
443 Ok(pkt) if pkt.stream == stream => {
444 out.clear();
445 if dec.decode(&pkt, &mut out).is_ok() {
446 samples += (out.len() / dec.channels().max(1)) as u64;
447 }
448 }
449 Ok(_) => {}
450 Err(_) => break,
451 }
452 }
453 let _ = dec.flush(&mut out);
454 let wall = start.elapsed().as_secs_f64();
455 let media_s = samples as f64 / dec.sample_rate().max(1) as f64;
456 let name = path.file_name().unwrap().to_string_lossy().into_owned();
457 rows.push(Row {
458 component: Box::leak(format!("ec-probe/{codec}").into_boxed_str()),
459 direction: "decode",
460 content: name,
461 media: format!("{media_s:.1}s"),
462 wall_ms: wall * 1000.0,
463 rtf: (wall > 0.0 && media_s > 0.0).then_some(media_s / wall),
464 });
465 }
466}
467
468// ---------------------------------------------------------------------------
469// images: one decode entry point (`ec_image::decode`) covers every format
470// the crate sniffs, so every real-library still is a candidate.
471// ---------------------------------------------------------------------------
472
473fn bench_image_decode(rows: &mut Vec<Row>) {
474 let mut candidates: Vec<PathBuf> = Vec::new();
475 if let Ok(entries) = std::fs::read_dir(fixtures().join("stills")) {
476 candidates.extend(
477 entries
478 .flatten()
479 .map(|e| e.path())
480 .filter(|p| p.extension().is_some()),
481 );
482 }
483 for f in [
484 "IMG_20260804_170612.jpg",
485 "drawing-1.png",
486 "20260722-233942.png",
487 "giphy.gif",
488 ] {
489 let p = home().join("Downloads").join(f);
490 if p.exists() {
491 candidates.push(p);
492 }
493 }
494 candidates.sort();
495
496 for path in candidates {
497 let Ok(bytes) = std::fs::read(&path) else {
498 continue;
499 };
500 let mp = bytes.len() as f64 / 1_000_000.0;
501 let start = Instant::now();
502 let Ok(img) = ec_image::decode(&bytes) else {
503 continue;
504 };
505 let wall_ms = start.elapsed().as_secs_f64() * 1000.0;
506 let (w, h) = img.dimensions();
507 let megapixels = (w as f64 * h as f64) / 1_000_000.0;
508 let name = path.file_name().unwrap().to_string_lossy().into_owned();
509 rows.push(Row {
510 component: "ec-image",
511 direction: "decode",
512 content: format!("{name} ({w}x{h}, {mp:.2} MB coded)"),
513 media: format!("{megapixels:.2} MP"),
514 wall_ms,
515 rtf: (wall_ms > 0.0).then_some(megapixels / (wall_ms / 1000.0)),
516 });
517 }
518}
519
520// ---------------------------------------------------------------------------
521// ec-inflate: the zlib stream a real PNG's IDAT chain already carries.
522// ---------------------------------------------------------------------------
523
524fn bench_inflate(rows: &mut Vec<Row>) {
525 let Some(png) = [
526 fixtures().join("stills/gray16.png"),
527 home().join("Downloads/drawing-1.png"),
528 ]
529 .into_iter()
530 .find(|p| p.exists()) else {
531 rows.push(missing("ec-inflate", "inflate"));
532 return;
533 };
534 let Ok(bytes) = std::fs::read(&png) else {
535 rows.push(missing("ec-inflate", "inflate"));
536 return;
537 };
538 // Concatenate every IDAT chunk's payload: that byte string is exactly the
539 // zlib stream `ec_image`'s own PNG path hands to `ec_inflate`.
540 let mut idat = Vec::new();
541 let mut i = 8usize; // past the PNG signature
542 while i + 8 <= bytes.len() {
543 let len = u32::from_be_bytes(bytes[i..i + 4].try_into().unwrap()) as usize;
544 let kind = &bytes[i + 4..i + 8];
545 let start = i + 8;
546 if kind == b"IDAT" && start + len <= bytes.len() {
547 idat.extend_from_slice(&bytes[start..start + len]);
548 }
549 i = start + len + 4; // skip CRC
550 }
551 if idat.is_empty() {
552 rows.push(missing("ec-inflate", "inflate"));
553 return;
554 }
555 let compressed_mb = idat.len() as f64 / 1_000_000.0;
556 let start = Instant::now();
557 let Ok(out) = ec_inflate::inflate_zlib(&idat, 1 << 30) else {
558 rows.push(missing("ec-inflate", "inflate"));
559 return;
560 };
561 let wall_ms = start.elapsed().as_secs_f64() * 1000.0;
562 let out_mb = out.len() as f64 / 1_000_000.0;
563 rows.push(Row {
564 component: "ec-inflate",
565 direction: "inflate",
566 content: format!(
567 "{} IDAT stream, {compressed_mb:.2} MB in",
568 png.file_name().unwrap().to_string_lossy()
569 ),
570 media: format!("{out_mb:.2} MB out"),
571 wall_ms,
572 rtf: (wall_ms > 0.0).then_some(out_mb / (wall_ms / 1000.0)),
573 });
574}
575
576fn missing(component: &'static str, direction: &'static str) -> Row {
577 missing_direction(component, direction, "no real-media candidate found")
578}
579
580fn missing_direction(component: &'static str, direction: &'static str, why: &str) -> Row {
581 Row {
582 component,
583 direction,
584 content: why.to_string(),
585 media: "-".to_string(),
586 wall_ms: 0.0,
587 rtf: None,
588 }
589}