forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9a6b2f7Tahinli2 months ago2510 commits

main.rs1022 lines, 36.5 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, Level, Pyramid};
17use ec_core::frame::{
18 AudioFrame, ChannelLayout, Frame, PixelFormat, Plane, SampleFormat, VideoFrame,
19};
20use ec_core::packet::Buf;
21use ec_core::registry::{Encoder as CoreEncoder, MediaType};
22use ec_h264::{
23 Decoder as H264Decoder, Encoder as H264Encoder, EncoderConfig as H264Config, NalOutcome,
24 PictureView,
25};
26use ec_h264_syntax::AnnexBIter;
27use ec_h265::encoder::{Encoder as H265Encoder, EncoderConfig as H265Config};
28use ec_probe::Reader;
29
30struct Row {
31 component: &'static str,
32 direction: &'static str,
33 content: String,
34 media: String,
35 wall_ms: f64,
36 rtf: Option<f64>,
37}
38
39fn main() {
40 let mut rows = Vec::new();
41
42 bench_h264(&mut rows);
43 bench_h265_encode(&mut rows);
44 bench_av1_encode(&mut rows);
45 bench_audio_decode(&mut rows);
46 bench_audio_encode(&mut rows);
47 bench_truehd(&mut rows);
48 bench_container_demux(&mut rows);
49 bench_image_decode(&mut rows);
50 bench_inflate(&mut rows);
51
52 rows.sort_by(|a, b| {
53 a.rtf
54 .unwrap_or(f64::INFINITY)
55 .partial_cmp(&b.rtf.unwrap_or(f64::INFINITY))
56 .unwrap()
57 });
58
59 println!("| component | direction | content | media | wall ms | realtime factor |");
60 println!("|---|---|---|---|---|---|");
61 for r in &rows {
62 let rtf = r
63 .rtf
64 .map_or_else(|| "-".to_string(), |v| format!("{v:.2}x"));
65 println!(
66 "| {} | {} | {} | {} | {:.1} | {} |",
67 r.component, r.direction, r.content, r.media, r.wall_ms, rtf
68 );
69 }
70}
71
72// ---------------------------------------------------------------------------
73// media discovery
74// ---------------------------------------------------------------------------
75
76fn fixtures() -> PathBuf {
77 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
78}
79
80fn home() -> PathBuf {
81 PathBuf::from(std::env::var("HOME").expect("HOME"))
82}
83
84/// A handful of real-library candidates, largest-effort first, that ffprobe
85/// confirms carry the wanted video codec. Read-only: never touches the file
86/// beyond `ffprobe`/`ffmpeg -i ... -o <scratch>`.
87fn real_video(codec: &str) -> Option<PathBuf> {
88 let roots = [home().join("Videos"), home().join("Downloads")];
89 let mut found = Vec::new();
90 for root in roots {
91 let Ok(walker) = std::fs::read_dir(&root) else {
92 continue;
93 };
94 for entry in walker.flatten() {
95 let p = entry.path();
96 let Some(ext) = p.extension().and_then(|e| e.to_str()) else {
97 continue;
98 };
99 if !matches!(
100 ext.to_ascii_lowercase().as_str(),
101 "mp4" | "mkv" | "mov" | "avi"
102 ) {
103 continue;
104 }
105 found.push(p);
106 }
107 }
108 found.sort();
109 for p in found {
110 if ffprobe_field(&p, "v:0", "codec_name").as_deref() == Some(codec) {
111 return Some(p);
112 }
113 }
114 None
115}
116
117fn ffprobe_field(path: &Path, stream: &str, key: &str) -> Option<String> {
118 let out = Command::new("ffprobe")
119 .args(["-v", "error", "-select_streams", stream, "-show_entries"])
120 .arg(format!("stream={key}"))
121 .args(["-of", "default=nw=1:nk=1"])
122 .arg(path)
123 .output()
124 .ok()?;
125 if !out.status.success() {
126 return None;
127 }
128 let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
129 (!s.is_empty()).then_some(s)
130}
131
132// ---------------------------------------------------------------------------
133// h264: decode (real film, 10s) + encode (raw planes from the same clip)
134// ---------------------------------------------------------------------------
135
136fn bench_h264(rows: &mut Vec<Row>) {
137 let Some(src) = real_video("h264") else {
138 rows.push(missing("ec-h264", "decode"));
139 rows.push(missing("ec-h264", "encode"));
140 return;
141 };
142 let w: u32 = ffprobe_field(&src, "v:0", "width")
143 .and_then(|s| s.parse().ok())
144 .unwrap_or(0);
145 let h: u32 = ffprobe_field(&src, "v:0", "height")
146 .and_then(|s| s.parse().ok())
147 .unwrap_or(0);
148
149 // decode: 10s Annex-B extract, trimmed inside ffmpeg (never decode-then-trim).
150 let out = Command::new("ffmpeg")
151 .args(["-v", "error", "-t", "10", "-i"])
152 .arg(&src)
153 .args([
154 "-an",
155 "-c:v",
156 "copy",
157 "-bsf:v",
158 "h264_mp4toannexb",
159 "-f",
160 "h264",
161 "-",
162 ])
163 .output()
164 .expect("ffmpeg extract h264");
165 if out.status.success() && !out.stdout.is_empty() {
166 let bytes = out.stdout;
167 let start = Instant::now();
168 let mut dec = H264Decoder::new();
169 let mut frames = 0u64;
170 for nal in AnnexBIter::new(&bytes) {
171 if let Ok(NalOutcome::PictureBoundary) = dec.push_nal(nal) {
172 let _ = dec.end_picture();
173 let _ = dec.push_nal(nal);
174 }
175 while dec.next_frame().is_some() {
176 frames += 1;
177 }
178 }
179 let _ = dec.flush();
180 while dec.next_frame().is_some() {
181 frames += 1;
182 }
183 let wall = start.elapsed().as_secs_f64();
184 let fps = ffprobe_field(&src, "v:0", "r_frame_rate")
185 .and_then(|s| parse_ratio(&s))
186 .unwrap_or(25.0);
187 let media_s = frames as f64 / fps;
188 rows.push(Row {
189 component: "ec-h264",
190 direction: "decode",
191 content: format!("{w}x{h} film, {frames} frames"),
192 media: format!("{media_s:.1}s"),
193 wall_ms: wall * 1000.0,
194 rtf: (wall > 0.0).then_some(media_s / wall),
195 });
196 } else {
197 rows.push(missing("ec-h264", "decode"));
198 }
199
200 // encode: 30 raw yuv420p frames scaled to 640x360 from the same clip.
201 let (planes, ew, eh, n) = extract_yuv420p(&src, 640, 360, 30);
202 if n > 0 {
203 let mut cfg = H264Config::new(ew, eh);
204 cfg.threads = 1; // one worker: single-core cost, not a parallelism claim
205 let mut enc = H264Encoder::new(cfg).expect("h264 encoder");
206 let frame_len = (ew * eh + 2 * (ew.div_ceil(2) * eh.div_ceil(2))) as usize;
207 let start = Instant::now();
208 for frame in planes.chunks_exact(frame_len) {
209 let (y, rest) = frame.split_at((ew * eh) as usize);
210 let (u, v) = rest.split_at(rest.len() / 2);
211 let view = PictureView::i420(ew, eh, y, u, v);
212 enc.encode(&view).expect("h264 encode");
213 }
214 let wall = start.elapsed().as_secs_f64();
215 let media_s = n as f64 / 30.0;
216 rows.push(Row {
217 component: "ec-h264",
218 direction: "encode",
219 content: format!("{ew}x{eh}, {n} frames, 1 thread"),
220 media: format!("{media_s:.1}s"),
221 wall_ms: wall * 1000.0,
222 rtf: (wall > 0.0).then_some(media_s / wall),
223 });
224 } else {
225 rows.push(missing("ec-h264", "encode"));
226 }
227}
228
229/// `n` progressive frames of raw I420 at `w x h`, scaled and trimmed inside
230/// ffmpeg.
231fn extract_yuv420p(src: &Path, w: u32, h: u32, n: u32) -> (Vec<u8>, u32, u32, u32) {
232 let out = Command::new("ffmpeg")
233 .args(["-v", "error", "-i"])
234 .arg(src)
235 .args([
236 "-vf",
237 &format!("scale={w}:{h}"),
238 "-frames:v",
239 &n.to_string(),
240 "-pix_fmt",
241 "yuv420p",
242 "-f",
243 "rawvideo",
244 "-",
245 ])
246 .output()
247 .expect("ffmpeg extract yuv420p");
248 if !out.status.success() || out.stdout.is_empty() {
249 return (Vec::new(), w, h, 0);
250 }
251 let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
252 let frames = (out.stdout.len() / frame_len) as u32;
253 (out.stdout, w, h, frames)
254}
255
256fn parse_ratio(s: &str) -> Option<f64> {
257 let (n, d) = s.split_once('/')?;
258 let (n, d) = (n.parse::<f64>().ok()?, d.parse::<f64>().ok()?);
259 (d != 0.0).then_some(n / d)
260}
261
262// ---------------------------------------------------------------------------
263// h265: encode, then software-decode the encoded stream back.
264// ---------------------------------------------------------------------------
265
266fn bench_h265_encode(rows: &mut Vec<Row>) {
267 let Some(src) = real_video("h264").or_else(|| real_video("hevc")) else {
268 rows.push(missing("ec-h265", "decode"));
269 rows.push(missing("ec-h265", "encode"));
270 return;
271 };
272 let (planes, w, h, n) = extract_yuv420p(&src, 640, 360, 10);
273 if n == 0 {
274 rows.push(missing("ec-h265", "encode"));
275 rows.push(missing("ec-h265", "decode"));
276 return;
277 }
278 let mut cfg = H265Config::new(w, h);
279 // A/B knob for the RDOQ estimated-bit-cost path (off by default, matching
280 // the encoder's own default): EC_H265_RDOQ_ESTIMATE=1 to measure it.
281 cfg.rdoq_estimate = std::env::var("EC_H265_RDOQ_ESTIMATE").is_ok_and(|v| v != "0");
282 let enc = H265Encoder::new(cfg).expect("h265 encoder");
283 let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
284 let cw = w.div_ceil(2);
285 let ch = h.div_ceil(2);
286 let mut aus = Vec::new();
287 let start = Instant::now();
288 for frame in planes.chunks_exact(frame_len) {
289 let (y, rest) = frame.split_at((w * h) as usize);
290 let (u, v) = rest.split_at(rest.len() / 2);
291 let vf = VideoFrame::try_new(
292 PixelFormat::I420,
293 w,
294 h,
295 vec![
296 Plane::new(y.to_vec(), w as usize),
297 Plane::new(u.to_vec(), cw as usize),
298 Plane::new(v.to_vec(), cw as usize),
299 ],
300 )
301 .expect("i420 frame");
302 let _ = ch; // silence unused if plane_geometry ignores it
303 aus.push(enc.encode_idr(&vf).expect("h265 encode").au);
304 }
305 let wall = start.elapsed().as_secs_f64();
306 let media_s = n as f64 / 30.0;
307 rows.push(Row {
308 component: "ec-h265",
309 direction: "encode",
310 content: format!("{w}x{h}, {n} frames, IDR-only"),
311 media: format!("{media_s:.1}s"),
312 wall_ms: wall * 1000.0,
313 rtf: (wall > 0.0).then_some(media_s / wall),
314 });
315
316 let start = Instant::now();
317 for au in &aus {
318 ec_h265::decode::decode_idr_au(au).expect("h265 decode");
319 }
320 let wall = start.elapsed().as_secs_f64();
321 rows.push(Row {
322 component: "ec-h265",
323 direction: "decode",
324 content: format!("{w}x{h}, {n} frames, own IDR stream"),
325 media: format!("{media_s:.1}s"),
326 wall_ms: wall * 1000.0,
327 rtf: (wall > 0.0).then_some(media_s / wall),
328 });
329}
330
331// ---------------------------------------------------------------------------
332// av1: encode only -- same shape as h265.
333// ---------------------------------------------------------------------------
334
335fn bench_av1_encode(rows: &mut Vec<Row>) {
336 let Some(src) = real_video("h264") else {
337 rows.push(missing("ec-av1", "encode"));
338 rows.push(missing("ec-av1", "decode"));
339 return;
340 };
341 // AV1's block grid is 32x32 superblocks: pick a size already a multiple of it.
342 let (planes, w, h, n) = extract_yuv420p(&src, 640, 384, 10);
343 if n == 0 {
344 rows.push(missing("ec-av1", "encode"));
345 rows.push(missing("ec-av1", "decode"));
346 return;
347 }
348 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` benches the encoder's tile
349 // grid (spec 5.9.15's uniform spacing): `1:0` is two tile columns, `1:1`
350 // a 2x2 grid. Unset keeps the one-tile default, whose bytes are the ones
351 // the byte pins carry. `EC_AV1_TILE_THREADS=<n>` (read by `ec_av1::par`)
352 // spreads those tiles across `n` pool workers; the bytes are the same
353 // either way, only the wall changes.
354 let (tile_cols_log2, tile_rows_log2) = std::env::var("EC_AV1_TILES")
355 .ok()
356 .and_then(|spec| {
357 let mut f = spec.split(':');
358 let cols = f.next()?.parse().ok()?;
359 Some((cols, f.next().and_then(|v| v.parse().ok()).unwrap_or(0)))
360 })
361 .unwrap_or((0, 0));
362 let cfg = Av1Config {
363 width: w as usize,
364 height: h as usize,
365 base_q_idx: 100,
366 gop: 10,
367 colour: Colour::default(),
368 tile_cols_log2,
369 tile_rows_log2,
370 };
371 // The encoder's coding pyramid (hidden ALTREF + show_existing_frame) is
372 // the default, as it is in `encode_sequence`; `EC_AV1_PYRAMID=0` benches
373 // the flat one-picture-one-packet stream instead, and
374 // `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` another
375 // shape of it. The `hidden` column below is how many frames of the row
376 // were coded ahead of their display position.
377 let pyramid = Pyramid::from_env();
378 let mut enc = match pyramid {
379 None => Av1Encoder::new(cfg).expect("av1 encoder"),
380 Some(p) => Av1Encoder::with_pyramid(cfg, p).expect("av1 encoder"),
381 };
382 let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
383 let mut stream = Vec::new();
384 let mut hidden = 0usize;
385 let start = Instant::now();
386 for frame in planes.chunks_exact(frame_len) {
387 let (y, rest) = frame.split_at((w * h) as usize);
388 let (u, v) = rest.split_at(rest.len() / 2);
389 let pic = Av1Picture {
390 width: w as usize,
391 height: h as usize,
392 // ec-av1's Picture carries u16 samples since the high-bit-depth
393 // widen; this bench feeds 8-bit y4m, so widen each plane here.
394 y: y.iter().map(|&s| u16::from(s)).collect(),
395 u: u.iter().map(|&s| u16::from(s)).collect(),
396 v: v.iter().map(|&s| u16::from(s)).collect(),
397 };
398 for packet in enc.encode_frames(&pic).expect("av1 encode") {
399 hidden += usize::from(packet.level == Level::Arf);
400 stream.extend_from_slice(&packet.data);
401 }
402 }
403 for packet in enc.flush().expect("av1 flush") {
404 hidden += usize::from(packet.level == Level::Arf);
405 stream.extend_from_slice(&packet.data);
406 }
407 let wall = start.elapsed().as_secs_f64();
408 // What the content gate left this clip coding under: a screen-content
409 // source asks for the pyramid and codes flat, and then `hidden` is 0 for
410 // a reason the row itself names.
411 let coded_under = match (pyramid, enc.pyramid()) {
412 (_, Some(p)) => format!("pyramid {}:{}:{}", p.mini_gop, p.arf_q_offset, p.leaf_q_offset),
413 (Some(_), None) => "flat (gated: screen content)".to_string(),
414 (None, None) => "flat".to_string(),
415 };
416 let media_s = n as f64 / 30.0;
417 let fps = if wall > 0.0 { f64::from(n) / wall } else { 0.0 };
418 let bytes_per_frame = stream.len() as f64 / f64::from(n);
419 rows.push(Row {
420 component: "ec-av1",
421 direction: "encode",
422 content: format!(
423 "{w}x{h}, {n} frames, gop=10, {coded_under}, {hidden} hidden, {fps:.1} fps, \
424 {bytes_per_frame:.0} B/frame"
425 ),
426 media: format!("{media_s:.1}s"),
427 wall_ms: wall * 1000.0,
428 rtf: (wall > 0.0).then_some(media_s / wall),
429 });
430
431 let start = Instant::now();
432 let pictures = ec_av1::stream::decode_stream(&stream).expect("av1 decode_stream");
433 let wall = start.elapsed().as_secs_f64();
434 assert_eq!(pictures.len(), n as usize, "decode_stream frame count");
435 rows.push(Row {
436 component: "ec-av1",
437 direction: "decode",
438 content: format!("{w}x{h}, {n} frames, gop=10"),
439 media: format!("{media_s:.1}s"),
440 wall_ms: wall * 1000.0,
441 rtf: (wall > 0.0).then_some(media_s / wall),
442 });
443}
444
445// ---------------------------------------------------------------------------
446// audio decode: one loop over ec-probe's unified reader covers every codec
447// it wraps (mp3/flac/aac/alac/ac3/truehd/opus/vorbis via ogg/mp4/matroska).
448// ---------------------------------------------------------------------------
449
450fn bench_audio_decode(rows: &mut Vec<Row>) {
451 let mut candidates: Vec<PathBuf> = Vec::new();
452 if let Ok(entries) = std::fs::read_dir(fixtures().join("audio")) {
453 candidates.extend(entries.flatten().map(|e| e.path()));
454 }
455 // Real-library samples: mp3 and wav are on disk; ac3 lives inside the
456 // ReelT mux (5.1 AC-3), extracted as its own elementary file.
457 for f in ["8a3b6d1d19.mp3", "test.wav"] {
458 let p = home().join("Downloads").join(f);
459 if p.exists() {
460 candidates.push(p);
461 }
462 }
463 if let Some(src) = real_video("h264") {
464 if ffprobe_field(&src, "a:0", "codec_name").as_deref() == Some("ac3") {
465 let out = Command::new("ffmpeg")
466 .args(["-v", "error", "-t", "10", "-i"])
467 .arg(&src)
468 .args(["-vn", "-c:a", "copy", "-f", "ac3"])
469 .arg(
470 Path::new(&std::env::var("HOME").unwrap())
471 .join(".cache/bench-media/sample.ac3"),
472 )
473 .output();
474 if let Ok(o) = out {
475 if o.status.success() {
476 candidates.push(home().join(".cache/bench-media/sample.ac3"));
477 }
478 }
479 }
480 }
481 candidates.sort();
482 candidates.dedup();
483
484 for path in candidates {
485 let Ok(mut reader) = Reader::open(&path) else {
486 continue;
487 };
488 let Some(stream) = reader.default_stream(MediaType::Audio).map(|s| s.index) else {
489 continue;
490 };
491 let Ok(mut dec) = reader.make_decoder(stream) else {
492 continue;
493 };
494 let codec = format!("{:?}", dec.codec());
495 let mut samples = 0u64;
496 let start = Instant::now();
497 let mut out = Vec::new();
498 loop {
499 match reader.next_packet() {
500 Ok(pkt) if pkt.stream == stream => {
501 out.clear();
502 if dec.decode(&pkt, &mut out).is_ok() {
503 samples += (out.len() / dec.channels().max(1)) as u64;
504 }
505 }
506 Ok(_) => {}
507 Err(_) => break,
508 }
509 }
510 let _ = dec.flush(&mut out);
511 let wall = start.elapsed().as_secs_f64();
512 let media_s = samples as f64 / dec.sample_rate().max(1) as f64;
513 let name = path.file_name().unwrap().to_string_lossy().into_owned();
514 rows.push(Row {
515 component: Box::leak(format!("ec-probe/{codec}").into_boxed_str()),
516 direction: "decode",
517 content: name,
518 media: format!("{media_s:.1}s"),
519 wall_ms: wall * 1000.0,
520 rtf: (wall > 0.0 && media_s > 0.0).then_some(media_s / wall),
521 });
522 }
523}
524
525// ---------------------------------------------------------------------------
526// audio encode: real, decoded PCM (the same WAV fixture the decode rows
527// already read, run back through `AudioDecoder`'s own PCM path) fed to each
528// crate's own encoder at its default/representative settings.
529// ---------------------------------------------------------------------------
530
531/// `seconds` of real interleaved `f32` PCM, decoded through `ec-probe`'s own
532/// `Reader`/`AudioDecoder` route (the same one `bench_audio_decode` drives).
533fn real_pcm(seconds: f64) -> Option<(Vec<f32>, u32, usize)> {
534 let path = fixtures().join("audio/wav16-stereo-48000.wav");
535 let mut reader = Reader::open(&path).ok()?;
536 let stream = reader.default_stream(MediaType::Audio)?.index;
537 let mut dec = reader.make_decoder(stream).ok()?;
538 let channels = dec.channels();
539 let rate = dec.sample_rate();
540 let want = (seconds * f64::from(rate)) as usize * channels;
541 let mut pcm = Vec::new();
542 let mut out = Vec::new();
543 while pcm.len() < want {
544 match reader.next_packet() {
545 Ok(pkt) if pkt.stream == stream => {
546 if dec.decode(&pkt, &mut out).is_ok() {
547 pcm.extend_from_slice(&out);
548 }
549 }
550 Ok(_) => {}
551 Err(_) => break,
552 }
553 }
554 pcm.truncate(want - want % channels);
555 (!pcm.is_empty()).then_some((pcm, rate, channels))
556}
557
558fn bench_audio_encode(rows: &mut Vec<Row>) {
559 let Some((pcm, rate, channels)) = real_pcm(5.0) else {
560 for name in ["opus", "vorbis", "aac", "mp3", "flac", "alac", "ac3"] {
561 rows.push(missing(
562 Box::leak(format!("ec-{name}").into_boxed_str()),
563 "encode",
564 ));
565 }
566 return;
567 };
568 let frames = pcm.len() / channels;
569 let media_s = frames as f64 / f64::from(rate);
570 let content = format!("{media_s:.1}s wav16 {channels}ch @ {rate}Hz");
571
572 // opus: 20ms frames at the input rate, dropping a short tail frame.
573 {
574 let frame_size = rate as usize / 50;
575 let mut enc = ec_opus::Encoder::new(rate, channels, ec_opus::Application::Audio)
576 .expect("opus encoder");
577 let mut out = vec![0u8; 4000];
578 let start = Instant::now();
579 for chunk in pcm.chunks_exact(frame_size * channels) {
580 enc.encode_float(chunk, frame_size, &mut out)
581 .expect("opus encode");
582 }
583 let wall = start.elapsed().as_secs_f64();
584 rows.push(Row {
585 component: "ec-opus",
586 direction: "encode",
587 content: content.clone(),
588 media: format!("{media_s:.1}s"),
589 wall_ms: wall * 1000.0,
590 rtf: (wall > 0.0).then_some(media_s / wall),
591 });
592 }
593
594 // vorbis: quality 0.6, the level the oracle tests already encode at.
595 {
596 let mut enc = ec_vorbis::VorbisEncoder::new(ec_vorbis::EncoderConfig {
597 sample_rate: rate,
598 channels: channels as u16,
599 bitrate_bps: 0,
600 quality: 0.6,
601 })
602 .expect("vorbis encoder");
603 let start = Instant::now();
604 enc.push_interleaved(&pcm).expect("vorbis push");
605 enc.finish();
606 let mut n = 0usize;
607 loop {
608 match enc.next_packet() {
609 Ok(p) => n += p.data.len(),
610 Err(e) if e.is_eof() => break,
611 Err(e) => panic!("vorbis encode: {e}"),
612 }
613 }
614 let wall = start.elapsed().as_secs_f64();
615 let _ = n;
616 rows.push(Row {
617 component: "ec-vorbis",
618 direction: "encode",
619 content: content.clone(),
620 media: format!("{media_s:.1}s"),
621 wall_ms: wall * 1000.0,
622 rtf: (wall > 0.0).then_some(media_s / wall),
623 });
624 }
625
626 // aac: 128 kbit/s, raw (no ADTS wrap) -- the default config.
627 {
628 let mut enc = ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig::default());
629 let start = Instant::now();
630 enc.push_pcm(&pcm, channels as u16, rate).expect("aac pcm");
631 enc.finish();
632 while enc.next_packet().is_ok() {}
633 let wall = start.elapsed().as_secs_f64();
634 rows.push(Row {
635 component: "ec-aac",
636 direction: "encode",
637 content: content.clone(),
638 media: format!("{media_s:.1}s"),
639 wall_ms: wall * 1000.0,
640 rtf: (wall > 0.0).then_some(media_s / wall),
641 });
642 }
643
644 // mp3: CBR 192 kbit/s, the incumbent-matching default the tests gate on.
645 {
646 let mut enc = ec_mp3::Mp3Encoder::new(ec_mp3::Mp3EncoderConfig {
647 bitrate_kbps: 192,
648 vbr_quality: None,
649 });
650 let start = Instant::now();
651 enc.push_pcm_f32(&pcm, channels as u16, rate)
652 .expect("mp3 pcm");
653 enc.finish();
654 while enc.next_packet().is_ok() {}
655 let wall = start.elapsed().as_secs_f64();
656 rows.push(Row {
657 component: "ec-mp3",
658 direction: "encode",
659 content: content.clone(),
660 media: format!("{media_s:.1}s"),
661 wall_ms: wall * 1000.0,
662 rtf: (wall > 0.0).then_some(media_s / wall),
663 });
664 }
665
666 // flac: single-shot, default config (4096-sample blocks, LPC-12), 16-bit.
667 {
668 let samples: Vec<i32> = pcm
669 .iter()
670 .map(|&s| (s.clamp(-1.0, 1.0) * 32767.0) as i32)
671 .collect();
672 let cfg = ec_flac::EncoderConfig::default();
673 let start = Instant::now();
674 let _ = ec_flac::encode(&cfg, &samples, channels, 16, rate).expect("flac encode");
675 let wall = start.elapsed().as_secs_f64();
676 rows.push(Row {
677 component: "ec-flac",
678 direction: "encode",
679 content: content.clone(),
680 media: format!("{media_s:.1}s"),
681 wall_ms: wall * 1000.0,
682 rtf: (wall > 0.0).then_some(media_s / wall),
683 });
684 }
685
686 // alac: 4096-sample frames, 16-bit -- same shape the round-trip tests use.
687 {
688 let samples: Vec<i32> = pcm
689 .iter()
690 .map(|&s| (s.clamp(-1.0, 1.0) * 32767.0) as i32)
691 .collect();
692 let enc = ec_alac::AlacEncoder::new(rate, channels as u8, 16, 4096).expect("alac encoder");
693 let per_frame = 4096 * channels;
694 let start = Instant::now();
695 for chunk in samples.chunks(per_frame) {
696 let _ = enc.encode_frame(chunk);
697 }
698 let wall = start.elapsed().as_secs_f64();
699 rows.push(Row {
700 component: "ec-alac",
701 direction: "encode",
702 content: content.clone(),
703 media: format!("{media_s:.1}s"),
704 wall_ms: wall * 1000.0,
705 rtf: (wall > 0.0).then_some(media_s / wall),
706 });
707 }
708
709 // ac3: 192 kbit/s -- only if the source's channel count is one A/52 codes.
710 if (1..=6).contains(&channels) && matches!(rate, 48_000 | 44_100 | 32_000) {
711 let mut enc = ec_ac3::Ac3Encoder::new(ec_ac3::EncoderConfig {
712 sample_rate: rate,
713 channels: channels as u16,
714 bitrate_kbps: 192,
715 })
716 .expect("ac3 encoder");
717 let start = Instant::now();
718 enc.push_pcm_f32(&pcm).expect("ac3 pcm");
719 enc.finish();
720 loop {
721 match enc.next_packet() {
722 Ok(_) => {}
723 Err(e) if e.is_eof() => break,
724 Err(e) => panic!("ac3 encode: {e}"),
725 }
726 }
727 let wall = start.elapsed().as_secs_f64();
728 rows.push(Row {
729 component: "ec-ac3",
730 direction: "encode",
731 content,
732 media: format!("{media_s:.1}s"),
733 wall_ms: wall * 1000.0,
734 rtf: (wall > 0.0).then_some(media_s / wall),
735 });
736 } else {
737 rows.push(missing_direction(
738 "ec-ac3",
739 "encode",
740 "source channel/rate combination is not one A/52 codes",
741 ));
742 }
743}
744
745// ---------------------------------------------------------------------------
746// truehd: no fixture stream exists yet, so this round-trips the new encoder
747// through its own decoder, same shape as ec-h265's own-stream decode row.
748// ---------------------------------------------------------------------------
749
750fn bench_truehd(rows: &mut Vec<Row>) {
751 let Some((pcm, rate, channels)) = real_pcm(5.0) else {
752 rows.push(missing("ec-truehd", "encode"));
753 rows.push(missing("ec-truehd", "decode"));
754 return;
755 };
756 if channels != 2 || !matches!(rate, 48_000 | 44_100 | 96_000 | 88_200 | 192_000 | 176_400) {
757 rows.push(missing_direction(
758 "ec-truehd",
759 "encode",
760 "this encoder writes 44.1/48 kHz-family stereo only",
761 ));
762 rows.push(missing_direction(
763 "ec-truehd",
764 "decode",
765 "this encoder writes 44.1/48 kHz-family stereo only",
766 ));
767 return;
768 }
769 let n = pcm.len() / channels;
770 let media_s = n as f64 / f64::from(rate);
771 let mut bytes = Vec::with_capacity(pcm.len() * 4);
772 for &s in &pcm {
773 let sample = (s.clamp(-1.0, 1.0) * 8_388_607.0) as i32;
774 bytes.extend_from_slice(&(sample << 8).to_le_bytes());
775 }
776 let frame = AudioFrame::try_new(
777 SampleFormat::S32,
778 false,
779 ChannelLayout::Stereo,
780 rate,
781 n,
782 vec![Buf::from_vec(bytes)],
783 )
784 .expect("audio frame");
785
786 let mut enc = ec_truehd::TrueHdEncoder::new(rate).expect("truehd encoder");
787 let start = Instant::now();
788 enc.send_frame(&Frame::Audio(frame)).expect("truehd send");
789 enc.flush().expect("truehd flush");
790 let mut thd = Vec::new();
791 while let Ok(pkt) = enc.receive_packet() {
792 thd.extend_from_slice(&pkt.data);
793 }
794 let wall = start.elapsed().as_secs_f64();
795 rows.push(Row {
796 component: "ec-truehd",
797 direction: "encode",
798 content: format!("{media_s:.1}s wav16 stereo @ {rate}Hz"),
799 media: format!("{media_s:.1}s"),
800 wall_ms: wall * 1000.0,
801 rtf: (wall > 0.0).then_some(media_s / wall),
802 });
803
804 let mut dec = ec_truehd::TrueHdDecoder::new();
805 let start = Instant::now();
806 let mut samples = 0u64;
807 let mut pos = 0usize;
808 while pos < thd.len() {
809 let Ok(len) = ec_truehd::frame_length(&thd[pos..]) else {
810 break;
811 };
812 if len == 0 || pos + len > thd.len() {
813 break;
814 }
815 if let Ok(Some(f)) = dec.decode_access_unit(&thd[pos..pos + len]) {
816 samples += (f.data[0].len() / 4 / channels) as u64;
817 }
818 pos += len;
819 }
820 let wall = start.elapsed().as_secs_f64();
821 let media_s = samples as f64 / f64::from(rate);
822 rows.push(Row {
823 component: "ec-truehd",
824 direction: "decode",
825 content: "own encoded stream, stereo".to_string(),
826 media: format!("{media_s:.1}s"),
827 wall_ms: wall * 1000.0,
828 rtf: (wall > 0.0).then_some(media_s / wall),
829 });
830}
831
832// ---------------------------------------------------------------------------
833// container demux: whole-file `ec-matroska`/`ec-mp4` packet reads (through
834// `ec-probe`'s own container routing) over real muxes already on disk.
835// ---------------------------------------------------------------------------
836
837/// Container-level duration (`format=duration`), for a mux whose per-stream
838/// packets carry no duration field of their own (some Matroska tracks don't).
839fn format_duration(path: &Path) -> Option<String> {
840 let out = Command::new("ffprobe")
841 .args(["-v", "error", "-show_entries", "format=duration"])
842 .args(["-of", "default=nw=1:nk=1"])
843 .arg(path)
844 .output()
845 .ok()?;
846 if !out.status.success() {
847 return None;
848 }
849 let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
850 (!s.is_empty() && s != "N/A").then_some(s)
851}
852
853fn bench_container_demux(rows: &mut Vec<Row>) {
854 for (component, ext) in [("ec-matroska", "mkv"), ("ec-mp4", "mp4")] {
855 let Some(src) = [fixtures().join("video"), home().join("Videos")]
856 .into_iter()
857 .filter_map(|d| std::fs::read_dir(d).ok())
858 .flatten()
859 .flatten()
860 .map(|e| e.path())
861 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some(ext))
862 .max_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0))
863 else {
864 rows.push(missing(component, "demux"));
865 continue;
866 };
867 let Ok(mut reader) = Reader::open(&src) else {
868 rows.push(missing(component, "demux"));
869 continue;
870 };
871 let file_mb = std::fs::metadata(&src).map(|m| m.len()).unwrap_or(0) as f64 / 1_000_000.0;
872 let duration_s = [
873 ffprobe_field(&src, "v:0", "duration"),
874 ffprobe_field(&src, "a:0", "duration"),
875 format_duration(&src),
876 ]
877 .into_iter()
878 .find_map(|s| s.and_then(|s| s.parse::<f64>().ok()))
879 .unwrap_or(0.0);
880 let mut packets = 0u64;
881 let start = Instant::now();
882 loop {
883 match reader.next_packet() {
884 Ok(_) => packets += 1,
885 Err(_) => break,
886 }
887 }
888 let wall = start.elapsed().as_secs_f64();
889 let name = src.file_name().unwrap().to_string_lossy().into_owned();
890 rows.push(Row {
891 component,
892 direction: "demux",
893 content: format!("{name} ({file_mb:.1} MB, {packets} packets)"),
894 media: format!("{duration_s:.1}s"),
895 wall_ms: wall * 1000.0,
896 rtf: (wall > 0.0 && duration_s > 0.0).then_some(duration_s / wall),
897 });
898 }
899}
900
901// ---------------------------------------------------------------------------
902// images: one decode entry point (`ec_image::decode`) covers every format
903// the crate sniffs, so every real-library still is a candidate.
904// ---------------------------------------------------------------------------
905
906fn bench_image_decode(rows: &mut Vec<Row>) {
907 let mut candidates: Vec<PathBuf> = Vec::new();
908 if let Ok(entries) = std::fs::read_dir(fixtures().join("stills")) {
909 candidates.extend(
910 entries
911 .flatten()
912 .map(|e| e.path())
913 .filter(|p| p.extension().is_some()),
914 );
915 }
916 for f in [
917 "IMG_20260804_170612.jpg",
918 "drawing-1.png",
919 "20260722-233942.png",
920 "giphy.gif",
921 ] {
922 let p = home().join("Downloads").join(f);
923 if p.exists() {
924 candidates.push(p);
925 }
926 }
927 candidates.sort();
928
929 for path in candidates {
930 let Ok(bytes) = std::fs::read(&path) else {
931 continue;
932 };
933 let mp = bytes.len() as f64 / 1_000_000.0;
934 let start = Instant::now();
935 let Ok(img) = ec_image::decode(&bytes) else {
936 continue;
937 };
938 let wall_ms = start.elapsed().as_secs_f64() * 1000.0;
939 let (w, h) = img.dimensions();
940 let megapixels = (w as f64 * h as f64) / 1_000_000.0;
941 let name = path.file_name().unwrap().to_string_lossy().into_owned();
942 rows.push(Row {
943 component: "ec-image",
944 direction: "decode",
945 content: format!("{name} ({w}x{h}, {mp:.2} MB coded)"),
946 media: format!("{megapixels:.2} MP"),
947 wall_ms,
948 rtf: (wall_ms > 0.0).then_some(megapixels / (wall_ms / 1000.0)),
949 });
950 }
951}
952
953// ---------------------------------------------------------------------------
954// ec-inflate: the zlib stream a real PNG's IDAT chain already carries.
955// ---------------------------------------------------------------------------
956
957fn bench_inflate(rows: &mut Vec<Row>) {
958 let Some(png) = [
959 fixtures().join("stills/gray16.png"),
960 home().join("Downloads/drawing-1.png"),
961 ]
962 .into_iter()
963 .find(|p| p.exists()) else {
964 rows.push(missing("ec-inflate", "inflate"));
965 return;
966 };
967 let Ok(bytes) = std::fs::read(&png) else {
968 rows.push(missing("ec-inflate", "inflate"));
969 return;
970 };
971 // Concatenate every IDAT chunk's payload: that byte string is exactly the
972 // zlib stream `ec_image`'s own PNG path hands to `ec_inflate`.
973 let mut idat = Vec::new();
974 let mut i = 8usize; // past the PNG signature
975 while i + 8 <= bytes.len() {
976 let len = u32::from_be_bytes(bytes[i..i + 4].try_into().unwrap()) as usize;
977 let kind = &bytes[i + 4..i + 8];
978 let start = i + 8;
979 if kind == b"IDAT" && start + len <= bytes.len() {
980 idat.extend_from_slice(&bytes[start..start + len]);
981 }
982 i = start + len + 4; // skip CRC
983 }
984 if idat.is_empty() {
985 rows.push(missing("ec-inflate", "inflate"));
986 return;
987 }
988 let compressed_mb = idat.len() as f64 / 1_000_000.0;
989 let start = Instant::now();
990 let Ok(out) = ec_inflate::inflate_zlib(&idat, 1 << 30) else {
991 rows.push(missing("ec-inflate", "inflate"));
992 return;
993 };
994 let wall_ms = start.elapsed().as_secs_f64() * 1000.0;
995 let out_mb = out.len() as f64 / 1_000_000.0;
996 rows.push(Row {
997 component: "ec-inflate",
998 direction: "inflate",
999 content: format!(
1000 "{} IDAT stream, {compressed_mb:.2} MB in",
1001 png.file_name().unwrap().to_string_lossy()
1002 ),
1003 media: format!("{out_mb:.2} MB out"),
1004 wall_ms,
1005 rtf: (wall_ms > 0.0).then_some(out_mb / (wall_ms / 1000.0)),
1006 });
1007}
1008
1009fn missing(component: &'static str, direction: &'static str) -> Row {
1010 missing_direction(component, direction, "no real-media candidate found")
1011}
1012
1013fn missing_direction(component: &'static str, direction: &'static str, why: &str) -> Row {
1014 Row {
1015 component,
1016 direction,
1017 content: why.to_string(),
1018 media: "-".to_string(),
1019 wall_ms: 0.0,
1020 rtf: None,
1021 }
1022}