| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | use std::path::{Path, PathBuf}; |
| 12 | use std::process::Command; |
| 13 | use std::time::Instant; |
| 14 | |
| 15 | use ec_av1::encode::Picture as Av1Picture; |
| 16 | use ec_av1::encoder::{Av1Encoder, Colour, EncoderConfig as Av1Config, Level, Pyramid}; |
| 17 | use ec_core::frame::{ |
| 18 | AudioFrame, ChannelLayout, Frame, PixelFormat, Plane, SampleFormat, VideoFrame, |
| 19 | }; |
| 20 | use ec_core::packet::Buf; |
| 21 | use ec_core::registry::{Encoder as CoreEncoder, MediaType}; |
| 22 | use ec_h264::{ |
| 23 | Decoder as H264Decoder, Encoder as H264Encoder, EncoderConfig as H264Config, NalOutcome, |
| 24 | PictureView, |
| 25 | }; |
| 26 | use ec_h264_syntax::AnnexBIter; |
| 27 | use ec_h265::encoder::{Encoder as H265Encoder, EncoderConfig as H265Config}; |
| 28 | use ec_probe::Reader; |
| 29 | |
| 30 | struct 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 | |
| 39 | fn 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_audio_decode(&mut rows); |
| 46 | bench_audio_encode(&mut rows); |
| 47 | bench_truehd(&mut rows); |
| 48 | bench_container_demux(&mut rows); |
| 49 | bench_image_decode(&mut rows); |
| 50 | bench_inflate(&mut rows); |
| 51 | |
| 52 | rows.sort_by(|a, b| { |
| 53 | a.rtf |
| 54 | .unwrap_or(f64::INFINITY) |
| 55 | .partial_cmp(&b.rtf.unwrap_or(f64::INFINITY)) |
| 56 | .unwrap() |
| 57 | }); |
| 58 | |
| 59 | println!("| component | direction | content | media | wall ms | realtime factor |"); |
| 60 | println!("|---|---|---|---|---|---|"); |
| 61 | for r in &rows { |
| 62 | let rtf = r |
| 63 | .rtf |
| 64 | .map_or_else(|| "-".to_string(), |v| format!("{v:.2}x")); |
| 65 | println!( |
| 66 | "| {} | {} | {} | {} | {:.1} | {} |", |
| 67 | r.component, r.direction, r.content, r.media, r.wall_ms, rtf |
| 68 | ); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | fn fixtures() -> PathBuf { |
| 77 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") |
| 78 | } |
| 79 | |
| 80 | fn home() -> PathBuf { |
| 81 | PathBuf::from(std::env::var("HOME").expect("HOME")) |
| 82 | } |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | fn real_video(codec: &str) -> Option<PathBuf> { |
| 88 | let roots = [home().join("Videos"), home().join("Downloads")]; |
| 89 | let mut found = Vec::new(); |
| 90 | for root in roots { |
| 91 | let Ok(walker) = std::fs::read_dir(&root) else { |
| 92 | continue; |
| 93 | }; |
| 94 | for entry in walker.flatten() { |
| 95 | let p = entry.path(); |
| 96 | let Some(ext) = p.extension().and_then(|e| e.to_str()) else { |
| 97 | continue; |
| 98 | }; |
| 99 | if !matches!( |
| 100 | ext.to_ascii_lowercase().as_str(), |
| 101 | "mp4" | "mkv" | "mov" | "avi" |
| 102 | ) { |
| 103 | continue; |
| 104 | } |
| 105 | found.push(p); |
| 106 | } |
| 107 | } |
| 108 | found.sort(); |
| 109 | for p in found { |
| 110 | if ffprobe_field(&p, "v:0", "codec_name").as_deref() == Some(codec) { |
| 111 | return Some(p); |
| 112 | } |
| 113 | } |
| 114 | None |
| 115 | } |
| 116 | |
| 117 | fn ffprobe_field(path: &Path, stream: &str, key: &str) -> Option<String> { |
| 118 | let out = Command::new("ffprobe") |
| 119 | .args(["-v", "error", "-select_streams", stream, "-show_entries"]) |
| 120 | .arg(format!("stream={key}")) |
| 121 | .args(["-of", "default=nw=1:nk=1"]) |
| 122 | .arg(path) |
| 123 | .output() |
| 124 | .ok()?; |
| 125 | if !out.status.success() { |
| 126 | return None; |
| 127 | } |
| 128 | let s = String::from_utf8_lossy(&out.stdout).trim().to_string(); |
| 129 | (!s.is_empty()).then_some(s) |
| 130 | } |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | fn bench_h264(rows: &mut Vec<Row>) { |
| 137 | let Some(src) = real_video("h264") else { |
| 138 | rows.push(missing("ec-h264", "decode")); |
| 139 | rows.push(missing("ec-h264", "encode")); |
| 140 | return; |
| 141 | }; |
| 142 | let w: u32 = ffprobe_field(&src, "v:0", "width") |
| 143 | .and_then(|s| s.parse().ok()) |
| 144 | .unwrap_or(0); |
| 145 | let h: u32 = ffprobe_field(&src, "v:0", "height") |
| 146 | .and_then(|s| s.parse().ok()) |
| 147 | .unwrap_or(0); |
| 148 | |
| 149 | |
| 150 | let out = Command::new("ffmpeg") |
| 151 | .args(["-v", "error", "-t", "10", "-i"]) |
| 152 | .arg(&src) |
| 153 | .args([ |
| 154 | "-an", |
| 155 | "-c:v", |
| 156 | "copy", |
| 157 | "-bsf:v", |
| 158 | "h264_mp4toannexb", |
| 159 | "-f", |
| 160 | "h264", |
| 161 | "-", |
| 162 | ]) |
| 163 | .output() |
| 164 | .expect("ffmpeg extract h264"); |
| 165 | if out.status.success() && !out.stdout.is_empty() { |
| 166 | let bytes = out.stdout; |
| 167 | let start = Instant::now(); |
| 168 | let mut dec = H264Decoder::new(); |
| 169 | let mut frames = 0u64; |
| 170 | for nal in AnnexBIter::new(&bytes) { |
| 171 | if let Ok(NalOutcome::PictureBoundary) = dec.push_nal(nal) { |
| 172 | let _ = dec.end_picture(); |
| 173 | let _ = dec.push_nal(nal); |
| 174 | } |
| 175 | while dec.next_frame().is_some() { |
| 176 | frames += 1; |
| 177 | } |
| 178 | } |
| 179 | let _ = dec.flush(); |
| 180 | while dec.next_frame().is_some() { |
| 181 | frames += 1; |
| 182 | } |
| 183 | let wall = start.elapsed().as_secs_f64(); |
| 184 | let fps = ffprobe_field(&src, "v:0", "r_frame_rate") |
| 185 | .and_then(|s| parse_ratio(&s)) |
| 186 | .unwrap_or(25.0); |
| 187 | let media_s = frames as f64 / fps; |
| 188 | rows.push(Row { |
| 189 | component: "ec-h264", |
| 190 | direction: "decode", |
| 191 | content: format!("{w}x{h} film, {frames} frames"), |
| 192 | media: format!("{media_s:.1}s"), |
| 193 | wall_ms: wall * 1000.0, |
| 194 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 195 | }); |
| 196 | } else { |
| 197 | rows.push(missing("ec-h264", "decode")); |
| 198 | } |
| 199 | |
| 200 | |
| 201 | let (planes, ew, eh, n) = extract_yuv420p(&src, 640, 360, 30); |
| 202 | if n > 0 { |
| 203 | let mut cfg = H264Config::new(ew, eh); |
| 204 | cfg.threads = 1; |
| 205 | let mut enc = H264Encoder::new(cfg).expect("h264 encoder"); |
| 206 | let frame_len = (ew * eh + 2 * (ew.div_ceil(2) * eh.div_ceil(2))) as usize; |
| 207 | let start = Instant::now(); |
| 208 | for frame in planes.chunks_exact(frame_len) { |
| 209 | let (y, rest) = frame.split_at((ew * eh) as usize); |
| 210 | let (u, v) = rest.split_at(rest.len() / 2); |
| 211 | let view = PictureView::i420(ew, eh, y, u, v); |
| 212 | enc.encode(&view).expect("h264 encode"); |
| 213 | } |
| 214 | let wall = start.elapsed().as_secs_f64(); |
| 215 | let media_s = n as f64 / 30.0; |
| 216 | rows.push(Row { |
| 217 | component: "ec-h264", |
| 218 | direction: "encode", |
| 219 | content: format!("{ew}x{eh}, {n} frames, 1 thread"), |
| 220 | media: format!("{media_s:.1}s"), |
| 221 | wall_ms: wall * 1000.0, |
| 222 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 223 | }); |
| 224 | } else { |
| 225 | rows.push(missing("ec-h264", "encode")); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | |
| 230 | |
| 231 | fn extract_yuv420p(src: &Path, w: u32, h: u32, n: u32) -> (Vec<u8>, u32, u32, u32) { |
| 232 | let out = Command::new("ffmpeg") |
| 233 | .args(["-v", "error", "-i"]) |
| 234 | .arg(src) |
| 235 | .args([ |
| 236 | "-vf", |
| 237 | &format!("scale={w}:{h}"), |
| 238 | "-frames:v", |
| 239 | &n.to_string(), |
| 240 | "-pix_fmt", |
| 241 | "yuv420p", |
| 242 | "-f", |
| 243 | "rawvideo", |
| 244 | "-", |
| 245 | ]) |
| 246 | .output() |
| 247 | .expect("ffmpeg extract yuv420p"); |
| 248 | if !out.status.success() || out.stdout.is_empty() { |
| 249 | return (Vec::new(), w, h, 0); |
| 250 | } |
| 251 | let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; |
| 252 | let frames = (out.stdout.len() / frame_len) as u32; |
| 253 | (out.stdout, w, h, frames) |
| 254 | } |
| 255 | |
| 256 | fn parse_ratio(s: &str) -> Option<f64> { |
| 257 | let (n, d) = s.split_once('/')?; |
| 258 | let (n, d) = (n.parse::<f64>().ok()?, d.parse::<f64>().ok()?); |
| 259 | (d != 0.0).then_some(n / d) |
| 260 | } |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | fn bench_h265_encode(rows: &mut Vec<Row>) { |
| 267 | let Some(src) = real_video("h264").or_else(|| real_video("hevc")) else { |
| 268 | rows.push(missing("ec-h265", "decode")); |
| 269 | rows.push(missing("ec-h265", "encode")); |
| 270 | return; |
| 271 | }; |
| 272 | let (planes, w, h, n) = extract_yuv420p(&src, 640, 360, 10); |
| 273 | if n == 0 { |
| 274 | rows.push(missing("ec-h265", "encode")); |
| 275 | rows.push(missing("ec-h265", "decode")); |
| 276 | return; |
| 277 | } |
| 278 | let mut cfg = H265Config::new(w, h); |
| 279 | |
| 280 | |
| 281 | cfg.rdoq_estimate = std::env::var("EC_H265_RDOQ_ESTIMATE").is_ok_and(|v| v != "0"); |
| 282 | let enc = H265Encoder::new(cfg).expect("h265 encoder"); |
| 283 | let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; |
| 284 | let cw = w.div_ceil(2); |
| 285 | let ch = h.div_ceil(2); |
| 286 | let mut aus = Vec::new(); |
| 287 | let start = Instant::now(); |
| 288 | for frame in planes.chunks_exact(frame_len) { |
| 289 | let (y, rest) = frame.split_at((w * h) as usize); |
| 290 | let (u, v) = rest.split_at(rest.len() / 2); |
| 291 | let vf = VideoFrame::try_new( |
| 292 | PixelFormat::I420, |
| 293 | w, |
| 294 | h, |
| 295 | vec![ |
| 296 | Plane::new(y.to_vec(), w as usize), |
| 297 | Plane::new(u.to_vec(), cw as usize), |
| 298 | Plane::new(v.to_vec(), cw as usize), |
| 299 | ], |
| 300 | ) |
| 301 | .expect("i420 frame"); |
| 302 | let _ = ch; |
| 303 | aus.push(enc.encode_idr(&vf).expect("h265 encode").au); |
| 304 | } |
| 305 | let wall = start.elapsed().as_secs_f64(); |
| 306 | let media_s = n as f64 / 30.0; |
| 307 | rows.push(Row { |
| 308 | component: "ec-h265", |
| 309 | direction: "encode", |
| 310 | content: format!("{w}x{h}, {n} frames, IDR-only"), |
| 311 | media: format!("{media_s:.1}s"), |
| 312 | wall_ms: wall * 1000.0, |
| 313 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 314 | }); |
| 315 | |
| 316 | let start = Instant::now(); |
| 317 | for au in &aus { |
| 318 | ec_h265::decode::decode_idr_au(au).expect("h265 decode"); |
| 319 | } |
| 320 | let wall = start.elapsed().as_secs_f64(); |
| 321 | rows.push(Row { |
| 322 | component: "ec-h265", |
| 323 | direction: "decode", |
| 324 | content: format!("{w}x{h}, {n} frames, own IDR stream"), |
| 325 | media: format!("{media_s:.1}s"), |
| 326 | wall_ms: wall * 1000.0, |
| 327 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 328 | }); |
| 329 | } |
| 330 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | fn bench_av1_encode(rows: &mut Vec<Row>) { |
| 336 | let Some(src) = real_video("h264") else { |
| 337 | rows.push(missing("ec-av1", "encode")); |
| 338 | rows.push(missing("ec-av1", "decode")); |
| 339 | return; |
| 340 | }; |
| 341 | |
| 342 | let (planes, w, h, n) = extract_yuv420p(&src, 640, 384, 10); |
| 343 | if n == 0 { |
| 344 | rows.push(missing("ec-av1", "encode")); |
| 345 | rows.push(missing("ec-av1", "decode")); |
| 346 | return; |
| 347 | } |
| 348 | |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | let (tile_cols_log2, tile_rows_log2) = std::env::var("EC_AV1_TILES") |
| 355 | .ok() |
| 356 | .and_then(|spec| { |
| 357 | let mut f = spec.split(':'); |
| 358 | let cols = f.next()?.parse().ok()?; |
| 359 | Some((cols, f.next().and_then(|v| v.parse().ok()).unwrap_or(0))) |
| 360 | }) |
| 361 | .unwrap_or((0, 0)); |
| 362 | let cfg = Av1Config { |
| 363 | width: w as usize, |
| 364 | height: h as usize, |
| 365 | base_q_idx: 100, |
| 366 | gop: 10, |
| 367 | colour: Colour::default(), |
| 368 | tile_cols_log2, |
| 369 | tile_rows_log2, |
| 370 | }; |
| 371 | |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | let pyramid = Pyramid::from_env(); |
| 378 | let mut enc = match pyramid { |
| 379 | None => Av1Encoder::new(cfg).expect("av1 encoder"), |
| 380 | Some(p) => Av1Encoder::with_pyramid(cfg, p).expect("av1 encoder"), |
| 381 | }; |
| 382 | let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; |
| 383 | let mut stream = Vec::new(); |
| 384 | let mut hidden = 0usize; |
| 385 | let start = Instant::now(); |
| 386 | for frame in planes.chunks_exact(frame_len) { |
| 387 | let (y, rest) = frame.split_at((w * h) as usize); |
| 388 | let (u, v) = rest.split_at(rest.len() / 2); |
| 389 | let pic = Av1Picture { |
| 390 | width: w as usize, |
| 391 | height: h as usize, |
| 392 | |
| 393 | |
| 394 | y: y.iter().map(|&s| u16::from(s)).collect(), |
| 395 | u: u.iter().map(|&s| u16::from(s)).collect(), |
| 396 | v: v.iter().map(|&s| u16::from(s)).collect(), |
| 397 | }; |
| 398 | for packet in enc.encode_frames(&pic).expect("av1 encode") { |
| 399 | hidden += usize::from(packet.level == Level::Arf); |
| 400 | stream.extend_from_slice(&packet.data); |
| 401 | } |
| 402 | } |
| 403 | for packet in enc.flush().expect("av1 flush") { |
| 404 | hidden += usize::from(packet.level == Level::Arf); |
| 405 | stream.extend_from_slice(&packet.data); |
| 406 | } |
| 407 | let wall = start.elapsed().as_secs_f64(); |
| 408 | let media_s = n as f64 / 30.0; |
| 409 | let fps = if wall > 0.0 { f64::from(n) / wall } else { 0.0 }; |
| 410 | let bytes_per_frame = stream.len() as f64 / f64::from(n); |
| 411 | rows.push(Row { |
| 412 | component: "ec-av1", |
| 413 | direction: "encode", |
| 414 | content: format!( |
| 415 | "{w}x{h}, {n} frames, gop=10, {hidden} hidden, {fps:.1} fps, {bytes_per_frame:.0} B/frame" |
| 416 | ), |
| 417 | media: format!("{media_s:.1}s"), |
| 418 | wall_ms: wall * 1000.0, |
| 419 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 420 | }); |
| 421 | |
| 422 | let start = Instant::now(); |
| 423 | let pictures = ec_av1::stream::decode_stream(&stream).expect("av1 decode_stream"); |
| 424 | let wall = start.elapsed().as_secs_f64(); |
| 425 | assert_eq!(pictures.len(), n as usize, "decode_stream frame count"); |
| 426 | rows.push(Row { |
| 427 | component: "ec-av1", |
| 428 | direction: "decode", |
| 429 | content: format!("{w}x{h}, {n} frames, gop=10"), |
| 430 | media: format!("{media_s:.1}s"), |
| 431 | wall_ms: wall * 1000.0, |
| 432 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 433 | }); |
| 434 | } |
| 435 | |
| 436 | |
| 437 | |
| 438 | |
| 439 | |
| 440 | |
| 441 | fn bench_audio_decode(rows: &mut Vec<Row>) { |
| 442 | let mut candidates: Vec<PathBuf> = Vec::new(); |
| 443 | if let Ok(entries) = std::fs::read_dir(fixtures().join("audio")) { |
| 444 | candidates.extend(entries.flatten().map(|e| e.path())); |
| 445 | } |
| 446 | |
| 447 | |
| 448 | for f in ["8a3b6d1d19.mp3", "test.wav"] { |
| 449 | let p = home().join("Downloads").join(f); |
| 450 | if p.exists() { |
| 451 | candidates.push(p); |
| 452 | } |
| 453 | } |
| 454 | if let Some(src) = real_video("h264") { |
| 455 | if ffprobe_field(&src, "a:0", "codec_name").as_deref() == Some("ac3") { |
| 456 | let out = Command::new("ffmpeg") |
| 457 | .args(["-v", "error", "-t", "10", "-i"]) |
| 458 | .arg(&src) |
| 459 | .args(["-vn", "-c:a", "copy", "-f", "ac3"]) |
| 460 | .arg( |
| 461 | Path::new(&std::env::var("HOME").unwrap()) |
| 462 | .join(".cache/bench-media/sample.ac3"), |
| 463 | ) |
| 464 | .output(); |
| 465 | if let Ok(o) = out { |
| 466 | if o.status.success() { |
| 467 | candidates.push(home().join(".cache/bench-media/sample.ac3")); |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 | } |
| 472 | candidates.sort(); |
| 473 | candidates.dedup(); |
| 474 | |
| 475 | for path in candidates { |
| 476 | let Ok(mut reader) = Reader::open(&path) else { |
| 477 | continue; |
| 478 | }; |
| 479 | let Some(stream) = reader.default_stream(MediaType::Audio).map(|s| s.index) else { |
| 480 | continue; |
| 481 | }; |
| 482 | let Ok(mut dec) = reader.make_decoder(stream) else { |
| 483 | continue; |
| 484 | }; |
| 485 | let codec = format!("{:?}", dec.codec()); |
| 486 | let mut samples = 0u64; |
| 487 | let start = Instant::now(); |
| 488 | let mut out = Vec::new(); |
| 489 | loop { |
| 490 | match reader.next_packet() { |
| 491 | Ok(pkt) if pkt.stream == stream => { |
| 492 | out.clear(); |
| 493 | if dec.decode(&pkt, &mut out).is_ok() { |
| 494 | samples += (out.len() / dec.channels().max(1)) as u64; |
| 495 | } |
| 496 | } |
| 497 | Ok(_) => {} |
| 498 | Err(_) => break, |
| 499 | } |
| 500 | } |
| 501 | let _ = dec.flush(&mut out); |
| 502 | let wall = start.elapsed().as_secs_f64(); |
| 503 | let media_s = samples as f64 / dec.sample_rate().max(1) as f64; |
| 504 | let name = path.file_name().unwrap().to_string_lossy().into_owned(); |
| 505 | rows.push(Row { |
| 506 | component: Box::leak(format!("ec-probe/{codec}").into_boxed_str()), |
| 507 | direction: "decode", |
| 508 | content: name, |
| 509 | media: format!("{media_s:.1}s"), |
| 510 | wall_ms: wall * 1000.0, |
| 511 | rtf: (wall > 0.0 && media_s > 0.0).then_some(media_s / wall), |
| 512 | }); |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | |
| 517 | |
| 518 | |
| 519 | |
| 520 | |
| 521 | |
| 522 | |
| 523 | |
| 524 | fn real_pcm(seconds: f64) -> Option<(Vec<f32>, u32, usize)> { |
| 525 | let path = fixtures().join("audio/wav16-stereo-48000.wav"); |
| 526 | let mut reader = Reader::open(&path).ok()?; |
| 527 | let stream = reader.default_stream(MediaType::Audio)?.index; |
| 528 | let mut dec = reader.make_decoder(stream).ok()?; |
| 529 | let channels = dec.channels(); |
| 530 | let rate = dec.sample_rate(); |
| 531 | let want = (seconds * f64::from(rate)) as usize * channels; |
| 532 | let mut pcm = Vec::new(); |
| 533 | let mut out = Vec::new(); |
| 534 | while pcm.len() < want { |
| 535 | match reader.next_packet() { |
| 536 | Ok(pkt) if pkt.stream == stream => { |
| 537 | if dec.decode(&pkt, &mut out).is_ok() { |
| 538 | pcm.extend_from_slice(&out); |
| 539 | } |
| 540 | } |
| 541 | Ok(_) => {} |
| 542 | Err(_) => break, |
| 543 | } |
| 544 | } |
| 545 | pcm.truncate(want - want % channels); |
| 546 | (!pcm.is_empty()).then_some((pcm, rate, channels)) |
| 547 | } |
| 548 | |
| 549 | fn bench_audio_encode(rows: &mut Vec<Row>) { |
| 550 | let Some((pcm, rate, channels)) = real_pcm(5.0) else { |
| 551 | for name in ["opus", "vorbis", "aac", "mp3", "flac", "alac", "ac3"] { |
| 552 | rows.push(missing( |
| 553 | Box::leak(format!("ec-{name}").into_boxed_str()), |
| 554 | "encode", |
| 555 | )); |
| 556 | } |
| 557 | return; |
| 558 | }; |
| 559 | let frames = pcm.len() / channels; |
| 560 | let media_s = frames as f64 / f64::from(rate); |
| 561 | let content = format!("{media_s:.1}s wav16 {channels}ch @ {rate}Hz"); |
| 562 | |
| 563 | |
| 564 | { |
| 565 | let frame_size = rate as usize / 50; |
| 566 | let mut enc = ec_opus::Encoder::new(rate, channels, ec_opus::Application::Audio) |
| 567 | .expect("opus encoder"); |
| 568 | let mut out = vec![0u8; 4000]; |
| 569 | let start = Instant::now(); |
| 570 | for chunk in pcm.chunks_exact(frame_size * channels) { |
| 571 | enc.encode_float(chunk, frame_size, &mut out) |
| 572 | .expect("opus encode"); |
| 573 | } |
| 574 | let wall = start.elapsed().as_secs_f64(); |
| 575 | rows.push(Row { |
| 576 | component: "ec-opus", |
| 577 | direction: "encode", |
| 578 | content: content.clone(), |
| 579 | media: format!("{media_s:.1}s"), |
| 580 | wall_ms: wall * 1000.0, |
| 581 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 582 | }); |
| 583 | } |
| 584 | |
| 585 | |
| 586 | { |
| 587 | let mut enc = ec_vorbis::VorbisEncoder::new(ec_vorbis::EncoderConfig { |
| 588 | sample_rate: rate, |
| 589 | channels: channels as u16, |
| 590 | bitrate_bps: 0, |
| 591 | quality: 0.6, |
| 592 | }) |
| 593 | .expect("vorbis encoder"); |
| 594 | let start = Instant::now(); |
| 595 | enc.push_interleaved(&pcm).expect("vorbis push"); |
| 596 | enc.finish(); |
| 597 | let mut n = 0usize; |
| 598 | loop { |
| 599 | match enc.next_packet() { |
| 600 | Ok(p) => n += p.data.len(), |
| 601 | Err(e) if e.is_eof() => break, |
| 602 | Err(e) => panic!("vorbis encode: {e}"), |
| 603 | } |
| 604 | } |
| 605 | let wall = start.elapsed().as_secs_f64(); |
| 606 | let _ = n; |
| 607 | rows.push(Row { |
| 608 | component: "ec-vorbis", |
| 609 | direction: "encode", |
| 610 | content: content.clone(), |
| 611 | media: format!("{media_s:.1}s"), |
| 612 | wall_ms: wall * 1000.0, |
| 613 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 614 | }); |
| 615 | } |
| 616 | |
| 617 | |
| 618 | { |
| 619 | let mut enc = ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig::default()); |
| 620 | let start = Instant::now(); |
| 621 | enc.push_pcm(&pcm, channels as u16, rate).expect("aac pcm"); |
| 622 | enc.finish(); |
| 623 | while enc.next_packet().is_ok() {} |
| 624 | let wall = start.elapsed().as_secs_f64(); |
| 625 | rows.push(Row { |
| 626 | component: "ec-aac", |
| 627 | direction: "encode", |
| 628 | content: content.clone(), |
| 629 | media: format!("{media_s:.1}s"), |
| 630 | wall_ms: wall * 1000.0, |
| 631 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 632 | }); |
| 633 | } |
| 634 | |
| 635 | |
| 636 | { |
| 637 | let mut enc = ec_mp3::Mp3Encoder::new(ec_mp3::Mp3EncoderConfig { |
| 638 | bitrate_kbps: 192, |
| 639 | vbr_quality: None, |
| 640 | }); |
| 641 | let start = Instant::now(); |
| 642 | enc.push_pcm_f32(&pcm, channels as u16, rate) |
| 643 | .expect("mp3 pcm"); |
| 644 | enc.finish(); |
| 645 | while enc.next_packet().is_ok() {} |
| 646 | let wall = start.elapsed().as_secs_f64(); |
| 647 | rows.push(Row { |
| 648 | component: "ec-mp3", |
| 649 | direction: "encode", |
| 650 | content: content.clone(), |
| 651 | media: format!("{media_s:.1}s"), |
| 652 | wall_ms: wall * 1000.0, |
| 653 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 654 | }); |
| 655 | } |
| 656 | |
| 657 | |
| 658 | { |
| 659 | let samples: Vec<i32> = pcm |
| 660 | .iter() |
| 661 | .map(|&s| (s.clamp(-1.0, 1.0) * 32767.0) as i32) |
| 662 | .collect(); |
| 663 | let cfg = ec_flac::EncoderConfig::default(); |
| 664 | let start = Instant::now(); |
| 665 | let _ = ec_flac::encode(&cfg, &samples, channels, 16, rate).expect("flac encode"); |
| 666 | let wall = start.elapsed().as_secs_f64(); |
| 667 | rows.push(Row { |
| 668 | component: "ec-flac", |
| 669 | direction: "encode", |
| 670 | content: content.clone(), |
| 671 | media: format!("{media_s:.1}s"), |
| 672 | wall_ms: wall * 1000.0, |
| 673 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 674 | }); |
| 675 | } |
| 676 | |
| 677 | |
| 678 | { |
| 679 | let samples: Vec<i32> = pcm |
| 680 | .iter() |
| 681 | .map(|&s| (s.clamp(-1.0, 1.0) * 32767.0) as i32) |
| 682 | .collect(); |
| 683 | let enc = ec_alac::AlacEncoder::new(rate, channels as u8, 16, 4096).expect("alac encoder"); |
| 684 | let per_frame = 4096 * channels; |
| 685 | let start = Instant::now(); |
| 686 | for chunk in samples.chunks(per_frame) { |
| 687 | let _ = enc.encode_frame(chunk); |
| 688 | } |
| 689 | let wall = start.elapsed().as_secs_f64(); |
| 690 | rows.push(Row { |
| 691 | component: "ec-alac", |
| 692 | direction: "encode", |
| 693 | content: content.clone(), |
| 694 | media: format!("{media_s:.1}s"), |
| 695 | wall_ms: wall * 1000.0, |
| 696 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 697 | }); |
| 698 | } |
| 699 | |
| 700 | |
| 701 | if (1..=6).contains(&channels) && matches!(rate, 48_000 | 44_100 | 32_000) { |
| 702 | let mut enc = ec_ac3::Ac3Encoder::new(ec_ac3::EncoderConfig { |
| 703 | sample_rate: rate, |
| 704 | channels: channels as u16, |
| 705 | bitrate_kbps: 192, |
| 706 | }) |
| 707 | .expect("ac3 encoder"); |
| 708 | let start = Instant::now(); |
| 709 | enc.push_pcm_f32(&pcm).expect("ac3 pcm"); |
| 710 | enc.finish(); |
| 711 | loop { |
| 712 | match enc.next_packet() { |
| 713 | Ok(_) => {} |
| 714 | Err(e) if e.is_eof() => break, |
| 715 | Err(e) => panic!("ac3 encode: {e}"), |
| 716 | } |
| 717 | } |
| 718 | let wall = start.elapsed().as_secs_f64(); |
| 719 | rows.push(Row { |
| 720 | component: "ec-ac3", |
| 721 | direction: "encode", |
| 722 | content, |
| 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 | } else { |
| 728 | rows.push(missing_direction( |
| 729 | "ec-ac3", |
| 730 | "encode", |
| 731 | "source channel/rate combination is not one A/52 codes", |
| 732 | )); |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | |
| 737 | |
| 738 | |
| 739 | |
| 740 | |
| 741 | fn bench_truehd(rows: &mut Vec<Row>) { |
| 742 | let Some((pcm, rate, channels)) = real_pcm(5.0) else { |
| 743 | rows.push(missing("ec-truehd", "encode")); |
| 744 | rows.push(missing("ec-truehd", "decode")); |
| 745 | return; |
| 746 | }; |
| 747 | if channels != 2 || !matches!(rate, 48_000 | 44_100 | 96_000 | 88_200 | 192_000 | 176_400) { |
| 748 | rows.push(missing_direction( |
| 749 | "ec-truehd", |
| 750 | "encode", |
| 751 | "this encoder writes 44.1/48 kHz-family stereo only", |
| 752 | )); |
| 753 | rows.push(missing_direction( |
| 754 | "ec-truehd", |
| 755 | "decode", |
| 756 | "this encoder writes 44.1/48 kHz-family stereo only", |
| 757 | )); |
| 758 | return; |
| 759 | } |
| 760 | let n = pcm.len() / channels; |
| 761 | let media_s = n as f64 / f64::from(rate); |
| 762 | let mut bytes = Vec::with_capacity(pcm.len() * 4); |
| 763 | for &s in &pcm { |
| 764 | let sample = (s.clamp(-1.0, 1.0) * 8_388_607.0) as i32; |
| 765 | bytes.extend_from_slice(&(sample << 8).to_le_bytes()); |
| 766 | } |
| 767 | let frame = AudioFrame::try_new( |
| 768 | SampleFormat::S32, |
| 769 | false, |
| 770 | ChannelLayout::Stereo, |
| 771 | rate, |
| 772 | n, |
| 773 | vec![Buf::from_vec(bytes)], |
| 774 | ) |
| 775 | .expect("audio frame"); |
| 776 | |
| 777 | let mut enc = ec_truehd::TrueHdEncoder::new(rate).expect("truehd encoder"); |
| 778 | let start = Instant::now(); |
| 779 | enc.send_frame(&Frame::Audio(frame)).expect("truehd send"); |
| 780 | enc.flush().expect("truehd flush"); |
| 781 | let mut thd = Vec::new(); |
| 782 | while let Ok(pkt) = enc.receive_packet() { |
| 783 | thd.extend_from_slice(&pkt.data); |
| 784 | } |
| 785 | let wall = start.elapsed().as_secs_f64(); |
| 786 | rows.push(Row { |
| 787 | component: "ec-truehd", |
| 788 | direction: "encode", |
| 789 | content: format!("{media_s:.1}s wav16 stereo @ {rate}Hz"), |
| 790 | media: format!("{media_s:.1}s"), |
| 791 | wall_ms: wall * 1000.0, |
| 792 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 793 | }); |
| 794 | |
| 795 | let mut dec = ec_truehd::TrueHdDecoder::new(); |
| 796 | let start = Instant::now(); |
| 797 | let mut samples = 0u64; |
| 798 | let mut pos = 0usize; |
| 799 | while pos < thd.len() { |
| 800 | let Ok(len) = ec_truehd::frame_length(&thd[pos..]) else { |
| 801 | break; |
| 802 | }; |
| 803 | if len == 0 || pos + len > thd.len() { |
| 804 | break; |
| 805 | } |
| 806 | if let Ok(Some(f)) = dec.decode_access_unit(&thd[pos..pos + len]) { |
| 807 | samples += (f.data[0].len() / 4 / channels) as u64; |
| 808 | } |
| 809 | pos += len; |
| 810 | } |
| 811 | let wall = start.elapsed().as_secs_f64(); |
| 812 | let media_s = samples as f64 / f64::from(rate); |
| 813 | rows.push(Row { |
| 814 | component: "ec-truehd", |
| 815 | direction: "decode", |
| 816 | content: "own encoded stream, stereo".to_string(), |
| 817 | media: format!("{media_s:.1}s"), |
| 818 | wall_ms: wall * 1000.0, |
| 819 | rtf: (wall > 0.0).then_some(media_s / wall), |
| 820 | }); |
| 821 | } |
| 822 | |
| 823 | |
| 824 | |
| 825 | |
| 826 | |
| 827 | |
| 828 | |
| 829 | |
| 830 | fn format_duration(path: &Path) -> Option<String> { |
| 831 | let out = Command::new("ffprobe") |
| 832 | .args(["-v", "error", "-show_entries", "format=duration"]) |
| 833 | .args(["-of", "default=nw=1:nk=1"]) |
| 834 | .arg(path) |
| 835 | .output() |
| 836 | .ok()?; |
| 837 | if !out.status.success() { |
| 838 | return None; |
| 839 | } |
| 840 | let s = String::from_utf8_lossy(&out.stdout).trim().to_string(); |
| 841 | (!s.is_empty() && s != "N/A").then_some(s) |
| 842 | } |
| 843 | |
| 844 | fn bench_container_demux(rows: &mut Vec<Row>) { |
| 845 | for (component, ext) in [("ec-matroska", "mkv"), ("ec-mp4", "mp4")] { |
| 846 | let Some(src) = [fixtures().join("video"), home().join("Videos")] |
| 847 | .into_iter() |
| 848 | .filter_map(|d| std::fs::read_dir(d).ok()) |
| 849 | .flatten() |
| 850 | .flatten() |
| 851 | .map(|e| e.path()) |
| 852 | .filter(|p| p.extension().and_then(|e| e.to_str()) == Some(ext)) |
| 853 | .max_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)) |
| 854 | else { |
| 855 | rows.push(missing(component, "demux")); |
| 856 | continue; |
| 857 | }; |
| 858 | let Ok(mut reader) = Reader::open(&src) else { |
| 859 | rows.push(missing(component, "demux")); |
| 860 | continue; |
| 861 | }; |
| 862 | let file_mb = std::fs::metadata(&src).map(|m| m.len()).unwrap_or(0) as f64 / 1_000_000.0; |
| 863 | let duration_s = [ |
| 864 | ffprobe_field(&src, "v:0", "duration"), |
| 865 | ffprobe_field(&src, "a:0", "duration"), |
| 866 | format_duration(&src), |
| 867 | ] |
| 868 | .into_iter() |
| 869 | .find_map(|s| s.and_then(|s| s.parse::<f64>().ok())) |
| 870 | .unwrap_or(0.0); |
| 871 | let mut packets = 0u64; |
| 872 | let start = Instant::now(); |
| 873 | loop { |
| 874 | match reader.next_packet() { |
| 875 | Ok(_) => packets += 1, |
| 876 | Err(_) => break, |
| 877 | } |
| 878 | } |
| 879 | let wall = start.elapsed().as_secs_f64(); |
| 880 | let name = src.file_name().unwrap().to_string_lossy().into_owned(); |
| 881 | rows.push(Row { |
| 882 | component, |
| 883 | direction: "demux", |
| 884 | content: format!("{name} ({file_mb:.1} MB, {packets} packets)"), |
| 885 | media: format!("{duration_s:.1}s"), |
| 886 | wall_ms: wall * 1000.0, |
| 887 | rtf: (wall > 0.0 && duration_s > 0.0).then_some(duration_s / wall), |
| 888 | }); |
| 889 | } |
| 890 | } |
| 891 | |
| 892 | |
| 893 | |
| 894 | |
| 895 | |
| 896 | |
| 897 | fn bench_image_decode(rows: &mut Vec<Row>) { |
| 898 | let mut candidates: Vec<PathBuf> = Vec::new(); |
| 899 | if let Ok(entries) = std::fs::read_dir(fixtures().join("stills")) { |
| 900 | candidates.extend( |
| 901 | entries |
| 902 | .flatten() |
| 903 | .map(|e| e.path()) |
| 904 | .filter(|p| p.extension().is_some()), |
| 905 | ); |
| 906 | } |
| 907 | for f in [ |
| 908 | "IMG_20260804_170612.jpg", |
| 909 | "drawing-1.png", |
| 910 | "20260722-233942.png", |
| 911 | "giphy.gif", |
| 912 | ] { |
| 913 | let p = home().join("Downloads").join(f); |
| 914 | if p.exists() { |
| 915 | candidates.push(p); |
| 916 | } |
| 917 | } |
| 918 | candidates.sort(); |
| 919 | |
| 920 | for path in candidates { |
| 921 | let Ok(bytes) = std::fs::read(&path) else { |
| 922 | continue; |
| 923 | }; |
| 924 | let mp = bytes.len() as f64 / 1_000_000.0; |
| 925 | let start = Instant::now(); |
| 926 | let Ok(img) = ec_image::decode(&bytes) else { |
| 927 | continue; |
| 928 | }; |
| 929 | let wall_ms = start.elapsed().as_secs_f64() * 1000.0; |
| 930 | let (w, h) = img.dimensions(); |
| 931 | let megapixels = (w as f64 * h as f64) / 1_000_000.0; |
| 932 | let name = path.file_name().unwrap().to_string_lossy().into_owned(); |
| 933 | rows.push(Row { |
| 934 | component: "ec-image", |
| 935 | direction: "decode", |
| 936 | content: format!("{name} ({w}x{h}, {mp:.2} MB coded)"), |
| 937 | media: format!("{megapixels:.2} MP"), |
| 938 | wall_ms, |
| 939 | rtf: (wall_ms > 0.0).then_some(megapixels / (wall_ms / 1000.0)), |
| 940 | }); |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | |
| 945 | |
| 946 | |
| 947 | |
| 948 | fn bench_inflate(rows: &mut Vec<Row>) { |
| 949 | let Some(png) = [ |
| 950 | fixtures().join("stills/gray16.png"), |
| 951 | home().join("Downloads/drawing-1.png"), |
| 952 | ] |
| 953 | .into_iter() |
| 954 | .find(|p| p.exists()) else { |
| 955 | rows.push(missing("ec-inflate", "inflate")); |
| 956 | return; |
| 957 | }; |
| 958 | let Ok(bytes) = std::fs::read(&png) else { |
| 959 | rows.push(missing("ec-inflate", "inflate")); |
| 960 | return; |
| 961 | }; |
| 962 | |
| 963 | |
| 964 | let mut idat = Vec::new(); |
| 965 | let mut i = 8usize; |
| 966 | while i + 8 <= bytes.len() { |
| 967 | let len = u32::from_be_bytes(bytes[i..i + 4].try_into().unwrap()) as usize; |
| 968 | let kind = &bytes[i + 4..i + 8]; |
| 969 | let start = i + 8; |
| 970 | if kind == b"IDAT" && start + len <= bytes.len() { |
| 971 | idat.extend_from_slice(&bytes[start..start + len]); |
| 972 | } |
| 973 | i = start + len + 4; |
| 974 | } |
| 975 | if idat.is_empty() { |
| 976 | rows.push(missing("ec-inflate", "inflate")); |
| 977 | return; |
| 978 | } |
| 979 | let compressed_mb = idat.len() as f64 / 1_000_000.0; |
| 980 | let start = Instant::now(); |
| 981 | let Ok(out) = ec_inflate::inflate_zlib(&idat, 1 << 30) else { |
| 982 | rows.push(missing("ec-inflate", "inflate")); |
| 983 | return; |
| 984 | }; |
| 985 | let wall_ms = start.elapsed().as_secs_f64() * 1000.0; |
| 986 | let out_mb = out.len() as f64 / 1_000_000.0; |
| 987 | rows.push(Row { |
| 988 | component: "ec-inflate", |
| 989 | direction: "inflate", |
| 990 | content: format!( |
| 991 | "{} IDAT stream, {compressed_mb:.2} MB in", |
| 992 | png.file_name().unwrap().to_string_lossy() |
| 993 | ), |
| 994 | media: format!("{out_mb:.2} MB out"), |
| 995 | wall_ms, |
| 996 | rtf: (wall_ms > 0.0).then_some(out_mb / (wall_ms / 1000.0)), |
| 997 | }); |
| 998 | } |
| 999 | |
| 1000 | fn missing(component: &'static str, direction: &'static str) -> Row { |
| 1001 | missing_direction(component, direction, "no real-media candidate found") |
| 1002 | } |
| 1003 | |
| 1004 | fn missing_direction(component: &'static str, direction: &'static str, why: &str) -> Row { |
| 1005 | Row { |
| 1006 | component, |
| 1007 | direction, |
| 1008 | content: why.to_string(), |
| 1009 | media: "-".to_string(), |
| 1010 | wall_ms: 0.0, |
| 1011 | rtf: None, |
| 1012 | } |
| 1013 | } |