forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBe18142dTahinli8 hours ago4543 commits

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