forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.0 MiBa69dfabTahinli4 hours ago4073 commits

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