forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB3d2e08fTahinli7 days ago3929 commits

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