fix(wasapi): release command events after worker exit

This commit is contained in:
fufesou 2026-09-12 18:09:47 +08:00
parent 69ad2578ad
commit 20fc4e430e
2 changed files with 184 additions and 19 deletions

View file

@ -4,16 +4,23 @@ use crate::{
BackendSpecificError, Data, InputCallbackInfo, OutputCallbackInfo, PauseStreamError,
PlayStreamError, SampleFormat, StreamError,
};
use std::mem;
use std::ptr;
use std::sync::mpsc::{channel, Receiver, SendError, Sender};
use std::thread::{self, JoinHandle};
use std::{
mem,
os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle},
ptr,
sync::mpsc::{channel, Receiver, Sender},
thread::{self, JoinHandle},
};
use windows::Win32::Foundation;
use windows::Win32::Foundation::WAIT_OBJECT_0;
use windows::Win32::Media::Audio;
use windows::Win32::System::SystemServices;
use windows::Win32::System::Threading;
#[cfg(test)]
#[path = "stream_lifecycle_tests.rs"]
mod lifecycle_tests;
pub struct Stream {
/// The high-priority audio processing thread calling callbacks.
/// Option used for moving out in destructor.
@ -26,7 +33,7 @@ pub struct Stream {
// This event is signalled after a new entry is added to `commands`, so that the `run()`
// method can be notified.
pending_scheduled_event: Foundation::HANDLE,
pending_scheduled_event: OwnedHandle,
}
struct RunContext {
@ -90,6 +97,7 @@ impl Stream {
Threading::CreateEventA(None, false, false, windows::core::PCSTR(ptr::null()))
}
.expect("cpal: could not create input stream event");
let owned_event = unsafe { OwnedHandle::from_raw_handle(pending_scheduled_event.0 as _) };
let (tx, rx) = channel();
let run_context = RunContext {
@ -106,7 +114,7 @@ impl Stream {
Stream {
thread: Some(thread),
commands: tx,
pending_scheduled_event,
pending_scheduled_event: owned_event,
}
}
@ -123,6 +131,7 @@ impl Stream {
Threading::CreateEventA(None, false, false, windows::core::PCSTR(ptr::null()))
}
.expect("cpal: could not create output stream event");
let owned_event = unsafe { OwnedHandle::from_raw_handle(pending_scheduled_event.0 as _) };
let (tx, rx) = channel();
let run_context = RunContext {
@ -139,27 +148,33 @@ impl Stream {
Stream {
thread: Some(thread),
commands: tx,
pending_scheduled_event,
pending_scheduled_event: owned_event,
}
}
#[inline]
fn push_command(&self, command: Command) -> Result<(), SendError<Command>> {
self.commands.send(command)?;
fn push_command(&self, command: Command) -> Result<(), StreamError> {
self.commands
.send(command)
.map_err(|_| StreamError::DeviceNotAvailable)?;
unsafe {
Threading::SetEvent(self.pending_scheduled_event).unwrap();
Threading::SetEvent(Foundation::HANDLE(
self.pending_scheduled_event.as_raw_handle() as _,
))
}
Ok(())
.map_err(windows_err_to_cpal_err)
}
}
impl Drop for Stream {
#[inline]
fn drop(&mut self) {
if self.push_command(Command::Terminate).is_ok() {
self.thread.take().unwrap().join().unwrap();
unsafe {
let _ = Foundation::CloseHandle(self.pending_scheduled_event);
if let Err(error) = self.push_command(Command::Terminate) {
eprintln!("cpal: WASAPI termination notification failed: {error}");
}
if let Some(thread) = self.thread.take() {
if thread.join().is_err() {
eprintln!("cpal: WASAPI worker panicked during stream processing");
}
}
}
@ -168,13 +183,21 @@ impl Drop for Stream {
impl StreamTrait for Stream {
fn play(&self) -> Result<(), PlayStreamError> {
self.push_command(Command::PlayStream)
.map_err(|_| crate::error::PlayStreamError::DeviceNotAvailable)?;
Ok(())
.map_err(|error| match error {
StreamError::DeviceNotAvailable => PlayStreamError::DeviceNotAvailable,
StreamError::BackendSpecific { err } | StreamError::StreamInterrupted { err } => {
PlayStreamError::BackendSpecific { err }
}
})
}
fn pause(&self) -> Result<(), PauseStreamError> {
self.push_command(Command::PauseStream)
.map_err(|_| crate::error::PauseStreamError::DeviceNotAvailable)?;
Ok(())
.map_err(|error| match error {
StreamError::DeviceNotAvailable => PauseStreamError::DeviceNotAvailable,
StreamError::BackendSpecific { err } | StreamError::StreamInterrupted { err } => {
PauseStreamError::BackendSpecific { err }
}
})
}
}

View file

@ -0,0 +1,142 @@
use super::*;
use crate::traits::{DeviceTrait, HostTrait};
use std::time::{Duration, Instant};
const WORKER_DEADLINE: Duration = Duration::from_secs(2);
enum WorkerExit {
Termination,
Finished,
Panicked,
}
fn stream(exit: WorkerExit) -> (Stream, Foundation::HANDLE) {
let event =
unsafe { Threading::CreateEventA(None, false, false, windows::core::PCSTR(ptr::null())) }
.unwrap();
let (tx, rx) = channel();
let wait_for_exit = !matches!(exit, WorkerExit::Termination);
let worker = thread::spawn(move || match exit {
WorkerExit::Termination => assert!(matches!(rx.recv().unwrap(), Command::Terminate)),
WorkerExit::Finished => drop(rx),
WorkerExit::Panicked => {
drop(rx);
panic!("Injected worker failure");
}
});
if wait_for_exit {
let deadline = Instant::now() + WORKER_DEADLINE;
while !worker.is_finished() {
assert!(Instant::now() < deadline, "Worker failed to exit");
thread::yield_now();
}
}
let owned_event = unsafe { OwnedHandle::from_raw_handle(event.0 as _) };
(
Stream {
thread: Some(worker),
commands: tx,
pending_scheduled_event: owned_event,
},
event,
)
}
fn assert_event_closed(exit: WorkerExit) {
let (stream, event) = stream(exit);
let mut flags = 0;
unsafe { Foundation::GetHandleInformation(event, &mut flags) }.unwrap();
drop(stream);
assert!(
unsafe { Foundation::GetHandleInformation(event, &mut flags) }.is_err(),
"Stream destruction leaked its command event"
);
}
#[test]
fn normal_shutdown_closes_command_event() {
assert_event_closed(WorkerExit::Termination);
}
#[test]
fn completed_worker_still_closes_command_event() {
assert_event_closed(WorkerExit::Finished);
}
#[test]
fn panicked_worker_does_not_panic_in_drop_or_leak_event() {
assert_event_closed(WorkerExit::Panicked);
}
const WARMUP_CYCLES: usize = 4;
const MEASURED_CYCLES: usize = 16;
const CALLBACK_TIMEOUT: Duration = Duration::from_secs(3);
const POLL_INTERVAL: Duration = Duration::from_millis(10);
const SETTLE_TIME: Duration = Duration::from_millis(100);
fn handle_count() -> u32 {
let mut count = 0;
unsafe { Threading::GetProcessHandleCount(Threading::GetCurrentProcess(), &mut count) }
.unwrap();
count
}
fn native_cycle(worker_exits_first: bool) {
let host = crate::default_host();
let device = host.default_output_device().unwrap();
let supported = device.default_output_config().unwrap();
assert_eq!(supported.sample_format(), SampleFormat::F32);
let (tx, rx) = channel();
let output = device
.build_output_stream(
&supported.into(),
move |data: &mut [f32], _| {
data.fill(0.0);
tx.send(()).unwrap();
// Test-only fault injection exits the real WASAPI worker before Drop.
assert!(!worker_exits_first, "Injected native worker exit");
},
|error| eprintln!("Native callback error: {error}"),
None,
)
.unwrap();
output.play().unwrap();
rx.recv_timeout(CALLBACK_TIMEOUT).unwrap();
if worker_exits_first {
let deadline = Instant::now() + CALLBACK_TIMEOUT;
while output.play().is_ok() {
assert!(Instant::now() < deadline, "Worker receiver did not close");
thread::sleep(POLL_INTERVAL);
}
}
drop(output);
thread::sleep(SETTLE_TIME);
}
fn measured_cycles(worker_exits_first: bool) -> Vec<u32> {
let mut counts = vec![handle_count()];
for _ in 0..MEASURED_CYCLES {
native_cycle(worker_exits_first);
counts.push(handle_count());
}
counts
}
#[test]
#[ignore = "Requires a native F32 output device; run alone with a 60-second process deadline"]
fn native_worker_exit_does_not_leak_process_handles() {
for _ in 0..WARMUP_CYCLES {
native_cycle(false);
}
let normal_before = measured_cycles(false);
let exited_first = measured_cycles(true);
let normal_after = measured_cycles(false);
eprintln!("normal_before={normal_before:?} worker_exits_first={exited_first:?} normal_after={normal_after:?}");
assert_eq!(normal_before.first(), normal_before.last());
assert_eq!(normal_after.first(), normal_after.last());
assert_eq!(
exited_first.first(),
exited_first.last(),
"Worker-exit-before-drop leaked native process handles"
);
}