forge
Explore
Log in

Don't you dare go Hollow

🔀 merge: main's live underrun query beside the lane's own

Browse files at this commit

64a9817b09d6c8ea0a1769a2373bc39b1bdb67e1Ahmet Kaan GümüşParent: c1793645fdd558
Their `ao_underruns(session, last_at)` is the richer of the two -- it says
where the last starved callback was, not only how many there have been --
so it is the one that stays, required symbol and all. What this lane keeps
is the *meaning* of the number it reports: the `primed` gate in the RT
callback, so the head of a restart and the tail of a played-out stream are
not counted, and `ao_stream_ended` beside it.
Cargo.lockmodified+151 -0
@@ -3372,6 +3372,16 @@ dependencies = [
33723372 "libc",
33733373 ]
33743374
3375+[[package]]
3376+name = "matrixmultiply"
3377+version = "0.3.11"
3378+source = "registry+https://github.com/rust-lang/crates.io-index"
3379+checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
3380+dependencies = [
3381+ "autocfg",
3382+ "rawpointer",
3383+]
3384+
33753385 [[package]]
33763386 name = "maybe-rayon"
33773387 version = "0.1.1"
@@ -3538,6 +3548,22 @@ dependencies = [
35383548 "getrandom 0.2.17",
35393549 ]
35403550
3551+[[package]]
3552+name = "ndarray"
3553+version = "0.17.2"
3554+source = "registry+https://github.com/rust-lang/crates.io-index"
3555+checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d"
3556+dependencies = [
3557+ "matrixmultiply",
3558+ "num-complex",
3559+ "num-integer",
3560+ "num-traits",
3561+ "portable-atomic",
3562+ "portable-atomic-util",
3563+ "rawpointer",
3564+ "serde",
3565+]
3566+
35413567 [[package]]
35423568 name = "new_debug_unreachable"
35433569 version = "1.0.6"
@@ -3608,6 +3634,34 @@ dependencies = [
36083634 "memchr",
36093635 ]
36103636
3637+[[package]]
3638+name = "non-empty-iter"
3639+version = "0.3.1"
3640+source = "registry+https://github.com/rust-lang/crates.io-index"
3641+checksum = "ac123b8e4bd1fef3e8e972ba7a07f046ac6b608633ad761c61876b7197313f63"
3642+dependencies = [
3643+ "non-zero-size",
3644+]
3645+
3646+[[package]]
3647+name = "non-empty-slice"
3648+version = "0.6.0"
3649+source = "registry+https://github.com/rust-lang/crates.io-index"
3650+checksum = "9935c822e11be79ef40f986558b00da0ff176b7c87ddf6d9fb8b9138a6112c20"
3651+dependencies = [
3652+ "non-empty-iter",
3653+ "non-zero-size",
3654+ "ownership",
3655+ "serde",
3656+ "thiserror 2.0.20",
3657+]
3658+
3659+[[package]]
3660+name = "non-zero-size"
3661+version = "0.2.0"
3662+source = "registry+https://github.com/rust-lang/crates.io-index"
3663+checksum = "401b3a4027292c1c318fd2305783f791d5579d18e7143ef72d653bf0c29e6b36"
3664+
36113665 [[package]]
36123666 name = "noop_proc_macro"
36133667 version = "0.3.0"
@@ -3672,6 +3726,7 @@ checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
36723726 dependencies = [
36733727 "bytemuck",
36743728 "num-traits",
3729+ "serde",
36753730 ]
36763731
36773732 [[package]]
@@ -3951,6 +4006,12 @@ dependencies = [
39514006 "pin-project-lite",
39524007 ]
39534008
4009+[[package]]
4010+name = "ownership"
4011+version = "0.3.0"
4012+source = "registry+https://github.com/rust-lang/crates.io-index"
4013+checksum = "cfb1aeb68b9f2683ee3f83960c10668b37a8a640224ba1169697ee8fd1e906c1"
4014+
39544015 [[package]]
39554016 name = "oxideav-ac3"
39564017 version = "0.0.10"
@@ -4279,6 +4340,21 @@ version = "0.2.5"
42794340 source = "registry+https://github.com/rust-lang/crates.io-index"
42804341 checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7"
42814342
4343+[[package]]
4344+name = "portable-atomic"
4345+version = "1.15.0"
4346+source = "registry+https://github.com/rust-lang/crates.io-index"
4347+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
4348+
4349+[[package]]
4350+name = "portable-atomic-util"
4351+version = "0.2.7"
4352+source = "registry+https://github.com/rust-lang/crates.io-index"
4353+checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"
4354+dependencies = [
4355+ "portable-atomic",
4356+]
4357+
42824358 [[package]]
42834359 name = "postage"
42844360 version = "0.5.0"
@@ -4324,6 +4400,15 @@ dependencies = [
43244400 "syn 2.0.119",
43254401 ]
43264402
4403+[[package]]
4404+name = "primal-check"
4405+version = "0.3.4"
4406+source = "registry+https://github.com/rust-lang/crates.io-index"
4407+checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08"
4408+dependencies = [
4409+ "num-integer",
4410+]
4411+
43274412 [[package]]
43284413 name = "proc-macro-crate"
43294414 version = "3.5.0"
@@ -4700,6 +4785,12 @@ dependencies = [
47004785 "raw-window-handle",
47014786 ]
47024787
4788+[[package]]
4789+name = "rawpointer"
4790+version = "0.2.1"
4791+source = "registry+https://github.com/rust-lang/crates.io-index"
4792+checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
4793+
47034794 [[package]]
47044795 name = "rayon"
47054796 version = "1.12.0"
@@ -4731,6 +4822,15 @@ dependencies = [
47314822 "once_cell",
47324823 ]
47334824
4825+[[package]]
4826+name = "realfft"
4827+version = "3.5.0"
4828+source = "registry+https://github.com/rust-lang/crates.io-index"
4829+checksum = "f821338fddb99d089116342c46e9f1fbf3828dba077674613e734e01d6ea8677"
4830+dependencies = [
4831+ "rustfft",
4832+]
4833+
47344834 [[package]]
47354835 name = "reborrow"
47364836 version = "0.5.5"
@@ -4869,6 +4969,9 @@ name = "ruopus"
48694969 version = "0.1.2"
48704970 source = "registry+https://github.com/rust-lang/crates.io-index"
48714971 checksum = "fcfcd963c83fc1ada2180ccdac7f1568d87fb0f2ad7236b266fdc9fb9122fbfd"
4972+dependencies = [
4973+ "spectrograms",
4974+]
48724975
48734976 [[package]]
48744977 name = "rust-embed"
@@ -4927,6 +5030,20 @@ dependencies = [
49275030 "semver",
49285031 ]
49295032
5033+[[package]]
5034+name = "rustfft"
5035+version = "6.4.1"
5036+source = "registry+https://github.com/rust-lang/crates.io-index"
5037+checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89"
5038+dependencies = [
5039+ "num-complex",
5040+ "num-integer",
5041+ "num-traits",
5042+ "primal-check",
5043+ "strength_reduce",
5044+ "transpose",
5045+]
5046+
49305047 [[package]]
49315048 name = "rustix"
49325049 version = "0.38.44"
@@ -5506,6 +5623,24 @@ dependencies = [
55065623 "windows-sys 0.61.2",
55075624 ]
55085625
5626+[[package]]
5627+name = "spectrograms"
5628+version = "2.1.3"
5629+source = "registry+https://github.com/rust-lang/crates.io-index"
5630+checksum = "3ff1e83612f5a16e413dbfaf0381753b5eee714932fc95db19fe0974d5e6462b"
5631+dependencies = [
5632+ "ndarray",
5633+ "non-empty-slice",
5634+ "num-complex",
5635+ "num-traits",
5636+ "once_cell",
5637+ "pkg-config",
5638+ "realfft",
5639+ "regex",
5640+ "rustfft",
5641+ "thiserror 2.0.20",
5642+]
5643+
55095644 [[package]]
55105645 name = "spin"
55115646 version = "0.9.9"
@@ -5570,6 +5705,12 @@ version = "1.1.0"
55705705 source = "registry+https://github.com/rust-lang/crates.io-index"
55715706 checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
55725707
5708+[[package]]
5709+name = "strength_reduce"
5710+version = "0.2.4"
5711+source = "registry+https://github.com/rust-lang/crates.io-index"
5712+checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
5713+
55735714 [[package]]
55745715 name = "strict-num"
55755716 version = "0.1.1"
@@ -6401,6 +6542,16 @@ dependencies = [
64016542 "once_cell",
64026543 ]
64036544
6545+[[package]]
6546+name = "transpose"
6547+version = "0.2.3"
6548+source = "registry+https://github.com/rust-lang/crates.io-index"
6549+checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"
6550+dependencies = [
6551+ "num-integer",
6552+ "strength_reduce",
6553+]
6554+
64046555 [[package]]
64056556 name = "try-lock"
64066557 version = "0.2.5"
crates/engine-audio/src/lib.rsmodified+27 -8
@@ -175,6 +175,11 @@ struct Shared {
175175 /// the clock holds still through it (`Audio::content_at`).
176176 primed: AtomicBool,
177177 underruns: AtomicU64,
178+ /// Device position (samples per channel) read at the most recent underrun,
179+ /// `-1` until one happens: what says whether the count in hand is old news
180+ /// or is still growing. Written on the RT thread, and only on the starved
181+ /// path, so the ordinary callback pays nothing for it.
182+ last_underrun: AtomicI64,
178183 }
179184
180185 enum Ctl {
@@ -273,6 +278,13 @@ fn run(
273278 // thread, which is what this branch can afford.
274279 if shared.primed.load(Ordering::Relaxed) {
275280 shared.underruns.fetch_add(1, Ordering::Relaxed);
281+ // The position this callback is about to compute
282+ // is not known yet; the previous one is a quantum
283+ // (~23 ms) behind and needs no clock call here.
284+ shared.last_underrun.store(
285+ shared.position.load(Ordering::Relaxed),
286+ Ordering::Relaxed,
287+ );
276288 }
277289 }
278290 // After the fill, so the silence stays silent whatever
@@ -436,6 +448,7 @@ pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void {
436448 // and the caller's first write have nothing to be late for.
437449 primed: AtomicBool::new(false),
438450 underruns: AtomicU64::new(0),
451+ last_underrun: AtomicI64::new(-1),
439452 });
440453 let (ready_tx, ready_rx) = mpsc::channel();
441454 let (ctl_tx, ctl_rx) = mpsc::channel();
@@ -532,23 +545,29 @@ pub unsafe extern "C" fn ao_stream_ended(session: *mut c_void) -> i32 {
532545 .unwrap_or(-1)
533546 }
534547
535-/// Quanta the device had to fill with silence because the ring was empty --
536-/// "the decoder was late", counted since the stream opened and never reset.
537-/// The same number [`Session::drop`] prints, readable while the stream runs so
538-/// a benchmark can attribute it to the seek it followed rather than to a whole
539-/// session. -1 on a null session; an inactive stream has no callbacks and so
540-/// cannot underrun at all.
548+/// Starved callbacks since the stream opened -- one per quantum the decoder was
549+/// late for -- and, through `last_at`, the device position the newest of them
550+/// was seen at (`-1` if there has been none). The same number the drop print
551+/// reports, asked for while the session is still running: a caller measuring a
552+/// seek reads it before and after and the difference is that seek's cost.
553+///
554+/// Two relaxed atomic loads, nothing else: the RT thread writes both and must
555+/// never wait on a reader.
541556 ///
542557 /// # Safety
543-/// `session` must come from [`ao_open`].
558+/// `session` must come from [`ao_open`]; `last_at` is either null or writable.
544559 #[unsafe(no_mangle)]
545-pub unsafe extern "C" fn ao_underruns(session: *mut c_void) -> i64 {
560+pub unsafe extern "C" fn ao_underruns(session: *mut c_void, last_at: *mut i64) -> i64 {
546561 catch_unwind(AssertUnwindSafe(|| {
547562 if session.is_null() {
548563 return -1;
549564 }
550565 // SAFETY: caller-guaranteed live session.
551566 let session = unsafe { &*(session as *const Session) };
567+ if !last_at.is_null() {
568+ // SAFETY: caller-guaranteed writable, and it is a plain i64.
569+ unsafe { *last_at = session.shared.last_underrun.load(Ordering::Relaxed) };
570+ }
552571 session.shared.underruns.load(Ordering::Relaxed) as i64
553572 }))
554573 .unwrap_or(-1)
crates/engine/Cargo.tomlmodified+18 -3
@@ -81,8 +81,23 @@ rusty_mp3 = "0.6"
8181 # packet. This one does the whole pipeline. Its quirks are measured and worked
8282 # around in [`crate::export::write_ogg`] -- read that before touching this line.
8383 rusty_vorbis = "0.1.1"
84-# The Opus decoder: pure Rust, MIT, no C and no FFI, and no dependencies at all
85-# without its default features (`spectrograms` is for its own analysis tools).
84+# The Opus decoder: pure Rust, MIT, no C and no FFI.
85+#
86+# `spectrograms` is not, as this line long claimed, "for its own analysis tools":
87+# it is the crate's *FFT backend*, and it is default-on because CELT synthesis is
88+# an N/4 complex FFT per block. Turned off -- which is what asking for `std`
89+# alone did -- `celt/mdct.rs` falls back to an O(n²) DFT evaluated in f64, and a
90+# 5.1 film soundtrack decodes at **0.95x realtime**: slower than playing it.
91+# With the backend on, the same file decodes at **104x** (7.1: 0.93x -> 112x,
92+# stereo: 10.4x -> 135x). The cost is fifteen pure-Rust crates (`spectrograms` ->
93+# `realfft`/`rustfft`, `ndarray`, `regex`), still no C and no `build.rs`.
94+# The output is *not* bit-identical to the DFT build -- FFT summation order
95+# differs -- but the two agree to 144 dB SNR (max |Δ| 3.7e-8, half an LSB at
96+# 24-bit) while *both* sit 93 dB from ffmpeg's own libopus decode of the same
97+# file. The change is 40 dB below the decoder's existing distance to the
98+# reference, i.e. inside float noise, and upstream says as much: Opus conformance
99+# is a quality threshold (`opus_compare`), not bit-exactness, and every
100+# bitstream-affecting computation stays exact either way.
86101 # Symphonia has no Opus at any version -- its feature list stops at vorbis and
87102 # there is no `symphonia-codec-opus` crate -- while both of its containers *read*
88103 # the format already: `A_OPUS` and `OpusHead` have always mapped to
@@ -99,7 +114,7 @@ rusty_vorbis = "0.1.1"
99114 # where the film is silent. This one matches ffmpeg's own decode of the same file to a
100115 # correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3`
101116 # below, because a decoder is a bit-exactness dependency.
102-ruopus = { version = "=0.1.2", default-features = false, features = ["std"] }
117+ruopus = { version = "=0.1.2", default-features = false, features = ["std", "spectrograms"] }
103118 # The Opus *encoder*, the other half of that pair: a pure-Rust port of libopus
104119 # 1.6, BSD-3, `build.rs`-less and with **no dependencies at all** -- checked, not
105120 # taken from the README (`cargo tree` is two lines; there is not one `.c`, `.h`
crates/engine/examples/bench.rsmodified+258 -2
@@ -1,5 +1,6 @@
11 //! The baseline every later decode/encode change is measured against: open,
2-//! seek, scrub and export, timed on the real library rather than on a fixture.
2+//! seek, seek storm, play loop, scrub and export, timed on the real library
3+//! rather than on a fixture.
34 //!
45 //! `cargo run --release -p engine --example bench -- <metric> <file> [args]`
56 //!
@@ -9,7 +10,10 @@
910 //! failure down as data.
1011 //!
1112 //! Every row is one TSV line -- `file, metric, unit, n, median, min, max, note`
12-//! -- so the whole baseline is `cat`ted together and diffed later.
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`).
1317 //!
1418 //! **Cold and warm.** Cold means the file's pages are dropped from the page
1519 //! cache immediately before the measurement, with `posix_fadvise(DONTNEED)` on
@@ -49,6 +53,8 @@ fn main() {
4953 match metric.as_str() {
5054 "open" => open_bench(&path),
5155 "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")),
56+ "seekstorm" => seekstorm_bench(&path, arg_seed(args.next())),
57+ "playloop" => playloop_bench(&path, arg_f64(args.next(), "seconds"), arg_seed(args.next())),
5258 "scrub" => scrub_bench(&path),
5359 "waveform" => waveform_bench(&path),
5460 "export" => {
@@ -63,6 +69,8 @@ fn main() {
6369 fn usage() -> ! {
6470 eprintln!(
6571 "usage: bench open <file>\n bench seek <file> <secs>\n \
72+ bench seekstorm <file> [seed]\n \
73+ bench playloop <file> <secs> [seed]\n \
6674 bench scrub <file>\n bench waveform <file>\n \
6775 bench export <file> <h264sw|h264hw|av1|hevc|hevchw> <out_dir>"
6876 );
@@ -74,6 +82,12 @@ fn arg_f64(arg: Option<String>, what: &str) -> f64 {
7482 .unwrap_or_else(|| panic!("missing {what}"))
7583 }
7684
85+/// The seed the random metrics draw their positions from: same seed, same
86+/// seeks, so a before and an after are the same measurement.
87+fn arg_seed(arg: Option<String>) -> u64 {
88+ arg.and_then(|s| s.parse().ok()).unwrap_or(1)
89+}
90+
7791 // ---------------------------------------------------------------- reporting
7892
7993 /// One TSV row: the median is what a comparison uses, the min and max are what
@@ -125,6 +139,34 @@ fn ttff_timeout() -> Duration {
125139 Duration::from_secs_f64(env_f64("BENCH_TTFF_TIMEOUT", 180.0))
126140 }
127141
142+/// The p'th percentile of `samples`, nearest rank on the sorted copy. The
143+/// median is [`row`]'s business; this is for the tail, which is the number a
144+/// dropped frame and a starved ring both live in.
145+fn pct(samples: &[f64], p: f64) -> f64 {
146+ if samples.is_empty() {
147+ return 0.0;
148+ }
149+ let mut sorted = samples.to_vec();
150+ sorted.sort_by(f64::total_cmp);
151+ sorted[((sorted.len() - 1) as f64 * p).round() as usize]
152+}
153+
154+/// A seeded LCG, so "random" seeks are the same random seeks tomorrow. Sixteen
155+/// lines of a crate would do the same thing and none of the quality a real
156+/// generator has matters to a list of positions in a film.
157+struct Lcg(u64);
158+
159+impl Lcg {
160+ /// The next position, in `0.0..1.0`.
161+ fn next(&mut self) -> f64 {
162+ self.0 = self
163+ .0
164+ .wrapping_mul(6_364_136_223_846_793_005)
165+ .wrapping_add(1_442_695_040_888_963_407);
166+ (self.0 >> 11) as f64 / (1u64 << 53) as f64
167+ }
168+}
169+
128170 fn env_f64(key: &str, default: f64) -> f64 {
129171 std::env::var(key)
130172 .ok()
@@ -250,6 +292,220 @@ fn seek_bench(path: &Path, secs: f64) {
250292 row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, &note);
251293 }
252294
295+// -------------------------------------------------------------- seek storm
296+
297+/// Seeks a film opens with none of: fifty positions nobody chose, drawn from a
298+/// seed so the same fifty come back tomorrow. `seek` measures one point five
299+/// times over; this measures the spread across the whole file, which is where
300+/// an index lookup, a keyframe distance and a decoder reopen all vary.
301+///
302+/// Cold is the first pass over a freshly evicted file, warm the same fifty
303+/// again straight after -- the same two questions the other metrics ask, and
304+/// the audio underruns each pass cost are counted with it
305+/// ([`engine::PlaybackSession::audio_underruns`]), because a seek that lands
306+/// fast and starves the ring is not a seek that worked.
307+const STORM_SEEKS: usize = 50;
308+
309+fn seekstorm_bench(path: &Path, seed: u64) {
310+ evict(path);
311+ let mut session = match engine::PlaybackSession::open(path) {
312+ Ok(session) => session,
313+ Err(e) => {
314+ row(path, "seekstorm_ttff_cold", "ms", &[], &format!("FAIL({e})"));
315+ return;
316+ }
317+ };
318+ // Playing throughout, because the underruns are the point: a paused device
319+ // runs no callbacks and can never starve, so a storm measured paused would
320+ // report zero however badly the seeks fed it. This is the complaint's own
321+ // shape -- a film that is playing, jumped around in.
322+ session.play();
323+ let duration = session.timeline_duration();
324+ let mut rng = Lcg(seed);
325+ // Short of the very end: a landing with no picture after it is a different
326+ // measurement (end of stream), and every seek here is meant to be one.
327+ let targets: Vec<f64> = (0..STORM_SEEKS)
328+ .map(|_| rng.next() * duration * 0.95)
329+ .collect();
330+
331+ for pass in ["cold", "warm"] {
332+ let before = session.audio_underruns().map_or(0, |(n, _)| n);
333+ let mut samples = Vec::new();
334+ let mut missed = Vec::new();
335+ let mut peak = threads();
336+ for &secs in &targets {
337+ match seek_ttff(&mut session, secs, &mut peak) {
338+ Ok(ms) => samples.push(ms),
339+ Err(why) => missed.push(why),
340+ }
341+ }
342+ let audio = session.audio_underruns();
343+ let backend = session.decode_backend().label();
344+ let mut note = format!(
345+ "backend {backend}, p95 {:.2}ms, peak {peak} threads, seed {seed}",
346+ pct(&samples, 0.95)
347+ );
348+ if !missed.is_empty() {
349+ note += &format!(", {}/{STORM_SEEKS} NO-FRAME({})", missed.len(), missed[0]);
350+ }
351+ row(path, &format!("seekstorm_ttff_{pass}"), "ms", &samples, &note);
352+ row(
353+ path,
354+ &format!("seekstorm_underruns_{pass}"),
355+ "count",
356+ &[audio.map_or(0, |(n, _)| n).saturating_sub(before) as f64],
357+ &match audio {
358+ None => "no audio device".into(),
359+ Some((total, last)) => format!(
360+ "backend {backend}, {total} since open, {}",
361+ last.map_or_else(|| "none yet".into(), |t| format!("last at {t:.1}s device"))
362+ ),
363+ },
364+ );
365+ }
366+}
367+
368+// --------------------------------------------------------------- play loop
369+
370+/// How long a picture waits between frames while the sound runs: the app's own
371+/// pump (`crates/app/src/player/transport.rs`), driven here for `secs` with a
372+/// seek to a random point every five seconds -- the shape of the complaint,
373+/// which is a film played and jumped around in rather than a seek measured on
374+/// its own.
375+///
376+/// Three numbers come out: the gap between frames (p50 and p99, the tail being
377+/// the jump a person sees), the audio underruns over the whole run, and how
378+/// many times the picture worker was restarted -- by a seek, by a clip
379+/// boundary, or by the late-picture resync, which is counted separately in the
380+/// note.
381+///
382+/// The resync rule is the app's, repeated here (`LATE_RESYNC`, `RESYNC_GAP` in
383+/// `crates/app/src/transport.rs`) because an engine example cannot depend on
384+/// the binary. Repeated only: nothing in this file changes how playback runs.
385+const PLAYLOOP_SEEK_GAP: Duration = Duration::from_secs(5);
386+const LATE_RESYNC: f64 = 0.4;
387+const RESYNC_GAP: Duration = Duration::from_secs(2);
388+
389+fn playloop_bench(path: &Path, secs: f64, seed: u64) {
390+ evict(path);
391+ let mut session = match engine::PlaybackSession::open(path) {
392+ Ok(session) => session,
393+ Err(e) => {
394+ row(path, "playloop_frame_gap", "ms", &[], &format!("FAIL({e})"));
395+ return;
396+ }
397+ };
398+ let fps = session.meta().frame_rate;
399+ let duration = session.timeline_duration();
400+ let mut rng = Lcg(seed);
401+
402+ let mut gaps = Vec::new();
403+ let mut held: Option<engine::Frame> = None;
404+ let (mut shown, mut dropped, mut seeks, mut resyncs) = (0u64, 0u64, 0u64, 0u64);
405+ let mut last_resync: Option<Instant> = None;
406+ // The first frame of the run is owed exactly as a seek's landing is.
407+ let mut owed = true;
408+
409+ session.play();
410+ let start = Instant::now();
411+ let deadline = start + Duration::from_secs_f64(secs);
412+ let mut last_frame = start;
413+ let mut next_seek = start + PLAYLOOP_SEEK_GAP;
414+ while Instant::now() < deadline {
415+ session.tick();
416+ let target = session.now() * fps;
417+ let mut newest = None;
418+ while session.is_playing() || owed {
419+ let frame = match held.take() {
420+ Some(frame) => frame,
421+ None => match session.try_frame() {
422+ // Timed here and only here: a frame taken back out of
423+ // `held` cost no decode, and counting it would report a
424+ // zero gap for a frame nobody waited for.
425+ Some(frame) => {
426+ let now = Instant::now();
427+ gaps.push((now - last_frame).as_secs_f64() * 1000.0);
428+ last_frame = now;
429+ frame
430+ }
431+ None => break,
432+ },
433+ };
434+ if f64::from(frame.index) <= target {
435+ dropped += u64::from(newest.is_some());
436+ newest = Some(frame);
437+ } else {
438+ held = Some(frame);
439+ break;
440+ }
441+ }
442+ let late = newest
443+ .as_ref()
444+ .map_or(0.0, |f| (target - f64::from(f.index)) / fps);
445+ if newest.is_some() {
446+ shown += 1;
447+ owed = false;
448+ }
449+ if !owed
450+ && session.is_playing()
451+ && late > LATE_RESYNC
452+ && last_resync.is_none_or(|t| t.elapsed() >= RESYNC_GAP)
453+ {
454+ session.resync_picture();
455+ held = None;
456+ last_resync = Some(Instant::now());
457+ resyncs += 1;
458+ }
459+ // End of stream inside a five-second stretch is the same jump early:
460+ // the loop is here to keep playing, not to stop at whatever it landed
461+ // near.
462+ if Instant::now() >= next_seek || session.is_eos() {
463+ session.seek(rng.next() * duration * 0.95);
464+ held = None;
465+ owed = true;
466+ seeks += 1;
467+ next_seek = Instant::now() + PLAYLOOP_SEEK_GAP;
468+ }
469+ std::thread::sleep(Duration::from_millis(1));
470+ }
471+ session.pause();
472+
473+ let elapsed = start.elapsed().as_secs_f64();
474+ let backend = session.decode_backend().label();
475+ let audio = session.audio_underruns();
476+ row(
477+ path,
478+ "playloop_frame_gap",
479+ "ms",
480+ &gaps,
481+ &format!(
482+ "backend {backend}, p99 {:.2}ms, {shown} shown, {dropped} dropped, \
483+ {seeks} seeks in {elapsed:.0}s, seed {seed}",
484+ pct(&gaps, 0.99)
485+ ),
486+ );
487+ row(
488+ path,
489+ "playloop_underruns",
490+ "count",
491+ &[audio.map_or(0, |(n, _)| n) as f64],
492+ &match audio {
493+ None => "no audio device".into(),
494+ Some((_, last)) => format!(
495+ "backend {backend}, {}",
496+ last.map_or_else(|| "none".into(), |t| format!("last at {t:.1}s device"))
497+ ),
498+ },
499+ );
500+ row(
501+ path,
502+ "playloop_restarts",
503+ "count",
504+ &[session.restarts() as f64],
505+ &format!("backend {backend}, {resyncs} late-picture resyncs, {seeks} seeks"),
506+ );
507+}
508+
253509 // ---------------------------------------------------------------- waveform
254510
255511 /// What a lane waits for before it has an envelope: one whole
crates/engine/src/ao.rsmodified+20 -17
@@ -20,13 +20,10 @@ struct Plugin {
2020 set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32,
2121 set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32,
2222 flush: unsafe extern "C" fn(*mut c_void) -> i32,
23- /// Optional, unlike its neighbours: this one is a *counter*, and a plugin
24- /// too old to have it is a session that plays perfectly and cannot say how
25- /// many quanta it starved for. Rejecting the whole plugin over that would
26- /// trade the sound for the diagnostic.
27- underruns: Option<unsafe extern "C" fn(*mut c_void) -> i64>,
28- /// Optional for [`Plugin::underruns`]'s reason: without it a plugin plays
29- /// exactly as it did, it only counts the tail of a stream as lateness.
23+ underruns: unsafe extern "C" fn(*mut c_void, *mut i64) -> i64,
24+ /// Optional, unlike its neighbours: without it a plugin plays exactly as it
25+ /// did and only counts the tail of a played-out stream as lateness, which
26+ /// is a worse diagnostic rather than a worse session.
3027 stream_ended: Option<unsafe extern "C" fn(*mut c_void) -> i32>,
3128 close: unsafe extern "C" fn(*mut c_void),
3229 // Never dropped (lives in a static), so the fn pointers above stay valid.
@@ -71,7 +68,11 @@ fn load() -> Option<Plugin> {
7168 // with no sound at all, which at least says so.
7269 set_volume: *lib.get(b"ao_set_volume\0").ok()?,
7370 flush: *lib.get(b"ao_flush\0").ok()?,
74- underruns: lib.get(b"ao_underruns\0").ok().map(|f| *f),
71+ // Required on the same terms as the two above: the plugin
72+ // ships from this build, and a measurement that silently
73+ // reads zero underruns is worse than a run that says the
74+ // plugin is the wrong one.
75+ underruns: *lib.get(b"ao_underruns\0").ok()?,
7576 stream_ended: lib.get(b"ao_stream_ended\0").ok().map(|f| *f),
7677 close: *lib.get(b"ao_close\0").ok()?,
7778 _lib: lib,
@@ -142,15 +143,6 @@ impl AoSession {
142143 }
143144 }
144145
145- /// Quanta the device filled with silence for want of samples, since the
146- /// stream opened: what a benchmark reads to say the decoder kept up.
147- /// `None` from a plugin that does not carry the counter.
148- pub fn underruns(&self) -> Option<u64> {
149- // SAFETY: `handle` came from `ao_open` and is still open.
150- let n = unsafe { (self.plugin.underruns?)(self.handle) };
151- (n >= 0).then_some(n as u64)
152- }
153-
154146 /// Pauses or resumes playback; while paused the position stays put.
155147 pub fn set_active(&self, active: bool) -> bool {
156148 // SAFETY: `handle` came from `ao_open` and is still open.
@@ -172,6 +164,17 @@ impl AoSession {
172164 // SAFETY: `handle` came from `ao_open` and is still open.
173165 unsafe { (self.plugin.flush)(self.handle) == 0 }
174166 }
167+
168+ /// Starved callbacks so far, and the device position (samples per channel)
169+ /// the last of them was seen at -- `None` for a stream that has never run
170+ /// dry. Two atomic loads inside the plugin, so it is cheap enough to poll
171+ /// and it never touches the RT thread's path.
172+ pub fn underruns(&self) -> (u64, Option<i64>) {
173+ let mut last = -1i64;
174+ // SAFETY: `handle` came from `ao_open`, and `last` is a live i64 of ours.
175+ let count = unsafe { (self.plugin.underruns)(self.handle, &raw mut last) };
176+ (count.max(0) as u64, (last >= 0).then_some(last))
177+ }
175178 }
176179
177180 impl Drop for AoSession {
crates/engine/src/playback.rsmodified+144 -15
@@ -296,6 +296,12 @@ pub struct PlaybackSession {
296296 ///
297297 /// [`retire`]: PlaybackSession::retire
298298 retired: Vec<Worker>,
299+ /// Picture workers that replaced another one, i.e. every restart the
300+ /// session's first worker did not cost: a seek, a resync, a clip boundary.
301+ /// Each carries a demuxer reopen and a VA-API init, so this is what a
302+ /// playback measurement counts to say how often the picture was thrown away
303+ /// ([`restarts`](Self::restarts)).
304+ restarts: u64,
299305 clock: PlaybackClock,
300306 audio: Option<Audio>,
301307 /// Why this timeline is silent, when the file itself is not: an audio track
@@ -316,6 +322,17 @@ pub struct PlaybackSession {
316322 /// not -- with the single exception `sources` itself has,
317323 /// [`Self::remove_source`], which takes the same entry out of both.
318324 counts: Vec<u32>,
325+ /// Audio headers already read, by the `(path, stream)` they were read for.
326+ /// Every door that checks a file against the timeline asks the same two
327+ /// questions -- what this file's sound is, and what the timeline's first
328+ /// source's is ([`audio_matches`], [`first_audio_of`]) -- and each answer is
329+ /// a container open. Warm that is 5-10 ms; on a film whose pages have been
330+ /// evicted it is **1.7 s** (measured, 3.1 GB HEVC mkv), and both of those
331+ /// are spent on the thread that draws, because placing and importing are
332+ /// what a drag lands on. A header does not change while a session holds the
333+ /// file, so it is read once and remembered. Errors are not kept: a file that
334+ /// failed to open is asked again next time.
335+ probes: std::collections::HashMap<(std::path::PathBuf, usize), Option<crate::AudioProbe>>,
319336 /// What each source's own frame rate is against this timeline's, indexed
320337 /// and grown exactly as [`Self::counts`] is (and shortened with it by
321338 /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the
@@ -457,11 +474,13 @@ impl PlaybackSession {
457474 worker: stream.worker,
458475 backend: stream.backend,
459476 retired: Vec::new(),
477+ restarts: 0,
460478 clock: PlaybackClock::new(source),
461479 audio,
462480 audio_disabled,
463481 project,
464482 counts: vec![meta.frame_count],
483+ probes: std::collections::HashMap::new(),
465484 // Source 0 *is* the timeline's rate: it defined it.
466485 rates: vec![Rate::REAL_TIME],
467486 span_rate: Rate::REAL_TIME,
@@ -561,6 +580,7 @@ impl PlaybackSession {
561580 worker: stream.worker,
562581 backend: stream.backend,
563582 retired: Vec::new(),
583+ restarts: 0,
564584 // The song keeps the clock, as a video's own sound does -- and wall
565585 // time keeps it on a machine with no device, where the picture
566586 // (black) still has to move at some rate.
@@ -572,6 +592,7 @@ impl PlaybackSession {
572592 audio_disabled,
573593 project,
574594 counts: vec![meta.frame_count],
595+ probes: std::collections::HashMap::new(),
575596 // Source 0 *is* the timeline's rate: it defined it.
576597 rates: vec![Rate::REAL_TIME],
577598 span_rate: Rate::REAL_TIME,
@@ -641,11 +662,13 @@ impl PlaybackSession {
641662 worker: stream.worker,
642663 backend: stream.backend,
643664 retired: Vec::new(),
665+ restarts: 0,
644666 clock: PlaybackClock::new(ClockSource::Wall),
645667 audio: None,
646668 audio_disabled: None,
647669 project,
648670 counts: vec![meta.frame_count],
671+ probes: std::collections::HashMap::new(),
649672 // Source 0 *is* the timeline's rate: it defined it.
650673 rates: vec![Rate::REAL_TIME],
651674 span_rate: Rate::REAL_TIME,
@@ -930,6 +953,7 @@ impl PlaybackSession {
930953 worker: stream.worker,
931954 backend: stream.backend,
932955 retired: Vec::new(),
956+ restarts: 0,
933957 clock: PlaybackClock::new(match audio {
934958 Some(_) => ClockSource::Audio,
935959 None => ClockSource::Wall,
@@ -938,6 +962,7 @@ impl PlaybackSession {
938962 audio_disabled,
939963 project,
940964 counts,
965+ probes: std::collections::HashMap::new(),
941966 rates,
942967 span_rate: Rate::REAL_TIME,
943968 span,
@@ -1276,11 +1301,32 @@ impl PlaybackSession {
12761301 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's
12771302 /// worker on this seek and the list stays a handful long. Nothing waits.
12781303 fn retire(&mut self, replacement: Worker) {
1304+ self.restarts += 1;
12791305 self.retired
12801306 .push(std::mem::replace(&mut self.worker, replacement));
12811307 self.retired.retain(|w| !w.is_finished());
12821308 }
12831309
1310+ /// Picture restarts so far; see [`restarts`](Self::restarts). The one place
1311+ /// a worker is ever replaced counts them, so a seek, a resync and a clip
1312+ /// boundary all land here and a measurement need not guess which it saw.
1313+ #[doc(hidden)]
1314+ pub fn restarts(&self) -> u64 {
1315+ self.restarts
1316+ }
1317+
1318+ /// Starved audio callbacks since the device opened, and how far into the
1319+ /// device's own playback (seconds) the last of them was -- `None` for a
1320+ /// session with no device at all. The counter the plugin prints on drop,
1321+ /// readable while the session runs: read it either side of a seek and the
1322+ /// difference is what that seek cost the ear.
1323+ #[doc(hidden)]
1324+ pub fn audio_underruns(&self) -> Option<(u64, Option<f64>)> {
1325+ let audio = self.audio.as_ref()?;
1326+ let (count, last) = audio.ao.lock().unwrap().underruns();
1327+ Some((count, last.map(|p| p as f64 / f64::from(audio.sample_rate))))
1328+ }
1329+
12841330 /// How many threads this session still has running of its own: the decode
12851331 /// worker, every retired one that has not returned yet, and the audio
12861332 /// feeders still in the air. One for a session playing along quietly.
@@ -2083,7 +2129,7 @@ impl PlaybackSession {
20832129 let image = crate::is_image(path);
20842130 if !image {
20852131 let first = self.first_audio()?;
2086- audio_matches(&wanted, &first)?;
2132+ self.audio_matches_cached(&wanted, &first)?;
20872133 }
20882134 let rate = self.file_rate(&wanted.path);
20892135 let source = self.project.import(path, stream);
@@ -2195,8 +2241,44 @@ impl PlaybackSession {
21952241 /// What the timeline's audio *is*: the chosen stream of the first source
21962242 /// that could have any ([`audio_source_of`]), probed. Every other source is
21972243 /// held to it.
2198- fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {
2199- first_audio_of(self.project.sources())
2244+ ///
2245+ /// Through the session's own memo ([`probes`](Self::probes)), because this
2246+ /// is asked on the render thread: the free [`first_audio_of`] is the one a
2247+ /// worker with no session to reach for calls.
2248+ fn first_audio(&mut self) -> crate::Result<Option<crate::AudioProbe>> {
2249+ match audio_source_of(self.project.sources()) {
2250+ Some(first) => {
2251+ let (path, stream) = (first.path.clone(), first.audio_stream);
2252+ self.probe_cached(&path, stream)
2253+ }
2254+ None => Ok(None),
2255+ }
2256+ }
2257+
2258+ /// One audio header, read at most once per session per `(path, stream)`.
2259+ fn probe_cached(
2260+ &mut self,
2261+ path: &Path,
2262+ stream: usize,
2263+ ) -> crate::Result<Option<crate::AudioProbe>> {
2264+ let key = (path.to_path_buf(), stream);
2265+ if let Some(probe) = self.probes.get(&key) {
2266+ return Ok(*probe);
2267+ }
2268+ let probe = AudioSession::probe(path, stream)?;
2269+ self.probes.insert(key, probe);
2270+ Ok(probe)
2271+ }
2272+
2273+ /// [`audio_matches`] with this session's memo behind the new file's own
2274+ /// header too -- the second of the two opens a place or an import pays.
2275+ fn audio_matches_cached(
2276+ &mut self,
2277+ source: &Source,
2278+ first: &Option<crate::AudioProbe>,
2279+ ) -> crate::Result<()> {
2280+ let probe = self.probe_cached(&source.path, source.audio_stream)?;
2281+ audio_matches_probed(probe, first)
22002282 }
22012283
22022284 /// Places `clip` on `lane` alone at the playhead, overwriting what it lands
@@ -2348,7 +2430,7 @@ impl PlaybackSession {
23482430 // Stream 0, and there is no other: a standalone audio file carries one
23492431 // track (`AudioSession::probe_streams`), so nothing here has a stream
23502432 // to pick the way `place_stream_at` does for an mp4.
2351- audio_matches(&Source::new(path, 0), &first)?;
2433+ self.audio_matches_cached(&Source::new(path, 0), &first)?;
23522434 let frames = audio_frames(path, self.meta.frame_rate)?;
23532435 let source = self.project.import(path, 0);
23542436 self.note_frames(source, frames, Rate::REAL_TIME);
@@ -2502,16 +2584,6 @@ impl PlaybackSession {
25022584 Some((tap, audio.sample_rate))
25032585 }
25042586
2505- /// How many quanta the device has had to fill with silence for want of
2506- /// samples since this session opened: the count that means "the decoder was
2507- /// late", sampled live rather than printed at the end of the process, so a
2508- /// caller can attribute it to the seek it followed
2509- /// ([`AoSession::underruns`]). `None` with no device, and with a plugin too
2510- /// old to carry the counter.
2511- pub fn audio_underruns(&self) -> Option<u64> {
2512- self.audio.as_ref()?.ao.lock().unwrap().underruns()
2513- }
2514-
25152587 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
25162588 /// workers are replaced rather than steered: a fresh channel cannot hold a
25172589 /// stale frame, and it works just as well after EOF, where the old workers
@@ -2967,12 +3039,22 @@ fn audio_source_of(sources: &[Source]) -> Option<&Source> {
29673039 }
29683040
29693041 fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
3042+ let probe = AudioSession::probe(&source.path, source.audio_stream)?;
3043+ audio_matches_probed(probe, first)
3044+}
3045+
3046+/// The verdict alone, once the file's own header is in hand: the half a session
3047+/// with a memo behind it ([`PlaybackSession::audio_matches_cached`]) does not
3048+/// have to open the file for.
3049+fn audio_matches_probed(
3050+ probe: Option<crate::AudioProbe>,
3051+ first: &Option<crate::AudioProbe>,
3052+) -> crate::Result<()> {
29703053 // The layout, which the audio worker holds every source to anyway -- and not
29713054 // the rate any more: a file written at another one is resampled to the
29723055 // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as
29733056 // a file shot at another frame rate is read through [`Rate`]. Both silent is
29743057 // a match.
2975- let probe = AudioSession::probe(&source.path, source.audio_stream)?;
29763058 if probe.map(|p| p.channels) == first.map(|p| p.channels) {
29773059 return Ok(());
29783060 }
@@ -3275,6 +3357,53 @@ mod tests {
32753357 assert_eq!(session.sources().len(), session.counts.len());
32763358 }
32773359
3360+ /// The two headers a place reads are read *once*: an mp4 dropped on a lane
3361+ /// used to open its own container and the timeline's first source every
3362+ /// time, both on the thread that draws, and a film whose pages have gone
3363+ /// cold is 1.7 s of that.
3364+ ///
3365+ /// Proved by answering, not by timing: the memo is filled with a layout the
3366+ /// file does not have, and the place is refused. Only a door that read the
3367+ /// remembered header rather than the disk can refuse it.
3368+ #[test]
3369+ fn a_place_reads_each_audio_header_once() {
3370+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3371+ session.set_gain(0.0);
3372+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
3373+ let end = session.timeline_duration();
3374+ assert!(
3375+ session
3376+ .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
3377+ .expect("a file just imported is on this timeline")
3378+ );
3379+ assert_eq!(
3380+ session.probes.len(),
3381+ 2,
3382+ "the timeline's first source and the file placed, once each"
3383+ );
3384+
3385+ // Now say av2 is 5.1. Nothing on disk changed, so a door that opens the
3386+ // file still matches; one that trusts the memo refuses by layout.
3387+ // Keyed exactly as a [`Source`] names a file -- canonical, symlinks
3388+ // resolved -- which is the key the doors look up.
3389+ let av2 = Source::new(asset("test_av2.mp4"), 0).path;
3390+ session.probes.insert(
3391+ (av2, 0),
3392+ Some(crate::AudioProbe {
3393+ sample_rate: 48_000,
3394+ channels: 6,
3395+ }),
3396+ );
3397+ let refused = session
3398+ .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
3399+ .expect_err("the remembered layout disagrees with the timeline's");
3400+ assert!(
3401+ refused.to_string().contains("6 ch"),
3402+ "refused in the layout's own words: {refused}"
3403+ );
3404+ assert_eq!(session.probes.len(), 2, "and nothing was opened to say so");
3405+ }
3406+
32783407 #[test]
32793408 fn boundary_seconds_round_trip_to_their_own_frame() {
32803409 for f in 0u32..300 {
crates/engine/tests/pgs_bitmaps.rsmodified+9 -4
@@ -62,12 +62,17 @@ fn the_session_maps_a_pgs_track_onto_the_timeline_and_draws_it() {
6262 let drawn = Instant::now();
6363 let image = cues[0].image.as_ref().expect("a picture cue");
6464 let rgba = image.rgba().expect("the first display set decodes");
65+ let took = drawn.elapsed();
6566 eprintln!(
66- "cue 0 decoded to {}x{} in {:?}",
67- image.width,
68- image.height,
69- drawn.elapsed()
67+ "cue 0 decoded to {}x{} in {took:?}",
68+ image.width, image.height,
7069 );
70+ // The run-length walk is paid once per cue *change* -- the window keeps the
71+ // picture while it is up ([`Player::sub_picture`]) -- so what this holds is
72+ // the cost of the one frame a new line appears on: 247 µs measured on this
73+ // remux, a sixty-eighth of that frame's budget. A whole repaint's worth
74+ // would mean the cache above it had stopped mattering.
75+ assert!(took.as_millis() < 16, "a frame's worth of decode: {took:?}");
7176 assert_eq!(rgba.len(), (image.width * image.height * 4) as usize);
7277 let opaque = rgba.chunks_exact(4).filter(|px| px[3] > 0).count();
7378 assert!(opaque > 0, "the block decoded to an empty canvas");
crates/engine/tests/playback.rsmodified+5 -3
@@ -481,7 +481,7 @@ fn a_cold_seek_storm_starves_no_quantum() {
481481 run_for(&mut session, &mut last_index, Duration::from_millis(300));
482482 // Only a machine with the plugin *and* a daemon can starve at all; without
483483 // one the session plays wall-paced and there is nothing to measure.
484- let Some(before) = session.audio_underruns() else {
484+ let Some((before, _)) = session.audio_underruns() else {
485485 eprintln!("no audio device: seek storm not measured");
486486 return;
487487 };
@@ -517,9 +517,11 @@ fn a_cold_seek_storm_starves_no_quantum() {
517517 // ...and then plays for a moment, which is where a late decoder shows.
518518 run_for(&mut session, &mut landed, Duration::from_millis(300));
519519 }
520- let underruns = session.audio_underruns().expect("device still open") - before;
520+ let (now, last) = session.audio_underruns().expect("device still open");
521+ let underruns = now - before;
521522 eprintln!(
522- "{seeks} cold seeks into {} in {:?}: {underruns} underruns ({before} before the storm)",
523+ "{seeks} cold seeks into {} in {:?}: {underruns} underruns ({before} before the storm, \
524+ last at {last:?})",
523525 path.display(),
524526 storm.elapsed()
525527 );
scripts/bench.shmodified+15 -2
@@ -19,7 +19,10 @@
1919 # before the measurement -- no root, nothing else on the machine evicted,
2020 # and advisory, so it is the optimistic end of cold.
2121 # * warm = the same call repeated straight after, cache as the cold run left it.
22-# * medians of 5 for open and seek, 20 steps for a scrub, and for export as
22+# * medians of 5 for open and seek, 50 seeded random seeks for a seek storm,
23+# $BENCH_PLAYLOOP_SECS (30) of playing with a jump every 5 s for a play
24+# loop -- both drawn from $BENCH_SEED (1), so a rerun seeks the same
25+# places -- 20 steps for a scrub, and for export as
2326 # many reps as $BENCH_EXPORT_CAP seconds leave room for (at least one,
2427 # which is then marked CAPPED if it did not finish).
2528 # * every metric runs as its own process: a decoder that panics costs one
@@ -41,7 +44,13 @@ LOG="$OUT_DIR/bench.log"
4144 # Absolute, because $CARGO_TARGET_DIR may already be one and the plugin path
4245 # below must not become "$PWD/$HOME/...".
4346 TARGET=$(realpath -m "${CARGO_TARGET_DIR:-target}")
44-cargo build --release -p engine -p engine-hw --example bench || exit 1
47+# The plugins are their own build: `--example` selects example targets in every
48+# package it is given, and a cdylib is not one, so `-p engine-hw --example
49+# bench` built no plugin at all and every run measured software while the line
50+# below said otherwise. engine-audio is here for the same reason -- the play
51+# loop's underruns come from the device, and with no plugin there is no device.
52+cargo build --release -p engine-hw -p engine-audio || exit 1
53+cargo build --release -p engine --example bench || exit 1
4554 BENCH="$TARGET/release/examples/bench"
4655 # The plugin is looked for beside the running executable, and an example binary
4756 # lives one directory below the plugin: without this, hardware decode and
@@ -98,6 +107,10 @@ for file in "${files[@]}"; do
98107 run 1800 "seek_ttff_${t}s" "$file" seek "$t"
99108 done
100109 run 3600 scrub "$file" scrub
110+ # The two random metrics: same seed both sides of a change, or the "before"
111+ # and the "after" are different seeks and the comparison means nothing.
112+ run 3600 seekstorm "$file" seekstorm "${BENCH_SEED:-1}"
113+ run 1800 playloop "$file" playloop "${BENCH_PLAYLOOP_SECS:-30}" "${BENCH_SEED:-1}"
101114 for seat in h264sw h264hw av1 hevc hevchw; do
102115 run "$export_limit" "export_fps_$seat" "$file" export "$seat" "$OUT_DIR"
103116 done