forge
Explore
Log in

Don't you dare go Hollow

A dead audio output is re-opened instead of ending the session's sound

Browse files at this commit

b05e9eeebf1020491083b46cd27aad267a189c67Ahmet Kaan GümüşParent: 0cf7335
  • fix
    • a dead audio output is re-opened instead of ending the session's sound
Show full message
🐛 fix(engine): a dead audio output is re-opened instead of ending the session's sound

The feeder flags the output dead when a write returns `None` -- a PipeWire
daemon that restarted, or a sink node that was removed. Nothing ever cleared
that flag: `start_audio` skipped its whole body for it, `arm_audio` was a no-op
while `self.audio` was `Some`, and `tick` handed the clock to wall time without
a word. The stream's position is frozen, so it can never satisfy `played_out`
again either. The session was silent for the rest of its life, through every
seek and every pause/play, with nothing shown to the user about it.

`rearm_audio` opens the output again at the rate and channel count the dead
stream carried -- the device only, never the file: the feeder is `start_audio`'s
at the seek that follows -- and clears the flag and the clock anchor that belong
to the stream that died. A seek (or the play after a pause) attempts it with no
cooldown, because that is a person asking and the one moment the sound can come
back into step with the picture; `tick` attempts it once a second, because a tick
is a rendered frame and a device that is gone for good must not be opened sixty
times a second. `tick`'s dead branch now runs *before* its clock-source guard:
the death is what puts the clock on wall time, so a session that only polled
once more would never try the device again -- the attempt has to be inside the
branch that keeps running. While it is dead, the session says so through the
door a front-end already reads for a silent one (`audio_disabled_reason`), and a
re-arm that takes clears that line again. `arm_audio` treats a dead device as no
device, so an import replaces it instead of being turned away by it.

Evidence: `cargo test -p engine --lib -- --exact
playback::tests::a_dead_output_is_rearmed_and_the_sound_comes_back` -- ok.
The test stops the stream and flags it exactly as `feed` does, stamps the
cooldown as spent, and then asserts: the notice is up, died is still set and the
tap is empty after a tick (no open inside the cooldown, nothing feeding), and
after a play + seek the flag is clear, the notice is gone and the *tap* -- the
samples that reached the device -- has samples in it again.
crates/engine/src/playback.rsmodified+187 -9
@@ -16,7 +16,7 @@ use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering}
1616 use std::sync::mpsc::{Receiver, TryRecvError};
1717 use std::sync::{Arc, Mutex};
1818 use std::thread;
19-use std::time::Duration;
19+use std::time::{Duration, Instant};
2020
2121 use crate::ao::AoSession;
2222 use crate::audio::{AudioChunk, AudioSession};
@@ -52,6 +52,18 @@ const FLUSH_WAIT: Duration = Duration::from_millis(1);
5252 /// all pays this once per span rather than freezing the preview outright.
5353 const DISSOLVE_B_TIMEOUT: Duration = Duration::from_millis(200);
5454
55+/// How long a dead output is left alone before another open is attempted. A
56+/// PipeWire daemon restart takes a moment, and the ask that makes the attempt
57+/// runs once per rendered frame: a second is long enough that a restart lands
58+/// inside it, and short enough that a play pressed after one does not wait.
59+const AUDIO_REARM_AFTER: Duration = Duration::from_secs(1);
60+
61+/// What a session says when its output dies ([`PlaybackSession::tick`]): the
62+/// one line a front-end shows for a session that has gone quiet, through the
63+/// same door a file's own refusal reaches it by
64+/// ([`PlaybackSession::audio_disabled_reason`]).
65+const AUDIO_LOST: &str = "output device went away -- reconnecting the timeline's sound";
66+
5567 /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --
5668 /// nothing was shot on it, so it is the canvas a *later* import meets rather
5769 /// than a description of the song. H.264 because it is the one codec that
@@ -149,6 +161,13 @@ struct Audio {
149161 /// at once -- which is precisely what
150162 /// [`live_workers`](PlaybackSession::live_workers) is asked about.
151163 feeders: Arc<AtomicUsize>,
164+ /// When this device was last opened *again* after dying
165+ /// ([`PlaybackSession::rearm_audio`]). A dead output is offered one open a
166+ /// second and no more, because the ask that makes the attempt runs once per
167+ /// rendered frame: a daemon restart takes a moment, and a device that is
168+ /// gone for good must not be opened sixty times a second for the rest of
169+ /// the session.
170+ rearm_at: Arc<Mutex<Option<Instant>>>,
152171 }
153172
154173 /// How much of the played signal the tap keeps. A power of two, because what
@@ -2672,7 +2691,12 @@ impl PlaybackSession {
26722691 /// ([`Self::seek`]'s own `switch_to_audio`), which is the seek a front-end
26732692 /// makes as it places the file it just imported.
26742693 fn arm_audio(&mut self) {
2675- if self.audio.is_some() {
2694+ // A device that is there but *dead* is not a device: the walk below
2695+ // opens another one, which is also what clears the notice a death put up
2696+ // ([`Self::tick`]).
2697+ if let Some(audio) = &self.audio
2698+ && !audio.died.load(Ordering::Acquire)
2699+ {
26762700 return;
26772701 }
26782702 for source in self
@@ -2690,6 +2714,63 @@ impl PlaybackSession {
26902714 }
26912715 }
26922716
2717+ /// Opens the output again for a stream that died, at the rate and channel
2718+ /// count it carried, and clears the flag that stopped the session feeding.
2719+ ///
2720+ /// An output that goes away -- a PipeWire daemon restarting, a sink node
2721+ /// removed and put back -- leaves every stream that was open on it dead for
2722+ /// good: its position is frozen, so the clock can only fall to wall time, and
2723+ /// a session that never opens another device is silent for the rest of its
2724+ /// life, through every seek and every pause/play, with nothing said about it.
2725+ ///
2726+ /// The device *only*, never the file: the feeder is [`Self::start_audio`]'s,
2727+ /// at the seek that follows. That is what lets [`Self::tick`] call this too,
2728+ /// once a frame -- a tick is not a seek and must not reseek the timeline. The
2729+ /// clock is on wall time by then and stays there until a seek comes, which is
2730+ /// the seek whose feeder opens in step with the picture.
2731+ ///
2732+ /// `if_idle_for` is the cooldown: a tick passes [`AUDIO_REARM_AFTER`], because
2733+ /// sixty opens a second against a device that is gone for good is a spin; a
2734+ /// seek passes zero, because that one is a person asking.
2735+ ///
2736+ /// `false` when there is nothing to open, nothing came back, or the cooldown
2737+ /// has not passed -- and the flag stays standing for the next attempt.
2738+ fn rearm_audio(&mut self, if_idle_for: Duration) -> bool {
2739+ let Some(audio) = &self.audio else {
2740+ return false;
2741+ };
2742+ if !audio.died.load(Ordering::Acquire) {
2743+ return true;
2744+ }
2745+ {
2746+ let mut at = audio.rearm_at.lock().unwrap();
2747+ if at.is_some_and(|at| at.elapsed() < if_idle_for) {
2748+ return false;
2749+ }
2750+ *at = Some(Instant::now());
2751+ }
2752+ let Some(ao) = AoSession::open(audio.sample_rate, audio.channels as u32) else {
2753+ return false;
2754+ };
2755+ // A stream comes up streaming and a session starts paused: the fresh one
2756+ // is silenced until the seek that feeds it says otherwise, which is the
2757+ // same two steps [`open_audio`] takes on the way in.
2758+ ao.set_active(false);
2759+ // Replacing the session is what closes the dead stream, so it is done
2760+ // under the device lock the feeder writes through.
2761+ *audio.ao.lock().unwrap() = ao;
2762+ // The clock anchor and the played-out arithmetic both belong to the
2763+ // stream that died: the new one stamps its own first sample
2764+ // ([`Audio::content_at`]), and `start_audio` re-bases the count from the
2765+ // device's own position.
2766+ audio.content_at.store(-1, Ordering::Release);
2767+ audio.died.store(false, Ordering::Release);
2768+ if self.audio_disabled.as_deref() == Some(AUDIO_LOST) {
2769+ self.audio_disabled = None;
2770+ }
2771+ true
2772+ }
2773+
26932774 /// The rate noted for whichever source plays `path`, by
26942775 /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however
26952776 /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session
@@ -3910,6 +3991,12 @@ impl PlaybackSession {
39103991 let fps = self.meta.frame_rate;
39113992 let mut audio_running = false;
39123993 let mut live = None;
3994+ // A dead output gets an attempt here without waiting out the cooldown: a
3995+ // seek is a person asking, and this is the one moment the sound can come
3996+ // back into step with the picture, because the feeder opened below starts
3997+ // at the target. If it does not come back the flag stands and the guard
3998+ // under it leaves the clock on wall time.
3999+ self.rearm_audio(Duration::ZERO);
39134000 if let Some(audio) = &self.audio
39144001 && !audio.died.load(Ordering::Acquire)
39154002 {
@@ -4079,19 +4166,37 @@ impl PlaybackSession {
40794166 // still be moving it -- otherwise the queue fills with pictures whose
40804167 // moment passed while nobody was taking them.
40814168 self.publish_playhead();
4169+ // Before the clock-source guard below, and not after it: a dead output is
4170+ // what *puts* the clock on wall time, so this branch has to keep running
4171+ // while it is there -- the one attempt that can bring the sound back is
4172+ // in it.
4173+ if self
4174+ .audio
4175+ .as_ref()
4176+ .is_some_and(|audio| audio.died.load(Ordering::Acquire))
4177+ {
4178+ // Output died mid-stream: its position will never reach `fed`, so the
4179+ // EOF comparison below is unreachable. Wall time takes over from
4180+ // wherever the clock last stood, and the session says so rather than
4181+ // going silent for good without a word: a front-end already has a
4182+ // line for a silent session ([`Self::audio_disabled_reason`]).
4183+ if self.audio_disabled.is_none() {
4184+ self.audio_disabled = Some(AUDIO_LOST.to_string());
4185+ }
4186+ self.clock.switch_to_wall();
4187+ // ...and the output is offered another open, once a second: a
4188+ // restarting daemon takes a moment, and this runs once a frame. A
4189+ // re-arm that takes is what clears the notice, and the next seek
4190+ // feeds it.
4191+ self.rearm_audio(AUDIO_REARM_AFTER);
4192+ return;
4193+ }
40824194 let Some(audio) = &self.audio else {
40834195 return; // wall time from the start, nothing to poll
40844196 };
40854197 if self.clock.source() != ClockSource::Audio {
40864198 return;
40874199 }
4088- if audio.died.load(Ordering::Acquire) {
4089- // Output died mid-stream: its position will never reach `fed`, so
4090- // the EOF comparison below is unreachable. Wall time takes over
4091- // from wherever the clock last stood.
4092- self.clock.switch_to_wall();
4093- return;
4094- }
40954200 // `None` until the device's first callback: the clock holds at its
40964201 // anchor rather than guessing, which is why playback starts on time
40974202 // instead of a quantum early.
@@ -4420,6 +4525,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
44204525 wants_active: Arc::new(AtomicBool::new(false)),
44214526 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),
44224527 feeders: Arc::new(AtomicUsize::new(0)),
4528+ rearm_at: Arc::new(Mutex::new(None)),
44234529 };
44244530 (audio.spawn_feeder(rx).then_some(audio), None)
44254531 }
@@ -4553,8 +4659,10 @@ fn blend_bgra(a: &[u8], b: &[u8], t: f32) -> Vec<u8> {
45534659 mod tests {
45544660 use super::{
45554661 Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of, blend_bgra, secs_to_frame,
4662+ AUDIO_LOST,
45564663 };
45574664 use std::path::PathBuf;
4665+ use std::sync::atomic::Ordering;
45584666
45594667 fn asset(name: &str) -> PathBuf {
45604668 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -4562,6 +4670,76 @@ mod tests {
45624670 .join(name)
45634671 }
45644672
4673+ /// A dead output is not the end of a session's sound.
4674+ ///
4675+ /// The stream is stopped the way a seek stops one and then flagged the way a
4676+ /// failed write flags it ([`feed`]): nothing is feeding and nothing will. The
4677+ /// session must say so -- a dead output used to hand the clock to wall time
4678+ /// in silence, for the rest of the session's life, through every seek -- and
4679+ /// the play (and the seek after it) must put the output back, which is read
4680+ /// off the tap: the samples that actually reached the device. A session that
4681+ /// only switched the clock leaves the tap empty.
4682+ ///
4683+ /// The tick below runs with the cooldown already spent (an attempt stamped
4684+ /// just now), which is what makes the notice observable at all *and* what
4685+ /// proves the one thing a frame-rate poll must not do: open a device that is
4686+ /// gone for good sixty times a second.
4687+ #[test]
4688+ fn a_dead_output_is_rearmed_and_the_sound_comes_back() {
4689+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4690+ assert!(
4691+ session.audio_tap().is_some(),
4692+ "test_av.mp4 carries an audio track, which is what this drives"
4693+ );
4694+
4695+ session.stop_audio();
4696+ let audio = session.audio.as_ref().expect("audio");
4697+ audio.died.store(true, Ordering::Release);
4698+ *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now());
4699+
4700+ session.tick();
4701+ assert_eq!(
4702+ session.audio_disabled_reason(),
4703+ Some(AUDIO_LOST),
4704+ "a dead output went to wall time without a word"
4705+ );
4706+ assert!(
4707+ session.audio.as_ref().expect("audio").died.load(Ordering::Acquire),
4708+ "a tick opened the output again inside the cooldown"
4709+ );
4710+ assert!(
4711+ session.audio_tap().expect("audio").0.is_empty(),
4712+ "something was still feeding the device"
4713+ );
4714+
4715+ // Playing is the ask that is not throttled: the output is opened again,
4716+ // the flag clears and a feeder fills the device -- asynchronously, so the
4717+ // tap is waited on.
4718+ session.play();
4719+ session.seek(1.0);
4720+ let mut fed = Vec::new();
4721+ for _ in 0..200 {
4722+ fed = session.audio_tap().expect("audio").0;
4723+ if !fed.is_empty() {
4724+ break;
4725+ }
4726+ std::thread::sleep(std::time::Duration::from_millis(5));
4727+ }
4728+ assert!(
4729+ !fed.is_empty(),
4730+ "playing after a dead output fed nothing: the session cannot come back"
4731+ );
4732+ assert!(
4733+ !session.audio.as_ref().expect("audio").died.load(Ordering::Acquire),
4734+ "the death flag stood after the output was replaced"
4735+ );
4736+ assert_eq!(
4737+ session.audio_disabled_reason(),
4738+ None,
4739+ "the notice was left standing over a session that is playing again"
4740+ );
4741+ }
4742+
45654743 /// `blend_bgra` at the two ends and the midpoint of its weight -- `t=0` is
45664744 /// pure A, `t=1` is pure B, `t=0.5` rounds each byte to its own midpoint.
45674745 /// Straight alpha (255 in both) survives every weight, which is the one