forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'main' into worktree-agent-ab6fdf12423ce2e46

Browse files at this commit

dd2001cef57e38c7958b2c4d76324f949f2d8b4cAhmet Kaan GümüşParent: 86e94555fdd558
# Conflicts:
#	crates/engine/src/playback.rs
Cargo.lockmodified+151 -0
@@ -3372,6 +3372,16 @@ dependencies = [
3372 "libc",3372 "libc",
3373 ]3373 ]
3374 3374
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+
3375 [[package]]3385 [[package]]
3376 name = "maybe-rayon"3386 name = "maybe-rayon"
3377 version = "0.1.1"3387 version = "0.1.1"
@@ -3538,6 +3548,22 @@ dependencies = [
3538 "getrandom 0.2.17",3548 "getrandom 0.2.17",
3539 ]3549 ]
3540 3550
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+
3541 [[package]]3567 [[package]]
3542 name = "new_debug_unreachable"3568 name = "new_debug_unreachable"
3543 version = "1.0.6"3569 version = "1.0.6"
@@ -3608,6 +3634,34 @@ dependencies = [
3608 "memchr",3634 "memchr",
3609 ]3635 ]
3610 3636
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+
3611 [[package]]3665 [[package]]
3612 name = "noop_proc_macro"3666 name = "noop_proc_macro"
3613 version = "0.3.0"3667 version = "0.3.0"
@@ -3672,6 +3726,7 @@ checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
3672 dependencies = [3726 dependencies = [
3673 "bytemuck",3727 "bytemuck",
3674 "num-traits",3728 "num-traits",
3729+ "serde",
3675 ]3730 ]
3676 3731
3677 [[package]]3732 [[package]]
@@ -3951,6 +4006,12 @@ dependencies = [
3951 "pin-project-lite",4006 "pin-project-lite",
3952 ]4007 ]
3953 4008
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+
3954 [[package]]4015 [[package]]
3955 name = "oxideav-ac3"4016 name = "oxideav-ac3"
3956 version = "0.0.10"4017 version = "0.0.10"
@@ -4279,6 +4340,21 @@ version = "0.2.5"
4279 source = "registry+https://github.com/rust-lang/crates.io-index"4340 source = "registry+https://github.com/rust-lang/crates.io-index"
4280 checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7"4341 checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7"
4281 4342
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+
4282 [[package]]4358 [[package]]
4283 name = "postage"4359 name = "postage"
4284 version = "0.5.0"4360 version = "0.5.0"
@@ -4324,6 +4400,15 @@ dependencies = [
4324 "syn 2.0.119",4400 "syn 2.0.119",
4325 ]4401 ]
4326 4402
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+
4327 [[package]]4412 [[package]]
4328 name = "proc-macro-crate"4413 name = "proc-macro-crate"
4329 version = "3.5.0"4414 version = "3.5.0"
@@ -4700,6 +4785,12 @@ dependencies = [
4700 "raw-window-handle",4785 "raw-window-handle",
4701 ]4786 ]
4702 4787
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+
4703 [[package]]4794 [[package]]
4704 name = "rayon"4795 name = "rayon"
4705 version = "1.12.0"4796 version = "1.12.0"
@@ -4731,6 +4822,15 @@ dependencies = [
4731 "once_cell",4822 "once_cell",
4732 ]4823 ]
4733 4824
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+
4734 [[package]]4834 [[package]]
4735 name = "reborrow"4835 name = "reborrow"
4736 version = "0.5.5"4836 version = "0.5.5"
@@ -4869,6 +4969,9 @@ name = "ruopus"
4869 version = "0.1.2"4969 version = "0.1.2"
4870 source = "registry+https://github.com/rust-lang/crates.io-index"4970 source = "registry+https://github.com/rust-lang/crates.io-index"
4871 checksum = "fcfcd963c83fc1ada2180ccdac7f1568d87fb0f2ad7236b266fdc9fb9122fbfd"4971 checksum = "fcfcd963c83fc1ada2180ccdac7f1568d87fb0f2ad7236b266fdc9fb9122fbfd"
4972+dependencies = [
4973+ "spectrograms",
4974+]
4872 4975
4873 [[package]]4976 [[package]]
4874 name = "rust-embed"4977 name = "rust-embed"
@@ -4927,6 +5030,20 @@ dependencies = [
4927 "semver",5030 "semver",
4928 ]5031 ]
4929 5032
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+
4930 [[package]]5047 [[package]]
4931 name = "rustix"5048 name = "rustix"
4932 version = "0.38.44"5049 version = "0.38.44"
@@ -5506,6 +5623,24 @@ dependencies = [
5506 "windows-sys 0.61.2",5623 "windows-sys 0.61.2",
5507 ]5624 ]
5508 5625
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+
5509 [[package]]5644 [[package]]
5510 name = "spin"5645 name = "spin"
5511 version = "0.9.9"5646 version = "0.9.9"
@@ -5570,6 +5705,12 @@ version = "1.1.0"
5570 source = "registry+https://github.com/rust-lang/crates.io-index"5705 source = "registry+https://github.com/rust-lang/crates.io-index"
5571 checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"5706 checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
5572 5707
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+
5573 [[package]]5714 [[package]]
5574 name = "strict-num"5715 name = "strict-num"
5575 version = "0.1.1"5716 version = "0.1.1"
@@ -6401,6 +6542,16 @@ dependencies = [
6401 "once_cell",6542 "once_cell",
6402 ]6543 ]
6403 6544
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+
6404 [[package]]6555 [[package]]
6405 name = "try-lock"6556 name = "try-lock"
6406 version = "0.2.5"6557 version = "0.2.5"
crates/engine-audio/src/lib.rsmodified+40 -0
@@ -157,6 +157,11 @@ struct Shared {
157 /// per callback on the RT thread, so it is an atomic rather than a lock.157 /// per callback on the RT thread, so it is an atomic rather than a lock.
158 gain: AtomicU32,158 gain: AtomicU32,
159 underruns: AtomicU64,159 underruns: AtomicU64,
160+ /// Device position (samples per channel) read at the most recent underrun,
161+ /// `-1` until one happens: what says whether the count in hand is old news
162+ /// or is still growing. Written on the RT thread, and only on the starved
163+ /// path, so the ordinary callback pays nothing for it.
164+ last_underrun: AtomicI64,
160 }165 }
161 166
162 enum Ctl {167 enum Ctl {
@@ -251,6 +256,12 @@ fn run(
251 // that silence, so it really is elapsed time.256 // that silence, so it really is elapsed time.
252 slice[got * 4..want * 4].fill(0);257 slice[got * 4..want * 4].fill(0);
253 shared.underruns.fetch_add(1, Ordering::Relaxed);258 shared.underruns.fetch_add(1, Ordering::Relaxed);
259+ // The position this callback is about to compute is
260+ // not known yet; the previous one is a quantum
261+ // (~23 ms) behind and needs no clock call here.
262+ shared
263+ .last_underrun
264+ .store(shared.position.load(Ordering::Relaxed), Ordering::Relaxed);
254 }265 }
255 // After the fill, so the silence stays silent whatever266 // After the fill, so the silence stays silent whatever
256 // the gain is, and the underrun count keeps meaning267 // the gain is, and the underrun count keeps meaning
@@ -410,6 +421,7 @@ pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void {
410 resumed: AtomicBool::new(false),421 resumed: AtomicBool::new(false),
411 gain: AtomicU32::new(1.0f32.to_bits()),422 gain: AtomicU32::new(1.0f32.to_bits()),
412 underruns: AtomicU64::new(0),423 underruns: AtomicU64::new(0),
424+ last_underrun: AtomicI64::new(-1),
413 });425 });
414 let (ready_tx, ready_rx) = mpsc::channel();426 let (ready_tx, ready_rx) = mpsc::channel();
415 let (ctl_tx, ctl_rx) = mpsc::channel();427 let (ctl_tx, ctl_rx) = mpsc::channel();
@@ -479,6 +491,34 @@ pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 {
479 .unwrap_or(-1)491 .unwrap_or(-1)
480 }492 }
481 493
494+/// Starved callbacks since the stream opened -- one per quantum the decoder was
495+/// late for -- and, through `last_at`, the device position the newest of them
496+/// was seen at (`-1` if there has been none). The same number the drop print
497+/// reports, asked for while the session is still running: a caller measuring a
498+/// seek reads it before and after and the difference is that seek's cost.
499+///
500+/// Two relaxed atomic loads, nothing else: the RT thread writes both and must
501+/// never wait on a reader.
502+///
503+/// # Safety
504+/// `session` must come from [`ao_open`]; `last_at` is either null or writable.
505+#[unsafe(no_mangle)]
506+pub unsafe extern "C" fn ao_underruns(session: *mut c_void, last_at: *mut i64) -> i64 {
507+ catch_unwind(AssertUnwindSafe(|| {
508+ if session.is_null() {
509+ return -1;
510+ }
511+ // SAFETY: caller-guaranteed live session.
512+ let session = unsafe { &*(session as *const Session) };
513+ if !last_at.is_null() {
514+ // SAFETY: caller-guaranteed writable, and it is a plain i64.
515+ unsafe { *last_at = session.shared.last_underrun.load(Ordering::Relaxed) };
516+ }
517+ session.shared.underruns.load(Ordering::Relaxed) as i64
518+ }))
519+ .unwrap_or(-1)
520+}
521+
482 /// Pauses (0) or resumes (non-zero) playback. Paused freezes the position.522 /// Pauses (0) or resumes (non-zero) playback. Paused freezes the position.
483 /// 0 on success, negative on failure.523 /// 0 on success, negative on failure.
484 ///524 ///
crates/engine/Cargo.tomlmodified+18 -3
@@ -81,8 +81,23 @@ rusty_mp3 = "0.6"
81 # packet. This one does the whole pipeline. Its quirks are measured and worked81 # packet. This one does the whole pipeline. Its quirks are measured and worked
82 # around in [`crate::export::write_ogg`] -- read that before touching this line.82 # around in [`crate::export::write_ogg`] -- read that before touching this line.
83 rusty_vorbis = "0.1.1"83 rusty_vorbis = "0.1.1"
84-# The Opus decoder: pure Rust, MIT, no C and no FFI, and no dependencies at all84+# The Opus decoder: pure Rust, MIT, no C and no FFI.
85-# without its default features (`spectrograms` is for its own analysis tools).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.
86 # Symphonia has no Opus at any version -- its feature list stops at vorbis and101 # Symphonia has no Opus at any version -- its feature list stops at vorbis and
87 # there is no `symphonia-codec-opus` crate -- while both of its containers *read*102 # there is no `symphonia-codec-opus` crate -- while both of its containers *read*
88 # the format already: `A_OPUS` and `OpusHead` have always mapped to103 # the format already: `A_OPUS` and `OpusHead` have always mapped to
@@ -99,7 +114,7 @@ rusty_vorbis = "0.1.1"
99 # where the film is silent. This one matches ffmpeg's own decode of the same file to a114 # where the film is silent. This one matches ffmpeg's own decode of the same file to a
100 # correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3`115 # correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3`
101 # below, because a decoder is a bit-exactness dependency.116 # 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"] }
103 # The Opus *encoder*, the other half of that pair: a pure-Rust port of libopus118 # The Opus *encoder*, the other half of that pair: a pure-Rust port of libopus
104 # 1.6, BSD-3, `build.rs`-less and with **no dependencies at all** -- checked, not119 # 1.6, BSD-3, `build.rs`-less and with **no dependencies at all** -- checked, not
105 # taken from the README (`cargo tree` is two lines; there is not one `.c`, `.h`120 # 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 @@
1 //! The baseline every later decode/encode change is measured against: open,1 //! 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.
3 //!4 //!
4 //! `cargo run --release -p engine --example bench -- <metric> <file> [args]`5 //! `cargo run --release -p engine --example bench -- <metric> <file> [args]`
5 //!6 //!
@@ -9,7 +10,10 @@
9 //! failure down as data.10 //! failure down as data.
10 //!11 //!
11 //! Every row is one TSV line -- `file, metric, unit, n, median, min, max, note`12 //! 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`).
13 //!17 //!
14 //! **Cold and warm.** Cold means the file's pages are dropped from the page18 //! **Cold and warm.** Cold means the file's pages are dropped from the page
15 //! cache immediately before the measurement, with `posix_fadvise(DONTNEED)` on19 //! cache immediately before the measurement, with `posix_fadvise(DONTNEED)` on
@@ -49,6 +53,8 @@ fn main() {
49 match metric.as_str() {53 match metric.as_str() {
50 "open" => open_bench(&path),54 "open" => open_bench(&path),
51 "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")),55 "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())),
52 "scrub" => scrub_bench(&path),58 "scrub" => scrub_bench(&path),
53 "waveform" => waveform_bench(&path),59 "waveform" => waveform_bench(&path),
54 "export" => {60 "export" => {
@@ -63,6 +69,8 @@ fn main() {
63 fn usage() -> ! {69 fn usage() -> ! {
64 eprintln!(70 eprintln!(
65 "usage: bench open <file>\n bench seek <file> <secs>\n \71 "usage: bench open <file>\n bench seek <file> <secs>\n \
72+ bench seekstorm <file> [seed]\n \
73+ bench playloop <file> <secs> [seed]\n \
66 bench scrub <file>\n bench waveform <file>\n \74 bench scrub <file>\n bench waveform <file>\n \
67 bench export <file> <h264sw|h264hw|av1|hevc|hevchw> <out_dir>"75 bench export <file> <h264sw|h264hw|av1|hevc|hevchw> <out_dir>"
68 );76 );
@@ -74,6 +82,12 @@ fn arg_f64(arg: Option<String>, what: &str) -> f64 {
74 .unwrap_or_else(|| panic!("missing {what}"))82 .unwrap_or_else(|| panic!("missing {what}"))
75 }83 }
76 84
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+
77 // ---------------------------------------------------------------- reporting91 // ---------------------------------------------------------------- reporting
78 92
79 /// One TSV row: the median is what a comparison uses, the min and max are what93 /// One TSV row: the median is what a comparison uses, the min and max are what
@@ -125,6 +139,34 @@ fn ttff_timeout() -> Duration {
125 Duration::from_secs_f64(env_f64("BENCH_TTFF_TIMEOUT", 180.0))139 Duration::from_secs_f64(env_f64("BENCH_TTFF_TIMEOUT", 180.0))
126 }140 }
127 141
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+
128 fn env_f64(key: &str, default: f64) -> f64 {170 fn env_f64(key: &str, default: f64) -> f64 {
129 std::env::var(key)171 std::env::var(key)
130 .ok()172 .ok()
@@ -250,6 +292,220 @@ fn seek_bench(path: &Path, secs: f64) {
250 row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, &note);292 row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, &note);
251 }293 }
252 294
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+
253 // ---------------------------------------------------------------- waveform509 // ---------------------------------------------------------------- waveform
254 510
255 /// What a lane waits for before it has an envelope: one whole511 /// What a lane waits for before it has an envelope: one whole
crates/engine/src/ao.rsmodified+17 -0
@@ -20,6 +20,7 @@ struct Plugin {
20 set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32,20 set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32,
21 set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32,21 set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32,
22 flush: unsafe extern "C" fn(*mut c_void) -> i32,22 flush: unsafe extern "C" fn(*mut c_void) -> i32,
23+ underruns: unsafe extern "C" fn(*mut c_void, *mut i64) -> i64,
23 close: unsafe extern "C" fn(*mut c_void),24 close: unsafe extern "C" fn(*mut c_void),
24 // Never dropped (lives in a static), so the fn pointers above stay valid.25 // Never dropped (lives in a static), so the fn pointers above stay valid.
25 _lib: Library,26 _lib: Library,
@@ -63,6 +64,11 @@ fn load() -> Option<Plugin> {
63 // with no sound at all, which at least says so.64 // with no sound at all, which at least says so.
64 set_volume: *lib.get(b"ao_set_volume\0").ok()?,65 set_volume: *lib.get(b"ao_set_volume\0").ok()?,
65 flush: *lib.get(b"ao_flush\0").ok()?,66 flush: *lib.get(b"ao_flush\0").ok()?,
67+ // Required on the same terms as the two above: the plugin
68+ // ships from this build, and a measurement that silently
69+ // reads zero underruns is worse than a run that says the
70+ // plugin is the wrong one.
71+ underruns: *lib.get(b"ao_underruns\0").ok()?,
66 close: *lib.get(b"ao_close\0").ok()?,72 close: *lib.get(b"ao_close\0").ok()?,
67 _lib: lib,73 _lib: lib,
68 })74 })
@@ -143,6 +149,17 @@ impl AoSession {
143 // SAFETY: `handle` came from `ao_open` and is still open.149 // SAFETY: `handle` came from `ao_open` and is still open.
144 unsafe { (self.plugin.flush)(self.handle) == 0 }150 unsafe { (self.plugin.flush)(self.handle) == 0 }
145 }151 }
152+
153+ /// Starved callbacks so far, and the device position (samples per channel)
154+ /// the last of them was seen at -- `None` for a stream that has never run
155+ /// dry. Two atomic loads inside the plugin, so it is cheap enough to poll
156+ /// and it never touches the RT thread's path.
157+ pub fn underruns(&self) -> (u64, Option<i64>) {
158+ let mut last = -1i64;
159+ // SAFETY: `handle` came from `ao_open`, and `last` is a live i64 of ours.
160+ let count = unsafe { (self.plugin.underruns)(self.handle, &raw mut last) };
161+ (count.max(0) as u64, (last >= 0).then_some(last))
162+ }
146 }163 }
147 164
148 impl Drop for AoSession {165 impl Drop for AoSession {
crates/engine/src/playback.rsmodified+149 -5
@@ -250,6 +250,12 @@ pub struct PlaybackSession {
250 ///250 ///
251 /// [`retire`]: PlaybackSession::retire251 /// [`retire`]: PlaybackSession::retire
252 retired: Vec<Worker>,252 retired: Vec<Worker>,
253+ /// Picture workers that replaced another one, i.e. every restart the
254+ /// session's first worker did not cost: a seek, a resync, a clip boundary.
255+ /// Each carries a demuxer reopen and a VA-API init, so this is what a
256+ /// playback measurement counts to say how often the picture was thrown away
257+ /// ([`restarts`](Self::restarts)).
258+ restarts: u64,
253 clock: PlaybackClock,259 clock: PlaybackClock,
254 audio: Option<Audio>,260 audio: Option<Audio>,
255 /// Why this timeline is silent, when the file itself is not: an audio track261 /// Why this timeline is silent, when the file itself is not: an audio track
@@ -270,6 +276,17 @@ pub struct PlaybackSession {
270 /// not -- with the single exception `sources` itself has,276 /// not -- with the single exception `sources` itself has,
271 /// [`Self::remove_source`], which takes the same entry out of both.277 /// [`Self::remove_source`], which takes the same entry out of both.
272 counts: Vec<u32>,278 counts: Vec<u32>,
279+ /// Audio headers already read, by the `(path, stream)` they were read for.
280+ /// Every door that checks a file against the timeline asks the same two
281+ /// questions -- what this file's sound is, and what the timeline's first
282+ /// source's is ([`audio_matches`], [`first_audio_of`]) -- and each answer is
283+ /// a container open. Warm that is 5-10 ms; on a film whose pages have been
284+ /// evicted it is **1.7 s** (measured, 3.1 GB HEVC mkv), and both of those
285+ /// are spent on the thread that draws, because placing and importing are
286+ /// what a drag lands on. A header does not change while a session holds the
287+ /// file, so it is read once and remembered. Errors are not kept: a file that
288+ /// failed to open is asked again next time.
289+ probes: std::collections::HashMap<(std::path::PathBuf, usize), Option<crate::AudioProbe>>,
273 /// What each source's own frame rate is against this timeline's, indexed290 /// What each source's own frame rate is against this timeline's, indexed
274 /// and grown exactly as [`Self::counts`] is (and shortened with it by291 /// and grown exactly as [`Self::counts`] is (and shortened with it by
275 /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the292 /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the
@@ -415,11 +432,13 @@ impl PlaybackSession {
415 worker: stream.worker,432 worker: stream.worker,
416 backend: stream.backend,433 backend: stream.backend,
417 retired: Vec::new(),434 retired: Vec::new(),
435+ restarts: 0,
418 clock: PlaybackClock::new(source),436 clock: PlaybackClock::new(source),
419 audio,437 audio,
420 audio_disabled,438 audio_disabled,
421 project,439 project,
422 counts: vec![meta.frame_count],440 counts: vec![meta.frame_count],
441+ probes: std::collections::HashMap::new(),
423 // Source 0 *is* the timeline's rate: it defined it.442 // Source 0 *is* the timeline's rate: it defined it.
424 rates: vec![Rate::REAL_TIME],443 rates: vec![Rate::REAL_TIME],
425 span_rate: Rate::REAL_TIME,444 span_rate: Rate::REAL_TIME,
@@ -520,6 +539,7 @@ impl PlaybackSession {
520 worker: stream.worker,539 worker: stream.worker,
521 backend: stream.backend,540 backend: stream.backend,
522 retired: Vec::new(),541 retired: Vec::new(),
542+ restarts: 0,
523 // The song keeps the clock, as a video's own sound does -- and wall543 // The song keeps the clock, as a video's own sound does -- and wall
524 // time keeps it on a machine with no device, where the picture544 // time keeps it on a machine with no device, where the picture
525 // (black) still has to move at some rate.545 // (black) still has to move at some rate.
@@ -531,6 +551,7 @@ impl PlaybackSession {
531 audio_disabled,551 audio_disabled,
532 project,552 project,
533 counts: vec![meta.frame_count],553 counts: vec![meta.frame_count],
554+ probes: std::collections::HashMap::new(),
534 // Source 0 *is* the timeline's rate: it defined it.555 // Source 0 *is* the timeline's rate: it defined it.
535 rates: vec![Rate::REAL_TIME],556 rates: vec![Rate::REAL_TIME],
536 span_rate: Rate::REAL_TIME,557 span_rate: Rate::REAL_TIME,
@@ -601,11 +622,13 @@ impl PlaybackSession {
601 worker: stream.worker,622 worker: stream.worker,
602 backend: stream.backend,623 backend: stream.backend,
603 retired: Vec::new(),624 retired: Vec::new(),
625+ restarts: 0,
604 clock: PlaybackClock::new(ClockSource::Wall),626 clock: PlaybackClock::new(ClockSource::Wall),
605 audio: None,627 audio: None,
606 audio_disabled: None,628 audio_disabled: None,
607 project,629 project,
608 counts: vec![meta.frame_count],630 counts: vec![meta.frame_count],
631+ probes: std::collections::HashMap::new(),
609 // Source 0 *is* the timeline's rate: it defined it.632 // Source 0 *is* the timeline's rate: it defined it.
610 rates: vec![Rate::REAL_TIME],633 rates: vec![Rate::REAL_TIME],
611 span_rate: Rate::REAL_TIME,634 span_rate: Rate::REAL_TIME,
@@ -891,6 +914,7 @@ impl PlaybackSession {
891 worker: stream.worker,914 worker: stream.worker,
892 backend: stream.backend,915 backend: stream.backend,
893 retired: Vec::new(),916 retired: Vec::new(),
917+ restarts: 0,
894 clock: PlaybackClock::new(match audio {918 clock: PlaybackClock::new(match audio {
895 Some(_) => ClockSource::Audio,919 Some(_) => ClockSource::Audio,
896 None => ClockSource::Wall,920 None => ClockSource::Wall,
@@ -899,6 +923,7 @@ impl PlaybackSession {
899 audio_disabled,923 audio_disabled,
900 project,924 project,
901 counts,925 counts,
926+ probes: std::collections::HashMap::new(),
902 rates,927 rates,
903 span_rate: Rate::REAL_TIME,928 span_rate: Rate::REAL_TIME,
904 span,929 span,
@@ -1265,6 +1290,12 @@ impl PlaybackSession {
1265 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's1290 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's
1266 /// worker on this seek and the list stays a handful long. Nothing waits.1291 /// worker on this seek and the list stays a handful long. Nothing waits.
1267 fn retire(&mut self, replacement: Worker) {1292 fn retire(&mut self, replacement: Worker) {
1293+ // A *replacement*, which is now the narrow case: a seek onto the file
1294+ // the worker already has open steers it instead ([`Worker::reseek`])
1295+ // and never comes here, so this count is the picture restarts that
1296+ // really cost a thread and a decoder open -- which is what makes it
1297+ // worth counting.
1298+ self.restarts += 1;
1268 let mut outgoing = std::mem::replace(&mut self.worker, replacement);1299 let mut outgoing = std::mem::replace(&mut self.worker, replacement);
1269 // Terminal, unlike the [`Worker::abandon`] a seek does: this worker is1300 // Terminal, unlike the [`Worker::abandon`] a seek does: this worker is
1270 // being replaced rather than steered, so its thread has to end -- and1301 // being replaced rather than steered, so its thread has to end -- and
@@ -1276,6 +1307,26 @@ impl PlaybackSession {
1276 self.retired.retain(|w| !w.is_finished());1307 self.retired.retain(|w| !w.is_finished());
1277 }1308 }
1278 1309
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+
1279 /// How many threads this session still has running of its own: the decode1330 /// How many threads this session still has running of its own: the decode
1280 /// worker, every retired one that has not returned yet, and the audio1331 /// worker, every retired one that has not returned yet, and the audio
1281 /// feeders still in the air. One for a session playing along quietly.1332 /// feeders still in the air. One for a session playing along quietly.
@@ -2089,7 +2140,7 @@ impl PlaybackSession {
2089 let image = crate::is_image(path);2140 let image = crate::is_image(path);
2090 if !image {2141 if !image {
2091 let first = self.first_audio()?;2142 let first = self.first_audio()?;
2092- audio_matches(&wanted, &first)?;2143+ self.audio_matches_cached(&wanted, &first)?;
2093 }2144 }
2094 let rate = self.file_rate(&wanted.path);2145 let rate = self.file_rate(&wanted.path);
2095 let source = self.project.import(path, stream);2146 let source = self.project.import(path, stream);
@@ -2201,8 +2252,44 @@ impl PlaybackSession {
2201 /// What the timeline's audio *is*: the chosen stream of the first source2252 /// What the timeline's audio *is*: the chosen stream of the first source
2202 /// that could have any ([`audio_source_of`]), probed. Every other source is2253 /// that could have any ([`audio_source_of`]), probed. Every other source is
2203 /// held to it.2254 /// held to it.
2204- fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {2255+ ///
2205- first_audio_of(self.project.sources())2256+ /// Through the session's own memo ([`probes`](Self::probes)), because this
2257+ /// is asked on the render thread: the free [`first_audio_of`] is the one a
2258+ /// worker with no session to reach for calls.
2259+ fn first_audio(&mut self) -> crate::Result<Option<crate::AudioProbe>> {
2260+ match audio_source_of(self.project.sources()) {
2261+ Some(first) => {
2262+ let (path, stream) = (first.path.clone(), first.audio_stream);
2263+ self.probe_cached(&path, stream)
2264+ }
2265+ None => Ok(None),
2266+ }
2267+ }
2268+
2269+ /// One audio header, read at most once per session per `(path, stream)`.
2270+ fn probe_cached(
2271+ &mut self,
2272+ path: &Path,
2273+ stream: usize,
2274+ ) -> crate::Result<Option<crate::AudioProbe>> {
2275+ let key = (path.to_path_buf(), stream);
2276+ if let Some(probe) = self.probes.get(&key) {
2277+ return Ok(*probe);
2278+ }
2279+ let probe = AudioSession::probe(path, stream)?;
2280+ self.probes.insert(key, probe);
2281+ Ok(probe)
2282+ }
2283+
2284+ /// [`audio_matches`] with this session's memo behind the new file's own
2285+ /// header too -- the second of the two opens a place or an import pays.
2286+ fn audio_matches_cached(
2287+ &mut self,
2288+ source: &Source,
2289+ first: &Option<crate::AudioProbe>,
2290+ ) -> crate::Result<()> {
2291+ let probe = self.probe_cached(&source.path, source.audio_stream)?;
2292+ audio_matches_probed(probe, first)
2206 }2293 }
2207 2294
2208 /// Places `clip` on `lane` alone at the playhead, overwriting what it lands2295 /// Places `clip` on `lane` alone at the playhead, overwriting what it lands
@@ -2354,7 +2441,7 @@ impl PlaybackSession {
2354 // Stream 0, and there is no other: a standalone audio file carries one2441 // Stream 0, and there is no other: a standalone audio file carries one
2355 // track (`AudioSession::probe_streams`), so nothing here has a stream2442 // track (`AudioSession::probe_streams`), so nothing here has a stream
2356 // to pick the way `place_stream_at` does for an mp4.2443 // to pick the way `place_stream_at` does for an mp4.
2357- audio_matches(&Source::new(path, 0), &first)?;2444+ self.audio_matches_cached(&Source::new(path, 0), &first)?;
2358 let frames = audio_frames(path, self.meta.frame_rate)?;2445 let frames = audio_frames(path, self.meta.frame_rate)?;
2359 let source = self.project.import(path, 0);2446 let source = self.project.import(path, 0);
2360 self.note_frames(source, frames, Rate::REAL_TIME);2447 self.note_frames(source, frames, Rate::REAL_TIME);
@@ -2974,12 +3061,22 @@ fn audio_source_of(sources: &[Source]) -> Option<&Source> {
2974 }3061 }
2975 3062
2976 fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {3063 fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
3064+ let probe = AudioSession::probe(&source.path, source.audio_stream)?;
3065+ audio_matches_probed(probe, first)
3066+}
3067+
3068+/// The verdict alone, once the file's own header is in hand: the half a session
3069+/// with a memo behind it ([`PlaybackSession::audio_matches_cached`]) does not
3070+/// have to open the file for.
3071+fn audio_matches_probed(
3072+ probe: Option<crate::AudioProbe>,
3073+ first: &Option<crate::AudioProbe>,
3074+) -> crate::Result<()> {
2977 // The layout, which the audio worker holds every source to anyway -- and not3075 // The layout, which the audio worker holds every source to anyway -- and not
2978 // the rate any more: a file written at another one is resampled to the3076 // the rate any more: a file written at another one is resampled to the
2979 // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as3077 // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as
2980 // a file shot at another frame rate is read through [`Rate`]. Both silent is3078 // a file shot at another frame rate is read through [`Rate`]. Both silent is
2981 // a match.3079 // a match.
2982- let probe = AudioSession::probe(&source.path, source.audio_stream)?;
2983 if probe.map(|p| p.channels) == first.map(|p| p.channels) {3080 if probe.map(|p| p.channels) == first.map(|p| p.channels) {
2984 return Ok(());3081 return Ok(());
2985 }3082 }
@@ -3249,6 +3346,53 @@ mod tests {
3249 assert_eq!(session.sources().len(), session.counts.len());3346 assert_eq!(session.sources().len(), session.counts.len());
3250 }3347 }
3251 3348
3349+ /// The two headers a place reads are read *once*: an mp4 dropped on a lane
3350+ /// used to open its own container and the timeline's first source every
3351+ /// time, both on the thread that draws, and a film whose pages have gone
3352+ /// cold is 1.7 s of that.
3353+ ///
3354+ /// Proved by answering, not by timing: the memo is filled with a layout the
3355+ /// file does not have, and the place is refused. Only a door that read the
3356+ /// remembered header rather than the disk can refuse it.
3357+ #[test]
3358+ fn a_place_reads_each_audio_header_once() {
3359+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3360+ session.set_gain(0.0);
3361+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
3362+ let end = session.timeline_duration();
3363+ assert!(
3364+ session
3365+ .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
3366+ .expect("a file just imported is on this timeline")
3367+ );
3368+ assert_eq!(
3369+ session.probes.len(),
3370+ 2,
3371+ "the timeline's first source and the file placed, once each"
3372+ );
3373+
3374+ // Now say av2 is 5.1. Nothing on disk changed, so a door that opens the
3375+ // file still matches; one that trusts the memo refuses by layout.
3376+ // Keyed exactly as a [`Source`] names a file -- canonical, symlinks
3377+ // resolved -- which is the key the doors look up.
3378+ let av2 = Source::new(asset("test_av2.mp4"), 0).path;
3379+ session.probes.insert(
3380+ (av2, 0),
3381+ Some(crate::AudioProbe {
3382+ sample_rate: 48_000,
3383+ channels: 6,
3384+ }),
3385+ );
3386+ let refused = session
3387+ .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
3388+ .expect_err("the remembered layout disagrees with the timeline's");
3389+ assert!(
3390+ refused.to_string().contains("6 ch"),
3391+ "refused in the layout's own words: {refused}"
3392+ );
3393+ assert_eq!(session.probes.len(), 2, "and nothing was opened to say so");
3394+ }
3395+
3252 #[test]3396 #[test]
3253 fn boundary_seconds_round_trip_to_their_own_frame() {3397 fn boundary_seconds_round_trip_to_their_own_frame() {
3254 for f in 0u32..300 {3398 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() {
62 let drawn = Instant::now();62 let drawn = Instant::now();
63 let image = cues[0].image.as_ref().expect("a picture cue");63 let image = cues[0].image.as_ref().expect("a picture cue");
64 let rgba = image.rgba().expect("the first display set decodes");64 let rgba = image.rgba().expect("the first display set decodes");
65+ let took = drawn.elapsed();
65 eprintln!(66 eprintln!(
66- "cue 0 decoded to {}x{} in {:?}",67+ "cue 0 decoded to {}x{} in {took:?}",
67- image.width,68+ image.width, image.height,
68- image.height,
69- drawn.elapsed()
70 );69 );
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:?}");
71 assert_eq!(rgba.len(), (image.width * image.height * 4) as usize);76 assert_eq!(rgba.len(), (image.width * image.height * 4) as usize);
72 let opaque = rgba.chunks_exact(4).filter(|px| px[3] > 0).count();77 let opaque = rgba.chunks_exact(4).filter(|px| px[3] > 0).count();
73 assert!(opaque > 0, "the block decoded to an empty canvas");78 assert!(opaque > 0, "the block decoded to an empty canvas");
scripts/bench.shmodified+15 -2
@@ -19,7 +19,10 @@
19 # before the measurement -- no root, nothing else on the machine evicted,19 # before the measurement -- no root, nothing else on the machine evicted,
20 # and advisory, so it is the optimistic end of cold.20 # and advisory, so it is the optimistic end of cold.
21 # * warm = the same call repeated straight after, cache as the cold run left it.21 # * 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 as22+# * 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
23 # many reps as $BENCH_EXPORT_CAP seconds leave room for (at least one,26 # many reps as $BENCH_EXPORT_CAP seconds leave room for (at least one,
24 # which is then marked CAPPED if it did not finish).27 # which is then marked CAPPED if it did not finish).
25 # * every metric runs as its own process: a decoder that panics costs one28 # * every metric runs as its own process: a decoder that panics costs one
@@ -41,7 +44,13 @@ LOG="$OUT_DIR/bench.log"
41 # Absolute, because $CARGO_TARGET_DIR may already be one and the plugin path44 # Absolute, because $CARGO_TARGET_DIR may already be one and the plugin path
42 # below must not become "$PWD/$HOME/...".45 # below must not become "$PWD/$HOME/...".
43 TARGET=$(realpath -m "${CARGO_TARGET_DIR:-target}")46 TARGET=$(realpath -m "${CARGO_TARGET_DIR:-target}")
44-cargo build --release -p engine -p engine-hw --example bench || exit 147+# 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
45 BENCH="$TARGET/release/examples/bench"54 BENCH="$TARGET/release/examples/bench"
46 # The plugin is looked for beside the running executable, and an example binary55 # The plugin is looked for beside the running executable, and an example binary
47 # lives one directory below the plugin: without this, hardware decode and56 # lives one directory below the plugin: without this, hardware decode and
@@ -98,6 +107,10 @@ for file in "${files[@]}"; do
98 run 1800 "seek_ttff_${t}s" "$file" seek "$t"107 run 1800 "seek_ttff_${t}s" "$file" seek "$t"
99 done108 done
100 run 3600 scrub "$file" scrub109 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}"
101 for seat in h264sw h264hw av1 hevc hevchw; do114 for seat in h264sw h264hw av1 hevc hevchw; do
102 run "$export_limit" "export_fps_$seat" "$file" export "$seat" "$OUT_DIR"115 run "$export_limit" "export_fps_$seat" "$file" export "$seat" "$OUT_DIR"
103 done116 done