//! Standing performance harness: real media in, each codec's own public //! one-shot API exercised, a ranked realtime-factor table out. //! //! Realtime factor = media-seconds decoded (or encoded) per wall-second; //! bigger is faster. ffmpeg/ffprobe are used only to extract elementary //! streams and raw planes and to read duration, exactly as the crates' own //! tests already do -- this binary never decodes anything itself. //! //! Run: `cargo run -p ec-bench --release` #![forbid(unsafe_code)] use std::path::{Path, PathBuf}; use std::process::Command; use std::time::Instant; use ec_av1::encode::Picture as Av1Picture; use ec_av1::encoder::{Av1Encoder, Colour, EncoderConfig as Av1Config, Level, Pyramid}; use ec_core::frame::{ AudioFrame, ChannelLayout, Frame, PixelFormat, Plane, SampleFormat, VideoFrame, }; use ec_core::packet::Buf; use ec_core::registry::{Encoder as CoreEncoder, MediaType}; use ec_h264::{ Decoder as H264Decoder, Encoder as H264Encoder, EncoderConfig as H264Config, NalOutcome, PictureView, }; use ec_h264_syntax::AnnexBIter; use ec_h265::encoder::{Encoder as H265Encoder, EncoderConfig as H265Config}; use ec_probe::Reader; struct Row { component: &'static str, direction: &'static str, content: String, media: String, wall_ms: f64, rtf: Option, } fn main() { let mut rows = Vec::new(); bench_h264(&mut rows); bench_h265_encode(&mut rows); bench_av1_encode(&mut rows); bench_hw_av1_encode(&mut rows); bench_hw_av1_encode_10bit(&mut rows); bench_audio_decode(&mut rows); bench_audio_encode(&mut rows); bench_truehd(&mut rows); bench_container_demux(&mut rows); bench_image_decode(&mut rows); bench_inflate(&mut rows); rows.sort_by(|a, b| { a.rtf .unwrap_or(f64::INFINITY) .partial_cmp(&b.rtf.unwrap_or(f64::INFINITY)) .unwrap() }); println!("| component | direction | content | media | wall ms | realtime factor |"); println!("|---|---|---|---|---|---|"); for r in &rows { let rtf = r .rtf .map_or_else(|| "-".to_string(), |v| format!("{v:.2}x")); println!( "| {} | {} | {} | {} | {:.1} | {} |", r.component, r.direction, r.content, r.media, r.wall_ms, rtf ); } } // --------------------------------------------------------------------------- // media discovery // --------------------------------------------------------------------------- fn fixtures() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") } fn home() -> PathBuf { PathBuf::from(std::env::var("HOME").expect("HOME")) } /// A handful of real-library candidates, largest-effort first, that ffprobe /// confirms carry the wanted video codec. Read-only: never touches the file /// beyond `ffprobe`/`ffmpeg -i ... -o `. fn real_video(codec: &str) -> Option { let roots = [home().join("Videos"), home().join("Downloads")]; let mut found = Vec::new(); for root in roots { let Ok(walker) = std::fs::read_dir(&root) else { continue; }; for entry in walker.flatten() { let p = entry.path(); let Some(ext) = p.extension().and_then(|e| e.to_str()) else { continue; }; if !matches!( ext.to_ascii_lowercase().as_str(), "mp4" | "mkv" | "mov" | "avi" ) { continue; } found.push(p); } } found.sort(); found .into_iter() .find(|p| ffprobe_field(p, "v:0", "codec_name").as_deref() == Some(codec)) } fn ffprobe_field(path: &Path, stream: &str, key: &str) -> Option { let out = Command::new("ffprobe") .args(["-v", "error", "-select_streams", stream, "-show_entries"]) .arg(format!("stream={key}")) .args(["-of", "default=nw=1:nk=1"]) .arg(path) .output() .ok()?; if !out.status.success() { return None; } let s = String::from_utf8_lossy(&out.stdout).trim().to_string(); (!s.is_empty()).then_some(s) } // --------------------------------------------------------------------------- // h264: decode (real film, 10s) + encode (raw planes from the same clip) // --------------------------------------------------------------------------- fn bench_h264(rows: &mut Vec) { let Some(src) = real_video("h264") else { rows.push(missing("ec-h264", "decode")); rows.push(missing("ec-h264", "encode")); return; }; let w: u32 = ffprobe_field(&src, "v:0", "width") .and_then(|s| s.parse().ok()) .unwrap_or(0); let h: u32 = ffprobe_field(&src, "v:0", "height") .and_then(|s| s.parse().ok()) .unwrap_or(0); // decode: 10s Annex-B extract, trimmed inside ffmpeg (never decode-then-trim). let out = Command::new("ffmpeg") .args(["-v", "error", "-t", "10", "-i"]) .arg(&src) .args([ "-an", "-c:v", "copy", "-bsf:v", "h264_mp4toannexb", "-f", "h264", "-", ]) .output() .expect("ffmpeg extract h264"); if out.status.success() && !out.stdout.is_empty() { let bytes = out.stdout; let start = Instant::now(); let mut dec = H264Decoder::new(); let mut frames = 0u64; for nal in AnnexBIter::new(&bytes) { if let Ok(NalOutcome::PictureBoundary) = dec.push_nal(nal) { let _ = dec.end_picture(); let _ = dec.push_nal(nal); } while dec.next_frame().is_some() { frames += 1; } } let _ = dec.flush(); while dec.next_frame().is_some() { frames += 1; } let wall = start.elapsed().as_secs_f64(); let fps = ffprobe_field(&src, "v:0", "r_frame_rate") .and_then(|s| parse_ratio(&s)) .unwrap_or(25.0); let media_s = frames as f64 / fps; rows.push(Row { component: "ec-h264", direction: "decode", content: format!("{w}x{h} film, {frames} frames"), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } else { rows.push(missing("ec-h264", "decode")); } // encode: 30 raw yuv420p frames scaled to 640x360 from the same clip. let (planes, ew, eh, n) = extract_yuv420p(&src, 640, 360, 30); if n > 0 { let mut cfg = H264Config::new(ew, eh); cfg.threads = 1; // one worker: single-core cost, not a parallelism claim let mut enc = H264Encoder::new(cfg).expect("h264 encoder"); let frame_len = (ew * eh + 2 * (ew.div_ceil(2) * eh.div_ceil(2))) as usize; let start = Instant::now(); for frame in planes.chunks_exact(frame_len) { let (y, rest) = frame.split_at((ew * eh) as usize); let (u, v) = rest.split_at(rest.len() / 2); let view = PictureView::i420(ew, eh, y, u, v); enc.encode(&view).expect("h264 encode"); } let wall = start.elapsed().as_secs_f64(); let media_s = n as f64 / 30.0; rows.push(Row { component: "ec-h264", direction: "encode", content: format!("{ew}x{eh}, {n} frames, 1 thread"), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } else { rows.push(missing("ec-h264", "encode")); } } /// `n` progressive frames of raw I420 at `w x h`, scaled and trimmed inside /// ffmpeg. fn extract_yuv420p(src: &Path, w: u32, h: u32, n: u32) -> (Vec, u32, u32, u32) { let out = Command::new("ffmpeg") .args(["-v", "error", "-i"]) .arg(src) .args([ "-vf", &format!("scale={w}:{h}"), "-frames:v", &n.to_string(), "-pix_fmt", "yuv420p", "-f", "rawvideo", "-", ]) .output() .expect("ffmpeg extract yuv420p"); if !out.status.success() || out.stdout.is_empty() { return (Vec::new(), w, h, 0); } let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; let frames = (out.stdout.len() / frame_len) as u32; (out.stdout, w, h, frames) } fn parse_ratio(s: &str) -> Option { let (n, d) = s.split_once('/')?; let (n, d) = (n.parse::().ok()?, d.parse::().ok()?); (d != 0.0).then_some(n / d) } // --------------------------------------------------------------------------- // h265: encode, then software-decode the encoded stream back. // --------------------------------------------------------------------------- fn bench_h265_encode(rows: &mut Vec) { let Some(src) = real_video("h264").or_else(|| real_video("hevc")) else { rows.push(missing("ec-h265", "decode")); rows.push(missing("ec-h265", "encode")); return; }; let (planes, w, h, n) = extract_yuv420p(&src, 640, 360, 10); if n == 0 { rows.push(missing("ec-h265", "encode")); rows.push(missing("ec-h265", "decode")); return; } let mut cfg = H265Config::new(w, h); // A/B knob for the RDOQ estimated-bit-cost path (off by default, matching // the encoder's own default): EC_H265_RDOQ_ESTIMATE=1 to measure it. cfg.rdoq_estimate = std::env::var("EC_H265_RDOQ_ESTIMATE").is_ok_and(|v| v != "0"); let enc = H265Encoder::new(cfg).expect("h265 encoder"); let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; let cw = w.div_ceil(2); let ch = h.div_ceil(2); let mut aus = Vec::new(); let start = Instant::now(); for frame in planes.chunks_exact(frame_len) { let (y, rest) = frame.split_at((w * h) as usize); let (u, v) = rest.split_at(rest.len() / 2); let vf = VideoFrame::try_new( PixelFormat::I420, w, h, vec![ Plane::new(y.to_vec(), w as usize), Plane::new(u.to_vec(), cw as usize), Plane::new(v.to_vec(), cw as usize), ], ) .expect("i420 frame"); let _ = ch; // silence unused if plane_geometry ignores it aus.push(enc.encode_idr(&vf).expect("h265 encode").au); } let wall = start.elapsed().as_secs_f64(); let media_s = n as f64 / 30.0; rows.push(Row { component: "ec-h265", direction: "encode", content: format!("{w}x{h}, {n} frames, IDR-only"), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); let start = Instant::now(); for au in &aus { ec_h265::decode::decode_idr_au(au).expect("h265 decode"); } let wall = start.elapsed().as_secs_f64(); rows.push(Row { component: "ec-h265", direction: "decode", content: format!("{w}x{h}, {n} frames, own IDR stream"), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } // --------------------------------------------------------------------------- // hardware av1: the GPU encoder, at the size his library is in. // --------------------------------------------------------------------------- /// AV1 encode on the GPU (`ec-hw`, VA-API). Skips as a row rather than a /// failure when there is no VA device or the driver has no AV1 encode /// entrypoint -- a machine without one is not a slow machine. fn bench_hw_av1_encode(rows: &mut Vec) { let Some(src) = real_video("h264").or_else(|| real_video("hevc")) else { rows.push(missing("ec-hw av1", "encode")); return; }; let display = match ec_va::open() { Ok(display) => display, Err(e) => { rows.push(missing_direction("ec-hw av1", "encode", &format!("no VA display ({e})"))); return; } }; let (planes, w, h, n) = extract_yuv420p(&src, 1920, 1080, 30); if n == 0 { rows.push(missing("ec-hw av1", "encode")); return; } let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h); cfg.rate_control = ec_hw::RateControlMode::ConstantQp { qp: 120 }; let mut enc = match ec_hw::Encoder::new(&display, cfg) { Ok(enc) => enc, Err(e) => { rows.push(missing_direction("ec-hw av1", "encode", &format!("driver refused ({e})"))); return; } }; let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); let frame_len = (w * h + 2 * cw * ch) as usize; let start = Instant::now(); let mut coded = 0usize; for (i, frame) in planes.chunks_exact(frame_len).enumerate() { let (y, rest) = frame.split_at((w * h) as usize); let (u, v) = rest.split_at(rest.len() / 2); let picture = ec_hw::I420 { y: y.to_vec(), u: u.to_vec(), v: v.to_vec(), width: w, height: h, }; let meta = ec_hw::FrameMetadata { timestamp: i as i64, force_keyframe: false, }; match enc.encode(&picture, meta) { Ok(out) => coded += out.data.len(), Err(e) => { rows.push(missing_direction("ec-hw av1", "encode", &format!("encode failed ({e})"))); return; } } } let wall = start.elapsed().as_secs_f64(); let media_s = n as f64 / 30.0; rows.push(Row { component: "ec-hw av1", direction: "encode", content: format!("{w}x{h}, {n} frames, CQP 120, {} kB", coded / 1000), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } /// The same row at 10 bits, which is the depth his own AV1 library is stored /// at (`yuv420p10le`, both films). Skips as a row when there is no VA device, /// no AV1 encode entrypoint, or no source to read. fn bench_hw_av1_encode_10bit(rows: &mut Vec) { let Some(src) = real_video("av1").or_else(|| real_video("hevc")).or_else(|| real_video("h264")) else { rows.push(missing("ec-hw av1 10-bit", "encode")); return; }; let display = match ec_va::open() { Ok(display) => display, Err(e) => { rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("no VA display ({e})"))); return; } }; let (w, h) = (1920u32, 1080u32); let raw = extract_yuv420p10(&src, w, h, 30); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); let frame_len = ((w * h + 2 * cw * ch) * 2) as usize; let n = (raw.len() / frame_len) as u32; if n == 0 { rows.push(missing("ec-hw av1 10-bit", "encode")); return; } let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h).ten_bit(); cfg.rate_control = ec_hw::RateControlMode::ConstantQp { qp: 120 }; let mut enc = match ec_hw::Encoder::new(&display, cfg) { Ok(enc) => enc, Err(e) => { rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("driver refused ({e})"))); return; } }; let read = |s: &[u8]| -> Vec { s.as_chunks::<2>().0.iter().map(|p| u16::from_le_bytes([p[0], p[1]])).collect() }; let start = Instant::now(); let mut coded = 0usize; for (i, frame) in raw.chunks_exact(frame_len).enumerate() { let (y, rest) = frame.split_at((w * h * 2) as usize); let (u, v) = rest.split_at(rest.len() / 2); let picture = ec_hw::I420_16 { y: read(y), u: read(u), v: read(v), width: w, height: h, bit_depth: 10, }; let meta = ec_hw::FrameMetadata { timestamp: i as i64, force_keyframe: false }; match enc.encode_16(&picture, meta) { Ok(out) => coded += out.data.len(), Err(e) => { rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("encode failed ({e})"))); return; } } } let wall = start.elapsed().as_secs_f64(); let media_s = f64::from(n) / 30.0; rows.push(Row { component: "ec-hw av1 10-bit", direction: "encode", content: format!("{w}x{h} yuv420p10le, {n} frames from 00:01:00, CQP 120, {} kB", coded / 1000), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } /// `extract_yuv420p` at ten bits, planar 16-bit little endian, seeked a /// minute in: frame 0 of a film is its black leader, and a black leader codes /// to nothing and benchmarks nothing. fn extract_yuv420p10(src: &Path, w: u32, h: u32, n: u32) -> Vec { let out = Command::new("ffmpeg") .args(["-v", "error", "-ss", "60", "-i"]) .arg(src) .args([ "-vf", &format!("scale={w}:{h}"), "-frames:v", &n.to_string(), "-pix_fmt", "yuv420p10le", "-f", "rawvideo", "-", ]) .output() .expect("ffmpeg extract yuv420p10le"); if !out.status.success() { return Vec::new(); } out.stdout } // --------------------------------------------------------------------------- // av1: encode only -- same shape as h265. // --------------------------------------------------------------------------- fn bench_av1_encode(rows: &mut Vec) { let Some(src) = real_video("h264") else { rows.push(missing("ec-av1", "encode")); rows.push(missing("ec-av1", "decode")); return; }; // AV1's block grid is 32x32 superblocks: pick a size already a multiple of it. let (planes, w, h, n) = extract_yuv420p(&src, 640, 384, 10); if n == 0 { rows.push(missing("ec-av1", "encode")); rows.push(missing("ec-av1", "decode")); return; } // `EC_AV1_TILES=[:]` benches the encoder's tile // grid (spec 5.9.15's uniform spacing): `1:0` is two tile columns, `1:1` // a 2x2 grid. Unset keeps the one-tile default, whose bytes are the ones // the byte pins carry. `EC_AV1_TILE_THREADS=` (read by `ec_av1::par`) // spreads those tiles across `n` pool workers; the bytes are the same // either way, only the wall changes. let (tile_cols_log2, tile_rows_log2) = std::env::var("EC_AV1_TILES") .ok() .and_then(|spec| { let mut f = spec.split(':'); let cols = f.next()?.parse().ok()?; Some((cols, f.next().and_then(|v| v.parse().ok()).unwrap_or(0))) }) .unwrap_or((0, 0)); // One row per SPEED PRESET (`ec_av1::speed`): 0 is the full search every // byte pin carries, 10 the fastest. `EC_AV1_SPEED=` benches a single // preset instead of the ladder. let presets: Vec = match std::env::var("EC_AV1_SPEED").ok().and_then(|v| v.parse().ok()) { Some(n) => vec![n], None => vec![0, 3, 6, 10], }; let mut first_stream = Vec::new(); for &speed in &presets { let cfg = Av1Config { width: w as usize, height: h as usize, base_q_idx: 100, gop: 10, colour: Colour::default(), tile_cols_log2, tile_rows_log2, }; // The encoder's coding pyramid (hidden ALTREF + show_existing_frame) is // the default, as it is in `encode_sequence`; `EC_AV1_PYRAMID=0` benches // the flat one-picture-one-packet stream instead, and // `EC_AV1_PYRAMID=[::]` another // shape of it. The `hidden` column below is how many frames of the row // were coded ahead of their display position. let pyramid = Pyramid::from_env(); ec_av1::speed::set_speed(speed); let mut enc = match pyramid { None => Av1Encoder::with_speed(cfg, speed).expect("av1 encoder"), Some(p) => Av1Encoder::with_pyramid(cfg, p).expect("av1 encoder"), }; let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; let mut stream = Vec::new(); let mut hidden = 0usize; let start = Instant::now(); for frame in planes.chunks_exact(frame_len) { let (y, rest) = frame.split_at((w * h) as usize); let (u, v) = rest.split_at(rest.len() / 2); let pic = Av1Picture { width: w as usize, height: h as usize, // ec-av1's Picture carries u16 samples since the high-bit-depth // widen; this bench feeds 8-bit y4m, so widen each plane here. y: y.iter().map(|&s| u16::from(s)).collect(), u: u.iter().map(|&s| u16::from(s)).collect(), v: v.iter().map(|&s| u16::from(s)).collect(), }; for packet in enc.encode_frames(&pic).expect("av1 encode") { hidden += usize::from(packet.level == Level::Arf); stream.extend_from_slice(&packet.data); } } for packet in enc.flush().expect("av1 flush") { hidden += usize::from(packet.level == Level::Arf); stream.extend_from_slice(&packet.data); } let wall = start.elapsed().as_secs_f64(); // What the content gate left this clip coding under: a screen-content // source asks for the pyramid and codes flat, and then `hidden` is 0 for // a reason the row itself names. let coded_under = match (pyramid, enc.pyramid()) { (_, Some(p)) => format!("pyramid {}:{}:{}", p.mini_gop, p.arf_q_offset, p.leaf_q_offset), (Some(_), None) => "flat (gated: screen content)".to_string(), (None, None) => "flat".to_string(), }; let media_s = n as f64 / 30.0; let levers = match ec_av1::speed::levers(speed) { v if v.is_empty() => "full search".to_string(), v => v.join(", "), }; let fps = if wall > 0.0 { f64::from(n) / wall } else { 0.0 }; let bytes_per_frame = stream.len() as f64 / f64::from(n); rows.push(Row { component: "ec-av1", direction: "encode", content: format!( "speed {speed} [{levers}], {w}x{h}, {n} frames, gop=10, {coded_under}, \ {hidden} hidden, {fps:.1} fps, {bytes_per_frame:.0} B/frame" ), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); if first_stream.is_empty() { first_stream = stream; } } // The decode row reads the FIRST preset's stream, so the number stays // comparable across runs of this bench. ec_av1::speed::set_speed(0); let stream = first_stream; let media_s = n as f64 / 30.0; let start = Instant::now(); let pictures = ec_av1::stream::decode_stream(&stream).expect("av1 decode_stream"); let wall = start.elapsed().as_secs_f64(); assert_eq!(pictures.len(), n as usize, "decode_stream frame count"); rows.push(Row { component: "ec-av1", direction: "decode", content: format!("{w}x{h}, {n} frames, gop=10"), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } // --------------------------------------------------------------------------- // audio decode: one loop over ec-probe's unified reader covers every codec // it wraps (mp3/flac/aac/alac/ac3/truehd/opus/vorbis via ogg/mp4/matroska). // --------------------------------------------------------------------------- fn bench_audio_decode(rows: &mut Vec) { let mut candidates: Vec = Vec::new(); if let Ok(entries) = std::fs::read_dir(fixtures().join("audio")) { candidates.extend(entries.flatten().map(|e| e.path())); } // Real-library samples: mp3 and wav are on disk; ac3 lives inside the // ReelT mux (5.1 AC-3), extracted as its own elementary file. for f in ["8a3b6d1d19.mp3", "test.wav"] { let p = home().join("Downloads").join(f); if p.exists() { candidates.push(p); } } if let Some(src) = real_video("h264") && ffprobe_field(&src, "a:0", "codec_name").as_deref() == Some("ac3") { let out = Command::new("ffmpeg") .args(["-v", "error", "-t", "10", "-i"]) .arg(&src) .args(["-vn", "-c:a", "copy", "-f", "ac3"]) .arg( Path::new(&std::env::var("HOME").unwrap()) .join(".cache/bench-media/sample.ac3"), ) .output(); if let Ok(o) = out && o.status.success() { candidates.push(home().join(".cache/bench-media/sample.ac3")); } } candidates.sort(); candidates.dedup(); for path in candidates { let Ok(mut reader) = Reader::open(&path) else { continue; }; let Some(stream) = reader.default_stream(MediaType::Audio).map(|s| s.index) else { continue; }; let Ok(mut dec) = reader.make_decoder(stream) else { continue; }; let codec = format!("{:?}", dec.codec()); let mut samples = 0u64; let start = Instant::now(); let mut out = Vec::new(); loop { match reader.next_packet() { Ok(pkt) if pkt.stream == stream => { out.clear(); if dec.decode(&pkt, &mut out).is_ok() { samples += (out.len() / dec.channels().max(1)) as u64; } } Ok(_) => {} Err(_) => break, } } let _ = dec.flush(&mut out); let wall = start.elapsed().as_secs_f64(); let media_s = samples as f64 / dec.sample_rate().max(1) as f64; let name = path.file_name().unwrap().to_string_lossy().into_owned(); rows.push(Row { component: Box::leak(format!("ec-probe/{codec}").into_boxed_str()), direction: "decode", content: name, media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0 && media_s > 0.0).then_some(media_s / wall), }); } } // --------------------------------------------------------------------------- // audio encode: real, decoded PCM (the same WAV fixture the decode rows // already read, run back through `AudioDecoder`'s own PCM path) fed to each // crate's own encoder at its default/representative settings. // --------------------------------------------------------------------------- /// `seconds` of real interleaved `f32` PCM, decoded through `ec-probe`'s own /// `Reader`/`AudioDecoder` route (the same one `bench_audio_decode` drives). fn real_pcm(seconds: f64) -> Option<(Vec, u32, usize)> { let path = fixtures().join("audio/wav16-stereo-48000.wav"); let mut reader = Reader::open(&path).ok()?; let stream = reader.default_stream(MediaType::Audio)?.index; let mut dec = reader.make_decoder(stream).ok()?; let channels = dec.channels(); let rate = dec.sample_rate(); let want = (seconds * f64::from(rate)) as usize * channels; let mut pcm = Vec::new(); let mut out = Vec::new(); while pcm.len() < want { match reader.next_packet() { Ok(pkt) if pkt.stream == stream => { if dec.decode(&pkt, &mut out).is_ok() { pcm.extend_from_slice(&out); } } Ok(_) => {} Err(_) => break, } } pcm.truncate(want - want % channels); (!pcm.is_empty()).then_some((pcm, rate, channels)) } fn bench_audio_encode(rows: &mut Vec) { let Some((pcm, rate, channels)) = real_pcm(5.0) else { for name in ["opus", "vorbis", "aac", "mp3", "flac", "alac", "ac3"] { rows.push(missing( Box::leak(format!("ec-{name}").into_boxed_str()), "encode", )); } return; }; let frames = pcm.len() / channels; let media_s = frames as f64 / f64::from(rate); let content = format!("{media_s:.1}s wav16 {channels}ch @ {rate}Hz"); // opus: 20ms frames at the input rate, dropping a short tail frame. { let frame_size = rate as usize / 50; let mut enc = ec_opus::Encoder::new(rate, channels, ec_opus::Application::Audio) .expect("opus encoder"); let mut out = vec![0u8; 4000]; let start = Instant::now(); for chunk in pcm.chunks_exact(frame_size * channels) { enc.encode_float(chunk, frame_size, &mut out) .expect("opus encode"); } let wall = start.elapsed().as_secs_f64(); rows.push(Row { component: "ec-opus", direction: "encode", content: content.clone(), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } // vorbis: quality 0.6, the level the oracle tests already encode at. { let mut enc = ec_vorbis::VorbisEncoder::new(ec_vorbis::EncoderConfig { sample_rate: rate, channels: channels as u16, bitrate_bps: 0, quality: 0.6, }) .expect("vorbis encoder"); let start = Instant::now(); enc.push_interleaved(&pcm).expect("vorbis push"); enc.finish(); let mut n = 0usize; loop { match enc.next_packet() { Ok(p) => n += p.data.len(), Err(e) if e.is_eof() => break, Err(e) => panic!("vorbis encode: {e}"), } } let wall = start.elapsed().as_secs_f64(); let _ = n; rows.push(Row { component: "ec-vorbis", direction: "encode", content: content.clone(), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } // aac: 128 kbit/s, raw (no ADTS wrap) -- the default config. { let mut enc = ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig::default()); let start = Instant::now(); enc.push_pcm(&pcm, channels as u16, rate).expect("aac pcm"); enc.finish(); while enc.next_packet().is_ok() {} let wall = start.elapsed().as_secs_f64(); rows.push(Row { component: "ec-aac", direction: "encode", content: content.clone(), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } // mp3: CBR 192 kbit/s, the incumbent-matching default the tests gate on. { let mut enc = ec_mp3::Mp3Encoder::new(ec_mp3::Mp3EncoderConfig { bitrate_kbps: 192, vbr_quality: None, }); let start = Instant::now(); enc.push_pcm_f32(&pcm, channels as u16, rate) .expect("mp3 pcm"); enc.finish(); while enc.next_packet().is_ok() {} let wall = start.elapsed().as_secs_f64(); rows.push(Row { component: "ec-mp3", direction: "encode", content: content.clone(), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } // flac: single-shot, default config (4096-sample blocks, LPC-12), 16-bit. { let samples: Vec = pcm .iter() .map(|&s| (s.clamp(-1.0, 1.0) * 32767.0) as i32) .collect(); let cfg = ec_flac::EncoderConfig::default(); let start = Instant::now(); let _ = ec_flac::encode(&cfg, &samples, channels, 16, rate).expect("flac encode"); let wall = start.elapsed().as_secs_f64(); rows.push(Row { component: "ec-flac", direction: "encode", content: content.clone(), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } // alac: 4096-sample frames, 16-bit -- same shape the round-trip tests use. { let samples: Vec = pcm .iter() .map(|&s| (s.clamp(-1.0, 1.0) * 32767.0) as i32) .collect(); let enc = ec_alac::AlacEncoder::new(rate, channels as u8, 16, 4096).expect("alac encoder"); let per_frame = 4096 * channels; let start = Instant::now(); for chunk in samples.chunks(per_frame) { let _ = enc.encode_frame(chunk); } let wall = start.elapsed().as_secs_f64(); rows.push(Row { component: "ec-alac", direction: "encode", content: content.clone(), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } // ac3: 192 kbit/s -- only if the source's channel count is one A/52 codes. if (1..=6).contains(&channels) && matches!(rate, 48_000 | 44_100 | 32_000) { let mut enc = ec_ac3::Ac3Encoder::new(ec_ac3::EncoderConfig { sample_rate: rate, channels: channels as u16, bitrate_kbps: 192, }) .expect("ac3 encoder"); let start = Instant::now(); enc.push_pcm_f32(&pcm).expect("ac3 pcm"); enc.finish(); loop { match enc.next_packet() { Ok(_) => {} Err(e) if e.is_eof() => break, Err(e) => panic!("ac3 encode: {e}"), } } let wall = start.elapsed().as_secs_f64(); rows.push(Row { component: "ec-ac3", direction: "encode", content, media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } else { rows.push(missing_direction( "ec-ac3", "encode", "source channel/rate combination is not one A/52 codes", )); } } // --------------------------------------------------------------------------- // truehd: no fixture stream exists yet, so this round-trips the new encoder // through its own decoder, same shape as ec-h265's own-stream decode row. // --------------------------------------------------------------------------- fn bench_truehd(rows: &mut Vec) { let Some((pcm, rate, channels)) = real_pcm(5.0) else { rows.push(missing("ec-truehd", "encode")); rows.push(missing("ec-truehd", "decode")); return; }; if channels != 2 || !matches!(rate, 48_000 | 44_100 | 96_000 | 88_200 | 192_000 | 176_400) { rows.push(missing_direction( "ec-truehd", "encode", "this encoder writes 44.1/48 kHz-family stereo only", )); rows.push(missing_direction( "ec-truehd", "decode", "this encoder writes 44.1/48 kHz-family stereo only", )); return; } let n = pcm.len() / channels; let media_s = n as f64 / f64::from(rate); let mut bytes = Vec::with_capacity(pcm.len() * 4); for &s in &pcm { let sample = (s.clamp(-1.0, 1.0) * 8_388_607.0) as i32; bytes.extend_from_slice(&(sample << 8).to_le_bytes()); } let frame = AudioFrame::try_new( SampleFormat::S32, false, ChannelLayout::Stereo, rate, n, vec![Buf::from_vec(bytes)], ) .expect("audio frame"); let mut enc = ec_truehd::TrueHdEncoder::new(rate).expect("truehd encoder"); let start = Instant::now(); enc.send_frame(&Frame::Audio(frame)).expect("truehd send"); enc.flush().expect("truehd flush"); let mut thd = Vec::new(); while let Ok(pkt) = enc.receive_packet() { thd.extend_from_slice(&pkt.data); } let wall = start.elapsed().as_secs_f64(); rows.push(Row { component: "ec-truehd", direction: "encode", content: format!("{media_s:.1}s wav16 stereo @ {rate}Hz"), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); let mut dec = ec_truehd::TrueHdDecoder::new(); let start = Instant::now(); let mut samples = 0u64; let mut pos = 0usize; while pos < thd.len() { let Ok(len) = ec_truehd::frame_length(&thd[pos..]) else { break; }; if len == 0 || pos + len > thd.len() { break; } if let Ok(Some(f)) = dec.decode_access_unit(&thd[pos..pos + len]) { samples += (f.data[0].len() / 4 / channels) as u64; } pos += len; } let wall = start.elapsed().as_secs_f64(); let media_s = samples as f64 / f64::from(rate); rows.push(Row { component: "ec-truehd", direction: "decode", content: "own encoded stream, stereo".to_string(), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); } // --------------------------------------------------------------------------- // container demux: whole-file `ec-matroska`/`ec-mp4` packet reads (through // `ec-probe`'s own container routing) over real muxes already on disk. // --------------------------------------------------------------------------- /// Container-level duration (`format=duration`), for a mux whose per-stream /// packets carry no duration field of their own (some Matroska tracks don't). fn format_duration(path: &Path) -> Option { let out = Command::new("ffprobe") .args(["-v", "error", "-show_entries", "format=duration"]) .args(["-of", "default=nw=1:nk=1"]) .arg(path) .output() .ok()?; if !out.status.success() { return None; } let s = String::from_utf8_lossy(&out.stdout).trim().to_string(); (!s.is_empty() && s != "N/A").then_some(s) } fn bench_container_demux(rows: &mut Vec) { for (component, ext) in [("ec-matroska", "mkv"), ("ec-mp4", "mp4")] { let Some(src) = [fixtures().join("video"), home().join("Videos")] .into_iter() .filter_map(|d| std::fs::read_dir(d).ok()) .flatten() .flatten() .map(|e| e.path()) .filter(|p| p.extension().and_then(|e| e.to_str()) == Some(ext)) .max_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)) else { rows.push(missing(component, "demux")); continue; }; let Ok(mut reader) = Reader::open(&src) else { rows.push(missing(component, "demux")); continue; }; let file_mb = std::fs::metadata(&src).map(|m| m.len()).unwrap_or(0) as f64 / 1_000_000.0; let duration_s = [ ffprobe_field(&src, "v:0", "duration"), ffprobe_field(&src, "a:0", "duration"), format_duration(&src), ] .into_iter() .find_map(|s| s.and_then(|s| s.parse::().ok())) .unwrap_or(0.0); let mut packets = 0u64; let start = Instant::now(); while reader.next_packet().is_ok() { packets += 1; } let wall = start.elapsed().as_secs_f64(); let name = src.file_name().unwrap().to_string_lossy().into_owned(); rows.push(Row { component, direction: "demux", content: format!("{name} ({file_mb:.1} MB, {packets} packets)"), media: format!("{duration_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0 && duration_s > 0.0).then_some(duration_s / wall), }); } } // --------------------------------------------------------------------------- // images: one decode entry point (`ec_image::decode`) covers every format // the crate sniffs, so every real-library still is a candidate. // --------------------------------------------------------------------------- fn bench_image_decode(rows: &mut Vec) { let mut candidates: Vec = Vec::new(); let stills = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/ec-image/tests/data/stills"); if let Ok(entries) = std::fs::read_dir(stills) { candidates.extend( entries .flatten() .map(|e| e.path()) .filter(|p| p.extension().is_some()), ); } for f in [ "IMG_20260804_170612.jpg", "drawing-1.png", "20260722-233942.png", "giphy.gif", ] { let p = home().join("Downloads").join(f); if p.exists() { candidates.push(p); } } candidates.sort(); for path in candidates { let Ok(bytes) = std::fs::read(&path) else { continue; }; let mp = bytes.len() as f64 / 1_000_000.0; let start = Instant::now(); let Ok(img) = ec_image::decode(&bytes) else { continue; }; let wall_ms = start.elapsed().as_secs_f64() * 1000.0; let (w, h) = img.dimensions(); let megapixels = (w as f64 * h as f64) / 1_000_000.0; let name = path.file_name().unwrap().to_string_lossy().into_owned(); rows.push(Row { component: "ec-image", direction: "decode", content: format!("{name} ({w}x{h}, {mp:.2} MB coded)"), media: format!("{megapixels:.2} MP"), wall_ms, rtf: (wall_ms > 0.0).then_some(megapixels / (wall_ms / 1000.0)), }); } } // --------------------------------------------------------------------------- // ec-inflate: the zlib stream a real PNG's IDAT chain already carries. // --------------------------------------------------------------------------- fn bench_inflate(rows: &mut Vec) { let Some(png) = [ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/ec-image/tests/data/stills/gray16.png"), home().join("Downloads/drawing-1.png"), ] .into_iter() .find(|p| p.exists()) else { rows.push(missing("ec-inflate", "inflate")); return; }; let Ok(bytes) = std::fs::read(&png) else { rows.push(missing("ec-inflate", "inflate")); return; }; // Concatenate every IDAT chunk's payload: that byte string is exactly the // zlib stream `ec_image`'s own PNG path hands to `ec_inflate`. let mut idat = Vec::new(); let mut i = 8usize; // past the PNG signature while i + 8 <= bytes.len() { let len = u32::from_be_bytes(bytes[i..i + 4].try_into().unwrap()) as usize; let kind = &bytes[i + 4..i + 8]; let start = i + 8; if kind == b"IDAT" && start + len <= bytes.len() { idat.extend_from_slice(&bytes[start..start + len]); } i = start + len + 4; // skip CRC } if idat.is_empty() { rows.push(missing("ec-inflate", "inflate")); return; } let compressed_mb = idat.len() as f64 / 1_000_000.0; let start = Instant::now(); let Ok(out) = ec_inflate::inflate_zlib(&idat, 1 << 30) else { rows.push(missing("ec-inflate", "inflate")); return; }; let wall_ms = start.elapsed().as_secs_f64() * 1000.0; let out_mb = out.len() as f64 / 1_000_000.0; rows.push(Row { component: "ec-inflate", direction: "inflate", content: format!( "{} IDAT stream, {compressed_mb:.2} MB in", png.file_name().unwrap().to_string_lossy() ), media: format!("{out_mb:.2} MB out"), wall_ms, rtf: (wall_ms > 0.0).then_some(out_mb / (wall_ms / 1000.0)), }); } fn missing(component: &'static str, direction: &'static str) -> Row { missing_direction(component, direction, "no real-media candidate found") } fn missing_direction(component: &'static str, direction: &'static str, why: &str) -> Row { Row { component, direction, content: why.to_string(), media: "-".to_string(), wall_ms: 0.0, rtf: None, } }