diff --git a/Cargo.lock b/Cargo.lock index 7185421..990056d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3372,6 +3372,16 @@ dependencies = [ "libc", ] +[[package]] +name = "matrixmultiply" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" +dependencies = [ + "autocfg", + "rawpointer", +] + [[package]] name = "maybe-rayon" version = "0.1.1" @@ -3538,6 +3548,22 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "ndarray" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d" +dependencies = [ + "matrixmultiply", + "num-complex", + "num-integer", + "num-traits", + "portable-atomic", + "portable-atomic-util", + "rawpointer", + "serde", +] + [[package]] name = "new_debug_unreachable" version = "1.0.6" @@ -3608,6 +3634,34 @@ dependencies = [ "memchr", ] +[[package]] +name = "non-empty-iter" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac123b8e4bd1fef3e8e972ba7a07f046ac6b608633ad761c61876b7197313f63" +dependencies = [ + "non-zero-size", +] + +[[package]] +name = "non-empty-slice" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9935c822e11be79ef40f986558b00da0ff176b7c87ddf6d9fb8b9138a6112c20" +dependencies = [ + "non-empty-iter", + "non-zero-size", + "ownership", + "serde", + "thiserror 2.0.20", +] + +[[package]] +name = "non-zero-size" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "401b3a4027292c1c318fd2305783f791d5579d18e7143ef72d653bf0c29e6b36" + [[package]] name = "noop_proc_macro" version = "0.3.0" @@ -3672,6 +3726,7 @@ checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" dependencies = [ "bytemuck", "num-traits", + "serde", ] [[package]] @@ -3951,6 +4006,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "ownership" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfb1aeb68b9f2683ee3f83960c10668b37a8a640224ba1169697ee8fd1e906c1" + [[package]] name = "oxideav-ac3" version = "0.0.10" @@ -4279,6 +4340,21 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", +] + [[package]] name = "postage" version = "0.5.0" @@ -4324,6 +4400,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -4700,6 +4785,12 @@ dependencies = [ "raw-window-handle", ] +[[package]] +name = "rawpointer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + [[package]] name = "rayon" version = "1.12.0" @@ -4731,6 +4822,15 @@ dependencies = [ "once_cell", ] +[[package]] +name = "realfft" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f821338fddb99d089116342c46e9f1fbf3828dba077674613e734e01d6ea8677" +dependencies = [ + "rustfft", +] + [[package]] name = "reborrow" version = "0.5.5" @@ -4869,6 +4969,9 @@ name = "ruopus" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fcfcd963c83fc1ada2180ccdac7f1568d87fb0f2ad7236b266fdc9fb9122fbfd" +dependencies = [ + "spectrograms", +] [[package]] name = "rust-embed" @@ -4927,6 +5030,20 @@ dependencies = [ "semver", ] +[[package]] +name = "rustfft" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", +] + [[package]] name = "rustix" version = "0.38.44" @@ -5506,6 +5623,24 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spectrograms" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ff1e83612f5a16e413dbfaf0381753b5eee714932fc95db19fe0974d5e6462b" +dependencies = [ + "ndarray", + "non-empty-slice", + "num-complex", + "num-traits", + "once_cell", + "pkg-config", + "realfft", + "regex", + "rustfft", + "thiserror 2.0.20", +] + [[package]] name = "spin" version = "0.9.9" @@ -5570,6 +5705,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + [[package]] name = "strict-num" version = "0.1.1" @@ -6401,6 +6542,16 @@ dependencies = [ "once_cell", ] +[[package]] +name = "transpose" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + [[package]] name = "try-lock" version = "0.2.5" diff --git a/crates/engine-audio/src/lib.rs b/crates/engine-audio/src/lib.rs index 5648b08..fd2e066 100644 --- a/crates/engine-audio/src/lib.rs +++ b/crates/engine-audio/src/lib.rs @@ -175,6 +175,11 @@ struct Shared { /// the clock holds still through it (`Audio::content_at`). primed: AtomicBool, underruns: AtomicU64, + /// Device position (samples per channel) read at the most recent underrun, + /// `-1` until one happens: what says whether the count in hand is old news + /// or is still growing. Written on the RT thread, and only on the starved + /// path, so the ordinary callback pays nothing for it. + last_underrun: AtomicI64, } enum Ctl { @@ -273,6 +278,13 @@ fn run( // thread, which is what this branch can afford. if shared.primed.load(Ordering::Relaxed) { shared.underruns.fetch_add(1, Ordering::Relaxed); + // The position this callback is about to compute + // is not known yet; the previous one is a quantum + // (~23 ms) behind and needs no clock call here. + shared.last_underrun.store( + shared.position.load(Ordering::Relaxed), + Ordering::Relaxed, + ); } } // 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 { // and the caller's first write have nothing to be late for. primed: AtomicBool::new(false), underruns: AtomicU64::new(0), + last_underrun: AtomicI64::new(-1), }); let (ready_tx, ready_rx) = mpsc::channel(); let (ctl_tx, ctl_rx) = mpsc::channel(); @@ -532,23 +545,29 @@ pub unsafe extern "C" fn ao_stream_ended(session: *mut c_void) -> i32 { .unwrap_or(-1) } -/// Quanta the device had to fill with silence because the ring was empty -- -/// "the decoder was late", counted since the stream opened and never reset. -/// The same number [`Session::drop`] prints, readable while the stream runs so -/// a benchmark can attribute it to the seek it followed rather than to a whole -/// session. -1 on a null session; an inactive stream has no callbacks and so -/// cannot underrun at all. +/// Starved callbacks since the stream opened -- one per quantum the decoder was +/// late for -- and, through `last_at`, the device position the newest of them +/// was seen at (`-1` if there has been none). The same number the drop print +/// reports, asked for while the session is still running: a caller measuring a +/// seek reads it before and after and the difference is that seek's cost. +/// +/// Two relaxed atomic loads, nothing else: the RT thread writes both and must +/// never wait on a reader. /// /// # Safety -/// `session` must come from [`ao_open`]. +/// `session` must come from [`ao_open`]; `last_at` is either null or writable. #[unsafe(no_mangle)] -pub unsafe extern "C" fn ao_underruns(session: *mut c_void) -> i64 { +pub unsafe extern "C" fn ao_underruns(session: *mut c_void, last_at: *mut i64) -> i64 { catch_unwind(AssertUnwindSafe(|| { if session.is_null() { return -1; } // SAFETY: caller-guaranteed live session. let session = unsafe { &*(session as *const Session) }; + if !last_at.is_null() { + // SAFETY: caller-guaranteed writable, and it is a plain i64. + unsafe { *last_at = session.shared.last_underrun.load(Ordering::Relaxed) }; + } session.shared.underruns.load(Ordering::Relaxed) as i64 })) .unwrap_or(-1) diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 4419a58..23b6059 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -81,8 +81,23 @@ rusty_mp3 = "0.6" # packet. This one does the whole pipeline. Its quirks are measured and worked # around in [`crate::export::write_ogg`] -- read that before touching this line. rusty_vorbis = "0.1.1" -# The Opus decoder: pure Rust, MIT, no C and no FFI, and no dependencies at all -# without its default features (`spectrograms` is for its own analysis tools). +# The Opus decoder: pure Rust, MIT, no C and no FFI. +# +# `spectrograms` is not, as this line long claimed, "for its own analysis tools": +# it is the crate's *FFT backend*, and it is default-on because CELT synthesis is +# an N/4 complex FFT per block. Turned off -- which is what asking for `std` +# alone did -- `celt/mdct.rs` falls back to an O(n²) DFT evaluated in f64, and a +# 5.1 film soundtrack decodes at **0.95x realtime**: slower than playing it. +# With the backend on, the same file decodes at **104x** (7.1: 0.93x -> 112x, +# stereo: 10.4x -> 135x). The cost is fifteen pure-Rust crates (`spectrograms` -> +# `realfft`/`rustfft`, `ndarray`, `regex`), still no C and no `build.rs`. +# The output is *not* bit-identical to the DFT build -- FFT summation order +# differs -- but the two agree to 144 dB SNR (max |Δ| 3.7e-8, half an LSB at +# 24-bit) while *both* sit 93 dB from ffmpeg's own libopus decode of the same +# file. The change is 40 dB below the decoder's existing distance to the +# reference, i.e. inside float noise, and upstream says as much: Opus conformance +# is a quality threshold (`opus_compare`), not bit-exactness, and every +# bitstream-affecting computation stays exact either way. # Symphonia has no Opus at any version -- its feature list stops at vorbis and # there is no `symphonia-codec-opus` crate -- while both of its containers *read* # the format already: `A_OPUS` and `OpusHead` have always mapped to @@ -99,7 +114,7 @@ rusty_vorbis = "0.1.1" # where the film is silent. This one matches ffmpeg's own decode of the same file to a # correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3` # below, because a decoder is a bit-exactness dependency. -ruopus = { version = "=0.1.2", default-features = false, features = ["std"] } +ruopus = { version = "=0.1.2", default-features = false, features = ["std", "spectrograms"] } # The Opus *encoder*, the other half of that pair: a pure-Rust port of libopus # 1.6, BSD-3, `build.rs`-less and with **no dependencies at all** -- checked, not # taken from the README (`cargo tree` is two lines; there is not one `.c`, `.h` diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs index ae88085..7672226 100644 --- a/crates/engine/examples/bench.rs +++ b/crates/engine/examples/bench.rs @@ -1,5 +1,6 @@ //! The baseline every later decode/encode change is measured against: open, -//! seek, scrub and export, timed on the real library rather than on a fixture. +//! seek, seek storm, play loop, scrub and export, timed on the real library +//! rather than on a fixture. //! //! `cargo run --release -p engine --example bench -- [args]` //! @@ -9,7 +10,10 @@ //! failure down as data. //! //! Every row is one TSV line -- `file, metric, unit, n, median, min, max, note` -//! -- so the whole baseline is `cat`ted together and diffed later. +//! -- so the whole baseline is `cat`ted together and diffed later. The note is +//! where the tail percentile and the **decode backend** live: a row that does +//! not say `backend hw` was measured in software, and a baseline that does not +//! say which is not a baseline (see `scripts/bench.sh` on `LD_LIBRARY_PATH`). //! //! **Cold and warm.** Cold means the file's pages are dropped from the page //! cache immediately before the measurement, with `posix_fadvise(DONTNEED)` on @@ -49,6 +53,8 @@ fn main() { match metric.as_str() { "open" => open_bench(&path), "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")), + "seekstorm" => seekstorm_bench(&path, arg_seed(args.next())), + "playloop" => playloop_bench(&path, arg_f64(args.next(), "seconds"), arg_seed(args.next())), "scrub" => scrub_bench(&path), "waveform" => waveform_bench(&path), "export" => { @@ -63,6 +69,8 @@ fn main() { fn usage() -> ! { eprintln!( "usage: bench open \n bench seek \n \ + bench seekstorm [seed]\n \ + bench playloop [seed]\n \ bench scrub \n bench waveform \n \ bench export " ); @@ -74,6 +82,12 @@ fn arg_f64(arg: Option, what: &str) -> f64 { .unwrap_or_else(|| panic!("missing {what}")) } +/// The seed the random metrics draw their positions from: same seed, same +/// seeks, so a before and an after are the same measurement. +fn arg_seed(arg: Option) -> u64 { + arg.and_then(|s| s.parse().ok()).unwrap_or(1) +} + // ---------------------------------------------------------------- reporting /// One TSV row: the median is what a comparison uses, the min and max are what @@ -125,6 +139,34 @@ fn ttff_timeout() -> Duration { Duration::from_secs_f64(env_f64("BENCH_TTFF_TIMEOUT", 180.0)) } +/// The p'th percentile of `samples`, nearest rank on the sorted copy. The +/// median is [`row`]'s business; this is for the tail, which is the number a +/// dropped frame and a starved ring both live in. +fn pct(samples: &[f64], p: f64) -> f64 { + if samples.is_empty() { + return 0.0; + } + let mut sorted = samples.to_vec(); + sorted.sort_by(f64::total_cmp); + sorted[((sorted.len() - 1) as f64 * p).round() as usize] +} + +/// A seeded LCG, so "random" seeks are the same random seeks tomorrow. Sixteen +/// lines of a crate would do the same thing and none of the quality a real +/// generator has matters to a list of positions in a film. +struct Lcg(u64); + +impl Lcg { + /// The next position, in `0.0..1.0`. + fn next(&mut self) -> f64 { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } +} + fn env_f64(key: &str, default: f64) -> f64 { std::env::var(key) .ok() @@ -250,6 +292,220 @@ fn seek_bench(path: &Path, secs: f64) { row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, ¬e); } +// -------------------------------------------------------------- seek storm + +/// Seeks a film opens with none of: fifty positions nobody chose, drawn from a +/// seed so the same fifty come back tomorrow. `seek` measures one point five +/// times over; this measures the spread across the whole file, which is where +/// an index lookup, a keyframe distance and a decoder reopen all vary. +/// +/// Cold is the first pass over a freshly evicted file, warm the same fifty +/// again straight after -- the same two questions the other metrics ask, and +/// the audio underruns each pass cost are counted with it +/// ([`engine::PlaybackSession::audio_underruns`]), because a seek that lands +/// fast and starves the ring is not a seek that worked. +const STORM_SEEKS: usize = 50; + +fn seekstorm_bench(path: &Path, seed: u64) { + evict(path); + let mut session = match engine::PlaybackSession::open(path) { + Ok(session) => session, + Err(e) => { + row(path, "seekstorm_ttff_cold", "ms", &[], &format!("FAIL({e})")); + return; + } + }; + // Playing throughout, because the underruns are the point: a paused device + // runs no callbacks and can never starve, so a storm measured paused would + // report zero however badly the seeks fed it. This is the complaint's own + // shape -- a film that is playing, jumped around in. + session.play(); + let duration = session.timeline_duration(); + let mut rng = Lcg(seed); + // Short of the very end: a landing with no picture after it is a different + // measurement (end of stream), and every seek here is meant to be one. + let targets: Vec = (0..STORM_SEEKS) + .map(|_| rng.next() * duration * 0.95) + .collect(); + + for pass in ["cold", "warm"] { + let before = session.audio_underruns().map_or(0, |(n, _)| n); + let mut samples = Vec::new(); + let mut missed = Vec::new(); + let mut peak = threads(); + for &secs in &targets { + match seek_ttff(&mut session, secs, &mut peak) { + Ok(ms) => samples.push(ms), + Err(why) => missed.push(why), + } + } + let audio = session.audio_underruns(); + let backend = session.decode_backend().label(); + let mut note = format!( + "backend {backend}, p95 {:.2}ms, peak {peak} threads, seed {seed}", + pct(&samples, 0.95) + ); + if !missed.is_empty() { + note += &format!(", {}/{STORM_SEEKS} NO-FRAME({})", missed.len(), missed[0]); + } + row(path, &format!("seekstorm_ttff_{pass}"), "ms", &samples, ¬e); + row( + path, + &format!("seekstorm_underruns_{pass}"), + "count", + &[audio.map_or(0, |(n, _)| n).saturating_sub(before) as f64], + &match audio { + None => "no audio device".into(), + Some((total, last)) => format!( + "backend {backend}, {total} since open, {}", + last.map_or_else(|| "none yet".into(), |t| format!("last at {t:.1}s device")) + ), + }, + ); + } +} + +// --------------------------------------------------------------- play loop + +/// How long a picture waits between frames while the sound runs: the app's own +/// pump (`crates/app/src/player/transport.rs`), driven here for `secs` with a +/// seek to a random point every five seconds -- the shape of the complaint, +/// which is a film played and jumped around in rather than a seek measured on +/// its own. +/// +/// Three numbers come out: the gap between frames (p50 and p99, the tail being +/// the jump a person sees), the audio underruns over the whole run, and how +/// many times the picture worker was restarted -- by a seek, by a clip +/// boundary, or by the late-picture resync, which is counted separately in the +/// note. +/// +/// The resync rule is the app's, repeated here (`LATE_RESYNC`, `RESYNC_GAP` in +/// `crates/app/src/transport.rs`) because an engine example cannot depend on +/// the binary. Repeated only: nothing in this file changes how playback runs. +const PLAYLOOP_SEEK_GAP: Duration = Duration::from_secs(5); +const LATE_RESYNC: f64 = 0.4; +const RESYNC_GAP: Duration = Duration::from_secs(2); + +fn playloop_bench(path: &Path, secs: f64, seed: u64) { + evict(path); + let mut session = match engine::PlaybackSession::open(path) { + Ok(session) => session, + Err(e) => { + row(path, "playloop_frame_gap", "ms", &[], &format!("FAIL({e})")); + return; + } + }; + let fps = session.meta().frame_rate; + let duration = session.timeline_duration(); + let mut rng = Lcg(seed); + + let mut gaps = Vec::new(); + let mut held: Option = None; + let (mut shown, mut dropped, mut seeks, mut resyncs) = (0u64, 0u64, 0u64, 0u64); + let mut last_resync: Option = None; + // The first frame of the run is owed exactly as a seek's landing is. + let mut owed = true; + + session.play(); + let start = Instant::now(); + let deadline = start + Duration::from_secs_f64(secs); + let mut last_frame = start; + let mut next_seek = start + PLAYLOOP_SEEK_GAP; + while Instant::now() < deadline { + session.tick(); + let target = session.now() * fps; + let mut newest = None; + while session.is_playing() || owed { + let frame = match held.take() { + Some(frame) => frame, + None => match session.try_frame() { + // Timed here and only here: a frame taken back out of + // `held` cost no decode, and counting it would report a + // zero gap for a frame nobody waited for. + Some(frame) => { + let now = Instant::now(); + gaps.push((now - last_frame).as_secs_f64() * 1000.0); + last_frame = now; + frame + } + None => break, + }, + }; + if f64::from(frame.index) <= target { + dropped += u64::from(newest.is_some()); + newest = Some(frame); + } else { + held = Some(frame); + break; + } + } + let late = newest + .as_ref() + .map_or(0.0, |f| (target - f64::from(f.index)) / fps); + if newest.is_some() { + shown += 1; + owed = false; + } + if !owed + && session.is_playing() + && late > LATE_RESYNC + && last_resync.is_none_or(|t| t.elapsed() >= RESYNC_GAP) + { + session.resync_picture(); + held = None; + last_resync = Some(Instant::now()); + resyncs += 1; + } + // End of stream inside a five-second stretch is the same jump early: + // the loop is here to keep playing, not to stop at whatever it landed + // near. + if Instant::now() >= next_seek || session.is_eos() { + session.seek(rng.next() * duration * 0.95); + held = None; + owed = true; + seeks += 1; + next_seek = Instant::now() + PLAYLOOP_SEEK_GAP; + } + std::thread::sleep(Duration::from_millis(1)); + } + session.pause(); + + let elapsed = start.elapsed().as_secs_f64(); + let backend = session.decode_backend().label(); + let audio = session.audio_underruns(); + row( + path, + "playloop_frame_gap", + "ms", + &gaps, + &format!( + "backend {backend}, p99 {:.2}ms, {shown} shown, {dropped} dropped, \ + {seeks} seeks in {elapsed:.0}s, seed {seed}", + pct(&gaps, 0.99) + ), + ); + row( + path, + "playloop_underruns", + "count", + &[audio.map_or(0, |(n, _)| n) as f64], + &match audio { + None => "no audio device".into(), + Some((_, last)) => format!( + "backend {backend}, {}", + last.map_or_else(|| "none".into(), |t| format!("last at {t:.1}s device")) + ), + }, + ); + row( + path, + "playloop_restarts", + "count", + &[session.restarts() as f64], + &format!("backend {backend}, {resyncs} late-picture resyncs, {seeks} seeks"), + ); +} + // ---------------------------------------------------------------- waveform /// What a lane waits for before it has an envelope: one whole diff --git a/crates/engine/src/ao.rs b/crates/engine/src/ao.rs index 1863d9c..31e7645 100644 --- a/crates/engine/src/ao.rs +++ b/crates/engine/src/ao.rs @@ -20,13 +20,10 @@ struct Plugin { set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32, set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32, flush: unsafe extern "C" fn(*mut c_void) -> i32, - /// Optional, unlike its neighbours: this one is a *counter*, and a plugin - /// too old to have it is a session that plays perfectly and cannot say how - /// many quanta it starved for. Rejecting the whole plugin over that would - /// trade the sound for the diagnostic. - underruns: Option i64>, - /// Optional for [`Plugin::underruns`]'s reason: without it a plugin plays - /// exactly as it did, it only counts the tail of a stream as lateness. + underruns: unsafe extern "C" fn(*mut c_void, *mut i64) -> i64, + /// Optional, unlike its neighbours: without it a plugin plays exactly as it + /// did and only counts the tail of a played-out stream as lateness, which + /// is a worse diagnostic rather than a worse session. stream_ended: Option i32>, close: unsafe extern "C" fn(*mut c_void), // Never dropped (lives in a static), so the fn pointers above stay valid. @@ -71,7 +68,11 @@ fn load() -> Option { // with no sound at all, which at least says so. set_volume: *lib.get(b"ao_set_volume\0").ok()?, flush: *lib.get(b"ao_flush\0").ok()?, - underruns: lib.get(b"ao_underruns\0").ok().map(|f| *f), + // Required on the same terms as the two above: the plugin + // ships from this build, and a measurement that silently + // reads zero underruns is worse than a run that says the + // plugin is the wrong one. + underruns: *lib.get(b"ao_underruns\0").ok()?, stream_ended: lib.get(b"ao_stream_ended\0").ok().map(|f| *f), close: *lib.get(b"ao_close\0").ok()?, _lib: lib, @@ -142,15 +143,6 @@ impl AoSession { } } - /// Quanta the device filled with silence for want of samples, since the - /// stream opened: what a benchmark reads to say the decoder kept up. - /// `None` from a plugin that does not carry the counter. - pub fn underruns(&self) -> Option { - // SAFETY: `handle` came from `ao_open` and is still open. - let n = unsafe { (self.plugin.underruns?)(self.handle) }; - (n >= 0).then_some(n as u64) - } - /// Pauses or resumes playback; while paused the position stays put. pub fn set_active(&self, active: bool) -> bool { // SAFETY: `handle` came from `ao_open` and is still open. @@ -172,6 +164,17 @@ impl AoSession { // SAFETY: `handle` came from `ao_open` and is still open. unsafe { (self.plugin.flush)(self.handle) == 0 } } + + /// Starved callbacks so far, and the device position (samples per channel) + /// the last of them was seen at -- `None` for a stream that has never run + /// dry. Two atomic loads inside the plugin, so it is cheap enough to poll + /// and it never touches the RT thread's path. + pub fn underruns(&self) -> (u64, Option) { + let mut last = -1i64; + // SAFETY: `handle` came from `ao_open`, and `last` is a live i64 of ours. + let count = unsafe { (self.plugin.underruns)(self.handle, &raw mut last) }; + (count.max(0) as u64, (last >= 0).then_some(last)) + } } impl Drop for AoSession { diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index f746b42..f03a1cf 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -296,6 +296,12 @@ pub struct PlaybackSession { /// /// [`retire`]: PlaybackSession::retire retired: Vec, + /// Picture workers that replaced another one, i.e. every restart the + /// session's first worker did not cost: a seek, a resync, a clip boundary. + /// Each carries a demuxer reopen and a VA-API init, so this is what a + /// playback measurement counts to say how often the picture was thrown away + /// ([`restarts`](Self::restarts)). + restarts: u64, clock: PlaybackClock, audio: Option