🔀 merge: main's live underrun query beside the lane's own
Browse files at this commit9 changed files +647 -54
- Cargo.lock +151 -0
- crates/engine-audio/src/lib.rs +27 -8
- crates/engine/Cargo.toml +18 -3
- crates/engine/examples/bench.rs +258 -2
- crates/engine/src/ao.rs +20 -17
- crates/engine/src/playback.rs +144 -15
- crates/engine/tests/pgs_bitmaps.rs +9 -4
- crates/engine/tests/playback.rs +5 -3
- scripts/bench.sh +15 -2
Cargo.lockmodified+151 -0
| @@ -3372,6 +3372,16 @@ dependencies = [ | ||
| 3372 | 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 | 3385 | [[package]] |
| 3376 | 3386 | name = "maybe-rayon" |
| 3377 | 3387 | version = "0.1.1" |
| @@ -3538,6 +3548,22 @@ dependencies = [ | ||
| 3538 | 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 | 3567 | [[package]] |
| 3542 | 3568 | name = "new_debug_unreachable" |
| 3543 | 3569 | version = "1.0.6" |
| @@ -3608,6 +3634,34 @@ dependencies = [ | ||
| 3608 | 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 | 3665 | [[package]] |
| 3612 | 3666 | name = "noop_proc_macro" |
| 3613 | 3667 | version = "0.3.0" |
| @@ -3672,6 +3726,7 @@ checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" | ||
| 3672 | 3726 | dependencies = [ |
| 3673 | 3727 | "bytemuck", |
| 3674 | 3728 | "num-traits", |
| 3729 | + "serde", | |
| 3675 | 3730 | ] |
| 3676 | 3731 | |
| 3677 | 3732 | [[package]] |
| @@ -3951,6 +4006,12 @@ dependencies = [ | ||
| 3951 | 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 | 4015 | [[package]] |
| 3955 | 4016 | name = "oxideav-ac3" |
| 3956 | 4017 | version = "0.0.10" |
| @@ -4279,6 +4340,21 @@ version = "0.2.5" | ||
| 4279 | 4340 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 4280 | 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 | 4358 | [[package]] |
| 4283 | 4359 | name = "postage" |
| 4284 | 4360 | version = "0.5.0" |
| @@ -4324,6 +4400,15 @@ dependencies = [ | ||
| 4324 | 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 | 4412 | [[package]] |
| 4328 | 4413 | name = "proc-macro-crate" |
| 4329 | 4414 | version = "3.5.0" |
| @@ -4700,6 +4785,12 @@ dependencies = [ | ||
| 4700 | 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 | 4794 | [[package]] |
| 4704 | 4795 | name = "rayon" |
| 4705 | 4796 | version = "1.12.0" |
| @@ -4731,6 +4822,15 @@ dependencies = [ | ||
| 4731 | 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 | 4834 | [[package]] |
| 4735 | 4835 | name = "reborrow" |
| 4736 | 4836 | version = "0.5.5" |
| @@ -4869,6 +4969,9 @@ name = "ruopus" | ||
| 4869 | 4969 | version = "0.1.2" |
| 4870 | 4970 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 4871 | 4971 | checksum = "fcfcd963c83fc1ada2180ccdac7f1568d87fb0f2ad7236b266fdc9fb9122fbfd" |
| 4972 | +dependencies = [ | |
| 4973 | + "spectrograms", | |
| 4974 | +] | |
| 4872 | 4975 | |
| 4873 | 4976 | [[package]] |
| 4874 | 4977 | name = "rust-embed" |
| @@ -4927,6 +5030,20 @@ dependencies = [ | ||
| 4927 | 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 | 5047 | [[package]] |
| 4931 | 5048 | name = "rustix" |
| 4932 | 5049 | version = "0.38.44" |
| @@ -5506,6 +5623,24 @@ dependencies = [ | ||
| 5506 | 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 | 5644 | [[package]] |
| 5510 | 5645 | name = "spin" |
| 5511 | 5646 | version = "0.9.9" |
| @@ -5570,6 +5705,12 @@ version = "1.1.0" | ||
| 5570 | 5705 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 5571 | 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 | 5714 | [[package]] |
| 5574 | 5715 | name = "strict-num" |
| 5575 | 5716 | version = "0.1.1" |
| @@ -6401,6 +6542,16 @@ dependencies = [ | ||
| 6401 | 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 | 6555 | [[package]] |
| 6405 | 6556 | name = "try-lock" |
| 6406 | 6557 | version = "0.2.5" |
crates/engine-audio/src/lib.rsmodified+27 -8
| @@ -175,6 +175,11 @@ struct Shared { | ||
| 175 | 175 | /// the clock holds still through it (`Audio::content_at`). |
| 176 | 176 | primed: AtomicBool, |
| 177 | 177 | 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, | |
| 178 | 183 | } |
| 179 | 184 | |
| 180 | 185 | enum Ctl { |
| @@ -273,6 +278,13 @@ fn run( | ||
| 273 | 278 | // thread, which is what this branch can afford. |
| 274 | 279 | if shared.primed.load(Ordering::Relaxed) { |
| 275 | 280 | 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 | + ); | |
| 276 | 288 | } |
| 277 | 289 | } |
| 278 | 290 | // 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 { | ||
| 436 | 448 | // and the caller's first write have nothing to be late for. |
| 437 | 449 | primed: AtomicBool::new(false), |
| 438 | 450 | underruns: AtomicU64::new(0), |
| 451 | + last_underrun: AtomicI64::new(-1), | |
| 439 | 452 | }); |
| 440 | 453 | let (ready_tx, ready_rx) = mpsc::channel(); |
| 441 | 454 | let (ctl_tx, ctl_rx) = mpsc::channel(); |
| @@ -532,23 +545,29 @@ pub unsafe extern "C" fn ao_stream_ended(session: *mut c_void) -> i32 { | ||
| 532 | 545 | .unwrap_or(-1) |
| 533 | 546 | } |
| 534 | 547 | |
| 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. | |
| 541 | 556 | /// |
| 542 | 557 | /// # Safety |
| 543 | -/// `session` must come from [`ao_open`]. | |
| 558 | +/// `session` must come from [`ao_open`]; `last_at` is either null or writable. | |
| 544 | 559 | #[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 { | |
| 546 | 561 | catch_unwind(AssertUnwindSafe(|| { |
| 547 | 562 | if session.is_null() { |
| 548 | 563 | return -1; |
| 549 | 564 | } |
| 550 | 565 | // SAFETY: caller-guaranteed live session. |
| 551 | 566 | 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 | + } | |
| 552 | 571 | session.shared.underruns.load(Ordering::Relaxed) as i64 |
| 553 | 572 | })) |
| 554 | 573 | .unwrap_or(-1) |
crates/engine/Cargo.tomlmodified+18 -3
| @@ -81,8 +81,23 @@ rusty_mp3 = "0.6" | ||
| 81 | 81 | # packet. This one does the whole pipeline. Its quirks are measured and worked |
| 82 | 82 | # around in [`crate::export::write_ogg`] -- read that before touching this line. |
| 83 | 83 | 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. | |
| 86 | 101 | # Symphonia has no Opus at any version -- its feature list stops at vorbis and |
| 87 | 102 | # there is no `symphonia-codec-opus` crate -- while both of its containers *read* |
| 88 | 103 | # the format already: `A_OPUS` and `OpusHead` have always mapped to |
| @@ -99,7 +114,7 @@ rusty_vorbis = "0.1.1" | ||
| 99 | 114 | # where the film is silent. This one matches ffmpeg's own decode of the same file to a |
| 100 | 115 | # correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3` |
| 101 | 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 | 118 | # The Opus *encoder*, the other half of that pair: a pure-Rust port of libopus |
| 104 | 119 | # 1.6, BSD-3, `build.rs`-less and with **no dependencies at all** -- checked, not |
| 105 | 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 | 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 | 5 | //! `cargo run --release -p engine --example bench -- <metric> <file> [args]` |
| 5 | 6 | //! |
| @@ -9,7 +10,10 @@ | ||
| 9 | 10 | //! failure down as data. |
| 10 | 11 | //! |
| 11 | 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 | 18 | //! **Cold and warm.** Cold means the file's pages are dropped from the page |
| 15 | 19 | //! cache immediately before the measurement, with `posix_fadvise(DONTNEED)` on |
| @@ -49,6 +53,8 @@ fn main() { | ||
| 49 | 53 | match metric.as_str() { |
| 50 | 54 | "open" => open_bench(&path), |
| 51 | 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 | 58 | "scrub" => scrub_bench(&path), |
| 53 | 59 | "waveform" => waveform_bench(&path), |
| 54 | 60 | "export" => { |
| @@ -63,6 +69,8 @@ fn main() { | ||
| 63 | 69 | fn usage() -> ! { |
| 64 | 70 | eprintln!( |
| 65 | 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 | 74 | bench scrub <file>\n bench waveform <file>\n \ |
| 67 | 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 | 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 | 91 | // ---------------------------------------------------------------- reporting |
| 78 | 92 | |
| 79 | 93 | /// 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 | 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 | 170 | fn env_f64(key: &str, default: f64) -> f64 { |
| 129 | 171 | std::env::var(key) |
| 130 | 172 | .ok() |
| @@ -250,6 +292,220 @@ fn seek_bench(path: &Path, secs: f64) { | ||
| 250 | 292 | row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, ¬e); |
| 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, ¬e); | |
| 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 | 509 | // ---------------------------------------------------------------- waveform |
| 254 | 510 | |
| 255 | 511 | /// 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 { | ||
| 20 | 20 | set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32, |
| 21 | 21 | set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32, |
| 22 | 22 | 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. | |
| 30 | 27 | stream_ended: Option<unsafe extern "C" fn(*mut c_void) -> i32>, |
| 31 | 28 | close: unsafe extern "C" fn(*mut c_void), |
| 32 | 29 | // Never dropped (lives in a static), so the fn pointers above stay valid. |
| @@ -71,7 +68,11 @@ fn load() -> Option<Plugin> { | ||
| 71 | 68 | // with no sound at all, which at least says so. |
| 72 | 69 | set_volume: *lib.get(b"ao_set_volume\0").ok()?, |
| 73 | 70 | 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()?, | |
| 75 | 76 | stream_ended: lib.get(b"ao_stream_ended\0").ok().map(|f| *f), |
| 76 | 77 | close: *lib.get(b"ao_close\0").ok()?, |
| 77 | 78 | _lib: lib, |
| @@ -142,15 +143,6 @@ impl AoSession { | ||
| 142 | 143 | } |
| 143 | 144 | } |
| 144 | 145 | |
| 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 | - | |
| 154 | 146 | /// Pauses or resumes playback; while paused the position stays put. |
| 155 | 147 | pub fn set_active(&self, active: bool) -> bool { |
| 156 | 148 | // SAFETY: `handle` came from `ao_open` and is still open. |
| @@ -172,6 +164,17 @@ impl AoSession { | ||
| 172 | 164 | // SAFETY: `handle` came from `ao_open` and is still open. |
| 173 | 165 | unsafe { (self.plugin.flush)(self.handle) == 0 } |
| 174 | 166 | } |
| 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 | + } | |
| 175 | 178 | } |
| 176 | 179 | |
| 177 | 180 | impl Drop for AoSession { |
crates/engine/src/playback.rsmodified+144 -15
| @@ -296,6 +296,12 @@ pub struct PlaybackSession { | ||
| 296 | 296 | /// |
| 297 | 297 | /// [`retire`]: PlaybackSession::retire |
| 298 | 298 | 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, | |
| 299 | 305 | clock: PlaybackClock, |
| 300 | 306 | audio: Option<Audio>, |
| 301 | 307 | /// Why this timeline is silent, when the file itself is not: an audio track |
| @@ -316,6 +322,17 @@ pub struct PlaybackSession { | ||
| 316 | 322 | /// not -- with the single exception `sources` itself has, |
| 317 | 323 | /// [`Self::remove_source`], which takes the same entry out of both. |
| 318 | 324 | 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>>, | |
| 319 | 336 | /// What each source's own frame rate is against this timeline's, indexed |
| 320 | 337 | /// and grown exactly as [`Self::counts`] is (and shortened with it by |
| 321 | 338 | /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the |
| @@ -457,11 +474,13 @@ impl PlaybackSession { | ||
| 457 | 474 | worker: stream.worker, |
| 458 | 475 | backend: stream.backend, |
| 459 | 476 | retired: Vec::new(), |
| 477 | + restarts: 0, | |
| 460 | 478 | clock: PlaybackClock::new(source), |
| 461 | 479 | audio, |
| 462 | 480 | audio_disabled, |
| 463 | 481 | project, |
| 464 | 482 | counts: vec![meta.frame_count], |
| 483 | + probes: std::collections::HashMap::new(), | |
| 465 | 484 | // Source 0 *is* the timeline's rate: it defined it. |
| 466 | 485 | rates: vec![Rate::REAL_TIME], |
| 467 | 486 | span_rate: Rate::REAL_TIME, |
| @@ -561,6 +580,7 @@ impl PlaybackSession { | ||
| 561 | 580 | worker: stream.worker, |
| 562 | 581 | backend: stream.backend, |
| 563 | 582 | retired: Vec::new(), |
| 583 | + restarts: 0, | |
| 564 | 584 | // The song keeps the clock, as a video's own sound does -- and wall |
| 565 | 585 | // time keeps it on a machine with no device, where the picture |
| 566 | 586 | // (black) still has to move at some rate. |
| @@ -572,6 +592,7 @@ impl PlaybackSession { | ||
| 572 | 592 | audio_disabled, |
| 573 | 593 | project, |
| 574 | 594 | counts: vec![meta.frame_count], |
| 595 | + probes: std::collections::HashMap::new(), | |
| 575 | 596 | // Source 0 *is* the timeline's rate: it defined it. |
| 576 | 597 | rates: vec![Rate::REAL_TIME], |
| 577 | 598 | span_rate: Rate::REAL_TIME, |
| @@ -641,11 +662,13 @@ impl PlaybackSession { | ||
| 641 | 662 | worker: stream.worker, |
| 642 | 663 | backend: stream.backend, |
| 643 | 664 | retired: Vec::new(), |
| 665 | + restarts: 0, | |
| 644 | 666 | clock: PlaybackClock::new(ClockSource::Wall), |
| 645 | 667 | audio: None, |
| 646 | 668 | audio_disabled: None, |
| 647 | 669 | project, |
| 648 | 670 | counts: vec![meta.frame_count], |
| 671 | + probes: std::collections::HashMap::new(), | |
| 649 | 672 | // Source 0 *is* the timeline's rate: it defined it. |
| 650 | 673 | rates: vec![Rate::REAL_TIME], |
| 651 | 674 | span_rate: Rate::REAL_TIME, |
| @@ -930,6 +953,7 @@ impl PlaybackSession { | ||
| 930 | 953 | worker: stream.worker, |
| 931 | 954 | backend: stream.backend, |
| 932 | 955 | retired: Vec::new(), |
| 956 | + restarts: 0, | |
| 933 | 957 | clock: PlaybackClock::new(match audio { |
| 934 | 958 | Some(_) => ClockSource::Audio, |
| 935 | 959 | None => ClockSource::Wall, |
| @@ -938,6 +962,7 @@ impl PlaybackSession { | ||
| 938 | 962 | audio_disabled, |
| 939 | 963 | project, |
| 940 | 964 | counts, |
| 965 | + probes: std::collections::HashMap::new(), | |
| 941 | 966 | rates, |
| 942 | 967 | span_rate: Rate::REAL_TIME, |
| 943 | 968 | span, |
| @@ -1276,11 +1301,32 @@ impl PlaybackSession { | ||
| 1276 | 1301 | /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's |
| 1277 | 1302 | /// worker on this seek and the list stays a handful long. Nothing waits. |
| 1278 | 1303 | fn retire(&mut self, replacement: Worker) { |
| 1304 | + self.restarts += 1; | |
| 1279 | 1305 | self.retired |
| 1280 | 1306 | .push(std::mem::replace(&mut self.worker, replacement)); |
| 1281 | 1307 | self.retired.retain(|w| !w.is_finished()); |
| 1282 | 1308 | } |
| 1283 | 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 | + | |
| 1284 | 1330 | /// How many threads this session still has running of its own: the decode |
| 1285 | 1331 | /// worker, every retired one that has not returned yet, and the audio |
| 1286 | 1332 | /// feeders still in the air. One for a session playing along quietly. |
| @@ -2083,7 +2129,7 @@ impl PlaybackSession { | ||
| 2083 | 2129 | let image = crate::is_image(path); |
| 2084 | 2130 | if !image { |
| 2085 | 2131 | let first = self.first_audio()?; |
| 2086 | - audio_matches(&wanted, &first)?; | |
| 2132 | + self.audio_matches_cached(&wanted, &first)?; | |
| 2087 | 2133 | } |
| 2088 | 2134 | let rate = self.file_rate(&wanted.path); |
| 2089 | 2135 | let source = self.project.import(path, stream); |
| @@ -2195,8 +2241,44 @@ impl PlaybackSession { | ||
| 2195 | 2241 | /// What the timeline's audio *is*: the chosen stream of the first source |
| 2196 | 2242 | /// that could have any ([`audio_source_of`]), probed. Every other source is |
| 2197 | 2243 | /// 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) | |
| 2200 | 2282 | } |
| 2201 | 2283 | |
| 2202 | 2284 | /// Places `clip` on `lane` alone at the playhead, overwriting what it lands |
| @@ -2348,7 +2430,7 @@ impl PlaybackSession { | ||
| 2348 | 2430 | // Stream 0, and there is no other: a standalone audio file carries one |
| 2349 | 2431 | // track (`AudioSession::probe_streams`), so nothing here has a stream |
| 2350 | 2432 | // 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)?; | |
| 2352 | 2434 | let frames = audio_frames(path, self.meta.frame_rate)?; |
| 2353 | 2435 | let source = self.project.import(path, 0); |
| 2354 | 2436 | self.note_frames(source, frames, Rate::REAL_TIME); |
| @@ -2502,16 +2584,6 @@ impl PlaybackSession { | ||
| 2502 | 2584 | Some((tap, audio.sample_rate)) |
| 2503 | 2585 | } |
| 2504 | 2586 | |
| 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 | - | |
| 2515 | 2587 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode |
| 2516 | 2588 | /// workers are replaced rather than steered: a fresh channel cannot hold a |
| 2517 | 2589 | /// 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> { | ||
| 2967 | 3039 | } |
| 2968 | 3040 | |
| 2969 | 3041 | 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<()> { | |
| 2970 | 3053 | // The layout, which the audio worker holds every source to anyway -- and not |
| 2971 | 3054 | // the rate any more: a file written at another one is resampled to the |
| 2972 | 3055 | // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as |
| 2973 | 3056 | // a file shot at another frame rate is read through [`Rate`]. Both silent is |
| 2974 | 3057 | // a match. |
| 2975 | - let probe = AudioSession::probe(&source.path, source.audio_stream)?; | |
| 2976 | 3058 | if probe.map(|p| p.channels) == first.map(|p| p.channels) { |
| 2977 | 3059 | return Ok(()); |
| 2978 | 3060 | } |
| @@ -3275,6 +3357,53 @@ mod tests { | ||
| 3275 | 3357 | assert_eq!(session.sources().len(), session.counts.len()); |
| 3276 | 3358 | } |
| 3277 | 3359 | |
| 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 | + | |
| 3278 | 3407 | #[test] |
| 3279 | 3408 | fn boundary_seconds_round_trip_to_their_own_frame() { |
| 3280 | 3409 | 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 | 62 | let drawn = Instant::now(); |
| 63 | 63 | let image = cues[0].image.as_ref().expect("a picture cue"); |
| 64 | 64 | let rgba = image.rgba().expect("the first display set decodes"); |
| 65 | + let took = drawn.elapsed(); | |
| 65 | 66 | 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, | |
| 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 | 76 | assert_eq!(rgba.len(), (image.width * image.height * 4) as usize); |
| 72 | 77 | let opaque = rgba.chunks_exact(4).filter(|px| px[3] > 0).count(); |
| 73 | 78 | 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() { | ||
| 481 | 481 | run_for(&mut session, &mut last_index, Duration::from_millis(300)); |
| 482 | 482 | // Only a machine with the plugin *and* a daemon can starve at all; without |
| 483 | 483 | // 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 { | |
| 485 | 485 | eprintln!("no audio device: seek storm not measured"); |
| 486 | 486 | return; |
| 487 | 487 | }; |
| @@ -517,9 +517,11 @@ fn a_cold_seek_storm_starves_no_quantum() { | ||
| 517 | 517 | // ...and then plays for a moment, which is where a late decoder shows. |
| 518 | 518 | run_for(&mut session, &mut landed, Duration::from_millis(300)); |
| 519 | 519 | } |
| 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; | |
| 521 | 522 | 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:?})", | |
| 523 | 525 | path.display(), |
| 524 | 526 | storm.elapsed() |
| 525 | 527 | ); |
scripts/bench.shmodified+15 -2
| @@ -19,7 +19,10 @@ | ||
| 19 | 19 | # before the measurement -- no root, nothing else on the machine evicted, |
| 20 | 20 | # and advisory, so it is the optimistic end of cold. |
| 21 | 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 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 | |
| 23 | 26 | # many reps as $BENCH_EXPORT_CAP seconds leave room for (at least one, |
| 24 | 27 | # which is then marked CAPPED if it did not finish). |
| 25 | 28 | # * every metric runs as its own process: a decoder that panics costs one |
| @@ -41,7 +44,13 @@ LOG="$OUT_DIR/bench.log" | ||
| 41 | 44 | # Absolute, because $CARGO_TARGET_DIR may already be one and the plugin path |
| 42 | 45 | # below must not become "$PWD/$HOME/...". |
| 43 | 46 | 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 | |
| 45 | 54 | BENCH="$TARGET/release/examples/bench" |
| 46 | 55 | # The plugin is looked for beside the running executable, and an example binary |
| 47 | 56 | # lives one directory below the plugin: without this, hardware decode and |
| @@ -98,6 +107,10 @@ for file in "${files[@]}"; do | ||
| 98 | 107 | run 1800 "seek_ttff_${t}s" "$file" seek "$t" |
| 99 | 108 | done |
| 100 | 109 | 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 | 114 | for seat in h264sw h264hw av1 hevc hevchw; do |
| 102 | 115 | run "$export_limit" "export_fps_$seat" "$file" export "$seat" "$OUT_DIR" |
| 103 | 116 | done |