forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe2fa4f0Tahinli2 months ago3028 commits

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