forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.2 MiBcdccbc2Tahinli7 hours ago4263 commits

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