Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M4.8: benchmark suite (cargo xtask bench)

Brandon Thomas457aca112e57
diff --git a/crates/ui-egui/examples/bench/fixtures.rs b/crates/ui-egui/examples/bench/fixtures.rs
new file mode 100644
index 000000000..51b0a9868
--- /dev/null
+++ b/crates/ui-egui/examples/bench/fixtures.rs
@@ -0,0 +1,92 @@
+//! Benchmark fixtures, generated with ffmpeg (an external fixture generator only; never linked or
+//! shipped) into `target/fixtures/playback/` on first use. Never committed.
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+/// `<repo>/target/fixtures/playback`, or `$FILMCRAFT_FIXTURES/playback` (lets worktrees share one set).
+pub fn fixtures_dir() -> PathBuf {
+ match std::env::var_os("FILMCRAFT_FIXTURES") {
+ Some(d) => PathBuf::from(d).join("playback"),
+ None => Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/fixtures/playback"),
+ }
+}
+
+pub fn ffmpeg() -> Option<PathBuf> {
+ if let Some(p) = std::env::var_os("FILMCRAFT_FFMPEG") {
+ return Some(PathBuf::from(p));
+ }
+ ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"].iter().map(PathBuf::from).find(|p| p.exists())
+}
+
+/// A fixture: file name, lavfi video source, seconds, with audio, video encoder arguments.
+struct Spec {
+ name: &'static str,
+ src: &'static str,
+ secs: u32,
+ audio: bool,
+ codec: &'static [&'static str],
+}
+
+const X264: &[&str] = &["-c:v", "libx264", "-preset", "fast", "-crf", "20", "-pix_fmt", "yuv420p"];
+const X265: &[&str] = &["-c:v", "libx265", "-preset", "fast", "-crf", "22", "-pix_fmt", "yuv420p", "-tag:v", "hvc1", "-x265-params", "log-level=error"];
+const VP9: &[&str] = &["-c:v", "libvpx-vp9", "-deadline", "realtime", "-cpu-used", "8", "-b:v", "0", "-crf", "32", "-row-mt", "1", "-pix_fmt", "yuv420p"];
+const AV1: &[&str] = &["-c:v", "libsvtav1", "-preset", "10", "-crf", "35", "-pix_fmt", "yuv420p", "-svtav1-params", "keyint=48"];
+const PRORES: &[&str] = &["-c:v", "prores_ks", "-profile:v", "3", "-pix_fmt", "yuv422p10le", "-vendor", "apl0"];
+
+const SPECS: &[Spec] = &[
+ // Playback scenarios (also used by `bench_playback`).
+ Spec { name: "a1080.mp4", src: "testsrc2=s=1920x1080:r=24000/1001:d=20,noise=alls=6:allf=t", secs: 20, audio: true, codec: X264 },
+ Spec { name: "b1080.mp4", src: "mandelbrot=s=1920x1080:r=24000/1001,trim=duration=20,noise=alls=6:allf=t", secs: 20, audio: false, codec: X264 },
+ Spec { name: "c1080.mp4", src: "smptehdbars=s=1920x1080:r=24000/1001:d=20,noise=alls=10:allf=t+u", secs: 20, audio: false, codec: X264 },
+ Spec { name: "a2160.mp4", src: "testsrc2=s=3840x2160:r=24000/1001:d=10,noise=alls=6:allf=t", secs: 10, audio: false, codec: X264 },
+ Spec { name: "hevc2160.mp4", src: "testsrc2=s=3840x2160:r=24000/1001:d=10,noise=alls=6:allf=t", secs: 10, audio: false, codec: X265 },
+ // Decode-speed matrix: 1080p (5 s) and 2160p (3 s) per codec, same picture content.
+ Spec { name: "dec_h264_1080.mp4", src: "testsrc2=s=1920x1080:r=24000/1001:d=5,noise=alls=6:allf=t", secs: 5, audio: false, codec: X264 },
+ Spec { name: "dec_h264_2160.mp4", src: "testsrc2=s=3840x2160:r=24000/1001:d=3,noise=alls=6:allf=t", secs: 3, audio: false, codec: X264 },
+ Spec { name: "dec_hevc_1080.mp4", src: "testsrc2=s=1920x1080:r=24000/1001:d=5,noise=alls=6:allf=t", secs: 5, audio: false, codec: X265 },
+ Spec { name: "dec_hevc_2160.mp4", src: "testsrc2=s=3840x2160:r=24000/1001:d=3,noise=alls=6:allf=t", secs: 3, audio: false, codec: X265 },
+ Spec { name: "dec_vp9_1080.webm", src: "testsrc2=s=1920x1080:r=24000/1001:d=5,noise=alls=6:allf=t", secs: 5, audio: false, codec: VP9 },
+ Spec { name: "dec_vp9_2160.webm", src: "testsrc2=s=3840x2160:r=24000/1001:d=3,noise=alls=6:allf=t", secs: 3, audio: false, codec: VP9 },
+ Spec { name: "dec_av1_1080.mp4", src: "testsrc2=s=1920x1080:r=24000/1001:d=5,noise=alls=6:allf=t", secs: 5, audio: false, codec: AV1 },
+ Spec { name: "dec_av1_2160.mp4", src: "testsrc2=s=3840x2160:r=24000/1001:d=3,noise=alls=6:allf=t", secs: 3, audio: false, codec: AV1 },
+ Spec { name: "dec_prores_1080.mov", src: "testsrc2=s=1920x1080:r=24000/1001:d=5,noise=alls=6:allf=t", secs: 5, audio: false, codec: PRORES },
+ Spec { name: "dec_prores_2160.mov", src: "testsrc2=s=3840x2160:r=24000/1001:d=3,noise=alls=6:allf=t", secs: 3, audio: false, codec: PRORES },
+ // Small clip media for the 1000-clip timeline / project benchmarks (video + audio).
+ Spec { name: "clip360.mp4", src: "testsrc2=s=640x360:r=24000/1001:d=20", secs: 20, audio: true, codec: X264 },
+];
+
+/// The fixture `name`, generating it on first use (None when ffmpeg or its encoder is missing).
+pub fn fixture(name: &str) -> Option<PathBuf> {
+ let dir = fixtures_dir();
+ let path = dir.join(name);
+ if path.exists() {
+ return Some(path);
+ }
+ let ff = ffmpeg()?;
+ let spec = SPECS.iter().find(|f| f.name == name)?;
+ std::fs::create_dir_all(&dir).ok()?;
+ eprintln!("generating {}", path.display());
+ // Write under a temporary name and rename, so a concurrent run never sees half a file.
+ let ext = Path::new(name).extension().and_then(|e| e.to_str()).unwrap_or("mp4");
+ let tmp = dir.join(format!(".{}.{}.tmp.{ext}", name, std::process::id()));
+ let mut c = Command::new(ff);
+ c.env("SVT_LOG", "1");
+ c.args(["-v", "error", "-y", "-f", "lavfi", "-i", spec.src]);
+ if spec.audio {
+ c.args(["-f", "lavfi", "-i", &format!("sine=f=440:d={}", spec.secs), "-c:a", "aac", "-shortest"]);
+ }
+ c.args(spec.codec);
+ if ext != "webm" {
+ c.args(["-movflags", "+faststart"]);
+ }
+ c.arg(&tmp);
+ let ok = c.status().ok()?.success();
+ if !ok {
+ let _ = std::fs::remove_file(&tmp);
+ eprintln!(" ffmpeg failed for {name} (encoder missing?)");
+ return None;
+ }
+ std::fs::rename(&tmp, &path).ok()?;
+ Some(path)
+}
diff --git a/crates/ui-egui/examples/bench/main.rs b/crates/ui-egui/examples/bench/main.rs
new file mode 100644
index 000000000..ea2af8e12
--- /dev/null
+++ b/crates/ui-egui/examples/bench/main.rs
@@ -0,0 +1,340 @@
+//! FilmCraft benchmark suite (`cargo xtask bench`): decode speed per codec, Program-monitor
+//! playback and scrubbing through the real frame scheduler, timeline UI frame time with a large
+//! sequence, export throughput, project save/open, and peak memory per section.
+//!
+//! ```sh
+//! cargo xtask bench # every section, writes target/bench/bench-<label>.{json,md}
+//! cargo xtask bench --sections decode,scrub --repeat 3 --label after
+//! cargo run --release -p filmcraft-ui-egui --example bench -- --section timeline # one section, this process
+//! ```
+//!
+//! Each section runs in its own child process (fresh caches, and its own peak resident set size,
+//! measured with `/usr/bin/time`). Wall-clock results depend on machine load, so every row
+//! records the load average, and CPU-time columns are reported alongside. Fixtures are generated
+//! with ffmpeg into `target/fixtures/playback/` on first use (see `fixtures.rs`); sections whose
+//! fixtures cannot be made are skipped. See `docs/performance.md`.
+
+mod fixtures;
+#[allow(dead_code)]
+mod playback;
+mod sections;
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use serde_json::{Value, json};
+
+pub const SECTIONS: &[&str] = &["decode", "playback", "scrub", "timeline", "export", "project"];
+
+#[derive(Clone)]
+pub struct Opts {
+ pub repeat: usize,
+ pub quick: bool,
+ pub gpu: bool,
+ /// Only cases whose name contains this (decode fixtures, playback / scrub scenarios).
+ pub only: Option<String>,
+}
+
+impl Opts {
+ pub fn wants(&self, name: &str) -> bool {
+ self.only.as_ref().is_none_or(|o| name.contains(o.as_str()))
+ }
+}
+
+fn arg_value(args: &[String], name: &str) -> Option<String> {
+ args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()
+}
+
+fn main() {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ if args.iter().any(|a| a == "--help" || a == "-h") {
+ println!(
+ "bench [--sections {}] [--repeat N] [--quick] [--cpu] [--only SUBSTRING] [--label NAME] [--out DIR]\n bench --section NAME [--json FILE] (one section in this process)",
+ SECTIONS.join(",")
+ );
+ return;
+ }
+ let opts = Opts {
+ repeat: arg_value(&args, "--repeat").and_then(|v| v.parse().ok()).unwrap_or(1).max(1),
+ quick: args.iter().any(|a| a == "--quick"),
+ gpu: !args.iter().any(|a| a == "--cpu"),
+ only: arg_value(&args, "--only"),
+ };
+ if let Some(section) = arg_value(&args, "--section") {
+ let v = run_section(&section, &opts);
+ let text = serde_json::to_string_pretty(&v).unwrap_or_default();
+ match arg_value(&args, "--json") {
+ Some(p) => std::fs::write(&p, text).unwrap_or_else(|e| panic!("{p}: {e}")),
+ None => println!("{text}"),
+ }
+ return;
+ }
+ orchestrate(&args, &opts);
+}
+
+fn run_section(name: &str, o: &Opts) -> Value {
+ let t0 = std::time::Instant::now();
+ let load0 = playback::load_avg();
+ let rows = match name {
+ "decode" => sections::decode(o),
+ "playback" => sections::playback(o),
+ "scrub" => sections::scrub(o),
+ "timeline" => sections::timeline(o),
+ "export" => sections::export(o),
+ "project" => sections::project(o),
+ _ => panic!("unknown section {name} (one of {})", SECTIONS.join(", ")),
+ };
+ json!({"section": name, "rows": rows, "wall_s": t0.elapsed().as_secs_f64(), "load_before": load0, "load_after": playback::load_avg()})
+}
+
+/// Run each section in a child process under `/usr/bin/time` (peak RSS), then write JSON and
+/// Markdown reports.
+fn orchestrate(args: &[String], o: &Opts) {
+ let wanted: Vec<String> =
+ arg_value(args, "--sections").map(|s| s.split(',').map(str::to_string).collect()).unwrap_or_else(|| SECTIONS.iter().map(|s| s.to_string()).collect());
+ let label = arg_value(args, "--label").unwrap_or_else(|| "latest".into());
+ let out = arg_value(args, "--out").map(PathBuf::from).unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/bench"));
+ std::fs::create_dir_all(&out).expect("output dir");
+ let exe = std::env::current_exe().expect("exe");
+ let machine = machine_info();
+ println!("FilmCraft bench `{label}`: {}", machine["summary"].as_str().unwrap_or(""));
+ let mut results = Vec::new();
+ for name in &wanted {
+ let tmp = out.join(format!(".section-{name}-{}.json", std::process::id()));
+ let mut cmd = time_wrapper();
+ cmd.arg(&exe).args(["--section", name, "--json"]).arg(&tmp).args(["--repeat", &o.repeat.to_string()]);
+ if o.quick {
+ cmd.arg("--quick");
+ }
+ if !o.gpu {
+ cmd.arg("--cpu");
+ }
+ if let Some(only) = &o.only {
+ cmd.args(["--only", only]);
+ }
+ eprintln!("== {name} (load {})", playback::load_avg());
+ let output = cmd.stderr(std::process::Stdio::piped()).output().expect("run section");
+ let stderr = String::from_utf8_lossy(&output.stderr).to_string();
+ // pass the child's progress output through (minus the time report)
+ for l in child_lines(&stderr) {
+ eprintln!(" {l}");
+ }
+ let mut v: Value = std::fs::read(&tmp)
+ .ok()
+ .and_then(|b| serde_json::from_slice(&b).ok())
+ .unwrap_or_else(|| json!({"section": name, "error": format!("section failed: {}", output.status)}));
+ let _ = std::fs::remove_file(&tmp);
+ if let Some(rss) = peak_rss_bytes(&stderr) {
+ v["peak_rss_mb"] = json!(rss as f64 / 1e6);
+ }
+ println!("{}", section_markdown(&v));
+ results.push(v);
+ }
+ let doc = json!({"label": label, "machine": machine, "repeat": o.repeat, "quick": o.quick, "gpu": o.gpu, "sections": results});
+ let jp = out.join(format!("bench-{label}.json"));
+ let mp = out.join(format!("bench-{label}.md"));
+ std::fs::write(&jp, serde_json::to_string_pretty(&doc).unwrap_or_default()).expect("write json");
+ std::fs::write(&mp, markdown(&doc)).expect("write md");
+ println!("wrote {} and {}", jp.display(), mp.display());
+}
+
+fn time_wrapper() -> Command {
+ let time = Path::new("/usr/bin/time");
+ if time.exists() {
+ let mut c = Command::new(time);
+ c.arg(if cfg!(target_os = "macos") { "-l" } else { "-v" });
+ c
+ } else {
+ // No `time`: run the section directly (no peak RSS).
+ let mut c = Command::new("env");
+ c.arg("--");
+ c
+ }
+}
+
+/// The child's own output: everything before the `time` report (macOS `-l`: a "… real … user …"
+/// line; GNU `-v`: "Command being timed").
+fn child_lines(stderr: &str) -> Vec<&str> {
+ stderr.lines().take_while(|l| !(l.contains(" real ") && l.contains(" user ")) && !l.trim_start().starts_with("Command being timed")).collect()
+}
+
+/// Peak RSS in bytes from `/usr/bin/time -l` (macOS: bytes) or `-v` (GNU: kbytes).
+fn peak_rss_bytes(stderr: &str) -> Option<u64> {
+ for l in stderr.lines() {
+ let t = l.trim();
+ if let Some(n) = t.strip_suffix("maximum resident set size") {
+ return n.trim().parse().ok();
+ }
+ if let Some(n) = t.strip_prefix("Maximum resident set size (kbytes):") {
+ return n.trim().parse::<u64>().ok().map(|k| k * 1024);
+ }
+ }
+ None
+}
+
+fn sh(cmd: &str, args: &[&str]) -> Option<String> {
+ Command::new(cmd).args(args).output().ok().filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
+}
+
+fn machine_info() -> Value {
+ let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
+ let cpu = sh("sysctl", &["-n", "machdep.cpu.brand_string"])
+ .or_else(|| {
+ std::fs::read_to_string("/proc/cpuinfo")
+ .ok()
+ .and_then(|c| c.lines().find(|l| l.starts_with("model name")).and_then(|l| l.split(':').nth(1)).map(|s| s.trim().to_string()))
+ })
+ .unwrap_or_else(|| "unknown CPU".into());
+ let mem_gb = sh("sysctl", &["-n", "hw.memsize"]).and_then(|m| m.parse::<u64>().ok()).map(|b| b as f64 / (1u64 << 30) as f64);
+ let os = sh("uname", &["-sr"]).unwrap_or_default();
+ let date = sh("date", &["-u", "+%Y-%m-%d %H:%M UTC"]).unwrap_or_default();
+ let repo = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
+ let commit = Command::new("git")
+ .arg("-C")
+ .arg(&repo)
+ .args(["rev-parse", "--short", "HEAD"])
+ .output()
+ .ok()
+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
+ .unwrap_or_default();
+ let summary = format!(
+ "{cpu}, {cores} cores{}, {os}, commit {commit}, {date}, load {}",
+ mem_gb.map(|g| format!(", {g:.0} GB")).unwrap_or_default(),
+ playback::load_avg()
+ );
+ json!({"cpu": cpu, "cores": cores, "memory_gb": mem_gb, "os": os, "commit": commit, "date": date, "rayon_threads": rayon::current_num_threads(), "load": playback::load_avg(), "summary": summary})
+}
+
+// ------------------------------------------------------------------------------------ markdown
+
+fn f(v: &Value, k: &str, prec: usize) -> String {
+ match v.get(k) {
+ Some(Value::Number(n)) => match n.as_f64() {
+ Some(x) if x.is_finite() => format!("{x:.prec$}"),
+ _ => "–".into(),
+ },
+ Some(Value::String(s)) => s.clone(),
+ Some(Value::Bool(b)) => b.to_string(),
+ _ => "–".into(),
+ }
+}
+
+/// One section as a Markdown table.
+pub fn section_markdown(v: &Value) -> String {
+ let name = v["section"].as_str().unwrap_or("?");
+ let rows = v["rows"].as_array().cloned().unwrap_or_default();
+ let mut s = format!("### {name}\n\n");
+ if let Some(e) = v.get("error") {
+ s += &format!("failed: {e}\n");
+ return s;
+ }
+ let (cols, prec): (&[(&str, &str)], usize) = match name {
+ "decode" => (
+ &[
+ ("fixture", "fixture"),
+ ("codec", "codec"),
+ ("size", "size"),
+ ("frames", "frames"),
+ ("fps", "fps"),
+ ("fps_min", "fps (min)"),
+ ("cpu_ms_per_frame", "CPU ms/frame"),
+ ("first_frame_ms", "first frame ms"),
+ ("realtime", "× real time"),
+ ("load", "load"),
+ ],
+ 1,
+ ),
+ "playback" => (
+ &[
+ ("scenario", "scenario"),
+ ("res", "res"),
+ ("path", "path"),
+ ("shown", "shown"),
+ ("dropped", "dropped"),
+ ("drop_pct", "drop %"),
+ ("cpu_ms_per_frame", "CPU ms/frame"),
+ ("decode_ms", "decode ms/job"),
+ ("ui_p95_ms", "UI p95 ms"),
+ ("seeks", "seeks"),
+ ("load", "load"),
+ ],
+ 1,
+ ),
+ "scrub" => (
+ &[
+ ("scenario", "scenario"),
+ ("seek_p50_ms", "seek p50 ms"),
+ ("seek_p95_ms", "seek p95 ms"),
+ ("settle_p50_ms", "drag-stop p50 ms"),
+ ("settle_p95_ms", "drag-stop p95 ms"),
+ ("drag_shown_pct", "drag frames shown %"),
+ ("timeouts", "timeouts"),
+ ("decoded_per_seek", "decoded/seek"),
+ ("load", "load"),
+ ],
+ 1,
+ ),
+ "timeline" => (
+ &[
+ ("view", "view"),
+ ("clips", "clips"),
+ ("frames", "frames"),
+ ("update_p50_ms", "update p50 ms"),
+ ("update_p95_ms", "update p95 ms"),
+ ("tess_p50_ms", "tessellate p50 ms"),
+ ("render_p50_ms", "wgpu render p50 ms"),
+ ("total_p50_ms", "total p50 ms"),
+ ("total_p95_ms", "total p95 ms"),
+ ("vertices", "vertices"),
+ ("load", "load"),
+ ],
+ 2,
+ ),
+ "export" => (
+ &[
+ ("format", "format"),
+ ("frames", "frames"),
+ ("seconds", "wall s"),
+ ("fps", "fps"),
+ ("realtime", "× real time"),
+ ("cpu_ms_per_frame", "CPU ms/frame"),
+ ("mbytes", "MB"),
+ ("load", "load"),
+ ],
+ 2,
+ ),
+ "project" => (&[("what", "operation"), ("clips", "clips"), ("mbytes", "file MB"), ("p50_ms", "p50 ms"), ("min_ms", "min ms"), ("load", "load")], 1),
+ _ => (&[], 1),
+ };
+ s += &format!("| {} |\n|{}|\n", cols.iter().map(|c| c.1).collect::<Vec<_>>().join(" | "), cols.iter().map(|_| "---").collect::<Vec<_>>().join("|"));
+ for r in &rows {
+ s += &format!("| {} |\n", cols.iter().map(|c| f(r, c.0, prec)).collect::<Vec<_>>().join(" | "));
+ }
+ if let Some(m) = v.get("peak_rss_mb") {
+ s += &format!(
+ "\npeak RSS {:.0} MB; section wall {:.0} s; load {} → {}\n",
+ m.as_f64().unwrap_or(0.0),
+ v["wall_s"].as_f64().unwrap_or(0.0),
+ f(v, "load_before", 0),
+ f(v, "load_after", 0)
+ );
+ }
+ s
+}
+
+fn markdown(doc: &Value) -> String {
+ let m = &doc["machine"];
+ let mut s = format!(
+ "# FilmCraft benchmark `{}`\n\n- {}\n- repeat {} (best/median as noted), quick {}, monitor path {}\n\n",
+ doc["label"].as_str().unwrap_or(""),
+ m["summary"].as_str().unwrap_or(""),
+ doc["repeat"],
+ doc["quick"],
+ if doc["gpu"].as_bool() == Some(true) { "GPU" } else { "CPU" }
+ );
+ for sec in doc["sections"].as_array().into_iter().flatten() {
+ s += &section_markdown(sec);
+ s += "\n";
+ }
+ s
+}
diff --git a/crates/ui-egui/examples/bench/playback.rs b/crates/ui-egui/examples/bench/playback.rs
new file mode 100644
index 000000000..94e070df2
--- /dev/null
+++ b/crates/ui-egui/examples/bench/playback.rs
@@ -0,0 +1,762 @@
+//! Headless playback benchmark (`bench_playback`; also the playback and scrub sections of
+//! `bench`): drives the Program monitor's frame scheduler, prefetch and cache ([`FrameServer`],
+//! [`PlaybackMeter`]) exactly as the UI does, without a window.
+//!
+//! ```sh
+//! cargo xtask bench-playback # all scenarios, GPU path, Full + Half
+//! cargo run --release -p filmcraft-ui-egui --example bench_playback -- --scenario stack3 --res full --cpu
+//! ```
+//!
+//! Each play simulates display refreshes at `--refresh` Hz on the wall clock (as the app does
+//! without an audio device) and counts shown/dropped frames with the same meter as the app. Wall-
+//! clock numbers depend on machine load, so every run also reports CPU time (process and per
+//! frame-worker thread), which does not. See `docs/testing.md` §5.
+//!
+//! Fixtures are generated with ffmpeg into `target/fixtures/playback/` on first use (never
+//! committed). Scenarios that need them are skipped when ffmpeg is missing.
+
+use std::collections::HashMap;
+use std::path::Path;
+use std::process::Command;
+use std::time::{Duration, Instant};
+
+use filmcraft_engine::Session;
+use filmcraft_project::{ItemId, ParamValue, Project, SequenceSettings, TrackKind, find_effect, resolve_auto_points};
+use filmcraft_time::{FrameRate, Tick, TimeRange};
+use filmcraft_ui_egui::frames::{FrameKey, FrameServer, JobRecord, PREROLL_TIMEOUT_S, PlaybackMeter, Target, process_cpu_time, thread_cpu_time};
+use serde_json::{Value, json};
+
+use crate::fixtures::fixture;
+
+// ------------------------------------------------------------------------------------ projects
+
+pub fn import(s: &mut Session, path: &Path) -> ItemId {
+ let r = s.execute("file.import", json!({ "paths": [path.to_string_lossy()] })).expect("import");
+ ItemId(r["items"].as_array().and_then(|a| a.first()).and_then(Value::as_u64).unwrap_or_else(|| panic!("import {}: {r}", path.display())))
+}
+
+/// One clip per track from t = 0 (`layers[0]` on V1), with (scale %, position, rotation°,
+/// opacity %) Motion/Opacity settings per layer.
+pub fn build_sequence(s: &mut Session, w: u32, h: u32, layers: &[(ItemId, f64, Option<(f64, f64)>, f64, f64)], effects: &[&str], secs: f64) -> ItemId {
+ let rate = FrameRate::FPS_23_976;
+ let sizes: Vec<(u32, u32)> = layers
+ .iter()
+ .map(|l| match s.project.item(l.0).map(|i| &i.kind) {
+ Some(filmcraft_project::ItemKind::Media(m)) => m.info.video.as_ref().map(|v| (v.width, v.height)).unwrap_or((w, h)),
+ _ => (w, h),
+ })
+ .collect();
+ s.edit("bench sequence", |p: &mut Project, st| {
+ let settings = SequenceSettings { width: w, height: h, frame_rate: rate, ..SequenceSettings::default() };
+ let seq = p.new_sequence("Bench", settings, layers.len().max(1), 1, None);
+ for (i, &(item, scale, pos, rot, opacity)) in layers.iter().enumerate() {
+ let range = TimeRange::new(Tick::ZERO, rate.snap(Tick::from_seconds_f64(secs)));
+ let mut v = p.make_track_item(item, TrackKind::Video, Tick::ZERO, range, rate).expect("track item");
+ for e in &mut v.effects {
+ resolve_auto_points(e, (w, h), sizes[i]);
+ }
+ if let Some(m) = v.effect_mut("motion") {
+ if let Some(x) = m.params.get_mut("scale") {
+ x.value = ParamValue::Float(scale);
+ }
+ if let (Some(x), Some((px, py))) = (m.params.get_mut("position"), pos) {
+ x.value = ParamValue::Vec2(filmcraft_geom::Vec2::new(px, py));
+ }
+ if let Some(x) = m.params.get_mut("rotation") {
+ x.value = ParamValue::Float(rot);
+ }
+ }
+ if let Some(o) = v.effect_mut("opacity").and_then(|o| o.params.get_mut("opacity")) {
+ o.value = ParamValue::Float(opacity);
+ }
+ if i == 0 {
+ for (k, id) in effects.iter().enumerate() {
+ let mut e = find_effect(id).unwrap_or_else(|| panic!("effect {id}")).instance();
+ let set: &[(&str, f64)] = match *id {
+ "lumetri" => &[("temperature", 18.0), ("contrast", 22.0)],
+ "sharpen" => &[("amount", 40.0)],
+ _ => &[],
+ };
+ for (name, val) in set {
+ if let Some(p) = e.params.get_mut(*name) {
+ p.value = ParamValue::Float(*val);
+ }
+ }
+ v.effects.insert(k, e);
+ }
+ }
+ p.sequence_mut(seq).expect("seq").video_tracks[i].items.push(v);
+ }
+ st.active_sequence = Some(seq);
+ st.open_sequences = vec![seq];
+ st.playheads.insert(seq, Tick::ZERO);
+ Ok(seq)
+ })
+ .expect("sequence")
+}
+
+// ------------------------------------------------------------------------------------ display
+
+/// The UI side of a monitor: presents the frame it gets (GPU composite or texture conversion)
+/// and times that work, as `gpu_present` / `texture_for` do in the app.
+pub struct Display {
+ gpu: Option<(filmcraft_gpu::GpuCompositor, eframe::wgpu::Device)>,
+ last: Option<FrameKey>,
+ present: Vec<Duration>,
+ ui_cpu: Duration,
+ uploaded: u64,
+}
+
+impl Display {
+ pub fn new(gpu: bool) -> Self {
+ let gpu = if gpu {
+ let instance = eframe::wgpu::Instance::default();
+ let adapter = pollster::block_on(instance.request_adapter(&eframe::wgpu::RequestAdapterOptions::default())).ok();
+ adapter.and_then(|a| pollster::block_on(a.request_device(&eframe::wgpu::DeviceDescriptor::default())).ok()).map(|(d, q)| {
+ let c = filmcraft_gpu::GpuCompositor::new(&d, &q);
+ (c, d)
+ })
+ } else {
+ None
+ };
+ Self { gpu, last: None, present: Vec::new(), ui_cpu: Duration::ZERO, uploaded: 0 }
+ }
+
+ pub fn gpu_available(&self) -> bool {
+ self.gpu.is_some()
+ }
+
+ fn target(&self, seq: ItemId) -> Target {
+ if self.gpu.is_some() { Target::SequencePlan(seq) } else { Target::Sequence(seq) }
+ }
+
+ /// Show the exact frame, or the nearest earlier cached one; returns whether it was exact.
+ fn refresh(&mut self, server: &FrameServer, key: FrameKey) -> bool {
+ let (c0, t0) = (thread_cpu_time().unwrap_or_default(), Instant::now());
+ let exact;
+ let mut presented = false;
+ if let Some((comp, dev)) = self.gpu.as_mut() {
+ let plan = server.get_plan(&key).map(|p| (key, p));
+ exact = plan.is_some();
+ if let Some((k, plan)) = plan.or_else(|| server.nearest_plan(key, 6))
+ && self.last != Some(k)
+ {
+ let before = comp.uploaded_bytes;
+ let _ = comp.composite_prepared(&plan.plan, Some(&plan.prepared));
+ // Wait for the GPU so the time includes the upload and the draw.
+ let _ = dev.poll(eframe::wgpu::PollType::wait_indefinitely());
+ self.uploaded += comp.uploaded_bytes - before;
+ self.last = Some(k);
+ presented = true;
+ }
+ } else {
+ let img = server.get(&key).map(|i| (key, i));
+ exact = img.is_some();
+ let near = img.or_else(|| server.nearest(key.target, key.frame, key.size, key.revision, 6).map(|i| (FrameKey { frame: key.frame - 1, ..key }, i)));
+ if let Some((k, img)) = near
+ && self.last != Some(k)
+ {
+ let ci = egui::ColorImage::from_rgba_unmultiplied([img.w, img.h], &img.px);
+ std::hint::black_box(&ci);
+ self.uploaded += img.px.len() as u64;
+ self.last = Some(k);
+ presented = true;
+ }
+ }
+ if presented {
+ self.present.push(t0.elapsed());
+ }
+ self.ui_cpu += thread_cpu_time().unwrap_or_default().saturating_sub(c0);
+ exact
+ }
+}
+
+// ------------------------------------------------------------------------------------ measuring
+
+#[derive(Default)]
+pub struct PlayReport {
+ pub label: String,
+ pub seconds: f64,
+ pub shown: u64,
+ pub dropped: u64,
+ /// Due frames whose job finished before the frame was due.
+ pub on_time: usize,
+ pub due: usize,
+ /// ms: queue→done latency, service time, (due − done) slack of due frames.
+ pub latency: Vec<f64>,
+ pub service: Vec<f64>,
+ pub slack: Vec<f64>,
+ /// ms per job: worker thread CPU, source fetch (decode) wall and thread CPU.
+ pub job_cpu: Vec<f64>,
+ pub src_wall: Vec<f64>,
+ pub src_cpu: Vec<f64>,
+ pub present: Vec<f64>,
+ pub process_cpu: f64,
+ pub ui_cpu: f64,
+ pub jobs: usize,
+ pub wasted_jobs: usize,
+ pub cancelled_jobs: usize,
+ pub preview_jobs: usize,
+ pub gop: filmcraft_codecs::GopStats,
+ pub uploaded_mb: f64,
+ pub load: String,
+ pub preroll_ms: f64,
+}
+
+pub fn pct(v: &[f64], p: f64) -> f64 {
+ if v.is_empty() {
+ return f64::NAN;
+ }
+ let mut s = v.to_vec();
+ s.sort_by(|a, b| a.total_cmp(b));
+ s[((s.len() - 1) as f64 * p).round() as usize]
+}
+
+pub fn ms(d: Duration) -> f64 {
+ d.as_secs_f64() * 1000.0
+}
+
+pub fn load_avg() -> String {
+ Command::new("sysctl")
+ .args(["-n", "vm.loadavg"])
+ .output()
+ .ok()
+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().trim_matches(['{', '}', ' ']).to_string())
+ .unwrap_or_default()
+}
+
+pub struct Bench {
+ pub server: FrameServer,
+ pub refresh_hz: f64,
+ pub seconds: f64,
+}
+
+impl Bench {
+ /// Play `seconds` from `start` at `scale`, refreshing like the UI.
+ pub fn play(&self, s: &Session, seq: ItemId, display: &mut Display, scale: f32, start: Tick, label: &str) -> PlayReport {
+ let q = s.project.sequence(seq).expect("seq");
+ let rate = q.settings.frame_rate;
+ let end = (start + Tick::from_seconds_f64(self.seconds)).min(q.duration());
+ let project = s.project.clone();
+ let target = display.target(seq);
+ let size = (scale * 1000.0) as u32;
+ let mut meter = PlaybackMeter::default();
+ meter.start(1.0);
+ self.server.take_records();
+ let gop0 = filmcraft_codecs::gop_stats();
+ let (p0, ui0, up0) = (process_cpu_time().unwrap_or_default(), display.ui_cpu, display.uploaded);
+ display.present.clear();
+ let period = Duration::from_secs_f64(1.0 / self.refresh_hz);
+ // Preroll as the app does: refresh without moving the playhead until the first frames are
+ // ready (or the timeout), then start the clock.
+ let first = rate.frame_at(start);
+ let last_frame = rate.frame_at(q.duration()) - 1;
+ let t_pre = Instant::now();
+ loop {
+ let key = FrameKey { target, frame: first, size, revision: s.revision };
+ self.server.schedule_playback(key, rate, scale, &project, 1.0, true);
+ let exact = display.refresh(&self.server, key);
+ meter.refresh(first, exact);
+ if self.server.preroll_ready(key, 1.0, last_frame) || t_pre.elapsed().as_secs_f64() >= PREROLL_TIMEOUT_S {
+ break;
+ }
+ std::thread::sleep(period);
+ }
+ let preroll_ms = ms(t_pre.elapsed());
+ let anchor = Instant::now();
+ let mut due_at: HashMap<i64, Instant> = HashMap::new();
+ let mut next = anchor;
+ let mut frame;
+ loop {
+ let now = Instant::now();
+ let t = start + Tick::from_seconds_f64((now - anchor).as_secs_f64());
+ if t >= end {
+ break;
+ }
+ frame = rate.frame_at(t);
+ due_at.entry(frame).or_insert(now);
+ let key = FrameKey { target, frame, size, revision: s.revision };
+ self.server.schedule_playback(key, rate, scale, &project, 1.0, false);
+ let exact = display.refresh(&self.server, key);
+ meter.refresh(frame, exact);
+ next += period;
+ let now = Instant::now();
+ if next > now {
+ std::thread::sleep(next - now);
+ } else {
+ next = now;
+ }
+ }
+ meter.finish();
+ let wall = anchor.elapsed().as_secs_f64();
+ // Stop as the app does (drop and cancel prefetch), letting running jobs wind down so their
+ // CPU is counted.
+ self.server.stop_prefetch();
+ std::thread::sleep(Duration::from_millis(50));
+ let process_cpu = ms(process_cpu_time().unwrap_or_default().saturating_sub(p0));
+ let recs: Vec<JobRecord> = self.server.take_records();
+ let mut by_frame: HashMap<i64, JobRecord> = HashMap::new();
+ for r in &recs {
+ if r.key.target == target && r.key.size == size {
+ by_frame.insert(r.key.frame, *r);
+ }
+ }
+ let mut rep = PlayReport {
+ label: label.to_string(),
+ seconds: wall,
+ shown: meter.shown,
+ dropped: meter.dropped,
+ process_cpu,
+ ui_cpu: ms(display.ui_cpu - ui0),
+ jobs: recs.len(),
+ gop: filmcraft_codecs::gop_stats() - gop0,
+ uploaded_mb: (display.uploaded - up0) as f64 / 1e6,
+ load: load_avg(),
+ preroll_ms,
+ ..Default::default()
+ };
+ let last = rate.frame_at(end - Tick(1));
+ for f in first..=last {
+ let Some(due) = due_at.get(&f) else { continue };
+ rep.due += 1;
+ if let Some(r) = by_frame.get(&f) {
+ if r.finished <= *due {
+ rep.on_time += 1;
+ rep.slack.push(ms(*due - r.finished));
+ } else {
+ rep.slack.push(-ms(r.finished - *due));
+ }
+ }
+ }
+ for r in &recs {
+ rep.latency.push(ms(r.finished - r.queued));
+ rep.service.push(ms(r.finished - r.started));
+ rep.job_cpu.push(ms(r.cpu));
+ rep.src_wall.push(ms(r.source_wall));
+ rep.src_cpu.push(ms(r.source_cpu));
+ if !due_at.contains_key(&r.key.frame) || r.key.target != target {
+ rep.wasted_jobs += 1;
+ }
+ if r.preview {
+ rep.preview_jobs += 1;
+ }
+ if r.cancelled {
+ rep.cancelled_jobs += 1;
+ }
+ }
+ rep.present = display.present.iter().map(|d| ms(*d)).collect();
+ rep
+ }
+
+ /// Scrub: jump to a new random frame every `dwell` and measure how long the exact frame takes.
+ pub fn seek_storm(&self, s: &Session, seq: ItemId, display: &mut Display, scale: f32, jumps: usize, dwell: Duration) -> PlayReport {
+ let q = s.project.sequence(seq).expect("seq");
+ let rate = q.settings.frame_rate;
+ let frames = rate.frame_at(q.duration()).max(1);
+ let project = s.project.clone();
+ let target = display.target(seq);
+ let size = (scale * 1000.0) as u32;
+ self.server.take_records();
+ let gop0 = filmcraft_codecs::gop_stats();
+ let p0 = process_cpu_time().unwrap_or_default();
+ let t0 = Instant::now();
+ let mut rng = 0x2545_f491_4f6c_dd1du64;
+ let mut rep = PlayReport { label: format!("seek storm ({jumps} jumps, {} ms)", dwell.as_millis()), ..Default::default() };
+ let period = Duration::from_secs_f64(1.0 / self.refresh_hz);
+ for _ in 0..jumps {
+ rng ^= rng << 13;
+ rng ^= rng >> 7;
+ rng ^= rng << 17;
+ let frame = (rng % frames as u64) as i64;
+ let key = FrameKey { target, frame, size, revision: s.revision };
+ let start = Instant::now();
+ rep.due += 1;
+ loop {
+ // As the monitor does while not playing: request the frame under the playhead.
+ self.server.request(key, rate.tick_of(frame), scale, &project, 0);
+ if display.refresh(&self.server, key) {
+ rep.on_time += 1;
+ rep.latency.push(ms(start.elapsed()));
+ break;
+ }
+ if start.elapsed() >= dwell {
+ rep.dropped += 1;
+ break;
+ }
+ std::thread::sleep(period);
+ }
+ let left = dwell.saturating_sub(start.elapsed());
+ std::thread::sleep(left);
+ }
+ self.server.retain_queue(|_| false);
+ std::thread::sleep(Duration::from_millis(50));
+ rep.seconds = t0.elapsed().as_secs_f64();
+ rep.process_cpu = ms(process_cpu_time().unwrap_or_default().saturating_sub(p0));
+ let recs = self.server.take_records();
+ rep.jobs = recs.len();
+ for r in &recs {
+ rep.service.push(ms(r.finished - r.started));
+ rep.job_cpu.push(ms(r.cpu));
+ rep.src_wall.push(ms(r.source_wall));
+ rep.src_cpu.push(ms(r.source_cpu));
+ }
+ rep.shown = rep.on_time as u64;
+ rep.gop = filmcraft_codecs::gop_stats() - gop0;
+ rep.load = load_avg();
+ rep
+ }
+
+ /// Scrub latency, two ways, through the monitor's request path:
+ /// - `seeks` random jumps: time from the request to the exact frame on screen (no dwell cap:
+ /// every jump waits for its frame, up to `timeout`);
+ /// - `drags` playhead drags: the playhead moves `drag_frames` frames, one step per display
+ /// refresh (each refresh asks for the frame under the playhead, superseding the previous
+ /// request), then stops; time from the stop until the frame under it is on screen.
+ pub fn scrub(
+ &self,
+ s: &Session,
+ seq: ItemId,
+ display: &mut Display,
+ scale: f32,
+ seeks: usize,
+ drags: usize,
+ drag_frames: i64,
+ timeout: Duration,
+ ) -> ScrubReport {
+ let q = s.project.sequence(seq).expect("seq");
+ let rate = q.settings.frame_rate;
+ let frames = rate.frame_at(q.duration()).max(1);
+ let project = s.project.clone();
+ let target = display.target(seq);
+ let size = (scale * 1000.0) as u32;
+ let period = Duration::from_secs_f64(1.0 / self.refresh_hz);
+ let gop0 = filmcraft_codecs::gop_stats();
+ let p0 = process_cpu_time().unwrap_or_default();
+ let mut rep = ScrubReport { load: load_avg(), ..Default::default() };
+ let mut rng = 0x9e37_79b9_7f4a_7c15u64;
+ let mut next = move || {
+ rng ^= rng << 13;
+ rng ^= rng >> 7;
+ rng ^= rng << 17;
+ rng
+ };
+ let wait = |display: &mut Display, key: FrameKey, start: Instant| -> Option<f64> {
+ loop {
+ self.server.request(key, rate.tick_of(key.frame), scale, &project, 0);
+ if display.refresh(&self.server, key) {
+ return Some(ms(start.elapsed()));
+ }
+ if start.elapsed() >= timeout {
+ return None;
+ }
+ std::thread::sleep(period);
+ }
+ };
+ for _ in 0..seeks {
+ let frame = (next() % frames as u64) as i64;
+ let key = FrameKey { target, frame, size, revision: s.revision };
+ match wait(display, key, Instant::now()) {
+ Some(l) => rep.seek_ms.push(l),
+ None => rep.timeouts += 1,
+ }
+ }
+ for _ in 0..drags {
+ let from = (next() % (frames - drag_frames).max(1) as u64) as i64;
+ for f in from..from + drag_frames {
+ let key = FrameKey { target, frame: f.min(frames - 1), size, revision: s.revision };
+ self.server.request(key, rate.tick_of(key.frame), scale, &project, 0);
+ if display.refresh(&self.server, key) {
+ rep.drag_shown += 1;
+ }
+ rep.drag_steps += 1;
+ std::thread::sleep(period);
+ }
+ let key = FrameKey { target, frame: (from + drag_frames).min(frames - 1), size, revision: s.revision };
+ match wait(display, key, Instant::now()) {
+ Some(l) => rep.settle_ms.push(l),
+ None => rep.timeouts += 1,
+ }
+ }
+ self.server.retain_queue(|_| false);
+ std::thread::sleep(Duration::from_millis(50));
+ rep.process_cpu_ms = ms(process_cpu_time().unwrap_or_default().saturating_sub(p0));
+ rep.gop = filmcraft_codecs::gop_stats() - gop0;
+ rep
+ }
+}
+
+/// Result of [`Bench::scrub`].
+#[derive(Default)]
+pub struct ScrubReport {
+ pub seek_ms: Vec<f64>,
+ pub settle_ms: Vec<f64>,
+ pub timeouts: usize,
+ pub drag_steps: usize,
+ pub drag_shown: usize,
+ pub process_cpu_ms: f64,
+ pub gop: filmcraft_codecs::GopStats,
+ pub load: String,
+}
+
+pub fn print_header() {
+ println!(
+ "{:<34} {:>6} {:>5} {:>5} {:>7} | {:>6} {:>6} {:>6} | {:>6} {:>6} | {:>6} {:>6} {:>6} | {:>6} {:>6} | {:>7} {:>6} | {:>5} {:>5} {:>5} {:>4} | load",
+ "scenario",
+ "wall s",
+ "shown",
+ "drop",
+ "ontime",
+ "lat50",
+ "lat95",
+ "lat99",
+ "svc50",
+ "svc95",
+ "cpu/j",
+ "src/j",
+ "srcC/j",
+ "ui p50",
+ "ui p95",
+ "cpu ms/f",
+ "cores",
+ "seeks",
+ "dec",
+ "waste",
+ "canc"
+ );
+}
+
+pub fn print_row(r: &PlayReport, fps: f64) {
+ let frames = (r.shown + r.dropped).max(1) as f64;
+ let cpu_per_frame = r.process_cpu / frames;
+ println!(
+ "{:<34} {:>6.2} {:>5} {:>5} {:>6.0}% | {:>6.1} {:>6.1} {:>6.1} | {:>6.1} {:>6.1} | {:>6.1} {:>6.1} {:>6.1} | {:>6.2} {:>6.2} | {:>7.1} {:>6.2} | {:>5} {:>5} {:>5} {:>4} | {}",
+ r.label,
+ r.seconds,
+ r.shown,
+ r.dropped,
+ 100.0 * r.on_time as f64 / r.due.max(1) as f64,
+ pct(&r.latency, 0.5),
+ pct(&r.latency, 0.95),
+ pct(&r.latency, 0.99),
+ pct(&r.service, 0.5),
+ pct(&r.service, 0.95),
+ r.job_cpu.iter().sum::<f64>() / r.jobs.max(1) as f64,
+ r.src_wall.iter().sum::<f64>() / r.jobs.max(1) as f64,
+ r.src_cpu.iter().sum::<f64>() / r.jobs.max(1) as f64,
+ pct(&r.present, 0.5),
+ pct(&r.present, 0.95),
+ cpu_per_frame,
+ cpu_per_frame * fps / 1000.0,
+ r.gop.seeks,
+ r.gop.decoded,
+ r.wasted_jobs,
+ r.cancelled_jobs,
+ r.load
+ );
+}
+
+pub fn to_json(r: &PlayReport, scenario: &str, res: &str, path: &str) -> Value {
+ let frames = (r.shown + r.dropped).max(1) as f64;
+ json!({
+ "scenario": scenario, "res": res, "path": path, "play": r.label, "wall_s": r.seconds,
+ "shown": r.shown, "dropped": r.dropped, "on_time": r.on_time, "due": r.due,
+ "latency_ms": {"p50": pct(&r.latency, 0.5), "p95": pct(&r.latency, 0.95), "p99": pct(&r.latency, 0.99), "max": pct(&r.latency, 1.0)},
+ "service_ms": {"p50": pct(&r.service, 0.5), "p95": pct(&r.service, 0.95)},
+ "slack_ms": {"p5": pct(&r.slack, 0.05), "p50": pct(&r.slack, 0.5)},
+ "job_cpu_ms_mean": r.job_cpu.iter().sum::<f64>() / r.jobs.max(1) as f64,
+ "source_wall_ms_mean": r.src_wall.iter().sum::<f64>() / r.jobs.max(1) as f64,
+ "source_cpu_ms_mean": r.src_cpu.iter().sum::<f64>() / r.jobs.max(1) as f64,
+ "present_ms": {"p50": pct(&r.present, 0.5), "p95": pct(&r.present, 0.95), "max": pct(&r.present, 1.0)},
+ "ui_cpu_ms": r.ui_cpu, "process_cpu_ms": r.process_cpu, "cpu_ms_per_frame": r.process_cpu / frames,
+ "jobs": r.jobs, "wasted_jobs": r.wasted_jobs, "cancelled_jobs": r.cancelled_jobs, "preview_jobs": r.preview_jobs, "uploaded_mb": r.uploaded_mb,
+ "gop": {"hits": r.gop.hits, "misses": r.gop.misses, "seeks": r.gop.seeks, "decoded": r.gop.decoded, "evicted": r.gop.evicted},
+ "loadavg": r.load, "preroll_ms": r.preroll_ms,
+ })
+}
+
+// ------------------------------------------------------------------------------------ main
+
+struct Args {
+ scenarios: Vec<String>,
+ res: Vec<(String, f32)>,
+ gpu: bool,
+ seconds: f64,
+ refresh: f64,
+ workers: usize,
+ json: Option<String>,
+ repeat: usize,
+}
+
+fn parse_args() -> Args {
+ let mut a = Args {
+ scenarios: vec![],
+ res: vec![("full".into(), 1.0), ("half".into(), 0.5)],
+ gpu: true,
+ seconds: 8.0,
+ refresh: 60.0,
+ workers: FrameServer::default_workers(),
+ json: None,
+ repeat: 1,
+ };
+ let mut it = std::env::args().skip(1);
+ while let Some(x) = it.next() {
+ match x.as_str() {
+ "--scenario" | "-s" => a.scenarios.extend(it.next().unwrap_or_default().split(',').map(str::to_string)),
+ "--res" => {
+ a.res = it
+ .next()
+ .unwrap_or_default()
+ .split(',')
+ .map(|r| match r {
+ "half" => ("half".to_string(), 0.5),
+ "quarter" => ("quarter".to_string(), 0.25),
+ _ => ("full".to_string(), 1.0),
+ })
+ .collect()
+ }
+ "--cpu" => a.gpu = false,
+ "--gpu" => a.gpu = true,
+ "--seconds" => a.seconds = it.next().and_then(|v| v.parse().ok()).unwrap_or(8.0),
+ "--refresh" => a.refresh = it.next().and_then(|v| v.parse().ok()).unwrap_or(60.0),
+ "--workers" => a.workers = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.workers),
+ "--repeat" => a.repeat = it.next().and_then(|v| v.parse().ok()).unwrap_or(1),
+ "--json" => a.json = it.next(),
+ "--help" | "-h" => {
+ println!(
+ "bench_playback [--scenario h264-1080,stack3,h264-2160,hevc-2160,demo,after-preview,seek-storm] [--res full,half] [--cpu|--gpu] [--seconds 8] [--refresh 60] [--workers N] [--repeat N] [--json out.json]"
+ );
+ std::process::exit(0);
+ }
+ other => eprintln!("ignoring argument {other}"),
+ }
+ }
+ if a.scenarios.is_empty() {
+ a.scenarios = ["h264-1080", "stack3", "h264-2160", "hevc-2160", "demo", "after-preview", "seek-storm"].iter().map(|s| s.to_string()).collect();
+ }
+ a
+}
+
+/// Build the session for a scenario (None when its fixtures are unavailable).
+pub fn scenario_session(name: &str) -> Option<(Session, ItemId)> {
+ let mut s = Session::default();
+ let seq = match name {
+ "h264-1080" | "seek-storm" => {
+ let a = import(&mut s, &fixture("a1080.mp4")?);
+ build_sequence(&mut s, 1920, 1080, &[(a, 100.0, None, 0.0, 100.0)], &[], 20.0)
+ }
+ "stack3" => {
+ let (a, b, c) = (fixture("a1080.mp4")?, fixture("b1080.mp4")?, fixture("c1080.mp4")?);
+ let (a, b, c) = (import(&mut s, &a), import(&mut s, &b), import(&mut s, &c));
+ build_sequence(
+ &mut s,
+ 1920,
+ 1080,
+ &[(a, 100.0, None, 0.0, 100.0), (b, 60.0, Some((700.0, 420.0)), 0.0, 70.0), (c, 40.0, Some((1450.0, 760.0)), 12.0, 85.0)],
+ &[],
+ 20.0,
+ )
+ }
+ "h264-2160" | "seek-storm-2160" => {
+ let a = import(&mut s, &fixture("a2160.mp4")?);
+ build_sequence(&mut s, 3840, 2160, &[(a, 100.0, None, 0.0, 100.0)], &[], 10.0)
+ }
+ "hevc-2160" | "seek-storm-hevc-2160" => {
+ let a = import(&mut s, &fixture("hevc2160.mp4")?);
+ build_sequence(&mut s, 3840, 2160, &[(a, 100.0, None, 0.0, 100.0)], &[], 10.0)
+ }
+ "after-preview" => {
+ let a = import(&mut s, &fixture("a1080.mp4")?);
+ let seq = build_sequence(&mut s, 1920, 1080, &[(a, 100.0, None, 0.0, 100.0)], &["lumetri", "sharpen", "levels", "tint"], 20.0);
+ s.edit("marks", |p, _| {
+ let q = p.sequence_mut(seq).expect("seq");
+ q.mark_in = Some(Tick::ZERO);
+ q.mark_out = Some(q.settings.frame_rate.tick_of(8 * 24));
+ Ok(())
+ })
+ .ok()?;
+ seq
+ }
+ "demo" => {
+ s.execute("file.openDemoProject", json!({})).ok()?;
+ s.state.active_sequence?
+ }
+ _ => {
+ eprintln!("unknown scenario {name}");
+ return None;
+ }
+ };
+ Some((s, seq))
+}
+
+/// `bench_playback` / `cargo xtask bench-playback`.
+pub fn cli_main() {
+ let args = parse_args();
+ let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
+ println!(
+ "FilmCraft playback bench: {} path, {} frame workers, {} cores, refresh {} Hz, {} s per play; load avg {}",
+ if args.gpu { "GPU" } else { "CPU" },
+ args.workers,
+ cores,
+ args.refresh,
+ args.seconds,
+ load_avg()
+ );
+ println!(
+ "lat = queue→ready per job, svc = worker time per job, cpu/j = worker thread CPU, src/j = source fetch (decode) wall, srcC/j = its thread CPU,\nui = present time on the UI thread (GPU upload+draw / texture conversion), cpu ms/f = process CPU per due frame, cores = CPU cores that rate needs at the sequence fps,\nseeks/dec = decoder restarts / samples decoded, waste = finished jobs for frames never due, canc = jobs cancelled while running (all times ms)\n"
+ );
+ print_header();
+ let mut out = Vec::new();
+ for name in &args.scenarios {
+ for (res_name, scale) in &args.res {
+ if name == "seek-storm" && res_name != "full" && args.res.len() > 1 {
+ continue;
+ }
+ let Some((mut s, seq)) = scenario_session(name) else {
+ println!("{name}: skipped (fixtures unavailable: is ffmpeg installed?)");
+ continue;
+ };
+ let fps = s.project.sequence(seq).map(|q| q.settings.frame_rate.as_f64()).unwrap_or(24.0);
+ for rep_i in 0..args.repeat {
+ // A fresh frame server per run so caches start cold, as after opening a project.
+ let server = FrameServer::new(s.media.clone(), s.services.clone(), s.previews.clone(), args.workers);
+ server.set_profiling(true);
+ let bench = Bench { server, refresh_hz: args.refresh, seconds: args.seconds };
+ let mut display = Display::new(args.gpu);
+ if args.gpu && display.gpu.is_none() {
+ eprintln!("no GPU adapter; using the CPU path");
+ }
+ let path = if display.gpu.is_some() { "gpu" } else { "cpu" };
+ let tag = |l: &str| if args.repeat > 1 { format!("{name} {res_name} {l} #{}", rep_i + 1) } else { format!("{name} {res_name} {l}") };
+ let mut reports = Vec::new();
+ match name.as_str() {
+ "seek-storm" => {
+ let mut r = bench.seek_storm(&s, seq, &mut display, *scale, 40, Duration::from_millis(150));
+ r.label = tag("seek");
+ reports.push(r);
+ }
+ "after-preview" => {
+ // Live play (effects rendered per frame), render previews, then play twice.
+ reports.push(bench.play(&s, seq, &mut display, *scale, Tick::ZERO, &tag("live")));
+ let t0 = Instant::now();
+ s.execute("sequence.renderEffectsInToOut", json!({"wait": true})).expect("render previews");
+ eprintln!(" rendered previews in {:.1}s (load {})", t0.elapsed().as_secs_f64(), load_avg());
+ reports.push(bench.play(&s, seq, &mut display, *scale, Tick::ZERO, &tag("1st after")));
+ reports.push(bench.play(&s, seq, &mut display, *scale, Tick::ZERO, &tag("2nd after")));
+ s.previews.delete(None);
+ }
+ _ => reports.push(bench.play(&s, seq, &mut display, *scale, Tick::ZERO, &tag("play"))),
+ }
+ for r in &reports {
+ print_row(r, fps);
+ out.push(to_json(r, name, res_name, path));
+ }
+ }
+ }
+ }
+ if let Some(p) = args.json {
+ let doc = json!({"cores": cores, "workers": args.workers, "refresh_hz": args.refresh, "seconds": args.seconds, "runs": out});
+ if let Err(e) = std::fs::write(&p, serde_json::to_string_pretty(&doc).unwrap_or_default()) {
+ eprintln!("{p}: {e}");
+ }
+ }
+}
diff --git a/crates/ui-egui/examples/bench/sections.rs b/crates/ui-egui/examples/bench/sections.rs
new file mode 100644
index 000000000..841cf3480
--- /dev/null
+++ b/crates/ui-egui/examples/bench/sections.rs
@@ -0,0 +1,446 @@
+//! The benchmark sections. Each returns one JSON row per measured case.
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use filmcraft_engine::Session;
+use filmcraft_project::{ItemId, Project, SequenceSettings, TrackKind};
+use filmcraft_time::{FrameRate, Tick, TimeRange};
+use filmcraft_ui_egui::frames::{FrameServer, process_cpu_time};
+use serde_json::{Value, json};
+
+use crate::Opts;
+use crate::fixtures::fixture;
+use crate::playback::{self, Bench, Display, load_avg, ms, pct};
+
+fn median(v: &[f64]) -> f64 {
+ pct(v, 0.5)
+}
+
+fn cpu_now() -> Duration {
+ process_cpu_time().unwrap_or_default()
+}
+
+// ------------------------------------------------------------------------------------ decode
+
+/// (fixture, codec, size)
+const DECODE: &[(&str, &str, &str)] = &[
+ ("dec_h264_1080.mp4", "H.264", "1080p"),
+ ("dec_h264_2160.mp4", "H.264", "2160p"),
+ ("dec_hevc_1080.mp4", "HEVC", "1080p"),
+ ("dec_hevc_2160.mp4", "HEVC", "2160p"),
+ ("dec_vp9_1080.webm", "VP9", "1080p"),
+ ("dec_vp9_2160.webm", "VP9", "2160p"),
+ ("dec_av1_1080.mp4", "AV1", "1080p"),
+ ("dec_av1_2160.mp4", "AV1", "2160p"),
+ ("dec_prores_1080.mov", "ProRes 422 HQ", "1080p"),
+ ("dec_prores_2160.mov", "ProRes 422 HQ", "2160p"),
+];
+
+/// Sequential decode of every frame through the media stack (container source, GOP cache,
+/// decoder, frame conversion), as playback reads a clip. A fresh source per repeat.
+pub fn decode(o: &Opts) -> Vec<Value> {
+ let mut rows = Vec::new();
+ for &(name, codec, size) in DECODE.iter().filter(|d| o.wants(d.0)) {
+ let Some(path) = fixture(name) else {
+ eprintln!("decode {name}: skipped (fixture unavailable)");
+ continue;
+ };
+ let bytes: Arc<[u8]> = std::fs::read(&path).expect("read fixture").into();
+ let mut fps = Vec::new();
+ let mut cpu = Vec::new();
+ let mut first = Vec::new();
+ let mut frames = 0;
+ let mut rate = FrameRate::FPS_23_976;
+ for _ in 0..o.repeat {
+ let src = match filmcraft_codecs::open_bytes(name, bytes.clone()) {
+ Ok(s) => s,
+ Err(e) => {
+ eprintln!("decode {name}: {e}");
+ break;
+ }
+ };
+ rate = src.info().frame_rate();
+ let n = rate.frame_at(src.info().duration).max(1);
+ let n = if o.quick { n.min(48) } else { n };
+ frames = n;
+ let (t0, c0) = (Instant::now(), cpu_now());
+ for f in 0..n {
+ if let Err(e) = src.video_frame(filmcraft_media::FrameRequest::full(rate.tick_of(f))) {
+ eprintln!("decode {name} frame {f}: {e}");
+ break;
+ }
+ if f == 0 {
+ first.push(ms(t0.elapsed()));
+ }
+ }
+ let dt = t0.elapsed().as_secs_f64();
+ fps.push(n as f64 / dt);
+ cpu.push(ms(cpu_now() - c0) / n as f64);
+ }
+ if fps.is_empty() {
+ continue;
+ }
+ let best = fps.iter().cloned().fold(0.0, f64::max);
+ let row = json!({
+ "fixture": name, "codec": codec, "size": size, "frames": frames,
+ "fps": best, "fps_min": fps.iter().cloned().fold(f64::MAX, f64::min), "fps_runs": fps,
+ "cpu_ms_per_frame": median(&cpu), "first_frame_ms": median(&first), "realtime": best / rate.as_f64(),
+ "decode_threads": rayon::current_num_threads(), "load": load_avg(),
+ });
+ eprintln!("decode {name}: {best:.1} fps");
+ rows.push(row);
+ }
+ rows
+}
+
+// ------------------------------------------------------------------------------------ playback
+
+fn new_bench(s: &Session, seconds: f64) -> Bench {
+ let server = FrameServer::new(s.media.clone(), s.services.clone(), s.previews.clone(), FrameServer::default_workers());
+ server.set_profiling(true);
+ Bench { server, refresh_hz: 60.0, seconds }
+}
+
+/// Program-monitor playback through the real scheduler (see `playback.rs`), frames shown vs
+/// dropped over N seconds.
+pub fn playback(o: &Opts) -> Vec<Value> {
+ let seconds = if o.quick { 4.0 } else { 8.0 };
+ let cases: &[(&str, &str, f32)] = &[
+ ("h264-1080", "full", 1.0),
+ ("stack3", "full", 1.0),
+ ("h264-2160", "full", 1.0),
+ ("h264-2160", "half", 0.5),
+ ("hevc-2160", "full", 1.0),
+ ("hevc-2160", "half", 0.5),
+ ];
+ let mut rows = Vec::new();
+ for &(scenario, res, scale) in cases.iter().filter(|c| o.wants(&format!("{} {}", c.0, c.1))) {
+ let Some((s, seq)) = playback::scenario_session(scenario) else {
+ eprintln!("playback {scenario}: skipped (fixtures unavailable)");
+ continue;
+ };
+ let fps = s.project.sequence(seq).map(|q| q.settings.frame_rate.as_f64()).unwrap_or(24.0);
+ for rep in 0..o.repeat {
+ // A fresh frame server per run: caches start cold, as after opening a project.
+ let bench = new_bench(&s, seconds);
+ let mut display = Display::new(o.gpu);
+ let path = if display.gpu_available() { "gpu" } else { "cpu" };
+ let r = bench.play(&s, seq, &mut display, scale, Tick::ZERO, &format!("{scenario} {res} #{}", rep + 1));
+ let mut v = playback::to_json(&r, scenario, res, path);
+ let frames = (r.shown + r.dropped).max(1) as f64;
+ v["drop_pct"] = json!(100.0 * r.dropped as f64 / frames);
+ v["decode_ms"] = json!(r.src_wall.iter().sum::<f64>() / r.jobs.max(1) as f64);
+ v["ui_p95_ms"] = json!(pct(&r.present, 0.95));
+ v["seeks"] = json!(r.gop.seeks);
+ v["load"] = json!(r.load);
+ v["cores_needed"] = json!(r.process_cpu / frames * fps / 1000.0);
+ eprintln!("playback {scenario} {res}: {}/{} shown/dropped (load {})", r.shown, r.dropped, r.load);
+ rows.push(v);
+ }
+ }
+ rows
+}
+
+// ------------------------------------------------------------------------------------ scrub
+
+/// Scrubbing: random seeks and playhead drags at full resolution; time until the exact frame
+/// under the playhead is on screen.
+pub fn scrub(o: &Opts) -> Vec<Value> {
+ let (seeks, drags) = if o.quick { (8, 3) } else { (24, 8) };
+ let mut rows = Vec::new();
+ for scenario in ["h264-1080", "h264-2160", "hevc-2160"].into_iter().filter(|s| o.wants(s)) {
+ let Some((s, seq)) = playback::scenario_session(scenario) else {
+ eprintln!("scrub {scenario}: skipped (fixtures unavailable)");
+ continue;
+ };
+ for _ in 0..o.repeat {
+ let bench = new_bench(&s, 0.0);
+ let mut display = Display::new(o.gpu);
+ let r = bench.scrub(&s, seq, &mut display, 1.0, seeks, drags, 24, Duration::from_secs(8));
+ let positions = (seeks + drags) as f64;
+ let row = json!({
+ "scenario": scenario,
+ "seek_p50_ms": pct(&r.seek_ms, 0.5), "seek_p95_ms": pct(&r.seek_ms, 0.95), "seek_max_ms": pct(&r.seek_ms, 1.0),
+ "settle_p50_ms": pct(&r.settle_ms, 0.5), "settle_p95_ms": pct(&r.settle_ms, 0.95),
+ "drag_shown_pct": 100.0 * r.drag_shown as f64 / r.drag_steps.max(1) as f64,
+ "timeouts": r.timeouts, "gop_seeks": r.gop.seeks, "decoded": r.gop.decoded,
+ "decoded_per_seek": r.gop.decoded as f64 / positions, "process_cpu_ms": r.process_cpu_ms, "load": r.load,
+ });
+ eprintln!("scrub {scenario}: seek p50 {:.0} ms p95 {:.0} ms (load {})", pct(&r.seek_ms, 0.5), pct(&r.seek_ms, 0.95), r.load);
+ rows.push(row);
+ }
+ }
+ rows
+}
+
+// ------------------------------------------------------------------------------------ big projects
+
+/// A sequence of 20 tracks (12 video, 8 audio) × 50 clips = 1000 clips of the small clip fixture,
+/// 1–3 s each with small gaps, varied source in-points. Returns the sequence and its clip count.
+pub fn big_sequence(s: &mut Session, item: ItemId, name: &str, seed: u64) -> (ItemId, usize) {
+ let rate = FrameRate::FPS_23_976;
+ let src_frames = rate.frame_at(Tick::from_seconds_f64(19.0));
+ let mut rng = seed | 1;
+ let mut next = move || {
+ rng ^= rng << 13;
+ rng ^= rng >> 7;
+ rng ^= rng << 17;
+ rng
+ };
+ s.edit("bench sequence", |p: &mut Project, st| {
+ let settings = SequenceSettings { width: 1920, height: 1080, frame_rate: rate, ..SequenceSettings::default() };
+ let seq = p.new_sequence(name, settings, 12, 8, None);
+ let mut clips = 0;
+ for t in 0..20 {
+ let kind = if t < 12 { TrackKind::Video } else { TrackKind::Audio };
+ let mut at = (next() % 24) as i64;
+ let mut items = Vec::new();
+ for _ in 0..50 {
+ let len = 24 + (next() % 48) as i64;
+ let src_in = (next() % (src_frames - len) as u64) as i64;
+ let mut it =
+ p.make_track_item(item, kind, rate.tick_of(at), TimeRange::new(rate.tick_of(src_in), rate.tick_of(len)), rate).expect("track item");
+ // "auto" (NaN) Motion points resolve against the frame, as the edit commands do
+ for e in &mut it.effects {
+ filmcraft_project::resolve_auto_points(e, (1920, 1080), (640, 360));
+ }
+ items.push(it);
+ at += len + (next() % 12) as i64;
+ clips += 1;
+ }
+ let q = p.sequence_mut(seq).expect("seq");
+ if t < 12 {
+ q.video_tracks[t].items = items;
+ } else {
+ q.audio_tracks[t - 12].items = items;
+ }
+ }
+ st.active_sequence = Some(seq);
+ st.open_sequences = vec![seq];
+ st.playheads.insert(seq, Tick::ZERO);
+ Ok((seq, clips))
+ })
+ .expect("big sequence")
+}
+
+// ------------------------------------------------------------------------------------ timeline UI
+
+struct Ui {
+ harness: egui_kittest::Harness<'static, filmcraft_ui_egui::FilmcraftApp>,
+ tx: std::sync::mpsc::Sender<filmcraft_ui_egui::control::ControlRequest>,
+}
+
+impl Ui {
+ fn frame(&mut self) {
+ let ctx = self.harness.ctx.clone();
+ let mut raw = std::mem::take(self.harness.input_mut());
+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);
+ *self.harness.input_mut() = raw;
+ self.harness.step();
+ }
+
+ fn call(&mut self, method: &str, params: Value) -> Value {
+ let (req, reply) = filmcraft_ui_egui::control::ControlRequest::new(method, params.clone());
+ self.tx.send(req).expect("control");
+ for _ in 0..600 {
+ self.frame();
+ if let Ok(v) = reply.try_recv() {
+ return v;
+ }
+ }
+ panic!("no reply to {method} {params}");
+ }
+}
+
+/// Timeline UI frame time with a 1000-clip / 20-track sequence: the real app under
+/// `egui_kittest` (no window), per frame: app update (layout + painting), tessellation, and the
+/// wgpu render of the frame when a GPU adapter exists.
+pub fn timeline(o: &Opts) -> Vec<Value> {
+ let Some(path) = fixture("clip360.mp4") else {
+ eprintln!("timeline: skipped (fixture unavailable)");
+ return Vec::new();
+ };
+ let gpu = o.gpu && Display::new(true).gpu_available();
+ let frames = if o.quick { 40 } else { 120 };
+ let mut rows = Vec::new();
+ for _ in 0..o.repeat {
+ let mut s = Session::default();
+ let item = playback::import(&mut s, &path);
+ let (_, clips) = big_sequence(&mut s, item, "Timeline 1000", 7);
+ let (tx, rx) = std::sync::mpsc::channel();
+ let app = filmcraft_ui_egui::FilmcraftApp::new(s).with_control(rx);
+ let mut b = egui_kittest::Harness::builder().with_size(egui::vec2(1920.0, 1080.0)).with_max_steps(100_000);
+ if gpu {
+ b = b.wgpu();
+ }
+ let harness = b.build_eframe(move |_cc| app);
+ let mut ui = Ui { harness, tx };
+ for _ in 0..8 {
+ ui.frame();
+ }
+ ui.call("ui.set", json!({"timeline": {"videoTrackHeight": 34, "audioTrackHeight": 30}}));
+ for (view, setup) in
+ [("fit: all 1000 clips", json!({"timeline": {"fit": true}})), ("zoomed, scrolling", json!({"timeline": {"pps": 120.0, "scroll": 0.0}}))]
+ {
+ ui.call("ui.set", setup);
+ // settle the zoom animation, let thumbnails and waveforms arrive
+ let t_settle = Instant::now();
+ while t_settle.elapsed() < Duration::from_millis(if o.quick { 800 } else { 2500 }) {
+ ui.frame();
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ let (mut upd, mut tess, mut rend, mut total) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
+ let mut vertices = 0usize;
+ let mut shapes = 0usize;
+ let scrolling = view.starts_with("zoomed");
+ for i in 0..frames {
+ // Pointer moving over the timeline (hover feedback), and a scroll step when zoomed.
+ let x = 300.0 + (i as f32 * 13.0) % 1500.0;
+ ui.harness.hover_at(egui::pos2(x, 820.0));
+ if scrolling {
+ let tl = &mut ui.harness.state_mut().ui.timeline;
+ tl.target_scroll += 0.2;
+ tl.scroll = tl.target_scroll;
+ }
+ let t0 = Instant::now();
+ ui.frame();
+ let u = ms(t0.elapsed());
+ let out = ui.harness.output();
+ shapes = out.shapes.len();
+ let t1 = Instant::now();
+ let prims = ui.harness.ctx.tessellate(out.shapes.clone(), out.pixels_per_point);
+ let te = ms(t1.elapsed());
+ vertices = prims
+ .iter()
+ .map(|p| match &p.primitive {
+ egui::epaint::Primitive::Mesh(m) => m.vertices.len(),
+ _ => 0,
+ })
+ .sum();
+ let r = if gpu {
+ let t2 = Instant::now();
+ let _ = ui.harness.render();
+ Some(ms(t2.elapsed()))
+ } else {
+ None
+ };
+ upd.push(u);
+ tess.push(te);
+ total.push(u + r.unwrap_or(te));
+ if let Some(r) = r {
+ rend.push(r);
+ }
+ }
+ eprintln!("timeline {view}: update p50 {:.2} ms, p95 {:.2} ms", pct(&upd, 0.5), pct(&upd, 0.95));
+ rows.push(json!({
+ "view": view, "clips": clips, "frames": frames, "gpu": gpu,
+ "update_p50_ms": pct(&upd, 0.5), "update_p95_ms": pct(&upd, 0.95),
+ "tess_p50_ms": pct(&tess, 0.5), "tess_p95_ms": pct(&tess, 0.95),
+ "render_p50_ms": pct(&rend, 0.5), "render_p95_ms": pct(&rend, 0.95),
+ "total_p50_ms": pct(&total, 0.5), "total_p95_ms": pct(&total, 0.95),
+ "shapes": shapes, "vertices": vertices, "load": load_avg(),
+ }));
+ }
+ }
+ rows
+}
+
+// ------------------------------------------------------------------------------------ export
+
+/// Export throughput of a 1080p H.264 sequence (clip with AAC audio) to H.264 + AAC and ProRes.
+pub fn export(o: &Opts) -> Vec<Value> {
+ let Some(path) = fixture("a1080.mp4") else {
+ eprintln!("export: skipped (fixture unavailable)");
+ return Vec::new();
+ };
+ let secs = if o.quick { 3.0 } else { 8.0 };
+ let dir = std::env::temp_dir().join(format!("filmcraft-bench-export-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).expect("tmp dir");
+ let mut rows = Vec::new();
+ for (format, label, ext) in [("h264", "H.264 + AAC (MP4)", "mp4"), ("prores", "ProRes 422 (MOV)", "mov")] {
+ let mut runs = Vec::new();
+ let mut cpu = Vec::new();
+ let mut bytes = 0u64;
+ let mut frames = 0i64;
+ for _ in 0..o.repeat {
+ let mut s = Session::default();
+ let a = playback::import(&mut s, &path);
+ let seq = playback::build_sequence(&mut s, 1920, 1080, &[(a, 100.0, None, 0.0, 100.0)], &[], secs);
+ // build_sequence adds video only: add the clip's audio on A1 for the AAC encode
+ s.edit("audio", |p, _| {
+ let rate = FrameRate::FPS_23_976;
+ let it = p
+ .make_track_item(a, TrackKind::Audio, Tick::ZERO, TimeRange::new(Tick::ZERO, rate.snap(Tick::from_seconds_f64(secs))), rate)
+ .expect("audio item");
+ p.sequence_mut(seq).expect("seq").audio_tracks[0].items.push(it);
+ Ok(())
+ })
+ .expect("audio");
+ frames = s.project.sequence(seq).map(|q| q.settings.frame_rate.frame_at(q.duration())).unwrap_or(0);
+ let out = dir.join(format!("out.{ext}"));
+ let (t0, c0) = (Instant::now(), cpu_now());
+ let r = s.execute("file.exportMedia", json!({"path": out.to_string_lossy(), "format": format, "wait": true}));
+ let dt = t0.elapsed().as_secs_f64();
+ if let Err(e) = r {
+ eprintln!("export {format}: {e}");
+ break;
+ }
+ if let Some(e) = s.jobs.last().and_then(|j| j.progress.error.lock().ok().and_then(|g| g.clone())) {
+ eprintln!("export {format}: {e}");
+ break;
+ }
+ runs.push(dt);
+ cpu.push(ms(cpu_now() - c0) / frames.max(1) as f64);
+ bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
+ }
+ if runs.is_empty() {
+ continue;
+ }
+ let best = runs.iter().cloned().fold(f64::MAX, f64::min);
+ eprintln!("export {format}: {frames} frames in {best:.1} s");
+ rows.push(json!({
+ "format": label, "frames": frames, "seconds": best, "fps": frames as f64 / best,
+ "realtime": frames as f64 / best / FrameRate::FPS_23_976.as_f64(), "cpu_ms_per_frame": median(&cpu),
+ "mbytes": bytes as f64 / 1e6, "runs_s": runs, "load": load_avg(),
+ }));
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ rows
+}
+
+// ------------------------------------------------------------------------------------ project
+
+/// Save and open a large project: 5 sequences × 1000 clips (20 tracks each).
+pub fn project(o: &Opts) -> Vec<Value> {
+ let Some(path) = fixture("clip360.mp4") else {
+ eprintln!("project: skipped (fixture unavailable)");
+ return Vec::new();
+ };
+ let mut s = Session::default();
+ let item = playback::import(&mut s, &path);
+ let mut clips = 0;
+ for k in 0..5 {
+ clips += big_sequence(&mut s, item, &format!("Sequence {}", k + 1), 11 + k as u64).1;
+ }
+ let dir = std::env::temp_dir().join(format!("filmcraft-bench-project-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).expect("tmp dir");
+ let file = dir.join("big.fcproj");
+ let n = o.repeat.max(3);
+ let (mut save, mut open) = (Vec::new(), Vec::new());
+ for _ in 0..n {
+ let t0 = Instant::now();
+ s.execute("file.saveAs", json!({"path": file.to_string_lossy()})).expect("save");
+ save.push(ms(t0.elapsed()));
+ let mut s2 = Session::default();
+ let t1 = Instant::now();
+ s2.execute("file.open", json!({"path": file.to_string_lossy()})).expect("open");
+ open.push(ms(t1.elapsed()));
+ assert_eq!(s2.project.items.len(), s.project.items.len());
+ }
+ let mbytes = std::fs::metadata(&file).map(|m| m.len()).unwrap_or(0) as f64 / 1e6;
+ let _ = std::fs::remove_dir_all(&dir);
+ eprintln!("project: save {:.0} ms, open {:.0} ms ({clips} clips, {mbytes:.1} MB)", median(&save), median(&open));
+ let row = |what: &str, v: &[f64]| json!({"what": what, "clips": clips, "mbytes": mbytes, "p50_ms": median(v), "min_ms": v.iter().cloned().fold(f64::MAX, f64::min), "runs_ms": v, "load": load_avg()});
+ vec![row("save (file.saveAs)", &save), row("open (file.open)", &open)]
+}
diff --git a/crates/ui-egui/examples/bench_playback.rs b/crates/ui-egui/examples/bench_playback.rs
index 2a6be0659..5210b71bf 100644
--- a/crates/ui-egui/examples/bench_playback.rs
+++ b/crates/ui-egui/examples/bench_playback.rs
@@ -1,701 +1,12 @@
-//! Headless playback benchmark: drives the Program monitor's frame scheduler, prefetch and cache
-//! ([`FrameServer`], [`PlaybackMeter`]) exactly as the UI does, without a window.
-//!
-//! ```sh
-//! cargo xtask bench-playback # all scenarios, GPU path, Full + Half
-//! cargo run --release -p filmcraft-ui-egui --example bench_playback -- --scenario stack3 --res full --cpu
-//! ```
-//!
-//! Each play simulates display refreshes at `--refresh` Hz on the wall clock (as the app does
-//! without an audio device) and counts shown/dropped frames with the same meter as the app. Wall-
-//! clock numbers depend on machine load, so every run also reports CPU time (process and per
-//! frame-worker thread), which does not. See `docs/testing.md` §5.
-//!
-//! Fixtures are generated with ffmpeg into `target/fixtures/playback/` on first use (never
-//! committed). Scenarios that need them are skipped when ffmpeg is missing.
+//! Headless playback benchmark; see `bench/playback.rs` (`cargo xtask bench-playback`).
-use std::collections::HashMap;
-use std::path::{Path, PathBuf};
-use std::process::Command;
-use std::time::{Duration, Instant};
+#![allow(dead_code)]
-use filmcraft_engine::Session;
-use filmcraft_project::{ItemId, ParamValue, Project, SequenceSettings, TrackKind, find_effect, resolve_auto_points};
-use filmcraft_time::{FrameRate, Tick, TimeRange};
-use filmcraft_ui_egui::frames::{FrameKey, FrameServer, JobRecord, PREROLL_TIMEOUT_S, PlaybackMeter, Target, process_cpu_time, thread_cpu_time};
-use serde_json::{Value, json};
-
-// ------------------------------------------------------------------------------------ fixtures
-
-/// `<repo>/target/fixtures/playback`, or `$FILMCRAFT_FIXTURES/playback` (lets worktrees share one set).
-fn fixtures_dir() -> PathBuf {
- match std::env::var_os("FILMCRAFT_FIXTURES") {
- Some(d) => PathBuf::from(d).join("playback"),
- None => Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/fixtures/playback"),
- }
-}
-
-fn ffmpeg() -> Option<PathBuf> {
- ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"].iter().map(PathBuf::from).find(|p| p.exists())
-}
-
-/// (file, lavfi video source, seconds, with audio)
-const FIXTURES: &[(&str, &str, u32, bool)] = &[
- ("a1080.mp4", "testsrc2=s=1920x1080:r=24000/1001:d=20,noise=alls=6:allf=t", 20, true),
- ("b1080.mp4", "mandelbrot=s=1920x1080:r=24000/1001,trim=duration=20,noise=alls=6:allf=t", 20, false),
- ("c1080.mp4", "smptehdbars=s=1920x1080:r=24000/1001:d=20,noise=alls=10:allf=t+u", 20, false),
- ("a2160.mp4", "testsrc2=s=3840x2160:r=24000/1001:d=10,noise=alls=6:allf=t", 10, false),
-];
-
-fn fixture(name: &str) -> Option<PathBuf> {
- let dir = fixtures_dir();
- let path = dir.join(name);
- if path.exists() {
- return Some(path);
- }
- let ff = ffmpeg()?;
- let &(_, src, secs, audio) = FIXTURES.iter().find(|f| f.0 == name)?;
- std::fs::create_dir_all(&dir).ok()?;
- eprintln!("generating {}", path.display());
- let mut c = Command::new(ff);
- c.args(["-v", "error", "-y", "-f", "lavfi", "-i", src]);
- if audio {
- c.args(["-f", "lavfi", "-i", &format!("sine=f=440:d={secs}"), "-c:a", "aac", "-shortest"]);
- }
- c.args(["-c:v", "libx264", "-preset", "fast", "-crf", "20", "-pix_fmt", "yuv420p", "-movflags", "+faststart"]);
- c.arg(&path);
- c.status().ok()?.success().then_some(path)
-}
-
-// ------------------------------------------------------------------------------------ projects
-
-fn import(s: &mut Session, path: &Path) -> ItemId {
- let r = s.execute("file.import", json!({ "paths": [path.to_string_lossy()] })).expect("import");
- ItemId(r["items"].as_array().and_then(|a| a.first()).and_then(Value::as_u64).unwrap_or_else(|| panic!("import {}: {r}", path.display())))
-}
-
-/// One clip per track from t = 0 (`layers[0]` on V1), with (scale %, position, rotation°,
-/// opacity %) Motion/Opacity settings per layer.
-fn build_sequence(s: &mut Session, w: u32, h: u32, layers: &[(ItemId, f64, Option<(f64, f64)>, f64, f64)], effects: &[&str], secs: f64) -> ItemId {
- let rate = FrameRate::FPS_23_976;
- let sizes: Vec<(u32, u32)> = layers
- .iter()
- .map(|l| match s.project.item(l.0).map(|i| &i.kind) {
- Some(filmcraft_project::ItemKind::Media(m)) => m.info.video.as_ref().map(|v| (v.width, v.height)).unwrap_or((w, h)),
- _ => (w, h),
- })
- .collect();
- s.edit("bench sequence", |p: &mut Project, st| {
- let settings = SequenceSettings { width: w, height: h, frame_rate: rate, ..SequenceSettings::default() };
- let seq = p.new_sequence("Bench", settings, layers.len().max(1), 1, None);
- for (i, &(item, scale, pos, rot, opacity)) in layers.iter().enumerate() {
- let range = TimeRange::new(Tick::ZERO, rate.snap(Tick::from_seconds_f64(secs)));
- let mut v = p.make_track_item(item, TrackKind::Video, Tick::ZERO, range, rate).expect("track item");
- for e in &mut v.effects {
- resolve_auto_points(e, (w, h), sizes[i]);
- }
- if let Some(m) = v.effect_mut("motion") {
- if let Some(x) = m.params.get_mut("scale") {
- x.value = ParamValue::Float(scale);
- }
- if let (Some(x), Some((px, py))) = (m.params.get_mut("position"), pos) {
- x.value = ParamValue::Vec2(filmcraft_geom::Vec2::new(px, py));
- }
- if let Some(x) = m.params.get_mut("rotation") {
- x.value = ParamValue::Float(rot);
- }
- }
- if let Some(o) = v.effect_mut("opacity").and_then(|o| o.params.get_mut("opacity")) {
- o.value = ParamValue::Float(opacity);
- }
- if i == 0 {
- for (k, id) in effects.iter().enumerate() {
- let mut e = find_effect(id).unwrap_or_else(|| panic!("effect {id}")).instance();
- let set: &[(&str, f64)] = match *id {
- "lumetri" => &[("temperature", 18.0), ("contrast", 22.0)],
- "sharpen" => &[("amount", 40.0)],
- _ => &[],
- };
- for (name, val) in set {
- if let Some(p) = e.params.get_mut(*name) {
- p.value = ParamValue::Float(*val);
- }
- }
- v.effects.insert(k, e);
- }
- }
- p.sequence_mut(seq).expect("seq").video_tracks[i].items.push(v);
- }
- st.active_sequence = Some(seq);
- st.open_sequences = vec![seq];
- st.playheads.insert(seq, Tick::ZERO);
- Ok(seq)
- })
- .expect("sequence")
-}
-
-// ------------------------------------------------------------------------------------ display
-
-/// The UI side of a monitor: presents the frame it gets (GPU composite or texture conversion)
-/// and times that work, as `gpu_present` / `texture_for` do in the app.
-struct Display {
- gpu: Option<(filmcraft_gpu::GpuCompositor, eframe::wgpu::Device)>,
- last: Option<FrameKey>,
- present: Vec<Duration>,
- ui_cpu: Duration,
- uploaded: u64,
-}
-
-impl Display {
- fn new(gpu: bool) -> Self {
- let gpu = if gpu {
- let instance = eframe::wgpu::Instance::default();
- let adapter = pollster::block_on(instance.request_adapter(&eframe::wgpu::RequestAdapterOptions::default())).ok();
- adapter.and_then(|a| pollster::block_on(a.request_device(&eframe::wgpu::DeviceDescriptor::default())).ok()).map(|(d, q)| {
- let c = filmcraft_gpu::GpuCompositor::new(&d, &q);
- (c, d)
- })
- } else {
- None
- };
- Self { gpu, last: None, present: Vec::new(), ui_cpu: Duration::ZERO, uploaded: 0 }
- }
-
- fn target(&self, seq: ItemId) -> Target {
- if self.gpu.is_some() { Target::SequencePlan(seq) } else { Target::Sequence(seq) }
- }
-
- /// Show the exact frame, or the nearest earlier cached one; returns whether it was exact.
- fn refresh(&mut self, server: &FrameServer, key: FrameKey) -> bool {
- let (c0, t0) = (thread_cpu_time().unwrap_or_default(), Instant::now());
- let exact;
- let mut presented = false;
- if let Some((comp, dev)) = self.gpu.as_mut() {
- let plan = server.get_plan(&key).map(|p| (key, p));
- exact = plan.is_some();
- if let Some((k, plan)) = plan.or_else(|| server.nearest_plan(key, 6))
- && self.last != Some(k)
- {
- let before = comp.uploaded_bytes;
- let _ = comp.composite_prepared(&plan.plan, Some(&plan.prepared));
- // Wait for the GPU so the time includes the upload and the draw.
- let _ = dev.poll(eframe::wgpu::PollType::wait_indefinitely());
- self.uploaded += comp.uploaded_bytes - before;
- self.last = Some(k);
- presented = true;
- }
- } else {
- let img = server.get(&key).map(|i| (key, i));
- exact = img.is_some();
- let near = img.or_else(|| server.nearest(key.target, key.frame, key.size, key.revision, 6).map(|i| (FrameKey { frame: key.frame - 1, ..key }, i)));
- if let Some((k, img)) = near
- && self.last != Some(k)
- {
- let ci = egui::ColorImage::from_rgba_unmultiplied([img.w, img.h], &img.px);
- std::hint::black_box(&ci);
- self.uploaded += img.px.len() as u64;
- self.last = Some(k);
- presented = true;
- }
- }
- if presented {
- self.present.push(t0.elapsed());
- }
- self.ui_cpu += thread_cpu_time().unwrap_or_default().saturating_sub(c0);
- exact
- }
-}
-
-// ------------------------------------------------------------------------------------ measuring
-
-#[derive(Default)]
-struct PlayReport {
- label: String,
- seconds: f64,
- shown: u64,
- dropped: u64,
- /// Due frames whose job finished before the frame was due.
- on_time: usize,
- due: usize,
- /// ms: queue→done latency, service time, (due − done) slack of due frames.
- latency: Vec<f64>,
- service: Vec<f64>,
- slack: Vec<f64>,
- /// ms per job: worker thread CPU, source fetch (decode) wall and thread CPU.
- job_cpu: Vec<f64>,
- src_wall: Vec<f64>,
- src_cpu: Vec<f64>,
- present: Vec<f64>,
- process_cpu: f64,
- ui_cpu: f64,
- jobs: usize,
- wasted_jobs: usize,
- cancelled_jobs: usize,
- preview_jobs: usize,
- gop: filmcraft_codecs::GopStats,
- uploaded_mb: f64,
- load: String,
- preroll_ms: f64,
-}
-
-fn pct(v: &[f64], p: f64) -> f64 {
- if v.is_empty() {
- return f64::NAN;
- }
- let mut s = v.to_vec();
- s.sort_by(|a, b| a.total_cmp(b));
- s[((s.len() - 1) as f64 * p).round() as usize]
-}
-
-fn ms(d: Duration) -> f64 {
- d.as_secs_f64() * 1000.0
-}
-
-fn load_avg() -> String {
- Command::new("sysctl")
- .args(["-n", "vm.loadavg"])
- .output()
- .ok()
- .map(|o| String::from_utf8_lossy(&o.stdout).trim().trim_matches(['{', '}', ' ']).to_string())
- .unwrap_or_default()
-}
-
-struct Bench {
- server: FrameServer,
- refresh_hz: f64,
- seconds: f64,
-}
-
-impl Bench {
- /// Play `seconds` from `start` at `scale`, refreshing like the UI.
- fn play(&self, s: &Session, seq: ItemId, display: &mut Display, scale: f32, start: Tick, label: &str) -> PlayReport {
- let q = s.project.sequence(seq).expect("seq");
- let rate = q.settings.frame_rate;
- let end = (start + Tick::from_seconds_f64(self.seconds)).min(q.duration());
- let project = s.project.clone();
- let target = display.target(seq);
- let size = (scale * 1000.0) as u32;
- let mut meter = PlaybackMeter::default();
- meter.start(1.0);
- self.server.take_records();
- let gop0 = filmcraft_codecs::gop_stats();
- let (p0, ui0, up0) = (process_cpu_time().unwrap_or_default(), display.ui_cpu, display.uploaded);
- display.present.clear();
- let period = Duration::from_secs_f64(1.0 / self.refresh_hz);
- // Preroll as the app does: refresh without moving the playhead until the first frames are
- // ready (or the timeout), then start the clock.
- let first = rate.frame_at(start);
- let last_frame = rate.frame_at(q.duration()) - 1;
- let t_pre = Instant::now();
- loop {
- let key = FrameKey { target, frame: first, size, revision: s.revision };
- self.server.schedule_playback(key, rate, scale, &project, 1.0, true);
- let exact = display.refresh(&self.server, key);
- meter.refresh(first, exact);
- if self.server.preroll_ready(key, 1.0, last_frame) || t_pre.elapsed().as_secs_f64() >= PREROLL_TIMEOUT_S {
- break;
- }
- std::thread::sleep(period);
- }
- let preroll_ms = ms(t_pre.elapsed());
- let anchor = Instant::now();
- let mut due_at: HashMap<i64, Instant> = HashMap::new();
- let mut next = anchor;
- let mut frame;
- loop {
- let now = Instant::now();
- let t = start + Tick::from_seconds_f64((now - anchor).as_secs_f64());
- if t >= end {
- break;
- }
- frame = rate.frame_at(t);
- due_at.entry(frame).or_insert(now);
- let key = FrameKey { target, frame, size, revision: s.revision };
- self.server.schedule_playback(key, rate, scale, &project, 1.0, false);
- let exact = display.refresh(&self.server, key);
- meter.refresh(frame, exact);
- next += period;
- let now = Instant::now();
- if next > now {
- std::thread::sleep(next - now);
- } else {
- next = now;
- }
- }
- meter.finish();
- let wall = anchor.elapsed().as_secs_f64();
- // Stop as the app does (drop and cancel prefetch), letting running jobs wind down so their
- // CPU is counted.
- self.server.stop_prefetch();
- std::thread::sleep(Duration::from_millis(50));
- let process_cpu = ms(process_cpu_time().unwrap_or_default().saturating_sub(p0));
- let recs: Vec<JobRecord> = self.server.take_records();
- let mut by_frame: HashMap<i64, JobRecord> = HashMap::new();
- for r in &recs {
- if r.key.target == target && r.key.size == size {
- by_frame.insert(r.key.frame, *r);
- }
- }
- let mut rep = PlayReport {
- label: label.to_string(),
- seconds: wall,
- shown: meter.shown,
- dropped: meter.dropped,
- process_cpu,
- ui_cpu: ms(display.ui_cpu - ui0),
- jobs: recs.len(),
- gop: filmcraft_codecs::gop_stats() - gop0,
- uploaded_mb: (display.uploaded - up0) as f64 / 1e6,
- load: load_avg(),
- preroll_ms,
- ..Default::default()
- };
- let last = rate.frame_at(end - Tick(1));
- for f in first..=last {
- let Some(due) = due_at.get(&f) else { continue };
- rep.due += 1;
- if let Some(r) = by_frame.get(&f) {
- if r.finished <= *due {
- rep.on_time += 1;
- rep.slack.push(ms(*due - r.finished));
- } else {
- rep.slack.push(-ms(r.finished - *due));
- }
- }
- }
- for r in &recs {
- rep.latency.push(ms(r.finished - r.queued));
- rep.service.push(ms(r.finished - r.started));
- rep.job_cpu.push(ms(r.cpu));
- rep.src_wall.push(ms(r.source_wall));
- rep.src_cpu.push(ms(r.source_cpu));
- if !due_at.contains_key(&r.key.frame) || r.key.target != target {
- rep.wasted_jobs += 1;
- }
- if r.preview {
- rep.preview_jobs += 1;
- }
- if r.cancelled {
- rep.cancelled_jobs += 1;
- }
- }
- rep.present = display.present.iter().map(|d| ms(*d)).collect();
- rep
- }
-
- /// Scrub: jump to a new random frame every `dwell` and measure how long the exact frame takes.
- fn seek_storm(&self, s: &Session, seq: ItemId, display: &mut Display, scale: f32, jumps: usize, dwell: Duration) -> PlayReport {
- let q = s.project.sequence(seq).expect("seq");
- let rate = q.settings.frame_rate;
- let frames = rate.frame_at(q.duration()).max(1);
- let project = s.project.clone();
- let target = display.target(seq);
- let size = (scale * 1000.0) as u32;
- self.server.take_records();
- let gop0 = filmcraft_codecs::gop_stats();
- let p0 = process_cpu_time().unwrap_or_default();
- let t0 = Instant::now();
- let mut rng = 0x2545_f491_4f6c_dd1du64;
- let mut rep = PlayReport { label: format!("seek storm ({jumps} jumps, {} ms)", dwell.as_millis()), ..Default::default() };
- let period = Duration::from_secs_f64(1.0 / self.refresh_hz);
- for _ in 0..jumps {
- rng ^= rng << 13;
- rng ^= rng >> 7;
- rng ^= rng << 17;
- let frame = (rng % frames as u64) as i64;
- let key = FrameKey { target, frame, size, revision: s.revision };
- let start = Instant::now();
- rep.due += 1;
- loop {
- // As the monitor does while not playing: request the frame under the playhead.
- self.server.request(key, rate.tick_of(frame), scale, &project, 0);
- if display.refresh(&self.server, key) {
- rep.on_time += 1;
- rep.latency.push(ms(start.elapsed()));
- break;
- }
- if start.elapsed() >= dwell {
- rep.dropped += 1;
- break;
- }
- std::thread::sleep(period);
- }
- let left = dwell.saturating_sub(start.elapsed());
- std::thread::sleep(left);
- }
- self.server.retain_queue(|_| false);
- std::thread::sleep(Duration::from_millis(50));
- rep.seconds = t0.elapsed().as_secs_f64();
- rep.process_cpu = ms(process_cpu_time().unwrap_or_default().saturating_sub(p0));
- let recs = self.server.take_records();
- rep.jobs = recs.len();
- for r in &recs {
- rep.service.push(ms(r.finished - r.started));
- rep.job_cpu.push(ms(r.cpu));
- rep.src_wall.push(ms(r.source_wall));
- rep.src_cpu.push(ms(r.source_cpu));
- }
- rep.shown = rep.on_time as u64;
- rep.gop = filmcraft_codecs::gop_stats() - gop0;
- rep.load = load_avg();
- rep
- }
-}
-
-fn print_header() {
- println!(
- "{:<34} {:>6} {:>5} {:>5} {:>7} | {:>6} {:>6} {:>6} | {:>6} {:>6} | {:>6} {:>6} {:>6} | {:>6} {:>6} | {:>7} {:>6} | {:>5} {:>5} {:>5} {:>4} | load",
- "scenario",
- "wall s",
- "shown",
- "drop",
- "ontime",
- "lat50",
- "lat95",
- "lat99",
- "svc50",
- "svc95",
- "cpu/j",
- "src/j",
- "srcC/j",
- "ui p50",
- "ui p95",
- "cpu ms/f",
- "cores",
- "seeks",
- "dec",
- "waste",
- "canc"
- );
-}
-
-fn print_row(r: &PlayReport, fps: f64) {
- let frames = (r.shown + r.dropped).max(1) as f64;
- let cpu_per_frame = r.process_cpu / frames;
- println!(
- "{:<34} {:>6.2} {:>5} {:>5} {:>6.0}% | {:>6.1} {:>6.1} {:>6.1} | {:>6.1} {:>6.1} | {:>6.1} {:>6.1} {:>6.1} | {:>6.2} {:>6.2} | {:>7.1} {:>6.2} | {:>5} {:>5} {:>5} {:>4} | {}",
- r.label,
- r.seconds,
- r.shown,
- r.dropped,
- 100.0 * r.on_time as f64 / r.due.max(1) as f64,
- pct(&r.latency, 0.5),
- pct(&r.latency, 0.95),
- pct(&r.latency, 0.99),
- pct(&r.service, 0.5),
- pct(&r.service, 0.95),
- r.job_cpu.iter().sum::<f64>() / r.jobs.max(1) as f64,
- r.src_wall.iter().sum::<f64>() / r.jobs.max(1) as f64,
- r.src_cpu.iter().sum::<f64>() / r.jobs.max(1) as f64,
- pct(&r.present, 0.5),
- pct(&r.present, 0.95),
- cpu_per_frame,
- cpu_per_frame * fps / 1000.0,
- r.gop.seeks,
- r.gop.decoded,
- r.wasted_jobs,
- r.cancelled_jobs,
- r.load
- );
-}
-
-fn to_json(r: &PlayReport, scenario: &str, res: &str, path: &str) -> Value {
- let frames = (r.shown + r.dropped).max(1) as f64;
- json!({
- "scenario": scenario, "res": res, "path": path, "play": r.label, "wall_s": r.seconds,
- "shown": r.shown, "dropped": r.dropped, "on_time": r.on_time, "due": r.due,
- "latency_ms": {"p50": pct(&r.latency, 0.5), "p95": pct(&r.latency, 0.95), "p99": pct(&r.latency, 0.99), "max": pct(&r.latency, 1.0)},
- "service_ms": {"p50": pct(&r.service, 0.5), "p95": pct(&r.service, 0.95)},
- "slack_ms": {"p5": pct(&r.slack, 0.05), "p50": pct(&r.slack, 0.5)},
- "job_cpu_ms_mean": r.job_cpu.iter().sum::<f64>() / r.jobs.max(1) as f64,
- "source_wall_ms_mean": r.src_wall.iter().sum::<f64>() / r.jobs.max(1) as f64,
- "source_cpu_ms_mean": r.src_cpu.iter().sum::<f64>() / r.jobs.max(1) as f64,
- "present_ms": {"p50": pct(&r.present, 0.5), "p95": pct(&r.present, 0.95), "max": pct(&r.present, 1.0)},
- "ui_cpu_ms": r.ui_cpu, "process_cpu_ms": r.process_cpu, "cpu_ms_per_frame": r.process_cpu / frames,
- "jobs": r.jobs, "wasted_jobs": r.wasted_jobs, "cancelled_jobs": r.cancelled_jobs, "preview_jobs": r.preview_jobs, "uploaded_mb": r.uploaded_mb,
- "gop": {"hits": r.gop.hits, "misses": r.gop.misses, "seeks": r.gop.seeks, "decoded": r.gop.decoded, "evicted": r.gop.evicted},
- "loadavg": r.load, "preroll_ms": r.preroll_ms,
- })
-}
-
-// ------------------------------------------------------------------------------------ main
-
-struct Args {
- scenarios: Vec<String>,
- res: Vec<(String, f32)>,
- gpu: bool,
- seconds: f64,
- refresh: f64,
- workers: usize,
- json: Option<String>,
- repeat: usize,
-}
-
-fn parse_args() -> Args {
- let mut a = Args {
- scenarios: vec![],
- res: vec![("full".into(), 1.0), ("half".into(), 0.5)],
- gpu: true,
- seconds: 8.0,
- refresh: 60.0,
- workers: FrameServer::default_workers(),
- json: None,
- repeat: 1,
- };
- let mut it = std::env::args().skip(1);
- while let Some(x) = it.next() {
- match x.as_str() {
- "--scenario" | "-s" => a.scenarios.extend(it.next().unwrap_or_default().split(',').map(str::to_string)),
- "--res" => {
- a.res = it
- .next()
- .unwrap_or_default()
- .split(',')
- .map(|r| match r {
- "half" => ("half".to_string(), 0.5),
- "quarter" => ("quarter".to_string(), 0.25),
- _ => ("full".to_string(), 1.0),
- })
- .collect()
- }
- "--cpu" => a.gpu = false,
- "--gpu" => a.gpu = true,
- "--seconds" => a.seconds = it.next().and_then(|v| v.parse().ok()).unwrap_or(8.0),
- "--refresh" => a.refresh = it.next().and_then(|v| v.parse().ok()).unwrap_or(60.0),
- "--workers" => a.workers = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.workers),
- "--repeat" => a.repeat = it.next().and_then(|v| v.parse().ok()).unwrap_or(1),
- "--json" => a.json = it.next(),
- "--help" | "-h" => {
- println!(
- "bench_playback [--scenario h264-1080,stack3,h264-2160,demo,after-preview,seek-storm] [--res full,half] [--cpu|--gpu] [--seconds 8] [--refresh 60] [--workers N] [--repeat N] [--json out.json]"
- );
- std::process::exit(0);
- }
- other => eprintln!("ignoring argument {other}"),
- }
- }
- if a.scenarios.is_empty() {
- a.scenarios = ["h264-1080", "stack3", "h264-2160", "demo", "after-preview", "seek-storm"].iter().map(|s| s.to_string()).collect();
- }
- a
-}
-
-/// Build the session for a scenario (None when its fixtures are unavailable).
-fn scenario_session(name: &str) -> Option<(Session, ItemId)> {
- let mut s = Session::default();
- let seq = match name {
- "h264-1080" | "seek-storm" => {
- let a = import(&mut s, &fixture("a1080.mp4")?);
- build_sequence(&mut s, 1920, 1080, &[(a, 100.0, None, 0.0, 100.0)], &[], 20.0)
- }
- "stack3" => {
- let (a, b, c) = (fixture("a1080.mp4")?, fixture("b1080.mp4")?, fixture("c1080.mp4")?);
- let (a, b, c) = (import(&mut s, &a), import(&mut s, &b), import(&mut s, &c));
- build_sequence(
- &mut s,
- 1920,
- 1080,
- &[(a, 100.0, None, 0.0, 100.0), (b, 60.0, Some((700.0, 420.0)), 0.0, 70.0), (c, 40.0, Some((1450.0, 760.0)), 12.0, 85.0)],
- &[],
- 20.0,
- )
- }
- "h264-2160" => {
- let a = import(&mut s, &fixture("a2160.mp4")?);
- build_sequence(&mut s, 3840, 2160, &[(a, 100.0, None, 0.0, 100.0)], &[], 10.0)
- }
- "after-preview" => {
- let a = import(&mut s, &fixture("a1080.mp4")?);
- let seq = build_sequence(&mut s, 1920, 1080, &[(a, 100.0, None, 0.0, 100.0)], &["lumetri", "sharpen", "levels", "tint"], 20.0);
- s.edit("marks", |p, _| {
- let q = p.sequence_mut(seq).expect("seq");
- q.mark_in = Some(Tick::ZERO);
- q.mark_out = Some(q.settings.frame_rate.tick_of(8 * 24));
- Ok(())
- })
- .ok()?;
- seq
- }
- "demo" => {
- s.execute("file.openDemoProject", json!({})).ok()?;
- s.state.active_sequence?
- }
- _ => {
- eprintln!("unknown scenario {name}");
- return None;
- }
- };
- Some((s, seq))
-}
+#[path = "bench/fixtures.rs"]
+mod fixtures;
+#[path = "bench/playback.rs"]
+mod playback;
fn main() {
- let args = parse_args();
- let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
- println!(
- "FilmCraft playback bench: {} path, {} frame workers, {} cores, refresh {} Hz, {} s per play; load avg {}",
- if args.gpu { "GPU" } else { "CPU" },
- args.workers,
- cores,
- args.refresh,
- args.seconds,
- load_avg()
- );
- println!(
- "lat = queue→ready per job, svc = worker time per job, cpu/j = worker thread CPU, src/j = source fetch (decode) wall, srcC/j = its thread CPU,\nui = present time on the UI thread (GPU upload+draw / texture conversion), cpu ms/f = process CPU per due frame, cores = CPU cores that rate needs at the sequence fps,\nseeks/dec = decoder restarts / samples decoded, waste = finished jobs for frames never due, canc = jobs cancelled while running (all times ms)\n"
- );
- print_header();
- let mut out = Vec::new();
- for name in &args.scenarios {
- for (res_name, scale) in &args.res {
- if name == "seek-storm" && res_name != "full" && args.res.len() > 1 {
- continue;
- }
- let Some((mut s, seq)) = scenario_session(name) else {
- println!("{name}: skipped (fixtures unavailable: is ffmpeg installed?)");
- continue;
- };
- let fps = s.project.sequence(seq).map(|q| q.settings.frame_rate.as_f64()).unwrap_or(24.0);
- for rep_i in 0..args.repeat {
- // A fresh frame server per run so caches start cold, as after opening a project.
- let server = FrameServer::new(s.media.clone(), s.services.clone(), s.previews.clone(), args.workers);
- server.set_profiling(true);
- let bench = Bench { server, refresh_hz: args.refresh, seconds: args.seconds };
- let mut display = Display::new(args.gpu);
- if args.gpu && display.gpu.is_none() {
- eprintln!("no GPU adapter; using the CPU path");
- }
- let path = if display.gpu.is_some() { "gpu" } else { "cpu" };
- let tag = |l: &str| if args.repeat > 1 { format!("{name} {res_name} {l} #{}", rep_i + 1) } else { format!("{name} {res_name} {l}") };
- let mut reports = Vec::new();
- match name.as_str() {
- "seek-storm" => {
- let mut r = bench.seek_storm(&s, seq, &mut display, *scale, 40, Duration::from_millis(150));
- r.label = tag("seek");
- reports.push(r);
- }
- "after-preview" => {
- // Live play (effects rendered per frame), render previews, then play twice.
- reports.push(bench.play(&s, seq, &mut display, *scale, Tick::ZERO, &tag("live")));
- let t0 = Instant::now();
- s.execute("sequence.renderEffectsInToOut", json!({"wait": true})).expect("render previews");
- eprintln!(" rendered previews in {:.1}s (load {})", t0.elapsed().as_secs_f64(), load_avg());
- reports.push(bench.play(&s, seq, &mut display, *scale, Tick::ZERO, &tag("1st after")));
- reports.push(bench.play(&s, seq, &mut display, *scale, Tick::ZERO, &tag("2nd after")));
- s.previews.delete(None);
- }
- _ => reports.push(bench.play(&s, seq, &mut display, *scale, Tick::ZERO, &tag("play"))),
- }
- for r in &reports {
- print_row(r, fps);
- out.push(to_json(r, name, res_name, path));
- }
- }
- }
- }
- if let Some(p) = args.json {
- let doc = json!({"cores": cores, "workers": args.workers, "refresh_hz": args.refresh, "seconds": args.seconds, "runs": out});
- if let Err(e) = std::fs::write(&p, serde_json::to_string_pretty(&doc).unwrap_or_default()) {
- eprintln!("{p}: {e}");
- }
- }
+ playback::cli_main();
}
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index be4064d4b..37cf027b2 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -425,6 +425,14 @@ fn bench_playback() -> Result<(), String> {
run(Command::new(env!("CARGO")).args(["run", "--release", "-p", "filmcraft-ui-egui", "--example", "bench_playback", "--"]).args(&extra))
}
+/// The benchmark suite (`crates/ui-egui/examples/bench/`): decode, playback, scrubbing, timeline
+/// UI, export, project save/open and peak memory, written to `target/bench/bench-<label>.{json,md}`
+/// (`cargo xtask bench --sections decode,scrub --repeat 3 --label after`). See docs/performance.md.
+fn bench() -> Result<(), String> {
+ let extra: Vec<String> = std::env::args().skip(2).collect();
+ run(Command::new(env!("CARGO")).args(["run", "--release", "-p", "filmcraft-ui-egui", "--example", "bench", "--"]).args(&extra))
+}
+
fn main() -> ExitCode {
let task = std::env::args().nth(1).unwrap_or_default();
let r = match task.as_str() {
@@ -433,9 +441,10 @@ fn main() -> ExitCode {
"assets" => assets(),
"fixtures" => fixtures(&std::env::args().skip(2).collect::<Vec<_>>()),
"ci" => ci(),
+ "bench" => bench(),
"bench-playback" => bench_playback(),
"web" => web(&std::env::args().skip(2).collect::<Vec<_>>()),
- _ => Err("usage: cargo xtask <layers|assets|wasm|web [--dev] [--serve PORT]|fixtures [crate…]|ci|bench-playback [args]>".into()),
+ _ => Err("usage: cargo xtask <layers|assets|wasm|web [--dev] [--serve PORT]|fixtures [crate…]|ci|bench [args]|bench-playback [args]>".into()),
};
match r {
Ok(()) => ExitCode::SUCCESS,