forge
Explore
Log in

Don't you dare go Hollow

Standing realtime-factor harness across every codec crate

Browse files at this commit

4d8621c755d1f6e7d03ccdae1bc735a1a09ae897Ahmet Kaan GümüşParent: f44b458
  • feat
    • standing realtime-factor harness across every codec crate
Show full message
feat(bench): standing realtime-factor harness across every codec crate

One new bin (tools/ec-bench) that drives each crate's own public one-shot
API against real media (h264/h265/av1 video, aac/mp3/opus/vorbis/flac/alac
audio via ec-probe's unified reader) and prints a ranked markdown table —
the baseline every future optimization lane measures against.
Cargo.lockmodified+12 -0
@@ -272,6 +272,18 @@ dependencies = [
272272 "ec-core",
273273 ]
274274
275+[[package]]
276+name = "ec-bench"
277+version = "0.1.0"
278+dependencies = [
279+ "ec-av1",
280+ "ec-core",
281+ "ec-h264",
282+ "ec-h264-syntax",
283+ "ec-h265",
284+ "ec-probe",
285+]
286+
275287 [[package]]
276288 name = "ec-core"
277289 version = "0.1.0"
tools/ec-bench/Cargo.tomladded+22 -0
@@ -0,0 +1,22 @@
1+[package]
2+name = "ec-bench"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+authors.workspace = true
7+publish = false
8+
9+[[bin]]
10+name = "ec-bench"
11+path = "src/main.rs"
12+
13+# Standing performance harness: real media -> each codec's public one-shot
14+# API -> a ranked realtime-factor table. Drives ffmpeg/ffprobe as a child
15+# process for extraction and duration only, same as the crates' own tests.
16+[dependencies]
17+ec-core = { workspace = true }
18+ec-h264 = { workspace = true }
19+ec-h265 = { workspace = true }
20+ec-av1 = { workspace = true }
21+ec-probe = { workspace = true }
22+ec-h264-syntax = { workspace = true }
tools/ec-bench/src/main.rsadded+455 -0
@@ -0,0 +1,455 @@
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+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};
17+use ec_core::frame::{PixelFormat, Plane, VideoFrame};
18+use ec_core::registry::MediaType;
19+use ec_h264::{
20+ Decoder as H264Decoder, Encoder as H264Encoder, EncoderConfig as H264Config, NalOutcome,
21+ PictureView,
22+};
23+use ec_h264_syntax::AnnexBIter;
24+use ec_h265::encoder::{Encoder as H265Encoder, EncoderConfig as H265Config};
25+use ec_probe::Reader;
26+
27+struct Row {
28+ component: &'static str,
29+ direction: &'static str,
30+ content: String,
31+ media: String,
32+ wall_ms: f64,
33+ rtf: Option<f64>,
34+}
35+
36+fn main() {
37+ let mut rows = Vec::new();
38+
39+ bench_h264(&mut rows);
40+ bench_h265_encode(&mut rows);
41+ bench_av1_encode(&mut rows);
42+ bench_audio_decode(&mut rows);
43+
44+ rows.sort_by(|a, b| {
45+ a.rtf
46+ .unwrap_or(f64::INFINITY)
47+ .partial_cmp(&b.rtf.unwrap_or(f64::INFINITY))
48+ .unwrap()
49+ });
50+
51+ println!("| component | direction | content | media | wall ms | realtime factor |");
52+ println!("|---|---|---|---|---|---|");
53+ for r in &rows {
54+ let rtf = r
55+ .rtf
56+ .map_or_else(|| "-".to_string(), |v| format!("{v:.2}x"));
57+ println!(
58+ "| {} | {} | {} | {} | {:.1} | {} |",
59+ r.component, r.direction, r.content, r.media, r.wall_ms, rtf
60+ );
61+ }
62+}
63+
64+// ---------------------------------------------------------------------------
65+// media discovery
66+// ---------------------------------------------------------------------------
67+
68+fn fixtures() -> PathBuf {
69+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
70+}
71+
72+fn home() -> PathBuf {
73+ PathBuf::from(std::env::var("HOME").expect("HOME"))
74+}
75+
76+/// A handful of real-library candidates, largest-effort first, that ffprobe
77+/// confirms carry the wanted video codec. Read-only: never touches the file
78+/// beyond `ffprobe`/`ffmpeg -i ... -o <scratch>`.
79+fn real_video(codec: &str) -> Option<PathBuf> {
80+ let roots = [home().join("Videos"), home().join("Downloads")];
81+ let mut found = Vec::new();
82+ for root in roots {
83+ let Ok(walker) = std::fs::read_dir(&root) else {
84+ continue;
85+ };
86+ for entry in walker.flatten() {
87+ let p = entry.path();
88+ let Some(ext) = p.extension().and_then(|e| e.to_str()) else {
89+ continue;
90+ };
91+ if !matches!(
92+ ext.to_ascii_lowercase().as_str(),
93+ "mp4" | "mkv" | "mov" | "avi"
94+ ) {
95+ continue;
96+ }
97+ found.push(p);
98+ }
99+ }
100+ found.sort();
101+ for p in found {
102+ if ffprobe_field(&p, "v:0", "codec_name").as_deref() == Some(codec) {
103+ return Some(p);
104+ }
105+ }
106+ None
107+}
108+
109+fn ffprobe_field(path: &Path, stream: &str, key: &str) -> Option<String> {
110+ let out = Command::new("ffprobe")
111+ .args(["-v", "error", "-select_streams", stream, "-show_entries"])
112+ .arg(format!("stream={key}"))
113+ .args(["-of", "default=nw=1:nk=1"])
114+ .arg(path)
115+ .output()
116+ .ok()?;
117+ if !out.status.success() {
118+ return None;
119+ }
120+ let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
121+ (!s.is_empty()).then_some(s)
122+}
123+
124+// ---------------------------------------------------------------------------
125+// h264: decode (real film, 10s) + encode (raw planes from the same clip)
126+// ---------------------------------------------------------------------------
127+
128+fn bench_h264(rows: &mut Vec<Row>) {
129+ let Some(src) = real_video("h264") else {
130+ rows.push(missing("ec-h264", "decode"));
131+ rows.push(missing("ec-h264", "encode"));
132+ return;
133+ };
134+ let w: u32 = ffprobe_field(&src, "v:0", "width")
135+ .and_then(|s| s.parse().ok())
136+ .unwrap_or(0);
137+ let h: u32 = ffprobe_field(&src, "v:0", "height")
138+ .and_then(|s| s.parse().ok())
139+ .unwrap_or(0);
140+
141+ // decode: 10s Annex-B extract, trimmed inside ffmpeg (never decode-then-trim).
142+ let out = Command::new("ffmpeg")
143+ .args(["-v", "error", "-t", "10", "-i"])
144+ .arg(&src)
145+ .args([
146+ "-an",
147+ "-c:v",
148+ "copy",
149+ "-bsf:v",
150+ "h264_mp4toannexb",
151+ "-f",
152+ "h264",
153+ "-",
154+ ])
155+ .output()
156+ .expect("ffmpeg extract h264");
157+ if out.status.success() && !out.stdout.is_empty() {
158+ let bytes = out.stdout;
159+ let start = Instant::now();
160+ let mut dec = H264Decoder::new();
161+ let mut frames = 0u64;
162+ for nal in AnnexBIter::new(&bytes) {
163+ if let Ok(NalOutcome::PictureBoundary) = dec.push_nal(nal) {
164+ let _ = dec.end_picture();
165+ let _ = dec.push_nal(nal);
166+ }
167+ while dec.next_frame().is_some() {
168+ frames += 1;
169+ }
170+ }
171+ let _ = dec.flush();
172+ while dec.next_frame().is_some() {
173+ frames += 1;
174+ }
175+ let wall = start.elapsed().as_secs_f64();
176+ let fps = ffprobe_field(&src, "v:0", "r_frame_rate")
177+ .and_then(|s| parse_ratio(&s))
178+ .unwrap_or(25.0);
179+ let media_s = frames as f64 / fps;
180+ rows.push(Row {
181+ component: "ec-h264",
182+ direction: "decode",
183+ content: format!("{w}x{h} film, {frames} frames"),
184+ media: format!("{media_s:.1}s"),
185+ wall_ms: wall * 1000.0,
186+ rtf: (wall > 0.0).then_some(media_s / wall),
187+ });
188+ } else {
189+ rows.push(missing("ec-h264", "decode"));
190+ }
191+
192+ // encode: 30 raw yuv420p frames scaled to 640x360 from the same clip.
193+ let (planes, ew, eh, n) = extract_yuv420p(&src, 640, 360, 30);
194+ if n > 0 {
195+ let mut cfg = H264Config::new(ew, eh);
196+ cfg.threads = 1; // one worker: single-core cost, not a parallelism claim
197+ let mut enc = H264Encoder::new(cfg).expect("h264 encoder");
198+ let frame_len = (ew * eh + 2 * (ew.div_ceil(2) * eh.div_ceil(2))) as usize;
199+ let start = Instant::now();
200+ for frame in planes.chunks_exact(frame_len) {
201+ let (y, rest) = frame.split_at((ew * eh) as usize);
202+ let (u, v) = rest.split_at(rest.len() / 2);
203+ let view = PictureView::i420(ew, eh, y, u, v);
204+ enc.encode(&view).expect("h264 encode");
205+ }
206+ let wall = start.elapsed().as_secs_f64();
207+ let media_s = n as f64 / 30.0;
208+ rows.push(Row {
209+ component: "ec-h264",
210+ direction: "encode",
211+ content: format!("{ew}x{eh}, {n} frames, 1 thread"),
212+ media: format!("{media_s:.1}s"),
213+ wall_ms: wall * 1000.0,
214+ rtf: (wall > 0.0).then_some(media_s / wall),
215+ });
216+ } else {
217+ rows.push(missing("ec-h264", "encode"));
218+ }
219+}
220+
221+/// `n` progressive frames of raw I420 at `w x h`, scaled and trimmed inside
222+/// ffmpeg.
223+fn extract_yuv420p(src: &Path, w: u32, h: u32, n: u32) -> (Vec<u8>, u32, u32, u32) {
224+ let out = Command::new("ffmpeg")
225+ .args(["-v", "error", "-i"])
226+ .arg(src)
227+ .args([
228+ "-vf",
229+ &format!("scale={w}:{h}"),
230+ "-frames:v",
231+ &n.to_string(),
232+ "-pix_fmt",
233+ "yuv420p",
234+ "-f",
235+ "rawvideo",
236+ "-",
237+ ])
238+ .output()
239+ .expect("ffmpeg extract yuv420p");
240+ if !out.status.success() || out.stdout.is_empty() {
241+ return (Vec::new(), w, h, 0);
242+ }
243+ let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
244+ let frames = (out.stdout.len() / frame_len) as u32;
245+ (out.stdout, w, h, frames)
246+}
247+
248+fn parse_ratio(s: &str) -> Option<f64> {
249+ let (n, d) = s.split_once('/')?;
250+ let (n, d) = (n.parse::<f64>().ok()?, d.parse::<f64>().ok()?);
251+ (d != 0.0).then_some(n / d)
252+}
253+
254+// ---------------------------------------------------------------------------
255+// h265: encode only -- this crate has no decoder (intra-only HEVC encoder).
256+// ---------------------------------------------------------------------------
257+
258+fn bench_h265_encode(rows: &mut Vec<Row>) {
259+ rows.push(missing_direction(
260+ "ec-h265",
261+ "decode",
262+ "encode-only crate, no decoder present",
263+ ));
264+ let Some(src) = real_video("h264").or_else(|| real_video("hevc")) else {
265+ rows.push(missing("ec-h265", "encode"));
266+ return;
267+ };
268+ let (planes, w, h, n) = extract_yuv420p(&src, 640, 360, 10);
269+ if n == 0 {
270+ rows.push(missing("ec-h265", "encode"));
271+ return;
272+ }
273+ let cfg = H265Config::new(w, h);
274+ let enc = H265Encoder::new(cfg).expect("h265 encoder");
275+ let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
276+ let cw = w.div_ceil(2);
277+ let ch = h.div_ceil(2);
278+ let start = Instant::now();
279+ for frame in planes.chunks_exact(frame_len) {
280+ let (y, rest) = frame.split_at((w * h) as usize);
281+ let (u, v) = rest.split_at(rest.len() / 2);
282+ let vf = VideoFrame::try_new(
283+ PixelFormat::I420,
284+ w,
285+ h,
286+ vec![
287+ Plane::new(y.to_vec(), w as usize),
288+ Plane::new(u.to_vec(), cw as usize),
289+ Plane::new(v.to_vec(), cw as usize),
290+ ],
291+ )
292+ .expect("i420 frame");
293+ let _ = ch; // silence unused if plane_geometry ignores it
294+ enc.encode_idr(&vf).expect("h265 encode");
295+ }
296+ let wall = start.elapsed().as_secs_f64();
297+ let media_s = n as f64 / 30.0;
298+ rows.push(Row {
299+ component: "ec-h265",
300+ direction: "encode",
301+ content: format!("{w}x{h}, {n} frames, IDR-only"),
302+ media: format!("{media_s:.1}s"),
303+ wall_ms: wall * 1000.0,
304+ rtf: (wall > 0.0).then_some(media_s / wall),
305+ });
306+}
307+
308+// ---------------------------------------------------------------------------
309+// av1: encode only -- same shape as h265.
310+// ---------------------------------------------------------------------------
311+
312+fn bench_av1_encode(rows: &mut Vec<Row>) {
313+ rows.push(missing_direction(
314+ "ec-av1",
315+ "decode",
316+ "encode-only crate, no decoder present",
317+ ));
318+ let Some(src) = real_video("h264") else {
319+ rows.push(missing("ec-av1", "encode"));
320+ return;
321+ };
322+ // AV1's block grid is 32x32 superblocks: pick a size already a multiple of it.
323+ let (planes, w, h, n) = extract_yuv420p(&src, 640, 384, 10);
324+ if n == 0 {
325+ rows.push(missing("ec-av1", "encode"));
326+ return;
327+ }
328+ let cfg = Av1Config {
329+ width: w as usize,
330+ height: h as usize,
331+ base_q_idx: 100,
332+ gop: 10,
333+ colour: Colour::default(),
334+ };
335+ let mut enc = Av1Encoder::new(cfg).expect("av1 encoder");
336+ let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
337+ let start = Instant::now();
338+ for frame in planes.chunks_exact(frame_len) {
339+ let (y, rest) = frame.split_at((w * h) as usize);
340+ let (u, v) = rest.split_at(rest.len() / 2);
341+ let pic = Av1Picture {
342+ width: w as usize,
343+ height: h as usize,
344+ y: y.to_vec(),
345+ u: u.to_vec(),
346+ v: v.to_vec(),
347+ };
348+ enc.encode(&pic).expect("av1 encode");
349+ }
350+ let wall = start.elapsed().as_secs_f64();
351+ let media_s = n as f64 / 30.0;
352+ rows.push(Row {
353+ component: "ec-av1",
354+ direction: "encode",
355+ content: format!("{w}x{h}, {n} frames, gop=10"),
356+ media: format!("{media_s:.1}s"),
357+ wall_ms: wall * 1000.0,
358+ rtf: (wall > 0.0).then_some(media_s / wall),
359+ });
360+}
361+
362+// ---------------------------------------------------------------------------
363+// audio decode: one loop over ec-probe's unified reader covers every codec
364+// it wraps (mp3/flac/aac/alac/ac3/truehd/opus/vorbis via ogg/mp4/matroska).
365+// ---------------------------------------------------------------------------
366+
367+fn bench_audio_decode(rows: &mut Vec<Row>) {
368+ let mut candidates: Vec<PathBuf> = Vec::new();
369+ if let Ok(entries) = std::fs::read_dir(fixtures().join("audio")) {
370+ candidates.extend(entries.flatten().map(|e| e.path()));
371+ }
372+ // Real-library samples: mp3 and wav are on disk; ac3 lives inside the
373+ // ReelT mux (5.1 AC-3), extracted as its own elementary file.
374+ for f in ["8a3b6d1d19.mp3", "test.wav"] {
375+ let p = home().join("Downloads").join(f);
376+ if p.exists() {
377+ candidates.push(p);
378+ }
379+ }
380+ if let Some(src) = real_video("h264") {
381+ if ffprobe_field(&src, "a:0", "codec_name").as_deref() == Some("ac3") {
382+ let out = Command::new("ffmpeg")
383+ .args(["-v", "error", "-t", "10", "-i"])
384+ .arg(&src)
385+ .args(["-vn", "-c:a", "copy", "-f", "ac3"])
386+ .arg(
387+ Path::new(&std::env::var("HOME").unwrap())
388+ .join(".cache/bench-media/sample.ac3"),
389+ )
390+ .output();
391+ if let Ok(o) = out {
392+ if o.status.success() {
393+ candidates.push(home().join(".cache/bench-media/sample.ac3"));
394+ }
395+ }
396+ }
397+ }
398+ candidates.sort();
399+ candidates.dedup();
400+
401+ for path in candidates {
402+ let Ok(mut reader) = Reader::open(&path) else {
403+ continue;
404+ };
405+ let Some(stream) = reader.default_stream(MediaType::Audio).map(|s| s.index) else {
406+ continue;
407+ };
408+ let Ok(mut dec) = reader.make_decoder(stream) else {
409+ continue;
410+ };
411+ let codec = format!("{:?}", dec.codec());
412+ let mut samples = 0u64;
413+ let start = Instant::now();
414+ let mut out = Vec::new();
415+ loop {
416+ match reader.next_packet() {
417+ Ok(pkt) if pkt.stream == stream => {
418+ out.clear();
419+ if dec.decode(&pkt, &mut out).is_ok() {
420+ samples += (out.len() / dec.channels().max(1)) as u64;
421+ }
422+ }
423+ Ok(_) => {}
424+ Err(_) => break,
425+ }
426+ }
427+ let _ = dec.flush(&mut out);
428+ let wall = start.elapsed().as_secs_f64();
429+ let media_s = samples as f64 / dec.sample_rate().max(1) as f64;
430+ let name = path.file_name().unwrap().to_string_lossy().into_owned();
431+ rows.push(Row {
432+ component: Box::leak(format!("ec-probe/{codec}").into_boxed_str()),
433+ direction: "decode",
434+ content: name,
435+ media: format!("{media_s:.1}s"),
436+ wall_ms: wall * 1000.0,
437+ rtf: (wall > 0.0 && media_s > 0.0).then_some(media_s / wall),
438+ });
439+ }
440+}
441+
442+fn missing(component: &'static str, direction: &'static str) -> Row {
443+ missing_direction(component, direction, "no real-media candidate found")
444+}
445+
446+fn missing_direction(component: &'static str, direction: &'static str, why: &str) -> Row {
447+ Row {
448+ component,
449+ direction,
450+ content: why.to_string(),
451+ media: "-".to_string(),
452+ wall_ms: 0.0,
453+ rtf: None,
454+ }
455+}