diff --git a/crates/engine-audio/src/lib.rs b/crates/engine-audio/src/lib.rs index 9a1c6e8..5648b08 100644 --- a/crates/engine-audio/src/lib.rs +++ b/crates/engine-audio/src/lib.rs @@ -123,11 +123,17 @@ fn scale(dst: &mut [u8], gain: f32) { /// seek) the next callback would then drain the new stream's head along with /// the stale tail. Refuse instead; the writer's retry loop parks until the /// RT thread consumes the flag. -fn accept(flush: &AtomicBool, ring: &Ring, samples: &[f32]) -> usize { +fn accept(flush: &AtomicBool, ring: &Ring, primed: &AtomicBool, samples: &[f32]) -> usize { if flush.load(Ordering::Acquire) { return 0; } - ring.push(samples) + let pushed = ring.push(samples); + if pushed > 0 { + // There is something to play from here on, so a starved callback means + // what it says again (`Shared::primed`). + primed.store(true, Ordering::Release); + } + pushed } fn consume(flush: &AtomicBool, ring: &Ring, dst: &mut [u8], want: usize) -> usize { @@ -477,13 +483,12 @@ 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) }; - 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 + accept( + &session.shared.flush, + &session.shared.ring, + &session.shared.primed, + samples, + ) as isize })) .unwrap_or(-1) } @@ -505,6 +510,28 @@ pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 { .unwrap_or(-1) } +/// Says the caller has queued the last sample this stream will ever have. +/// What is still in the ring plays out untouched -- this is not a flush and not +/// a pause -- but the silence *after* it stops being counted as a late decoder: +/// there is no decoder left to be late ([`Shared::primed`]). The next accepted +/// write is a stream again and counts again. 0 on success. +/// +/// # Safety +/// `session` must come from [`ao_open`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn ao_stream_ended(session: *mut c_void) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session. + let session = unsafe { &*(session as *const Session) }; + session.shared.primed.store(false, Ordering::Release); + 0 + })) + .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 @@ -655,26 +682,63 @@ mod tests { fn pending_flush_refuses_writes_until_consumed() { let ring = Ring::new(4); let flush = AtomicBool::new(false); + let primed = AtomicBool::new(false); let mut out = [0u8; 16]; // Stale pre-seek audio sits in the ring; a flush is requested while // paused (no callback runs yet). - assert_eq!(accept(&flush, &ring, &[1.0, 2.0]), 2); + assert_eq!(accept(&flush, &ring, &primed, &[1.0, 2.0]), 2); flush.store(true, Ordering::Release); // The new stream's feeder tries to write: refused, ring untouched. - assert_eq!(accept(&flush, &ring, &[3.0, 4.0]), 0); + assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 0); // First post-resume callback consumes the flag and drains the stale // tail -- and ONLY the stale tail, because nothing was queued behind it. assert_eq!(consume(&flush, &ring, &mut out, 2), 0); // Writer unparks; the new audio flows intact. - assert_eq!(accept(&flush, &ring, &[3.0, 4.0]), 2); + assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 2); assert_eq!(consume(&flush, &ring, &mut out, 2), 2); assert_eq!(&out[..4], &3.0f32.to_le_bytes()); } + /// What the underrun count is allowed to mean: a starved callback is a late + /// decoder only while a decoder is actually behind the ring. The head of a + /// restart (nothing queued since the flush) and the tail of a stream (the + /// decoder is done) are silence nobody is late for, and counting them made + /// the number say "a seek happened" instead. + #[test] + fn only_a_started_stream_can_be_late() { + let ring = Ring::new(4); + let flush = AtomicBool::new(false); + let primed = AtomicBool::new(false); + + // The open: callbacks may run before the first write, and there is + // nothing to be late for yet. + assert!(!primed.load(Ordering::Acquire), "primed before a sample"); + assert_eq!(accept(&flush, &ring, &primed, &[1.0, 2.0]), 2); + assert!( + primed.load(Ordering::Acquire), + "a queued sample is a stream that can fall behind" + ); + + // A seek: `ao_flush` unprimes, and the head of the new stream -- the + // decoder open, seconds on a cold film -- is not counted... + primed.store(false, Ordering::Release); + flush.store(true, Ordering::Release); + let mut out = [0u8; 16]; + assert_eq!(consume(&flush, &ring, &mut out, 2), 0, "the flush landed"); + assert!(!primed.load(Ordering::Acquire), "the restart counts as late"); + + // ...until its own first sample lands, from where it counts again -- + // which is also what makes the tail work: `ao_stream_ended` unprimes + // the same flag when the decoder is done, and only a write can prime it + // again. + assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 2); + assert!(primed.load(Ordering::Acquire), "the new stream is running"); + } + #[test] fn ring_wraps_fills_and_starves() { let ring = Ring::new(4); diff --git a/crates/engine/src/ao.rs b/crates/engine/src/ao.rs index 0ceae73..1863d9c 100644 --- a/crates/engine/src/ao.rs +++ b/crates/engine/src/ao.rs @@ -25,6 +25,9 @@ struct Plugin { /// 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. + 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. _lib: Library, @@ -69,6 +72,7 @@ fn load() -> Option { 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), + stream_ended: lib.get(b"ao_stream_ended\0").ok().map(|f| *f), close: *lib.get(b"ao_close\0").ok()?, _lib: lib, }) @@ -128,6 +132,16 @@ impl AoSession { } } + /// Says the last sample of this stream has been queued: the ring plays out + /// as it is, and the silence after it is not counted against a decoder that + /// has already finished. Nothing at all on a plugin without the symbol. + pub fn stream_ended(&self) { + if let Some(ended) = self.plugin.stream_ended { + // SAFETY: `handle` came from `ao_open` and is still open. + unsafe { ended(self.handle) }; + } + } + /// 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. diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index bad0255..f746b42 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -2797,6 +2797,16 @@ impl PlaybackSession { if audio.played_out(position) { // Audio EOF. Wall time carries the same timeline on from here, with // no jump, and this branch cannot be reached again. + // + // The device is stopped with it: nothing will ever be queued for + // this stream again, so every quantum it would go on playing is + // silence counted as a decoder that fell behind -- the tail of a + // stream, where [`crate::ao`]'s own `primed` covers the head of + // one. A seek from here starts it again like any other + // ([`resume`](Self::resume)), which is why the stamp goes with it: + // there is no sample of *this* stream left to start on. + audio.set_playing(false); + audio.content_at.store(-1, Ordering::Release); self.clock.switch_to_wall(); return; } @@ -3080,7 +3090,20 @@ fn feed(rx: Receiver, audio: &Audio, epoch: u64) { if pending.is_empty() { match rx.recv() { Ok(chunk) => pending = chunk.samples, - Err(_) => return, // decoder finished or went away + Err(_) => { + // Decoder finished or went away. What is in the ring still + // plays out; what comes after it is the end of the timeline + // and not a decoder that fell behind, so the device is told + // to stop counting it. Under the lock and past the epoch, + // like every other word this thread has with the device: a + // superseded feeder must not say this about the stream that + // replaced it. + let ao = audio.ao.lock().unwrap(); + if audio.epoch.load(Ordering::Acquire) == epoch { + ao.stream_ended(); + } + return; + } } } let accepted = {