forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcd32144Tahinli2 months ago2288 commits

main.rs980 lines, 34.4 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::{
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 let cfg = Av1Config {
349 width: w as usize,
350 height: h as usize,
351 base_q_idx: 100,
352 gop: 10,
353 colour: Colour::default(),
354 };
355 let mut enc = Av1Encoder::new(cfg).expect("av1 encoder");
356 let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
357 let mut stream = Vec::new();
358 let start = Instant::now();
359 for frame in planes.chunks_exact(frame_len) {
360 let (y, rest) = frame.split_at((w * h) as usize);
361 let (u, v) = rest.split_at(rest.len() / 2);
362 let pic = Av1Picture {
363 width: w as usize,
364 height: h as usize,
365 // ec-av1's Picture carries u16 samples since the high-bit-depth
366 // widen; this bench feeds 8-bit y4m, so widen each plane here.
367 y: y.iter().map(|&s| u16::from(s)).collect(),
368 u: u.iter().map(|&s| u16::from(s)).collect(),
369 v: v.iter().map(|&s| u16::from(s)).collect(),
370 };
371 let packet = enc.encode(&pic).expect("av1 encode");
372 stream.extend_from_slice(&packet.data);
373 }
374 let wall = start.elapsed().as_secs_f64();
375 let media_s = n as f64 / 30.0;
376 let fps = if wall > 0.0 { f64::from(n) / wall } else { 0.0 };
377 let bytes_per_frame = stream.len() as f64 / f64::from(n);
378 rows.push(Row {
379 component: "ec-av1",
380 direction: "encode",
381 content: format!(
382 "{w}x{h}, {n} frames, gop=10, {fps:.1} fps, {bytes_per_frame:.0} B/frame"
383 ),
384 media: format!("{media_s:.1}s"),
385 wall_ms: wall * 1000.0,
386 rtf: (wall > 0.0).then_some(media_s / wall),
387 });
388
389 let start = Instant::now();
390 let pictures = ec_av1::stream::decode_stream(&stream).expect("av1 decode_stream");
391 let wall = start.elapsed().as_secs_f64();
392 assert_eq!(pictures.len(), n as usize, "decode_stream frame count");
393 rows.push(Row {
394 component: "ec-av1",
395 direction: "decode",
396 content: format!("{w}x{h}, {n} frames, gop=10"),
397 media: format!("{media_s:.1}s"),
398 wall_ms: wall * 1000.0,
399 rtf: (wall > 0.0).then_some(media_s / wall),
400 });
401}
402
403// ---------------------------------------------------------------------------
404// audio decode: one loop over ec-probe's unified reader covers every codec
405// it wraps (mp3/flac/aac/alac/ac3/truehd/opus/vorbis via ogg/mp4/matroska).
406// ---------------------------------------------------------------------------
407
408fn bench_audio_decode(rows: &mut Vec<Row>) {
409 let mut candidates: Vec<PathBuf> = Vec::new();
410 if let Ok(entries) = std::fs::read_dir(fixtures().join("audio")) {
411 candidates.extend(entries.flatten().map(|e| e.path()));
412 }
413 // Real-library samples: mp3 and wav are on disk; ac3 lives inside the
414 // ReelT mux (5.1 AC-3), extracted as its own elementary file.
415 for f in ["8a3b6d1d19.mp3", "test.wav"] {
416 let p = home().join("Downloads").join(f);
417 if p.exists() {
418 candidates.push(p);
419 }
420 }
421 if let Some(src) = real_video("h264") {
422 if ffprobe_field(&src, "a:0", "codec_name").as_deref() == Some("ac3") {
423 let out = Command::new("ffmpeg")
424 .args(["-v", "error", "-t", "10", "-i"])
425 .arg(&src)
426 .args(["-vn", "-c:a", "copy", "-f", "ac3"])
427 .arg(
428 Path::new(&std::env::var("HOME").unwrap())
429 .join(".cache/bench-media/sample.ac3"),
430 )
431 .output();
432 if let Ok(o) = out {
433 if o.status.success() {
434 candidates.push(home().join(".cache/bench-media/sample.ac3"));
435 }
436 }
437 }
438 }
439 candidates.sort();
440 candidates.dedup();
441
442 for path in candidates {
443 let Ok(mut reader) = Reader::open(&path) else {
444 continue;
445 };
446 let Some(stream) = reader.default_stream(MediaType::Audio).map(|s| s.index) else {
447 continue;
448 };
449 let Ok(mut dec) = reader.make_decoder(stream) else {
450 continue;
451 };
452 let codec = format!("{:?}", dec.codec());
453 let mut samples = 0u64;
454 let start = Instant::now();
455 let mut out = Vec::new();
456 loop {
457 match reader.next_packet() {
458 Ok(pkt) if pkt.stream == stream => {
459 out.clear();
460 if dec.decode(&pkt, &mut out).is_ok() {
461 samples += (out.len() / dec.channels().max(1)) as u64;
462 }
463 }
464 Ok(_) => {}
465 Err(_) => break,
466 }
467 }
468 let _ = dec.flush(&mut out);
469 let wall = start.elapsed().as_secs_f64();
470 let media_s = samples as f64 / dec.sample_rate().max(1) as f64;
471 let name = path.file_name().unwrap().to_string_lossy().into_owned();
472 rows.push(Row {
473 component: Box::leak(format!("ec-probe/{codec}").into_boxed_str()),
474 direction: "decode",
475 content: name,
476 media: format!("{media_s:.1}s"),
477 wall_ms: wall * 1000.0,
478 rtf: (wall > 0.0 && media_s > 0.0).then_some(media_s / wall),
479 });
480 }
481}
482
483// ---------------------------------------------------------------------------
484// audio encode: real, decoded PCM (the same WAV fixture the decode rows
485// already read, run back through `AudioDecoder`'s own PCM path) fed to each
486// crate's own encoder at its default/representative settings.
487// ---------------------------------------------------------------------------
488
489/// `seconds` of real interleaved `f32` PCM, decoded through `ec-probe`'s own
490/// `Reader`/`AudioDecoder` route (the same one `bench_audio_decode` drives).
491fn real_pcm(seconds: f64) -> Option<(Vec<f32>, u32, usize)> {
492 let path = fixtures().join("audio/wav16-stereo-48000.wav");
493 let mut reader = Reader::open(&path).ok()?;
494 let stream = reader.default_stream(MediaType::Audio)?.index;
495 let mut dec = reader.make_decoder(stream).ok()?;
496 let channels = dec.channels();
497 let rate = dec.sample_rate();
498 let want = (seconds * f64::from(rate)) as usize * channels;
499 let mut pcm = Vec::new();
500 let mut out = Vec::new();
501 while pcm.len() < want {
502 match reader.next_packet() {
503 Ok(pkt) if pkt.stream == stream => {
504 if dec.decode(&pkt, &mut out).is_ok() {
505 pcm.extend_from_slice(&out);
506 }
507 }
508 Ok(_) => {}
509 Err(_) => break,
510 }
511 }
512 pcm.truncate(want - want % channels);
513 (!pcm.is_empty()).then_some((pcm, rate, channels))
514}
515
516fn bench_audio_encode(rows: &mut Vec<Row>) {
517 let Some((pcm, rate, channels)) = real_pcm(5.0) else {
518 for name in ["opus", "vorbis", "aac", "mp3", "flac", "alac", "ac3"] {
519 rows.push(missing(
520 Box::leak(format!("ec-{name}").into_boxed_str()),
521 "encode",
522 ));
523 }
524 return;
525 };
526 let frames = pcm.len() / channels;
527 let media_s = frames as f64 / f64::from(rate);
528 let content = format!("{media_s:.1}s wav16 {channels}ch @ {rate}Hz");
529
530 // opus: 20ms frames at the input rate, dropping a short tail frame.
531 {
532 let frame_size = rate as usize / 50;
533 let mut enc = ec_opus::Encoder::new(rate, channels, ec_opus::Application::Audio)
534 .expect("opus encoder");
535 let mut out = vec![0u8; 4000];
536 let start = Instant::now();
537 for chunk in pcm.chunks_exact(frame_size * channels) {
538 enc.encode_float(chunk, frame_size, &mut out)
539 .expect("opus encode");
540 }
541 let wall = start.elapsed().as_secs_f64();
542 rows.push(Row {
543 component: "ec-opus",
544 direction: "encode",
545 content: content.clone(),
546 media: format!("{media_s:.1}s"),
547 wall_ms: wall * 1000.0,
548 rtf: (wall > 0.0).then_some(media_s / wall),
549 });
550 }
551
552 // vorbis: quality 0.6, the level the oracle tests already encode at.
553 {
554 let mut enc = ec_vorbis::VorbisEncoder::new(ec_vorbis::EncoderConfig {
555 sample_rate: rate,
556 channels: channels as u16,
557 bitrate_bps: 0,
558 quality: 0.6,
559 })
560 .expect("vorbis encoder");
561 let start = Instant::now();
562 enc.push_interleaved(&pcm).expect("vorbis push");
563 enc.finish();
564 let mut n = 0usize;
565 loop {
566 match enc.next_packet() {
567 Ok(p) => n += p.data.len(),
568 Err(e) if e.is_eof() => break,
569 Err(e) => panic!("vorbis encode: {e}"),
570 }
571 }
572 let wall = start.elapsed().as_secs_f64();
573 let _ = n;
574 rows.push(Row {
575 component: "ec-vorbis",
576 direction: "encode",
577 content: content.clone(),
578 media: format!("{media_s:.1}s"),
579 wall_ms: wall * 1000.0,
580 rtf: (wall > 0.0).then_some(media_s / wall),
581 });
582 }
583
584 // aac: 128 kbit/s, raw (no ADTS wrap) -- the default config.
585 {
586 let mut enc = ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig::default());
587 let start = Instant::now();
588 enc.push_pcm(&pcm, channels as u16, rate).expect("aac pcm");
589 enc.finish();
590 while enc.next_packet().is_ok() {}
591 let wall = start.elapsed().as_secs_f64();
592 rows.push(Row {
593 component: "ec-aac",
594 direction: "encode",
595 content: content.clone(),
596 media: format!("{media_s:.1}s"),
597 wall_ms: wall * 1000.0,
598 rtf: (wall > 0.0).then_some(media_s / wall),
599 });
600 }
601
602 // mp3: CBR 192 kbit/s, the incumbent-matching default the tests gate on.
603 {
604 let mut enc = ec_mp3::Mp3Encoder::new(ec_mp3::Mp3EncoderConfig {
605 bitrate_kbps: 192,
606 vbr_quality: None,
607 });
608 let start = Instant::now();
609 enc.push_pcm_f32(&pcm, channels as u16, rate)
610 .expect("mp3 pcm");
611 enc.finish();
612 while enc.next_packet().is_ok() {}
613 let wall = start.elapsed().as_secs_f64();
614 rows.push(Row {
615 component: "ec-mp3",
616 direction: "encode",
617 content: content.clone(),
618 media: format!("{media_s:.1}s"),
619 wall_ms: wall * 1000.0,
620 rtf: (wall > 0.0).then_some(media_s / wall),
621 });
622 }
623
624 // flac: single-shot, default config (4096-sample blocks, LPC-12), 16-bit.
625 {
626 let samples: Vec<i32> = pcm
627 .iter()
628 .map(|&s| (s.clamp(-1.0, 1.0) * 32767.0) as i32)
629 .collect();
630 let cfg = ec_flac::EncoderConfig::default();
631 let start = Instant::now();
632 let _ = ec_flac::encode(&cfg, &samples, channels, 16, rate).expect("flac encode");
633 let wall = start.elapsed().as_secs_f64();
634 rows.push(Row {
635 component: "ec-flac",
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 // alac: 4096-sample frames, 16-bit -- same shape the round-trip tests use.
645 {
646 let samples: Vec<i32> = pcm
647 .iter()
648 .map(|&s| (s.clamp(-1.0, 1.0) * 32767.0) as i32)
649 .collect();
650 let enc = ec_alac::AlacEncoder::new(rate, channels as u8, 16, 4096).expect("alac encoder");
651 let per_frame = 4096 * channels;
652 let start = Instant::now();
653 for chunk in samples.chunks(per_frame) {
654 let _ = enc.encode_frame(chunk);
655 }
656 let wall = start.elapsed().as_secs_f64();
657 rows.push(Row {
658 component: "ec-alac",
659 direction: "encode",
660 content: content.clone(),
661 media: format!("{media_s:.1}s"),
662 wall_ms: wall * 1000.0,
663 rtf: (wall > 0.0).then_some(media_s / wall),
664 });
665 }
666
667 // ac3: 192 kbit/s -- only if the source's channel count is one A/52 codes.
668 if (1..=6).contains(&channels) && matches!(rate, 48_000 | 44_100 | 32_000) {
669 let mut enc = ec_ac3::Ac3Encoder::new(ec_ac3::EncoderConfig {
670 sample_rate: rate,
671 channels: channels as u16,
672 bitrate_kbps: 192,
673 })
674 .expect("ac3 encoder");
675 let start = Instant::now();
676 enc.push_pcm_f32(&pcm).expect("ac3 pcm");
677 enc.finish();
678 loop {
679 match enc.next_packet() {
680 Ok(_) => {}
681 Err(e) if e.is_eof() => break,
682 Err(e) => panic!("ac3 encode: {e}"),
683 }
684 }
685 let wall = start.elapsed().as_secs_f64();
686 rows.push(Row {
687 component: "ec-ac3",
688 direction: "encode",
689 content,
690 media: format!("{media_s:.1}s"),
691 wall_ms: wall * 1000.0,
692 rtf: (wall > 0.0).then_some(media_s / wall),
693 });
694 } else {
695 rows.push(missing_direction(
696 "ec-ac3",
697 "encode",
698 "source channel/rate combination is not one A/52 codes",
699 ));
700 }
701}
702
703// ---------------------------------------------------------------------------
704// truehd: no fixture stream exists yet, so this round-trips the new encoder
705// through its own decoder, same shape as ec-h265's own-stream decode row.
706// ---------------------------------------------------------------------------
707
708fn bench_truehd(rows: &mut Vec<Row>) {
709 let Some((pcm, rate, channels)) = real_pcm(5.0) else {
710 rows.push(missing("ec-truehd", "encode"));
711 rows.push(missing("ec-truehd", "decode"));
712 return;
713 };
714 if channels != 2 || !matches!(rate, 48_000 | 44_100 | 96_000 | 88_200 | 192_000 | 176_400) {
715 rows.push(missing_direction(
716 "ec-truehd",
717 "encode",
718 "this encoder writes 44.1/48 kHz-family stereo only",
719 ));
720 rows.push(missing_direction(
721 "ec-truehd",
722 "decode",
723 "this encoder writes 44.1/48 kHz-family stereo only",
724 ));
725 return;
726 }
727 let n = pcm.len() / channels;
728 let media_s = n as f64 / f64::from(rate);
729 let mut bytes = Vec::with_capacity(pcm.len() * 4);
730 for &s in &pcm {
731 let sample = (s.clamp(-1.0, 1.0) * 8_388_607.0) as i32;
732 bytes.extend_from_slice(&(sample << 8).to_le_bytes());
733 }
734 let frame = AudioFrame::try_new(
735 SampleFormat::S32,
736 false,
737 ChannelLayout::Stereo,
738 rate,
739 n,
740 vec![Buf::from_vec(bytes)],
741 )
742 .expect("audio frame");
743
744 let mut enc = ec_truehd::TrueHdEncoder::new(rate).expect("truehd encoder");
745 let start = Instant::now();
746 enc.send_frame(&Frame::Audio(frame)).expect("truehd send");
747 enc.flush().expect("truehd flush");
748 let mut thd = Vec::new();
749 while let Ok(pkt) = enc.receive_packet() {
750 thd.extend_from_slice(&pkt.data);
751 }
752 let wall = start.elapsed().as_secs_f64();
753 rows.push(Row {
754 component: "ec-truehd",
755 direction: "encode",
756 content: format!("{media_s:.1}s wav16 stereo @ {rate}Hz"),
757 media: format!("{media_s:.1}s"),
758 wall_ms: wall * 1000.0,
759 rtf: (wall > 0.0).then_some(media_s / wall),
760 });
761
762 let mut dec = ec_truehd::TrueHdDecoder::new();
763 let start = Instant::now();
764 let mut samples = 0u64;
765 let mut pos = 0usize;
766 while pos < thd.len() {
767 let Ok(len) = ec_truehd::frame_length(&thd[pos..]) else {
768 break;
769 };
770 if len == 0 || pos + len > thd.len() {
771 break;
772 }
773 if let Ok(Some(f)) = dec.decode_access_unit(&thd[pos..pos + len]) {
774 samples += (f.data[0].len() / 4 / channels) as u64;
775 }
776 pos += len;
777 }
778 let wall = start.elapsed().as_secs_f64();
779 let media_s = samples as f64 / f64::from(rate);
780 rows.push(Row {
781 component: "ec-truehd",
782 direction: "decode",
783 content: "own encoded stream, stereo".to_string(),
784 media: format!("{media_s:.1}s"),
785 wall_ms: wall * 1000.0,
786 rtf: (wall > 0.0).then_some(media_s / wall),
787 });
788}
789
790// ---------------------------------------------------------------------------
791// container demux: whole-file `ec-matroska`/`ec-mp4` packet reads (through
792// `ec-probe`'s own container routing) over real muxes already on disk.
793// ---------------------------------------------------------------------------
794
795/// Container-level duration (`format=duration`), for a mux whose per-stream
796/// packets carry no duration field of their own (some Matroska tracks don't).
797fn format_duration(path: &Path) -> Option<String> {
798 let out = Command::new("ffprobe")
799 .args(["-v", "error", "-show_entries", "format=duration"])
800 .args(["-of", "default=nw=1:nk=1"])
801 .arg(path)
802 .output()
803 .ok()?;
804 if !out.status.success() {
805 return None;
806 }
807 let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
808 (!s.is_empty() && s != "N/A").then_some(s)
809}
810
811fn bench_container_demux(rows: &mut Vec<Row>) {
812 for (component, ext) in [("ec-matroska", "mkv"), ("ec-mp4", "mp4")] {
813 let Some(src) = [fixtures().join("video"), home().join("Videos")]
814 .into_iter()
815 .filter_map(|d| std::fs::read_dir(d).ok())
816 .flatten()
817 .flatten()
818 .map(|e| e.path())
819 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some(ext))
820 .max_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0))
821 else {
822 rows.push(missing(component, "demux"));
823 continue;
824 };
825 let Ok(mut reader) = Reader::open(&src) else {
826 rows.push(missing(component, "demux"));
827 continue;
828 };
829 let file_mb = std::fs::metadata(&src).map(|m| m.len()).unwrap_or(0) as f64 / 1_000_000.0;
830 let duration_s = [
831 ffprobe_field(&src, "v:0", "duration"),
832 ffprobe_field(&src, "a:0", "duration"),
833 format_duration(&src),
834 ]
835 .into_iter()
836 .find_map(|s| s.and_then(|s| s.parse::<f64>().ok()))
837 .unwrap_or(0.0);
838 let mut packets = 0u64;
839 let start = Instant::now();
840 loop {
841 match reader.next_packet() {
842 Ok(_) => packets += 1,
843 Err(_) => break,
844 }
845 }
846 let wall = start.elapsed().as_secs_f64();
847 let name = src.file_name().unwrap().to_string_lossy().into_owned();
848 rows.push(Row {
849 component,
850 direction: "demux",
851 content: format!("{name} ({file_mb:.1} MB, {packets} packets)"),
852 media: format!("{duration_s:.1}s"),
853 wall_ms: wall * 1000.0,
854 rtf: (wall > 0.0 && duration_s > 0.0).then_some(duration_s / wall),
855 });
856 }
857}
858
859// ---------------------------------------------------------------------------
860// images: one decode entry point (`ec_image::decode`) covers every format
861// the crate sniffs, so every real-library still is a candidate.
862// ---------------------------------------------------------------------------
863
864fn bench_image_decode(rows: &mut Vec<Row>) {
865 let mut candidates: Vec<PathBuf> = Vec::new();
866 if let Ok(entries) = std::fs::read_dir(fixtures().join("stills")) {
867 candidates.extend(
868 entries
869 .flatten()
870 .map(|e| e.path())
871 .filter(|p| p.extension().is_some()),
872 );
873 }
874 for f in [
875 "IMG_20260804_170612.jpg",
876 "drawing-1.png",
877 "20260722-233942.png",
878 "giphy.gif",
879 ] {
880 let p = home().join("Downloads").join(f);
881 if p.exists() {
882 candidates.push(p);
883 }
884 }
885 candidates.sort();
886
887 for path in candidates {
888 let Ok(bytes) = std::fs::read(&path) else {
889 continue;
890 };
891 let mp = bytes.len() as f64 / 1_000_000.0;
892 let start = Instant::now();
893 let Ok(img) = ec_image::decode(&bytes) else {
894 continue;
895 };
896 let wall_ms = start.elapsed().as_secs_f64() * 1000.0;
897 let (w, h) = img.dimensions();
898 let megapixels = (w as f64 * h as f64) / 1_000_000.0;
899 let name = path.file_name().unwrap().to_string_lossy().into_owned();
900 rows.push(Row {
901 component: "ec-image",
902 direction: "decode",
903 content: format!("{name} ({w}x{h}, {mp:.2} MB coded)"),
904 media: format!("{megapixels:.2} MP"),
905 wall_ms,
906 rtf: (wall_ms > 0.0).then_some(megapixels / (wall_ms / 1000.0)),
907 });
908 }
909}
910
911// ---------------------------------------------------------------------------
912// ec-inflate: the zlib stream a real PNG's IDAT chain already carries.
913// ---------------------------------------------------------------------------
914
915fn bench_inflate(rows: &mut Vec<Row>) {
916 let Some(png) = [
917 fixtures().join("stills/gray16.png"),
918 home().join("Downloads/drawing-1.png"),
919 ]
920 .into_iter()
921 .find(|p| p.exists()) else {
922 rows.push(missing("ec-inflate", "inflate"));
923 return;
924 };
925 let Ok(bytes) = std::fs::read(&png) else {
926 rows.push(missing("ec-inflate", "inflate"));
927 return;
928 };
929 // Concatenate every IDAT chunk's payload: that byte string is exactly the
930 // zlib stream `ec_image`'s own PNG path hands to `ec_inflate`.
931 let mut idat = Vec::new();
932 let mut i = 8usize; // past the PNG signature
933 while i + 8 <= bytes.len() {
934 let len = u32::from_be_bytes(bytes[i..i + 4].try_into().unwrap()) as usize;
935 let kind = &bytes[i + 4..i + 8];
936 let start = i + 8;
937 if kind == b"IDAT" && start + len <= bytes.len() {
938 idat.extend_from_slice(&bytes[start..start + len]);
939 }
940 i = start + len + 4; // skip CRC
941 }
942 if idat.is_empty() {
943 rows.push(missing("ec-inflate", "inflate"));
944 return;
945 }
946 let compressed_mb = idat.len() as f64 / 1_000_000.0;
947 let start = Instant::now();
948 let Ok(out) = ec_inflate::inflate_zlib(&idat, 1 << 30) else {
949 rows.push(missing("ec-inflate", "inflate"));
950 return;
951 };
952 let wall_ms = start.elapsed().as_secs_f64() * 1000.0;
953 let out_mb = out.len() as f64 / 1_000_000.0;
954 rows.push(Row {
955 component: "ec-inflate",
956 direction: "inflate",
957 content: format!(
958 "{} IDAT stream, {compressed_mb:.2} MB in",
959 png.file_name().unwrap().to_string_lossy()
960 ),
961 media: format!("{out_mb:.2} MB out"),
962 wall_ms,
963 rtf: (wall_ms > 0.0).then_some(out_mb / (wall_ms / 1000.0)),
964 });
965}
966
967fn missing(component: &'static str, direction: &'static str) -> Row {
968 missing_direction(component, direction, "no real-media candidate found")
969}
970
971fn missing_direction(component: &'static str, direction: &'static str, why: &str) -> Row {
972 Row {
973 component,
974 direction,
975 content: why.to_string(),
976 media: "-".to_string(),
977 wall_ms: 0.0,
978 rtf: None,
979 }
980}