diff --git a/crates/engine-audio/src/lib.rs b/crates/engine-audio/src/lib.rs index 7cf435f..9a1c6e8 100644 --- a/crates/engine-audio/src/lib.rs +++ b/crates/engine-audio/src/lib.rs @@ -156,6 +156,18 @@ struct Shared { /// Output gain as f32 bits, 1.0 until the caller says otherwise. Read once /// per callback on the RT thread, so it is an atomic rather than a lock. gain: AtomicU32, + /// Whether the ring has been given a sample to play since it was last + /// emptied *on purpose*: `false` from the open and from every `ao_flush` + /// until the next accepted write. + /// + /// A callback that finds nothing to play while this is false is the silence + /// of a stream that has not started yet -- the head of a seek, whose decoder + /// is still being opened -- and not a decoder that fell behind. Counting it + /// made the number below say "a seek happened" (1721 of them over a scripted + /// cold play-seek-scrub, against 5 warm) instead of the one thing it is for. + /// The wait itself is not hidden by this: it is the clock's business, and + /// the clock holds still through it (`Audio::content_at`). + primed: AtomicBool, underruns: AtomicU64, } @@ -250,7 +262,12 @@ fn run( // the clock below keeps running -- the device plays // that silence, so it really is elapsed time. slice[got * 4..want * 4].fill(0); - shared.underruns.fetch_add(1, Ordering::Relaxed); + // ...but only a *started* stream can be late; see + // `Shared::primed`. One relaxed load on the RT + // thread, which is what this branch can afford. + if shared.primed.load(Ordering::Relaxed) { + shared.underruns.fetch_add(1, Ordering::Relaxed); + } } // After the fill, so the silence stays silent whatever // the gain is, and the underrun count keeps meaning @@ -409,6 +426,9 @@ pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void { flush: AtomicBool::new(false), resumed: AtomicBool::new(false), gain: AtomicU32::new(1.0f32.to_bits()), + // Nothing has been queued yet, so the callbacks between the connect + // and the caller's first write have nothing to be late for. + primed: AtomicBool::new(false), underruns: AtomicU64::new(0), }); let (ready_tx, ready_rx) = mpsc::channel(); @@ -457,7 +477,13 @@ pub unsafe extern "C" fn ao_write(session: *mut c_void, samples: *const f32, n: return -1; } let samples = unsafe { std::slice::from_raw_parts(samples, n) }; - accept(&session.shared.flush, &session.shared.ring, samples) as isize + let accepted = accept(&session.shared.flush, &session.shared.ring, samples); + if accepted > 0 { + // There is something to play from here on, so a starved callback + // means what it says again (`Shared::primed`). + session.shared.primed.store(true, Ordering::Release); + } + accepted as isize })) .unwrap_or(-1) } @@ -479,6 +505,28 @@ pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 { .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. +/// +/// # Safety +/// `session` must come from [`ao_open`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn ao_underruns(session: *mut c_void) -> i64 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session. + let session = unsafe { &*(session as *const Session) }; + session.shared.underruns.load(Ordering::Relaxed) as i64 + })) + .unwrap_or(-1) +} + /// Pauses (0) or resumes (non-zero) playback. Paused freezes the position. /// 0 on success, negative on failure. /// @@ -545,6 +593,10 @@ pub unsafe extern "C" fn ao_flush(session: *mut c_void) -> i32 { } // SAFETY: caller-guaranteed live session. let session = unsafe { &*(session as *const Session) }; + // Unprimed first, so the callback that consumes the flag below cannot + // find an empty ring and count the head of the restart as a late + // decoder (`Shared::primed`). + session.shared.primed.store(false, Ordering::Release); session.shared.flush.store(true, Ordering::Release); 0 })) diff --git a/crates/engine/src/ao.rs b/crates/engine/src/ao.rs index 00bded0..0ceae73 100644 --- a/crates/engine/src/ao.rs +++ b/crates/engine/src/ao.rs @@ -20,6 +20,11 @@ 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>, close: unsafe extern "C" fn(*mut c_void), // Never dropped (lives in a static), so the fn pointers above stay valid. _lib: Library, @@ -63,6 +68,7 @@ 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), close: *lib.get(b"ao_close\0").ok()?, _lib: lib, }) @@ -122,6 +128,15 @@ 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. diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index adc56de..617a394 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -111,6 +111,22 @@ struct Audio { /// seek counts it as such, which is a permanent offset between the picture /// and the sound, re-rolled by every edit made while playing. content_at: Arc, + /// The timeline is *meant* to be playing: what a play or a seek-while-playing + /// asks for, and what the feeder turns into a running device the moment it + /// has a real sample to play ([`Audio::set_playing`], [`feed`]). + /// + /// The device is not started by the intent, because an inactive stream has + /// no callbacks and therefore no starved quanta: between the flush of a seek + /// and the first sample of the new stream -- seconds, on a cold 25 GB film + /// whose decoder is opened on the feeder -- a device started here would play + /// its own silence and count every quantum of it as an underrun. + /// + /// Written and read under the device lock, beside the [`Audio::content_at`] + /// stamp, and that is the whole race: whichever of the two sides takes the + /// lock first, the other sees its half (a stamp already there, or an intent + /// already set), so the device is started exactly once and a pause landing + /// during an open can never be overtaken by a late activation. + wants_active: Arc, /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest /// first: what a meter or an analyser draws. Written by the feeder, which /// is not the device's own callback -- the plugin's RT thread never sees @@ -136,6 +152,22 @@ impl Audio { && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed) } + /// Says whether the timeline is playing, and starts or stops the device for + /// it: `true` runs it *if there is already something to play*, and otherwise + /// leaves it to the feeder's first sample ([`Audio::wants_active`]). `false` + /// stops it at once -- a pause is never deferred, whatever an open in flight + /// is about to find. + fn set_playing(&self, playing: bool) { + // The lock, not the atomics, is what orders this against the feeder's + // stamp: the store below and the load after it are one critical section, + // and so is the feeder's pair. + let ao = self.ao.lock().unwrap(); + self.wants_active.store(playing, Ordering::Release); + if !playing || self.content_at.load(Ordering::Acquire) >= 0 { + ao.set_active(playing); + } + } + /// Keeps the newest [`TAP_SAMPLES`] of what was just queued, downmixed to /// mono. Called from the feeder only, once per accepted write. fn note_tap(&self, accepted: &[f32]) { @@ -2368,7 +2400,7 @@ impl PlaybackSession { // here too -- `clock.seek_to(t)` and then `set_active(true)`. self.clock.play(); if let Some(audio) = &self.audio { - audio.ao.lock().unwrap().set_active(true); + audio.set_playing(true); } } @@ -2377,7 +2409,7 @@ impl PlaybackSession { return; } if let Some(audio) = &self.audio { - audio.ao.lock().unwrap().set_active(false); + audio.set_playing(false); } self.clock.pause(); } @@ -2443,6 +2475,16 @@ impl PlaybackSession { Some((tap, audio.sample_rate)) } + /// How many quanta the device has had to fill with silence for want of + /// samples since this session opened: the count that means "the decoder was + /// late", sampled live rather than printed at the end of the process, so a + /// caller can attribute it to the seek it followed + /// ([`AoSession::underruns`]). `None` with no device, and with a plugin too + /// old to carry the counter. + pub fn audio_underruns(&self) -> Option { + self.audio.as_ref()?.ao.lock().unwrap().underruns() + } + /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode /// workers are replaced rather than steered: a fresh channel cannot hold a /// stale frame, and it works just as well after EOF, where the old workers @@ -2526,23 +2568,17 @@ impl PlaybackSession { /// the clock held until the new stream is really audible (see /// [`Audio::content_at`]). /// - /// corner-cut: the device is made active here, before the new stream has been - /// opened ([`start_audio`](Self::start_audio) opens on the feeder now), so a - /// cold open leaves it playing its own silence with an empty ring -- audibly - /// the same silence as before, and counted: a scripted cold play-seek-scrub - /// session goes from 5 to 1721 `engine_audio: N underruns`, one per starved - /// quantum, while a warm one is unchanged (46 -> 53 over the suite's 11 - /// sessions). Ceiling: the count stops meaning "the decoder was late" during - /// a cold seek. Upgrade path is a `wants_active` flag written here and read - /// by the feeder under the device lock beside the [`Audio::content_at`] - /// stamp, so the device is started by the first real sample rather than by - /// the intent to play -- it has to be the lock and the epoch check, or a - /// pause during the open would be overtaken by a late activation and the - /// timeline would play while it says it is paused. + /// Only the *intent* is set here: the open runs on the feeder + /// ([`start_audio`](Self::start_audio)), so the device is started by that + /// stream's first real sample instead ([`Audio::wants_active`]). A device + /// made active over an empty ring plays its own silence and counts one + /// underrun per starved quantum -- a scripted cold play-seek-scrub session + /// used to go from 5 to 1721 of them -- while the ear hears the same silence + /// either way, so nothing is gained for the count that is lost. fn resume(&mut self, was_playing: bool) { self.priming = true; - if was_playing && let Some(audio) = &self.audio { - audio.ao.lock().unwrap().set_active(true); + if let Some(audio) = &self.audio { + audio.set_playing(was_playing); } } @@ -2988,6 +3024,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option