fix(qt): release audio at quit and fence late playback
Request output release with the first quit watchdog arm, independently of network teardown. Permanently reject late playback/reinit commands, interrupt abandoned feeders, and await release acknowledgement. Restore the owner queue at Connect shutdown without scheduling playback. cx
This commit is contained in:
4 files changed
+62
-8
No files matched your search
@@ -1404,6 +1404,8 @@ pub struct PlaybackEvent {
|
||||
/// Shared state between main thread and audio thread
|
||||
#[derive(Clone)]
|
||||
pub struct SharedState {
|
||||
/// Terminal fence: late transport/reinit commands cannot reopen a closing player.
|
||||
shutting_down: Arc<AtomicBool>,
|
||||
/// Is currently playing
|
||||
is_playing: Arc<AtomicBool>,
|
||||
/// Current position in seconds
|
||||
@@ -1508,6 +1510,7 @@ impl Default for SharedState {
|
||||
impl SharedState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
shutting_down: Arc::new(AtomicBool::new(false)),
|
||||
is_playing: Arc::new(AtomicBool::new(false)),
|
||||
position: Arc::new(AtomicU64::new(0)),
|
||||
duration: Arc::new(AtomicU64::new(0)),
|
||||
@@ -1623,7 +1626,7 @@ impl SharedState {
|
||||
|
||||
fn apply_playing_intent(&self, engine: &PlaybackEngine, generation: u64, playing: bool) -> bool {
|
||||
let intent = self.play_intent.lock().unwrap();
|
||||
if *intent != (generation, playing) { return false; }
|
||||
if self.shutting_down.load(Ordering::SeqCst) || *intent != (generation, playing) { return false; }
|
||||
if playing {
|
||||
engine.play();
|
||||
self.resume_playback_timer();
|
||||
@@ -1639,7 +1642,7 @@ impl SharedState {
|
||||
generation: u64, position: u64) -> Result<(), String>
|
||||
where S: Source<Item = f32> + Send + 'static {
|
||||
let intent = self.play_intent.lock().unwrap();
|
||||
if intent.0 != generation {
|
||||
if self.shutting_down.load(Ordering::SeqCst) || intent.0 != generation {
|
||||
return Err("source installation superseded".into());
|
||||
}
|
||||
engine.append_with_state(source, intent.1)?;
|
||||
@@ -1664,7 +1667,7 @@ impl SharedState {
|
||||
/// True while `gen` is still the newest play intent. The audio thread
|
||||
/// uses this to abandon buffer waits for superseded plays (#591).
|
||||
pub(crate) fn is_current_play(&self, gen: u64) -> bool {
|
||||
self.current_play_generation() == gen
|
||||
!self.shutting_down.load(Ordering::SeqCst) && self.current_play_generation() == gen
|
||||
}
|
||||
|
||||
fn begin_buffering(&self, track_id: u64, play_generation: u64) {
|
||||
@@ -2508,6 +2511,11 @@ impl Player {
|
||||
current_gain_atomic: &mut Option<Arc<AtomicU32>>,
|
||||
gapless_pending: &mut Option<GaplessPending>,
|
||||
gapless_request_armed: &mut bool| {
|
||||
if thread_state.shutting_down.load(Ordering::SeqCst)
|
||||
&& !matches!(&command, AudioCommand::ReleaseDevice { .. } | AudioCommand::Stop { .. })
|
||||
{
|
||||
return;
|
||||
}
|
||||
match command {
|
||||
AudioCommand::Play {
|
||||
data,
|
||||
@@ -5057,7 +5065,8 @@ impl Player {
|
||||
// were actually playing.
|
||||
if let Some(reason) = qbz_audio::stream_health::take_wedged() {
|
||||
let now = Instant::now();
|
||||
let was_playing = thread_state.is_playing.load(Ordering::SeqCst);
|
||||
let was_playing = thread_state.is_playing.load(Ordering::SeqCst)
|
||||
&& !thread_state.shutting_down.load(Ordering::SeqCst);
|
||||
let resume_at = thread_state.current_position();
|
||||
if let Some(engine) = current_engine.take() {
|
||||
engine.stop();
|
||||
@@ -7390,6 +7399,14 @@ impl Player {
|
||||
.map_err(|e| format!("Failed to send reinit command: {}", e))
|
||||
}
|
||||
|
||||
/// Close admission before asynchronous frontend teardown starts. Permanent
|
||||
/// for this player instance; unlike pause/reset, exit cannot reopen audio.
|
||||
pub fn begin_shutdown(&self) {
|
||||
self.state.shutting_down.store(true, Ordering::SeqCst);
|
||||
let _ = self.begin_play_with_state(false);
|
||||
self.state.seal_stream_feeder();
|
||||
}
|
||||
|
||||
/// Release the output device without reopening it. Drops the active
|
||||
/// stream — freeing an exclusive ALSA `hw:` grab and its D-Bus
|
||||
/// reservation — and un-suspends / un-forces anything QBZ parked, so
|
||||
@@ -7629,6 +7646,17 @@ mod tests {
|
||||
assert_eq!(*state.play_intent.lock().unwrap(), (second, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shutdown_fences_existing_and_late_play_generations() {
|
||||
let state = SharedState::new();
|
||||
let first = state.begin_play();
|
||||
assert!(state.is_current_play(first));
|
||||
state.shutting_down.store(true, Ordering::SeqCst);
|
||||
assert!(!state.is_current_play(first));
|
||||
let late = state.begin_play();
|
||||
assert!(!state.is_current_play(late));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_resume_preserves_live_clock_and_real_pause_can_resume() {
|
||||
let state = SharedState::new();
|
||||
|
||||
@@ -3824,6 +3824,9 @@ fn apply_interface_scale_preference() {
|
||||
|
||||
// ============================ Shutdown guarantee ==========================
|
||||
|
||||
static OUTPUT_RELEASE_TASK: std::sync::Mutex<Option<std::thread::JoinHandle<Result<(), String>>>> =
|
||||
std::sync::Mutex::new(None);
|
||||
|
||||
/// One-shot latch for [`arm_hard_exit_watchdog`].
|
||||
static HARD_EXIT_ARMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
@@ -3883,6 +3886,14 @@ pub(crate) fn arm_hard_exit_watchdog(source: &'static str) {
|
||||
// see the header above.
|
||||
unsafe { libc::_exit(0) };
|
||||
});
|
||||
// Send release at the first quit request, even if Qt never exits its loop.
|
||||
// The terminal player fence also rejects late Connect/Cast continuations.
|
||||
if let Some(runtime) = APP.get() {
|
||||
let player = runtime.core().player();
|
||||
player.begin_shutdown();
|
||||
playback_qt::cancel_owner_playback_tasks();
|
||||
*OUTPUT_RELEASE_TASK.lock().unwrap() = Some(std::thread::spawn(move || player.release_device()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Is THIS process one of the internal, disposable child processes that
|
||||
@@ -4255,7 +4266,7 @@ fn main() {
|
||||
};
|
||||
match tokio::time::timeout(
|
||||
std::time::Duration::from_secs(3),
|
||||
service.disconnect(),
|
||||
service.disconnect_for_shutdown(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -4305,6 +4316,14 @@ fn main() {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(task) = OUTPUT_RELEASE_TASK.lock().unwrap().take() {
|
||||
match task.join() {
|
||||
Ok(Ok(())) => log::info!("[shutdown] output-device release acknowledged"),
|
||||
Ok(Err(error)) => log::error!("[shutdown] output-device release failed: {error}"),
|
||||
Err(_) => log::error!("[shutdown] output-device release task panicked"),
|
||||
}
|
||||
}
|
||||
|
||||
// Final full snapshot. QConnect teardown MUST precede this write: a
|
||||
// delegated queue is ephemeral and may never become the owner's saved
|
||||
// session. If bounded teardown failed, preserving the previous saved
|
||||
|
||||
@@ -51,7 +51,7 @@ type Runtime = Arc<AppRuntime<LoggingAdapter>>;
|
||||
pub type QtDelegationCoordinator = DelegationCoordinator<QtDelegationHost>;
|
||||
|
||||
const SHUTDOWN_RESTORE_OWNER: u8 = 0;
|
||||
const SHUTDOWN_DISCARD_OWNER: u8 = 1;
|
||||
const SHUTDOWN_RESTORE_QUEUE_ONLY: u8 = 1;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct OwnerSnapshot {
|
||||
@@ -277,7 +277,7 @@ impl QtDelegationHost {
|
||||
if restore {
|
||||
SHUTDOWN_RESTORE_OWNER
|
||||
} else {
|
||||
SHUTDOWN_DISCARD_OWNER
|
||||
SHUTDOWN_RESTORE_QUEUE_ONLY
|
||||
},
|
||||
Ordering::Release,
|
||||
);
|
||||
@@ -874,8 +874,10 @@ impl DelegationHost for QtDelegationHost {
|
||||
{
|
||||
self.restore_owner_snapshot().await
|
||||
} else if was_delegated || has_owner_snapshot {
|
||||
// Process exit still restores the owner's queue for persistence,
|
||||
// but must never schedule audible playback or reopen the DAC.
|
||||
let _ = self.runtime.core().stop();
|
||||
recover_lock(&self.owner_snapshot).take();
|
||||
let _ = self.restore_owner_snapshot().await;
|
||||
None
|
||||
} else {
|
||||
// A pending candidate may have captured a snapshot, but disabling an
|
||||
|
||||
@@ -2597,6 +2597,11 @@ impl QtQconnectService {
|
||||
self.disconnect_safely().await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Process exit restores ownership bookkeeping, never audible playback.
|
||||
pub async fn disconnect_for_shutdown(&self) -> Result<(), String> {
|
||||
self.disconnect_with_owner_policy(false).await.map(|_| ())
|
||||
}
|
||||
|
||||
pub async fn disconnect_safely(&self) -> Result<QconnectDisconnectOutcome, String> {
|
||||
self.disconnect_with_owner_policy(true).await
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user