forge
Explore
Log in

Don't you dare go Hollow

A stream that has ended is not a decoder that fell behind

Browse files at this commit

c179364cf237ebae8ca628b290a44ecf23828c9fAhmet Kaan GümüşParent: 4d0dd2b
  • fix
    • a stream that has ended is not a decoder that fell behind
Show full message
🐛 fix(audio): a stream that has ended is not a decoder that fell behind

The last unattributed underruns were the *tail* of a stream: once the
decoder is done, the ring drains and every quantum after it was counted as
lateness, though there was nothing left to be late with. Ten to sixteen per
session on a file played to its end, four hundred on a cold scrub.

`ao_stream_ended` (optional symbol, like the counter) unprimes the flag
when the feeder's decode channel closes -- under the device lock and past
the epoch check, so a superseded feeder cannot say it about the stream that
replaced it. What is already queued still plays out untouched: this is not
a flush and not a pause.

The device is also stopped where the audio really is over
(`tick`'s played-out branch), since nothing will ever be queued for that
stream again, and the stamp goes with it so a later play defers to the
first sample of whatever comes next.

Whole `--include-ignored` playback suite, 31 sessions: not one
`engine_audio: N underruns` line left, where the same run printed 9-16 for
`seek_past_the_end_clamps` and ~400 for a 200-step cold scrub before.
crates/engine-audio/src/lib.rsmodified+76 -12
@@ -123,11 +123,17 @@ fn scale(dst: &mut [u8], gain: f32) {
123123 /// seek) the next callback would then drain the new stream's head along with
124124 /// the stale tail. Refuse instead; the writer's retry loop parks until the
125125 /// RT thread consumes the flag.
126-fn accept(flush: &AtomicBool, ring: &Ring, samples: &[f32]) -> usize {
126+fn accept(flush: &AtomicBool, ring: &Ring, primed: &AtomicBool, samples: &[f32]) -> usize {
127127 if flush.load(Ordering::Acquire) {
128128 return 0;
129129 }
130- ring.push(samples)
130+ let pushed = ring.push(samples);
131+ if pushed > 0 {
132+ // There is something to play from here on, so a starved callback means
133+ // what it says again (`Shared::primed`).
134+ primed.store(true, Ordering::Release);
135+ }
136+ pushed
131137 }
132138
133139 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:
477483 return -1;
478484 }
479485 let samples = unsafe { std::slice::from_raw_parts(samples, n) };
480- let accepted = accept(&session.shared.flush, &session.shared.ring, samples);
481- if accepted > 0 {
482- // There is something to play from here on, so a starved callback
483- // means what it says again (`Shared::primed`).
484- session.shared.primed.store(true, Ordering::Release);
485- }
486- accepted as isize
486+ accept(
487+ &session.shared.flush,
488+ &session.shared.ring,
489+ &session.shared.primed,
490+ samples,
491+ ) as isize
487492 }))
488493 .unwrap_or(-1)
489494 }
@@ -505,6 +510,28 @@ pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 {
505510 .unwrap_or(-1)
506511 }
507512
513+/// Says the caller has queued the last sample this stream will ever have.
514+/// What is still in the ring plays out untouched -- this is not a flush and not
515+/// a pause -- but the silence *after* it stops being counted as a late decoder:
516+/// there is no decoder left to be late ([`Shared::primed`]). The next accepted
517+/// write is a stream again and counts again. 0 on success.
518+///
519+/// # Safety
520+/// `session` must come from [`ao_open`].
521+#[unsafe(no_mangle)]
522+pub unsafe extern "C" fn ao_stream_ended(session: *mut c_void) -> i32 {
523+ catch_unwind(AssertUnwindSafe(|| {
524+ if session.is_null() {
525+ return -1;
526+ }
527+ // SAFETY: caller-guaranteed live session.
528+ let session = unsafe { &*(session as *const Session) };
529+ session.shared.primed.store(false, Ordering::Release);
530+ 0
531+ }))
532+ .unwrap_or(-1)
533+}
534+
508535 /// Quanta the device had to fill with silence because the ring was empty --
509536 /// "the decoder was late", counted since the stream opened and never reset.
510537 /// The same number [`Session::drop`] prints, readable while the stream runs so
@@ -655,26 +682,63 @@ mod tests {
655682 fn pending_flush_refuses_writes_until_consumed() {
656683 let ring = Ring::new(4);
657684 let flush = AtomicBool::new(false);
685+ let primed = AtomicBool::new(false);
658686 let mut out = [0u8; 16];
659687
660688 // Stale pre-seek audio sits in the ring; a flush is requested while
661689 // paused (no callback runs yet).
662- assert_eq!(accept(&flush, &ring, &[1.0, 2.0]), 2);
690+ assert_eq!(accept(&flush, &ring, &primed, &[1.0, 2.0]), 2);
663691 flush.store(true, Ordering::Release);
664692
665693 // The new stream's feeder tries to write: refused, ring untouched.
666- assert_eq!(accept(&flush, &ring, &[3.0, 4.0]), 0);
694+ assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 0);
667695
668696 // First post-resume callback consumes the flag and drains the stale
669697 // tail -- and ONLY the stale tail, because nothing was queued behind it.
670698 assert_eq!(consume(&flush, &ring, &mut out, 2), 0);
671699
672700 // Writer unparks; the new audio flows intact.
673- assert_eq!(accept(&flush, &ring, &[3.0, 4.0]), 2);
701+ assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 2);
674702 assert_eq!(consume(&flush, &ring, &mut out, 2), 2);
675703 assert_eq!(&out[..4], &3.0f32.to_le_bytes());
676704 }
677705
706+ /// What the underrun count is allowed to mean: a starved callback is a late
707+ /// decoder only while a decoder is actually behind the ring. The head of a
708+ /// restart (nothing queued since the flush) and the tail of a stream (the
709+ /// decoder is done) are silence nobody is late for, and counting them made
710+ /// the number say "a seek happened" instead.
711+ #[test]
712+ fn only_a_started_stream_can_be_late() {
713+ let ring = Ring::new(4);
714+ let flush = AtomicBool::new(false);
715+ let primed = AtomicBool::new(false);
716+
717+ // The open: callbacks may run before the first write, and there is
718+ // nothing to be late for yet.
719+ assert!(!primed.load(Ordering::Acquire), "primed before a sample");
720+ assert_eq!(accept(&flush, &ring, &primed, &[1.0, 2.0]), 2);
721+ assert!(
722+ primed.load(Ordering::Acquire),
723+ "a queued sample is a stream that can fall behind"
724+ );
725+
726+ // A seek: `ao_flush` unprimes, and the head of the new stream -- the
727+ // decoder open, seconds on a cold film -- is not counted...
728+ primed.store(false, Ordering::Release);
729+ flush.store(true, Ordering::Release);
730+ let mut out = [0u8; 16];
731+ assert_eq!(consume(&flush, &ring, &mut out, 2), 0, "the flush landed");
732+ assert!(!primed.load(Ordering::Acquire), "the restart counts as late");
733+
734+ // ...until its own first sample lands, from where it counts again --
735+ // which is also what makes the tail work: `ao_stream_ended` unprimes
736+ // the same flag when the decoder is done, and only a write can prime it
737+ // again.
738+ assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 2);
739+ assert!(primed.load(Ordering::Acquire), "the new stream is running");
740+ }
741+
678742 #[test]
679743 fn ring_wraps_fills_and_starves() {
680744 let ring = Ring::new(4);
crates/engine/src/ao.rsmodified+14 -0
@@ -25,6 +25,9 @@ struct Plugin {
2525 /// many quanta it starved for. Rejecting the whole plugin over that would
2626 /// trade the sound for the diagnostic.
2727 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.
30+ stream_ended: Option<unsafe extern "C" fn(*mut c_void) -> i32>,
2831 close: unsafe extern "C" fn(*mut c_void),
2932 // Never dropped (lives in a static), so the fn pointers above stay valid.
3033 _lib: Library,
@@ -69,6 +72,7 @@ fn load() -> Option<Plugin> {
6972 set_volume: *lib.get(b"ao_set_volume\0").ok()?,
7073 flush: *lib.get(b"ao_flush\0").ok()?,
7174 underruns: lib.get(b"ao_underruns\0").ok().map(|f| *f),
75+ stream_ended: lib.get(b"ao_stream_ended\0").ok().map(|f| *f),
7276 close: *lib.get(b"ao_close\0").ok()?,
7377 _lib: lib,
7478 })
@@ -128,6 +132,16 @@ impl AoSession {
128132 }
129133 }
130134
135+ /// Says the last sample of this stream has been queued: the ring plays out
136+ /// as it is, and the silence after it is not counted against a decoder that
137+ /// has already finished. Nothing at all on a plugin without the symbol.
138+ pub fn stream_ended(&self) {
139+ if let Some(ended) = self.plugin.stream_ended {
140+ // SAFETY: `handle` came from `ao_open` and is still open.
141+ unsafe { ended(self.handle) };
142+ }
143+ }
144+
131145 /// Quanta the device filled with silence for want of samples, since the
132146 /// stream opened: what a benchmark reads to say the decoder kept up.
133147 /// `None` from a plugin that does not carry the counter.
crates/engine/src/playback.rsmodified+24 -1
@@ -2797,6 +2797,16 @@ impl PlaybackSession {
27972797 if audio.played_out(position) {
27982798 // Audio EOF. Wall time carries the same timeline on from here, with
27992799 // no jump, and this branch cannot be reached again.
2800+ //
2801+ // The device is stopped with it: nothing will ever be queued for
2802+ // this stream again, so every quantum it would go on playing is
2803+ // silence counted as a decoder that fell behind -- the tail of a
2804+ // stream, where [`crate::ao`]'s own `primed` covers the head of
2805+ // one. A seek from here starts it again like any other
2806+ // ([`resume`](Self::resume)), which is why the stamp goes with it:
2807+ // there is no sample of *this* stream left to start on.
2808+ audio.set_playing(false);
2809+ audio.content_at.store(-1, Ordering::Release);
28002810 self.clock.switch_to_wall();
28012811 return;
28022812 }
@@ -3080,7 +3090,20 @@ fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
30803090 if pending.is_empty() {
30813091 match rx.recv() {
30823092 Ok(chunk) => pending = chunk.samples,
3083- Err(_) => return, // decoder finished or went away
3093+ Err(_) => {
3094+ // Decoder finished or went away. What is in the ring still
3095+ // plays out; what comes after it is the end of the timeline
3096+ // and not a decoder that fell behind, so the device is told
3097+ // to stop counting it. Under the lock and past the epoch,
3098+ // like every other word this thread has with the device: a
3099+ // superseded feeder must not say this about the stream that
3100+ // replaced it.
3101+ let ao = audio.ao.lock().unwrap();
3102+ if audio.epoch.load(Ordering::Acquire) == epoch {
3103+ ao.stream_ended();
3104+ }
3105+ return;
3106+ }
30843107 }
30853108 }
30863109 let accepted = {