forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

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