fix(wasapi): align worker teardown with upstream lifetime handling

Adapt the self-join check and worker event lifetime from RustAudio/cpal#1187 (dccd6b464dc49267fa214ee168eb2b3c17a1ebf6). Keep shared OwnedHandle ownership so command submission also retains a valid event. Verify callback-thread destruction with a real WASAPI regression.
This commit is contained in:
fufesou 2026-09-12 22:11:39 +08:00
parent 2738d2077a
commit a9fae8fac6
2 changed files with 55 additions and 6 deletions

View file

@ -8,7 +8,10 @@ use std::{
mem, mem,
os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}, os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle},
ptr, ptr,
sync::mpsc::{channel, Receiver, Sender}, sync::{
mpsc::{channel, Receiver, Sender},
Arc,
},
thread::{self, JoinHandle}, thread::{self, JoinHandle},
}; };
use windows::Win32::Foundation; use windows::Win32::Foundation;
@ -33,7 +36,7 @@ pub struct Stream {
// This event is signalled after a new entry is added to `commands`, so that the `run()` // This event is signalled after a new entry is added to `commands`, so that the `run()`
// method can be notified. // method can be notified.
pending_scheduled_event: OwnedHandle, pending_scheduled_event: Arc<OwnedHandle>,
} }
struct RunContext { struct RunContext {
@ -45,6 +48,9 @@ struct RunContext {
handles: Vec<Foundation::HANDLE>, handles: Vec<Foundation::HANDLE>,
commands: Receiver<Command>, commands: Receiver<Command>,
// Keep the event alive if Stream is dropped inside its own callback.
_pending_scheduled_event: Arc<OwnedHandle>,
} }
// Once we start running the eventloop, the RunContext will not be moved. // Once we start running the eventloop, the RunContext will not be moved.
@ -97,13 +103,15 @@ impl Stream {
Threading::CreateEventA(None, false, false, windows::core::PCSTR(ptr::null())) Threading::CreateEventA(None, false, false, windows::core::PCSTR(ptr::null()))
} }
.expect("cpal: could not create input stream event"); .expect("cpal: could not create input stream event");
let owned_event = unsafe { OwnedHandle::from_raw_handle(pending_scheduled_event.0 as _) }; let owned_event =
Arc::new(unsafe { OwnedHandle::from_raw_handle(pending_scheduled_event.0 as _) });
let (tx, rx) = channel(); let (tx, rx) = channel();
let run_context = RunContext { let run_context = RunContext {
handles: vec![pending_scheduled_event, stream_inner.event], handles: vec![pending_scheduled_event, stream_inner.event],
stream: stream_inner, stream: stream_inner,
commands: rx, commands: rx,
_pending_scheduled_event: Arc::clone(&owned_event),
}; };
let thread = thread::Builder::new() let thread = thread::Builder::new()
@ -131,13 +139,15 @@ impl Stream {
Threading::CreateEventA(None, false, false, windows::core::PCSTR(ptr::null())) Threading::CreateEventA(None, false, false, windows::core::PCSTR(ptr::null()))
} }
.expect("cpal: could not create output stream event"); .expect("cpal: could not create output stream event");
let owned_event = unsafe { OwnedHandle::from_raw_handle(pending_scheduled_event.0 as _) }; let owned_event =
Arc::new(unsafe { OwnedHandle::from_raw_handle(pending_scheduled_event.0 as _) });
let (tx, rx) = channel(); let (tx, rx) = channel();
let run_context = RunContext { let run_context = RunContext {
handles: vec![pending_scheduled_event, stream_inner.event], handles: vec![pending_scheduled_event, stream_inner.event],
stream: stream_inner, stream: stream_inner,
commands: rx, commands: rx,
_pending_scheduled_event: Arc::clone(&owned_event),
}; };
let thread = thread::Builder::new() let thread = thread::Builder::new()
@ -173,7 +183,7 @@ impl Drop for Stream {
eprintln!("cpal: WASAPI termination notification failed: {error}"); eprintln!("cpal: WASAPI termination notification failed: {error}");
} }
if let Some(thread) = self.thread.take() { if let Some(thread) = self.thread.take() {
if thread.join().is_err() { if thread.thread().id() != thread::current().id() && thread.join().is_err() {
eprintln!("cpal: WASAPI worker panicked during stream processing"); eprintln!("cpal: WASAPI worker panicked during stream processing");
} }
} }

View file

@ -46,7 +46,7 @@ fn stream(exit: WorkerExit) -> (Stream, CString) {
Stream { Stream {
thread: Some(worker), thread: Some(worker),
commands: tx, commands: tx,
pending_scheduled_event: owned_event, pending_scheduled_event: Arc::new(owned_event),
}, },
name, name,
) )
@ -95,6 +95,45 @@ const CALLBACK_TIMEOUT: Duration = Duration::from_secs(3);
const POLL_INTERVAL: Duration = Duration::from_millis(10); const POLL_INTERVAL: Duration = Duration::from_millis(10);
const SETTLE_TIME: Duration = Duration::from_millis(100); const SETTLE_TIME: Duration = Duration::from_millis(100);
#[test]
#[ignore = "Requires a native F32 output device; run alone with a 60-second process deadline"]
fn native_callback_can_drop_stream_before_worker_exit() {
let host = crate::host::wasapi::Host::new().unwrap();
let device = host.default_output_device().unwrap();
let supported = device.default_output_config().unwrap();
assert_eq!(supported.sample_format(), SampleFormat::F32);
let (stream_tx, stream_rx) = channel::<Stream>();
let (result_tx, result_rx) = channel();
let output = device
.build_output_stream(
&supported.into(),
move |data: &mut [f32], _| {
data.fill(0.0);
let output = stream_rx.recv_timeout(CALLBACK_TIMEOUT).unwrap();
let event = Foundation::HANDLE(output.pending_scheduled_event.as_raw_handle() as _);
drop(output);
// The worker still needs its command event after this callback returns.
result_tx
.send(unsafe { Threading::SetEvent(event) })
.unwrap();
},
|error| eprintln!("Native callback error: {error}"),
None,
)
.unwrap();
output.play().unwrap();
stream_tx.send(output).unwrap();
result_rx
.recv_timeout(CALLBACK_TIMEOUT)
.expect("Stream destruction blocked inside its own callback")
.expect("Stream destruction closed the live worker's command event");
assert_eq!(
result_rx.recv_timeout(CALLBACK_TIMEOUT),
Err(std::sync::mpsc::RecvTimeoutError::Disconnected),
"Worker did not exit after callback-thread destruction"
);
}
fn handle_count() -> u32 { fn handle_count() -> u32 {
let mut count = 0; let mut count = 0;
unsafe { Threading::GetProcessHandleCount(Threading::GetCurrentProcess(), &mut count) } unsafe { Threading::GetProcessHandleCount(Threading::GetCurrentProcess(), &mut count) }