forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

bench.rs975 lines, 37.7 KiBHistoryRawDownload
1//! The baseline every later decode/encode change is measured against: open,
2//! seek, seek storm, play loop, scrub and export, timed on the real library
3//! rather than on a fixture.
4//!
5//! `cargo run --release -p engine --example bench -- <metric> <file> [args]`
6//!
7//! One metric per process, on purpose: a decoder that panics (the vendored
8//! HEVC parser does, on a 2160p remux) must cost one row and not the run, so
9//! `scripts/bench.sh` reads the exit status of each of these and writes the
10//! failure down as data.
11//!
12//! Every row is one TSV line -- `file, metric, unit, n, median, min, max, note`
13//! -- so the whole baseline is `cat`ted together and diffed later. The note is
14//! where the tail percentile and the **decode backend** live: a row that does
15//! not say `backend hw` was measured in software, and a baseline that does not
16//! say which is not a baseline (see `scripts/bench.sh` on `LD_LIBRARY_PATH`).
17//!
18//! **Cold and warm.** Cold means the file's pages are dropped from the page
19//! cache immediately before the measurement, with `posix_fadvise(DONTNEED)` on
20//! a fd of our own: no `drop_caches`, no root, and nothing else on the machine
21//! is evicted. It is advisory -- a page another process still holds mapped
22//! stays -- which is why the cold numbers are a *floor* on the cold cost and
23//! the run log records that. Warm means the same open repeated with the cache
24//! left as the previous one filled it.
25//!
26//! **Media files are read only here.** Nothing in this file opens anything for
27//! writing except the export destination it is handed.
28//!
29//! Env: `BENCH_TTFF_TIMEOUT` (s, default 180) how long a seek may wait for its
30//! first frame, `BENCH_EXPORT_SPAN` (s, default 60) how much timeline one
31//! export measurement covers, `BENCH_EXPORT_AUDIO` (unset) whether that
32//! timeline carries its source's sound as well -- the row is named `_av` when
33//! it does, because an export's wall clock is the audio pass plus the picture
34//! and a picture-only number is not the thing a person waits for --
35//! `BENCH_EXPORT_ASTREAM` (default 0) which of the file's audio streams that
36//! is, a film's second track often being the one no sample table can copy and
37//! therefore the one that measures a re-encode,
38//! `BENCH_EXPORT_CAP` (s, default 300) the wall clock any single
39//! export measurement may take, `BENCH_EXPORT_REPS` (default 5) how many times
40//! an export is repeated *if the cap leaves room* -- a 4K encode gets one
41//! capped rep, the small control gets five -- and `BENCH_KEEP` (unset) whether
42//! the exported file survives the run instead of being deleted with the number.
43
44use std::path::{Path, PathBuf};
45use std::time::{Duration, Instant};
46
47use engine::export::{EncoderSeat, ExportSettings, Format};
48use engine::project::{Clip, Lane, LaneKind, Project, Source, Speed};
49
50// `posix_fadvise(2)`, straight from libc, which std already links: dropping
51// this file's pages needs no crate and no privilege.
52unsafe extern "C" {
53 fn posix_fadvise(fd: i32, offset: i64, len: i64, advice: i32) -> i32;
54}
55const POSIX_FADV_DONTNEED: i32 = 4;
56
57fn main() {
58 let mut args = std::env::args().skip(1);
59 let metric = args.next().unwrap_or_else(|| usage());
60 let path = PathBuf::from(args.next().unwrap_or_else(|| usage()));
61 match metric.as_str() {
62 "open" => open_bench(&path),
63 "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")),
64 "seekstorm" => seekstorm_bench(&path, arg_seed(args.next())),
65 "playloop" => playloop_bench(&path, arg_f64(args.next(), "seconds"), arg_seed(args.next())),
66 "cutloop" => cutloop_bench(
67 &path,
68 arg_or(args.next(), 20.0) as u32,
69 arg_or(args.next(), 0.5),
70 arg_or(args.next(), 0.3),
71 ),
72 "scrub" => scrub_bench(&path),
73 "waveform" => waveform_bench(&path),
74 "export" => {
75 let seat = args.next().unwrap_or_else(|| usage());
76 let out_dir = PathBuf::from(args.next().unwrap_or_else(|| usage()));
77 export_bench(&path, &seat, &out_dir);
78 }
79 _ => usage(),
80 }
81}
82
83fn usage() -> ! {
84 eprintln!(
85 "usage: bench open <file>\n bench seek <file> <secs>\n \
86 bench seekstorm <file> [seed]\n \
87 bench playloop <file> <secs> [seed]\n \
88 bench cutloop <file> [regions=20] [keep_s=0.5] [cut_s=0.3]\n \
89 bench scrub <file>\n bench waveform <file>\n \
90 bench export <file> <h264sw|h264hw|av1|hevc|hevchw> <out_dir>"
91 );
92 std::process::exit(2)
93}
94
95fn arg_f64(arg: Option<String>, what: &str) -> f64 {
96 arg.and_then(|s| s.parse().ok())
97 .unwrap_or_else(|| panic!("missing {what}"))
98}
99
100/// An optional measurement parameter with a default, so a rerun that names
101/// nothing runs the same shape of timeline the last one did.
102fn arg_or(arg: Option<String>, default: f64) -> f64 {
103 arg.and_then(|s| s.parse().ok()).unwrap_or(default)
104}
105
106/// The seed the random metrics draw their positions from: same seed, same
107/// seeks, so a before and an after are the same measurement.
108fn arg_seed(arg: Option<String>) -> u64 {
109 arg.and_then(|s| s.parse().ok()).unwrap_or(1)
110}
111
112// ---------------------------------------------------------------- reporting
113
114/// One TSV row: the median is what a comparison uses, the min and max are what
115/// says whether the median means anything.
116fn row(file: &Path, metric: &str, unit: &str, samples: &[f64], note: &str) {
117 let name = file.file_name().unwrap_or(file.as_os_str()).to_string_lossy();
118 if samples.is_empty() {
119 println!("{name}\t{metric}\t{unit}\t0\t\t\t\t{note}");
120 return;
121 }
122 let mut sorted = samples.to_vec();
123 sorted.sort_by(f64::total_cmp);
124 let median = if sorted.len() % 2 == 1 {
125 sorted[sorted.len() / 2]
126 } else {
127 (sorted[sorted.len() / 2 - 1] + sorted[sorted.len() / 2]) / 2.0
128 };
129 println!(
130 "{name}\t{metric}\t{unit}\t{}\t{median:.2}\t{:.2}\t{:.2}\t{note}",
131 sorted.len(),
132 sorted[0],
133 sorted[sorted.len() - 1],
134 );
135}
136
137// ------------------------------------------------------------------- helpers
138
139/// Drops this file's page cache. Advisory: pages someone else holds survive,
140/// so a "cold" number here is the optimistic end of cold.
141fn evict(path: &Path) {
142 use std::os::unix::io::AsRawFd;
143 let file = std::fs::File::open(path).expect("open for evict");
144 let len = file.metadata().map_or(0, |m| m.len());
145 // SAFETY: a valid fd of ours, a length from its own metadata, and an
146 // advice value that changes nothing but the kernel's cache bookkeeping.
147 let rc = unsafe { posix_fadvise(file.as_raw_fd(), 0, len as i64, POSIX_FADV_DONTNEED) };
148 if rc != 0 {
149 eprintln!("posix_fadvise: rc {rc} (measurement is warm, not cold)");
150 }
151}
152
153/// Threads this process holds right now -- the scrub metric that matters as
154/// much as the latency, a drag storm having peaked in the hundreds.
155fn threads() -> usize {
156 std::fs::read_dir("/proc/self/task").map_or(0, Iterator::count)
157}
158
159fn ttff_timeout() -> Duration {
160 Duration::from_secs_f64(env_f64("BENCH_TTFF_TIMEOUT", 180.0))
161}
162
163/// The p'th percentile of `samples`, nearest rank on the sorted copy. The
164/// median is [`row`]'s business; this is for the tail, which is the number a
165/// dropped frame and a starved ring both live in.
166fn pct(samples: &[f64], p: f64) -> f64 {
167 if samples.is_empty() {
168 return 0.0;
169 }
170 let mut sorted = samples.to_vec();
171 sorted.sort_by(f64::total_cmp);
172 sorted[((sorted.len() - 1) as f64 * p).round() as usize]
173}
174
175/// A seeded LCG, so "random" seeks are the same random seeks tomorrow. Sixteen
176/// lines of a crate would do the same thing and none of the quality a real
177/// generator has matters to a list of positions in a film.
178struct Lcg(u64);
179
180impl Lcg {
181 /// The next position, in `0.0..1.0`.
182 fn next(&mut self) -> f64 {
183 self.0 = self
184 .0
185 .wrapping_mul(6_364_136_223_846_793_005)
186 .wrapping_add(1_442_695_040_888_963_407);
187 (self.0 >> 11) as f64 / (1u64 << 53) as f64
188 }
189}
190
191fn env_f64(key: &str, default: f64) -> f64 {
192 std::env::var(key)
193 .ok()
194 .and_then(|v| v.parse().ok())
195 .unwrap_or(default)
196}
197
198/// Seeks and waits for the picture that seek asked for: the number a user
199/// feels. The error side is the two ways no picture arrives, and both are a
200/// row rather than a crash: `worker died`, which is what a decoder panicking
201/// on its own thread looks like from here (the channel drops, the session runs
202/// out of clips, and that is end-of-stream a millisecond after a seek), and
203/// `timeout`, which is a decode still grinding when the clock ran out.
204///
205/// `peak` collects the thread count seen while waiting, so the scrub's storm
206/// is measured by the same poll loop that measures its latency.
207fn seek_ttff(
208 session: &mut engine::PlaybackSession,
209 secs: f64,
210 peak: &mut usize,
211) -> Result<f64, &'static str> {
212 let deadline = Instant::now() + ttff_timeout();
213 let t = Instant::now();
214 session.seek(secs);
215 loop {
216 *peak = (*peak).max(threads());
217 if session.try_frame().is_some() {
218 return Ok(t.elapsed().as_secs_f64() * 1000.0);
219 }
220 if session.is_eos() {
221 return Err("worker died");
222 }
223 if Instant::now() >= deadline {
224 return Err("timeout");
225 }
226 std::thread::sleep(Duration::from_millis(1));
227 }
228}
229
230// -------------------------------------------------------------------- open
231
232/// `Demuxer::open`, five times cold and five times warm. Matroska has no index
233/// here and this walks every cluster header of the whole file, which is why it
234/// is the first thing measured.
235fn open_bench(path: &Path) {
236 let mut cold = Vec::new();
237 let mut warm = Vec::new();
238 let mut note = String::new();
239 for _ in 0..5 {
240 evict(path);
241 let t = Instant::now();
242 match engine::demux::Demuxer::open(path) {
243 Ok((meta, _)) => {
244 cold.push(t.elapsed().as_secs_f64() * 1000.0);
245 if note.is_empty() {
246 note = format!(
247 "{}x{} {:.3}fps {} frames",
248 meta.width, meta.height, meta.frame_rate, meta.frame_count
249 );
250 }
251 }
252 Err(e) => {
253 row(path, "open_cold", "ms", &[], &format!("FAIL({e})"));
254 return;
255 }
256 }
257 let t = Instant::now();
258 let _ = engine::demux::Demuxer::open(path).expect("warm open");
259 warm.push(t.elapsed().as_secs_f64() * 1000.0);
260 }
261 row(path, "open_cold", "ms", &cold, &note);
262 row(path, "open_warm", "ms", &warm, &note);
263}
264
265// -------------------------------------------------------------------- seek
266
267/// First-frame latency for a seek to `secs`, five times, on a session that is
268/// already open -- the `open_worker_deferred` path (`decode.rs`), which is
269/// what every seek, clip boundary and export span goes through.
270///
271/// The file is evicted once before the session is opened, so rep 1 is cold and
272/// the rest are as warm as the previous seek left them: the spread between min
273/// and max is that difference and is meant to be read.
274fn seek_bench(path: &Path, secs: f64) {
275 evict(path);
276 let mut session = match engine::PlaybackSession::open(path) {
277 Ok(session) => session,
278 Err(e) => {
279 row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &[], &format!("FAIL({e})"));
280 return;
281 }
282 };
283 let duration = session.timeline_duration();
284 if secs > duration {
285 row(
286 path,
287 &format!("seek_ttff_{secs:.0}s"),
288 "ms",
289 &[],
290 &format!("SKIP(file is {duration:.0}s)"),
291 );
292 return;
293 }
294 let mut samples = Vec::new();
295 let mut missed = Vec::new();
296 let mut peak = 0;
297 for _ in 0..5 {
298 match seek_ttff(&mut session, secs, &mut peak) {
299 Ok(ms) => samples.push(ms),
300 Err(why) => missed.push(why),
301 }
302 }
303 let backend = session.decode_backend().label();
304 let note = if missed.is_empty() {
305 format!("backend {backend}")
306 } else {
307 format!(
308 "backend {backend}, {}/5 NO-FRAME({})",
309 missed.len(),
310 missed[0]
311 )
312 };
313 row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, &note);
314}
315
316// -------------------------------------------------------------- seek storm
317
318/// Seeks a film opens with none of: fifty positions nobody chose, drawn from a
319/// seed so the same fifty come back tomorrow. `seek` measures one point five
320/// times over; this measures the spread across the whole file, which is where
321/// an index lookup, a keyframe distance and a decoder reopen all vary.
322///
323/// Cold is the first pass over a freshly evicted file, warm the same fifty
324/// again straight after -- the same two questions the other metrics ask, and
325/// the audio underruns each pass cost are counted with it
326/// ([`engine::PlaybackSession::audio_underruns`]), because a seek that lands
327/// fast and starves the ring is not a seek that worked.
328const STORM_SEEKS: usize = 50;
329
330fn seekstorm_bench(path: &Path, seed: u64) {
331 evict(path);
332 let mut session = match engine::PlaybackSession::open(path) {
333 Ok(session) => session,
334 Err(e) => {
335 row(path, "seekstorm_ttff_cold", "ms", &[], &format!("FAIL({e})"));
336 return;
337 }
338 };
339 // Playing throughout, because the underruns are the point: a paused device
340 // runs no callbacks and can never starve, so a storm measured paused would
341 // report zero however badly the seeks fed it. This is the complaint's own
342 // shape -- a film that is playing, jumped around in.
343 session.play();
344 let duration = session.timeline_duration();
345 let mut rng = Lcg(seed);
346 // Short of the very end: a landing with no picture after it is a different
347 // measurement (end of stream), and every seek here is meant to be one.
348 let targets: Vec<f64> = (0..STORM_SEEKS)
349 .map(|_| rng.next() * duration * 0.95)
350 .collect();
351
352 for pass in ["cold", "warm"] {
353 let before = session.audio_underruns().map_or(0, |(n, _)| n);
354 let mut samples = Vec::new();
355 let mut missed = Vec::new();
356 let mut peak = threads();
357 for &secs in &targets {
358 match seek_ttff(&mut session, secs, &mut peak) {
359 Ok(ms) => samples.push(ms),
360 Err(why) => missed.push(why),
361 }
362 }
363 let audio = session.audio_underruns();
364 let backend = session.decode_backend().label();
365 let mut note = format!(
366 "backend {backend}, p95 {:.2}ms, peak {peak} threads, seed {seed}",
367 pct(&samples, 0.95)
368 );
369 if !missed.is_empty() {
370 note += &format!(", {}/{STORM_SEEKS} NO-FRAME({})", missed.len(), missed[0]);
371 }
372 row(path, &format!("seekstorm_ttff_{pass}"), "ms", &samples, &note);
373 row(
374 path,
375 &format!("seekstorm_underruns_{pass}"),
376 "count",
377 &[audio.map_or(0, |(n, _)| n).saturating_sub(before) as f64],
378 &match audio {
379 None => "no audio device".into(),
380 Some((total, last)) => format!(
381 "backend {backend}, {total} since open, {}",
382 last.map_or_else(|| "none yet".into(), |t| format!("last at {t:.1}s device"))
383 ),
384 },
385 );
386 }
387}
388
389// --------------------------------------------------------------- play loop
390
391/// How long a picture waits between frames while the sound runs: the app's own
392/// pump (`crates/app/src/player/transport.rs`), driven here for `secs` with a
393/// seek to a random point every five seconds -- the shape of the complaint,
394/// which is a film played and jumped around in rather than a seek measured on
395/// its own.
396///
397/// Three numbers come out: the gap between frames (p50 and p99, the tail being
398/// the jump a person sees), the audio underruns over the whole run, and how
399/// many times the picture worker was restarted -- by a seek, by a clip
400/// boundary, or by the late-picture resync, which is counted separately in the
401/// note.
402///
403/// The resync rule is the app's, repeated here (`LATE_RESYNC`, `RESYNC_GAP`
404/// and the never-during-a-prime gate in `crates/app/src/player/transport.rs`)
405/// because an engine example cannot depend on the binary. Repeated only:
406/// nothing in this file changes how playback runs.
407const PLAYLOOP_SEEK_GAP: Duration = Duration::from_secs(5);
408const LATE_RESYNC: f64 = 0.4;
409const RESYNC_GAP: Duration = Duration::from_secs(2);
410
411fn playloop_bench(path: &Path, secs: f64, seed: u64) {
412 evict(path);
413 let mut session = match engine::PlaybackSession::open(path) {
414 Ok(session) => session,
415 Err(e) => {
416 row(path, "playloop_frame_gap", "ms", &[], &format!("FAIL({e})"));
417 return;
418 }
419 };
420 let fps = session.meta().frame_rate;
421 let duration = session.timeline_duration();
422 let mut rng = Lcg(seed);
423
424 let mut gaps = Vec::new();
425 let mut held: Option<engine::Frame> = None;
426 let (mut shown, mut dropped, mut seeks, mut resyncs) = (0u64, 0u64, 0u64, 0u64);
427 let mut last_resync: Option<Instant> = None;
428 // The first frame of the run is owed exactly as a seek's landing is.
429 let mut owed = true;
430
431 session.play();
432 let start = Instant::now();
433 let deadline = start + Duration::from_secs_f64(secs);
434 let mut last_frame = start;
435 let mut next_seek = start + PLAYLOOP_SEEK_GAP;
436 while Instant::now() < deadline {
437 session.tick();
438 // Read before the drain, as the app does: the frame the drain takes
439 // is the one that ends the prime, and its lateness is the reopen's.
440 let priming = session.picture_priming();
441 let target = session.now() * fps;
442 let mut newest = None;
443 while session.is_playing() || owed {
444 let frame = match held.take() {
445 Some(frame) => frame,
446 None => match session.try_frame() {
447 // Timed here and only here: a frame taken back out of
448 // `held` cost no decode, and counting it would report a
449 // zero gap for a frame nobody waited for.
450 Some(frame) => {
451 let now = Instant::now();
452 gaps.push((now - last_frame).as_secs_f64() * 1000.0);
453 last_frame = now;
454 frame
455 }
456 None => break,
457 },
458 };
459 if f64::from(frame.index) <= target {
460 dropped += u64::from(newest.is_some());
461 newest = Some(frame);
462 } else {
463 held = Some(frame);
464 break;
465 }
466 }
467 let late = newest
468 .as_ref()
469 .map_or(0.0, |f| (target - f64::from(f.index)) / fps);
470 if newest.is_some() {
471 shown += 1;
472 owed = false;
473 }
474 if !owed
475 && !priming
476 && session.is_playing()
477 && late > LATE_RESYNC
478 && last_resync.is_none_or(|t| t.elapsed() >= RESYNC_GAP)
479 {
480 session.resync_picture();
481 held = None;
482 last_resync = Some(Instant::now());
483 resyncs += 1;
484 }
485 // End of stream inside a five-second stretch is the same jump early:
486 // the loop is here to keep playing, not to stop at whatever it landed
487 // near.
488 if Instant::now() >= next_seek || session.is_eos() {
489 session.seek(rng.next() * duration * 0.95);
490 held = None;
491 owed = true;
492 seeks += 1;
493 next_seek = Instant::now() + PLAYLOOP_SEEK_GAP;
494 }
495 std::thread::sleep(Duration::from_millis(1));
496 }
497 session.pause();
498
499 let elapsed = start.elapsed().as_secs_f64();
500 let backend = session.decode_backend().label();
501 let audio = session.audio_underruns();
502 row(
503 path,
504 "playloop_frame_gap",
505 "ms",
506 &gaps,
507 &format!(
508 "backend {backend}, p99 {:.2}ms, {shown} shown, {dropped} dropped, \
509 {seeks} seeks in {elapsed:.0}s, seed {seed}",
510 pct(&gaps, 0.99)
511 ),
512 );
513 row(
514 path,
515 "playloop_underruns",
516 "count",
517 &[audio.map_or(0, |(n, _)| n) as f64],
518 &match audio {
519 None => "no audio device".into(),
520 Some((_, last)) => format!(
521 "backend {backend}, {}",
522 last.map_or_else(|| "none".into(), |t| format!("last at {t:.1}s device"))
523 ),
524 },
525 );
526 row(
527 path,
528 "playloop_restarts",
529 "count",
530 &[session.restarts() as f64],
531 &format!("backend {backend}, {resyncs} late-picture resyncs, {seeks} seeks"),
532 );
533}
534
535// ----------------------------------------------------------------- cutloop
536
537/// The freeze metric: a **silence-cut** timeline -- `regions` holes of
538/// `cut_s` punched out of one file, `keep_s` of picture left between them --
539/// played end to end with the app's own pump, drop policy and resync rule
540/// (`playloop_bench`'s, without the random seeks). Every boundary between two
541/// kept clips is a same-file reseek of the picture worker while the audio
542/// feeder runs straight through -- exactly the timeline a silence removal
543/// leaves, and the complaint it brought: clips shorter than a decoder's own
544/// re-prime, a picture that starves while the sound plays on, and a
545/// late-picture resync every `RESYNC_GAP` buying the same reopen again.
546///
547/// What comes out: displayed and dropped pictures per wall-clock second (a
548/// freeze is a second that shows nothing), on stderr one line each, and in
549/// the TSV the per-second displayed counts beside the totals -- restarts,
550/// resyncs and underruns -- that say which mechanism spent the time.
551///
552/// ```text
553/// bench cutloop <4k file> 20 0.5 0.3
554/// ```
555fn cutloop_bench(path: &Path, regions: u32, keep_s: f64, cut_s: f64) {
556 let mut session = match engine::PlaybackSession::open(path) {
557 Ok(session) => session,
558 Err(e) => {
559 row(path, "cutloop_displayed", "count", &[], &format!("FAIL({e})"));
560 return;
561 }
562 };
563 // Muted like the tests: the device still schedules the stream and the
564 // clock still counts its samples, which is the whole of what this
565 // measures -- the sound is the master the picture is starving against.
566 session.set_gain(0.0);
567 session.drop_late_pictures(true);
568 let fps = session.meta().frame_rate;
569
570 // Cut every hole out before a single picture decodes: keep, cut, keep,
571 // cut -- `regions` pairs of boundaries, so the timeline that plays is
572 // `regions + 1` clips of one file with the holes joined shut.
573 let stride = keep_s + cut_s;
574 for i in 0..regions {
575 let at = keep_s + f64::from(i) * stride;
576 if !session.cut_at(at) || !session.cut_at(at + cut_s) {
577 row(
578 path,
579 "cutloop_displayed",
580 "count",
581 &[],
582 &format!("FAIL(file shorter than region {i} of {regions})"),
583 );
584 return;
585 }
586 }
587 // ...and the end of the last keep, so the timeline that plays out is the
588 // keeps alone and not the rest of the film (a cut past the end of the
589 // file is no cut, and the shape check below says so if it mattered).
590 session.cut_at(f64::from(regions) * stride + keep_s);
591 eprintln!(
592 "cutloop: spans before the deletes: {:?}",
593 session.clip_spans()
594 );
595 // The holes are the odd clips and the tail is the last: deleted from the
596 // far end down, so no delete moves the index of a clip still to be
597 // deleted. V1 names each hole and the group takes the A1 half of the
598 // take with it; the shape check below guards the lot.
599 for idx in (1..=2 * regions as usize + 1).rev().step_by(2) {
600 if !session.delete_clip(Lane::V1, idx) {
601 row(
602 path,
603 "cutloop_displayed",
604 "count",
605 &[],
606 &format!("FAIL(clip {idx} of the cut timeline would not delete)"),
607 );
608 return;
609 }
610 }
611 eprintln!(
612 "cutloop: spans after the deletes: {:?}",
613 session.clip_spans()
614 );
615 let spans = session.clip_spans();
616 let timeline = session.timeline_duration();
617 let expect = (f64::from(regions) + 1.0) * keep_s;
618 if (timeline - expect).abs() > keep_s {
619 row(
620 path,
621 "cutloop_displayed",
622 "count",
623 &[],
624 &format!("FAIL(timeline {timeline:.2}s, expected ~{expect:.2}s of kept clips)"),
625 );
626 return;
627 }
628 eprintln!(
629 "cutloop: {regions} regions of {cut_s}s cut, {} clips left on the \
630 video lane, {timeline:.1}s of timeline at {fps:.3} fps",
631 spans.len()
632 );
633
634 session.seek(0.0);
635 session.play();
636 let start = Instant::now();
637 let mut held: Option<engine::Frame> = None;
638 let (mut shown, mut dropped, mut resyncs) = (0u64, 0u64, 0u64);
639 let mut last_resync: Option<Instant> = None;
640 // The first frame of the run is owed exactly as a seek's landing is.
641 let mut owed = true;
642 let mut per_second: Vec<(u64, u64)> = vec![(0, 0)];
643 loop {
644 session.tick();
645 // Read before the drain, as the app does: the frame the drain takes
646 // is the one that ends the prime, and its lateness is the reopen's.
647 let priming = session.picture_priming();
648 let target = session.now() * fps;
649 let mut newest = None;
650 let mut dropped_now = 0u64;
651 while session.is_playing() || owed {
652 let frame = match held.take() {
653 Some(frame) => frame,
654 None => match session.try_frame() {
655 Some(frame) => frame,
656 None => break,
657 },
658 };
659 if f64::from(frame.index) <= target {
660 dropped_now += u64::from(newest.is_some());
661 newest = Some(frame);
662 } else {
663 held = Some(frame);
664 break;
665 }
666 }
667 dropped += dropped_now;
668 let late = newest
669 .as_ref()
670 .map_or(0.0, |f| (target - f64::from(f.index)) / fps);
671 if newest.is_some() {
672 shown += 1;
673 owed = false;
674 }
675 let slot = start.elapsed().as_secs() as usize;
676 if per_second.len() <= slot {
677 per_second.resize(slot + 1, (0, 0));
678 }
679 per_second[slot].0 += u64::from(newest.is_some());
680 per_second[slot].1 += dropped_now;
681 if !owed
682 && !priming
683 && session.is_playing()
684 && late > LATE_RESYNC
685 && last_resync.is_none_or(|t| t.elapsed() >= RESYNC_GAP)
686 {
687 eprintln!("cutloop: picture {late:.3}s behind the clock: restarting it there");
688 session.resync_picture();
689 held = None;
690 last_resync = Some(Instant::now());
691 resyncs += 1;
692 }
693 // End of stream is the end of the run: the clock is halted on the out
694 // point, as the app's transport does, so the last second's bucket is
695 // closed rather than walked off the end of the timeline.
696 if session.is_eos() {
697 session.halt_at_end();
698 break;
699 }
700 std::thread::sleep(Duration::from_millis(1));
701 }
702 session.pause();
703
704 let elapsed = start.elapsed().as_secs_f64();
705 let rates: Vec<f64> = per_second.iter().map(|(s, _)| *s as f64).collect();
706 let backend = session.decode_backend().label();
707 let underruns = session.audio_underruns().map_or(0, |(n, _)| n);
708 for (i, (shown, dropped)) in per_second.iter().enumerate() {
709 eprintln!("cutloop[{i:2}s]: {shown:3} displayed, {dropped:3} dropped");
710 }
711 row(
712 path,
713 "cutloop_displayed",
714 "count",
715 &rates,
716 &format!(
717 "per second; backend {backend}, {shown} displayed, {dropped} dropped, \
718 {resyncs} resyncs in {elapsed:.1}s, {regions} x {cut_s}s cuts of {keep_s}s clips"
719 ),
720 );
721 row(
722 path,
723 "cutloop_restarts",
724 "count",
725 &[session.restarts() as f64],
726 &format!(
727 "backend {backend}, {resyncs} late-picture resyncs, {underruns} underruns"
728 ),
729 );
730}
731
732// ---------------------------------------------------------------- waveform
733
734/// What a lane waits for before it has an envelope: one whole
735/// [`engine::waveform::peaks`] of the file's first audio stream, at the app's
736/// own ten buckets a second. Cold once, then warm -- the mkv sidecar index is
737/// written on the first open, so the two are different questions.
738fn waveform_bench(path: &Path) {
739 const BPS: u32 = 10;
740 evict(path);
741 let mut cold = Vec::new();
742 let mut warm = Vec::new();
743 let mut note = String::new();
744 for i in 0..3 {
745 let t = Instant::now();
746 match engine::waveform::peaks(path, 0, BPS) {
747 Ok(peaks) => {
748 let ms = t.elapsed().as_secs_f64() * 1000.0;
749 if i == 0 { cold.push(ms) } else { warm.push(ms) }
750 if note.is_empty() {
751 note = format!("{} buckets", peaks.map_or(0, |p| p.len()));
752 }
753 }
754 Err(e) => {
755 row(path, "waveform_cold", "ms", &[], &format!("FAIL({e})"));
756 return;
757 }
758 }
759 }
760 row(path, "waveform_cold", "ms", &cold, &note);
761 row(path, "waveform_warm", "ms", &warm, &note);
762}
763
764// ------------------------------------------------------------------- scrub
765
766/// Twenty scrub steps: the playhead dragged across a quarter of the film, one
767/// frame waited for at each stop. Two numbers come out -- the per-step
768/// first-frame latency, and the peak thread count, because every abandoned
769/// step leaves a decode worker inside an uncancellable open.
770///
771/// Then the same twenty steps *without* waiting, which is the drag a user
772/// really makes: no latency to report (no frame is waited for), only the
773/// thread peak, which is where the hundreds came from.
774fn scrub_bench(path: &Path) {
775 evict(path);
776 let mut session = match engine::PlaybackSession::open(path) {
777 Ok(session) => session,
778 Err(e) => {
779 row(path, "scrub_ttff", "ms", &[], &format!("FAIL({e})"));
780 return;
781 }
782 };
783 let duration = session.timeline_duration();
784 let start = duration * 0.25;
785 let step = (duration * 0.25) / 20.0;
786 let mut samples = Vec::new();
787 let mut missed = Vec::new();
788 let mut peak = threads();
789 for i in 0..20 {
790 match seek_ttff(&mut session, start + step * f64::from(i), &mut peak) {
791 Ok(ms) => samples.push(ms),
792 Err(why) => missed.push(why),
793 }
794 }
795 let note = if missed.is_empty() {
796 format!("backend {}", session.decode_backend().label())
797 } else {
798 format!(
799 "backend {}, {}/20 NO-FRAME({})",
800 session.decode_backend().label(),
801 missed.len(),
802 missed[0]
803 )
804 };
805 row(path, "scrub_ttff", "ms", &samples, &note);
806 row(path, "scrub_threads_peak", "threads", &[peak as f64], "waited per step");
807
808 // The storm: seek, do not wait, seek again.
809 let mut storm_peak = threads();
810 for i in 0..20 {
811 session.seek(start + step * f64::from(i));
812 storm_peak = storm_peak.max(threads());
813 }
814 row(
815 path,
816 "scrub_storm_threads_peak",
817 "threads",
818 &[storm_peak as f64],
819 "20 seeks, no wait",
820 );
821}
822
823// ------------------------------------------------------------------ export
824
825/// Export throughput over a fixed 60 s span, one encoder seat per run.
826///
827/// The span is video only: what is being compared is the picture encoder, and
828/// a sound track that refuses (a 7.1 Opus film does, at the app's door) would
829/// otherwise take the row with it. The span starts a tenth of the way in --
830/// not on the black of a title card, which encodes at a rate no film sustains.
831///
832/// The rate is frames the worker reported written over wall seconds, so a run
833/// stopped at the cap still reports a rate; the row says `CAPPED` when it was.
834fn export_bench(path: &Path, seat: &str, out_dir: &Path) {
835 let (format, pick) = match seat {
836 "h264sw" => (Format::Mp4, EncoderSeat::Software),
837 "h264hw" => (Format::Mp4, EncoderSeat::Auto),
838 "av1" => (Format::Av1, EncoderSeat::Software),
839 // `hevc` keeps meaning the software intra seat, so a row measured
840 // against an older baseline still compares with the one beside it; the
841 // GPU seat is the new name.
842 "hevc" => (Format::Hevc, EncoderSeat::Software),
843 "hevchw" => (Format::Hevc, EncoderSeat::Auto),
844 _ => usage(),
845 };
846 // The sound is opt-in and named in the row, so an `_av` number is never
847 // compared against a picture-only one: what it measures is the *export* --
848 // audio pass, mux and all -- which is the only shape of the number a
849 // "twice real time" claim may be made from.
850 let with_audio = std::env::var_os("BENCH_EXPORT_AUDIO").is_some();
851 let metric = format!("export_fps_{seat}{}", if with_audio { "_av" } else { "" });
852 let (meta, _) = match engine::demux::Demuxer::open(path) {
853 Ok(opened) => opened,
854 Err(e) => {
855 row(path, &metric, "fps", &[], &format!("FAIL(open: {e})"));
856 return;
857 }
858 };
859 let span = ((meta.frame_rate * env_f64("BENCH_EXPORT_SPAN", 60.0)) as u32)
860 .min(meta.frame_count.max(1));
861 let in_frame = (meta.frame_count / 10).min(meta.frame_count.saturating_sub(span));
862 let clip = Clip {
863 fade_in: 0,
864 fade_out: 0,
865 transition_out: 0,
866 visualizer: 0,
867 viz_paint: 0,
868 start: 0,
869 in_frame,
870 out_frame: in_frame + span,
871 source: 0,
872 link: None,
873 eq: None,
874 color: None,
875 fit: engine::scale::FitPolicy::default(),
876 speed: Speed::NORMAL,
877 transform: None,
878 };
879 // The sound, where it was asked for, is the same clip on an audio lane:
880 // the very window the picture covers, so the two passes measure one export.
881 let mut lanes = vec![(LaneKind::Video, vec![clip.clone()])];
882 if with_audio {
883 lanes.push((LaneKind::Audio, vec![clip]));
884 }
885 let stream = env_f64("BENCH_EXPORT_ASTREAM", 0.0) as usize;
886 let project = match Project::from_parts(
887 vec![Source::new(path, stream)],
888 lanes,
889 Vec::new(),
890 Vec::new(),
891 Vec::new(),
892 ) {
893 Ok(project) => project,
894 Err(e) => {
895 row(path, &metric, "fps", &[], &format!("FAIL(project: {e})"));
896 return;
897 }
898 };
899 let settings = ExportSettings {
900 seat: pick,
901 format,
902 ..ExportSettings::default()
903 };
904 let out = out_dir.join(format!("bench_{seat}.{}", format.ext()));
905 let cap = Duration::from_secs_f64(env_f64("BENCH_EXPORT_CAP", 300.0));
906 let reps = env_f64("BENCH_EXPORT_REPS", 5.0) as usize;
907
908 let mut samples = Vec::new();
909 let mut notes = Vec::new();
910 let budget = Instant::now();
911 for _ in 0..reps.max(1) {
912 let handle = engine::export::start(project.clone(), meta, &out, &settings, None);
913 let t = Instant::now();
914 let mut capped = false;
915 // The highest the bar was ever seen at, not wherever it happens to
916 // stand when the clock stops: an export publishes one bar from two
917 // stages, and a capped run's rate is derived from this number. Taking
918 // the maximum over the poll loop means a single unlucky read cannot
919 // under-report the work that was really done.
920 let mut peak = 0.0f64;
921 while !handle.is_finished() {
922 peak = peak.max(f64::from(handle.progress()));
923 if t.elapsed() >= cap {
924 capped = true;
925 handle.cancel();
926 break;
927 }
928 std::thread::sleep(Duration::from_millis(200));
929 }
930 // A cancel is answered at the worker's next checkpoint; the rate is
931 // read from the progress at the moment the clock stopped either way.
932 let progress = peak.max(f64::from(handle.progress()));
933 let elapsed = t.elapsed().as_secs_f64();
934 let done = Instant::now() + Duration::from_secs(60);
935 while !handle.is_finished() && Instant::now() < done {
936 std::thread::sleep(Duration::from_millis(100));
937 }
938 let seats = handle.encoders().unwrap_or_else(|| "?".into());
939 let outcome = handle.result();
940 // A throughput run leaves nothing behind; `BENCH_KEEP=1` keeps the last
941 // one, which is how a seat is checked for *decodability* rather than
942 // speed (`ffprobe -count_frames` on the file it wrote).
943 if std::env::var_os("BENCH_KEEP").is_none() {
944 let _ = std::fs::remove_file(&out);
945 }
946 if capped {
947 samples.push(progress * f64::from(span) / elapsed);
948 notes.push(format!("CAPPED at {:.0}s, {:.0}% done, {seats}", elapsed, progress * 100.0));
949 break;
950 }
951 match outcome {
952 Some(Ok(())) => {
953 samples.push(f64::from(span) / elapsed);
954 notes.push(seats);
955 }
956 Some(Err(e)) => {
957 notes.push(format!("FAIL({e})"));
958 break;
959 }
960 // Finished without an outcome cannot happen (the worker settles
961 // before it flips the flag); a wait that ran out of its own minute
962 // does, and it is the same "no number" either way.
963 None => {
964 notes.push("FAIL(no outcome inside 60 s of the cap)".into());
965 break;
966 }
967 }
968 if budget.elapsed() >= cap {
969 notes.push(format!("{} rep(s) inside the {:.0}s budget", samples.len(), cap.as_secs_f64()));
970 break;
971 }
972 }
973 notes.dedup();
974 row(path, &metric, "fps", &samples, &notes.join("; "));
975}