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) {
123 /// seek) the next callback would then drain the new stream's head along with123 /// seek) the next callback would then drain the new stream's head along with
124 /// the stale tail. Refuse instead; the writer's retry loop parks until the124 /// the stale tail. Refuse instead; the writer's retry loop parks until the
125 /// RT thread consumes the flag.125 /// 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 {
127 if flush.load(Ordering::Acquire) {127 if flush.load(Ordering::Acquire) {
128 return 0;128 return 0;
129 }129 }
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
131 }137 }
132 138
133 fn consume(flush: &AtomicBool, ring: &Ring, dst: &mut [u8], want: usize) -> usize {139 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:
477 return -1;483 return -1;
478 }484 }
479 let samples = unsafe { std::slice::from_raw_parts(samples, n) };485 let samples = unsafe { std::slice::from_raw_parts(samples, n) };
480- let accepted = accept(&session.shared.flush, &session.shared.ring, samples);486+ accept(
481- if accepted > 0 {487+ &session.shared.flush,
482- // There is something to play from here on, so a starved callback488+ &session.shared.ring,
483- // means what it says again (`Shared::primed`).489+ &session.shared.primed,
484- session.shared.primed.store(true, Ordering::Release);490+ samples,
485- }491+ ) as isize
486- accepted as isize
487 }))492 }))
488 .unwrap_or(-1)493 .unwrap_or(-1)
489 }494 }
@@ -505,6 +510,28 @@ pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 {
505 .unwrap_or(-1)510 .unwrap_or(-1)
506 }511 }
507 512
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+
508 /// Quanta the device had to fill with silence because the ring was empty --535 /// Quanta the device had to fill with silence because the ring was empty --
509 /// "the decoder was late", counted since the stream opened and never reset.536 /// "the decoder was late", counted since the stream opened and never reset.
510 /// The same number [`Session::drop`] prints, readable while the stream runs so537 /// The same number [`Session::drop`] prints, readable while the stream runs so
@@ -655,26 +682,63 @@ mod tests {
655 fn pending_flush_refuses_writes_until_consumed() {682 fn pending_flush_refuses_writes_until_consumed() {
656 let ring = Ring::new(4);683 let ring = Ring::new(4);
657 let flush = AtomicBool::new(false);684 let flush = AtomicBool::new(false);
685+ let primed = AtomicBool::new(false);
658 let mut out = [0u8; 16];686 let mut out = [0u8; 16];
659 687
660 // Stale pre-seek audio sits in the ring; a flush is requested while688 // Stale pre-seek audio sits in the ring; a flush is requested while
661 // paused (no callback runs yet).689 // 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);
663 flush.store(true, Ordering::Release);691 flush.store(true, Ordering::Release);
664 692
665 // The new stream's feeder tries to write: refused, ring untouched.693 // 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);
667 695
668 // First post-resume callback consumes the flag and drains the stale696 // First post-resume callback consumes the flag and drains the stale
669 // tail -- and ONLY the stale tail, because nothing was queued behind it.697 // tail -- and ONLY the stale tail, because nothing was queued behind it.
670 assert_eq!(consume(&flush, &ring, &mut out, 2), 0);698 assert_eq!(consume(&flush, &ring, &mut out, 2), 0);
671 699
672 // Writer unparks; the new audio flows intact.700 // 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);
674 assert_eq!(consume(&flush, &ring, &mut out, 2), 2);702 assert_eq!(consume(&flush, &ring, &mut out, 2), 2);
675 assert_eq!(&out[..4], &3.0f32.to_le_bytes());703 assert_eq!(&out[..4], &3.0f32.to_le_bytes());
676 }704 }
677 705
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+
678 #[test]742 #[test]
679 fn ring_wraps_fills_and_starves() {743 fn ring_wraps_fills_and_starves() {
680 let ring = Ring::new(4);744 let ring = Ring::new(4);
crates/engine/src/ao.rsmodified+14 -0
@@ -25,6 +25,9 @@ struct Plugin {
25 /// many quanta it starved for. Rejecting the whole plugin over that would25 /// many quanta it starved for. Rejecting the whole plugin over that would
26 /// trade the sound for the diagnostic.26 /// trade the sound for the diagnostic.
27 underruns: Option<unsafe extern "C" fn(*mut c_void) -> i64>,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.
30+ stream_ended: Option<unsafe extern "C" fn(*mut c_void) -> i32>,
28 close: unsafe extern "C" fn(*mut c_void),31 close: unsafe extern "C" fn(*mut c_void),
29 // Never dropped (lives in a static), so the fn pointers above stay valid.32 // Never dropped (lives in a static), so the fn pointers above stay valid.
30 _lib: Library,33 _lib: Library,
@@ -69,6 +72,7 @@ fn load() -> Option<Plugin> {
69 set_volume: *lib.get(b"ao_set_volume\0").ok()?,72 set_volume: *lib.get(b"ao_set_volume\0").ok()?,
70 flush: *lib.get(b"ao_flush\0").ok()?,73 flush: *lib.get(b"ao_flush\0").ok()?,
71 underruns: lib.get(b"ao_underruns\0").ok().map(|f| *f),74 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),
72 close: *lib.get(b"ao_close\0").ok()?,76 close: *lib.get(b"ao_close\0").ok()?,
73 _lib: lib,77 _lib: lib,
74 })78 })
@@ -128,6 +132,16 @@ impl AoSession {
128 }132 }
129 }133 }
130 134
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+
131 /// Quanta the device filled with silence for want of samples, since the145 /// Quanta the device filled with silence for want of samples, since the
132 /// stream opened: what a benchmark reads to say the decoder kept up.146 /// stream opened: what a benchmark reads to say the decoder kept up.
133 /// `None` from a plugin that does not carry the counter.147 /// `None` from a plugin that does not carry the counter.
crates/engine/src/playback.rsmodified+24 -1
@@ -2797,6 +2797,16 @@ impl PlaybackSession {
2797 if audio.played_out(position) {2797 if audio.played_out(position) {
2798 // Audio EOF. Wall time carries the same timeline on from here, with2798 // Audio EOF. Wall time carries the same timeline on from here, with
2799 // no jump, and this branch cannot be reached again.2799 // 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);
2800 self.clock.switch_to_wall();2810 self.clock.switch_to_wall();
2801 return;2811 return;
2802 }2812 }
@@ -3080,7 +3090,20 @@ fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
3080 if pending.is_empty() {3090 if pending.is_empty() {
3081 match rx.recv() {3091 match rx.recv() {
3082 Ok(chunk) => pending = chunk.samples,3092 Ok(chunk) => pending = chunk.samples,
3083- Err(_) => return, // decoder finished or went away3093+ 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+ }
3084 }3107 }
3085 }3108 }
3086 let accepted = {3109 let accepted = {