diff --git a/src/host/wasapi/stream.rs b/src/host/wasapi/stream.rs index 20f6c2b..4b63d30 100644 --- a/src/host/wasapi/stream.rs +++ b/src/host/wasapi/stream.rs @@ -8,7 +8,10 @@ use std::{ mem, os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}, ptr, - sync::mpsc::{channel, Receiver, Sender}, + sync::{ + mpsc::{channel, Receiver, Sender}, + Arc, + }, thread::{self, JoinHandle}, }; 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()` // method can be notified. - pending_scheduled_event: OwnedHandle, + pending_scheduled_event: Arc, } struct RunContext { @@ -45,6 +48,9 @@ struct RunContext { handles: Vec, commands: Receiver, + + // Keep the event alive if Stream is dropped inside its own callback. + _pending_scheduled_event: Arc, } // 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())) } .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 run_context = RunContext { handles: vec![pending_scheduled_event, stream_inner.event], stream: stream_inner, commands: rx, + _pending_scheduled_event: Arc::clone(&owned_event), }; let thread = thread::Builder::new() @@ -131,13 +139,15 @@ 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 owned_event = + Arc::new(unsafe { OwnedHandle::from_raw_handle(pending_scheduled_event.0 as _) }); let (tx, rx) = channel(); let run_context = RunContext { handles: vec![pending_scheduled_event, stream_inner.event], stream: stream_inner, commands: rx, + _pending_scheduled_event: Arc::clone(&owned_event), }; let thread = thread::Builder::new() @@ -173,7 +183,7 @@ impl Drop for Stream { eprintln!("cpal: WASAPI termination notification failed: {error}"); } 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"); } } diff --git a/src/host/wasapi/stream_lifecycle_tests.rs b/src/host/wasapi/stream_lifecycle_tests.rs index 50c488e..3b1ba7b 100644 --- a/src/host/wasapi/stream_lifecycle_tests.rs +++ b/src/host/wasapi/stream_lifecycle_tests.rs @@ -46,7 +46,7 @@ fn stream(exit: WorkerExit) -> (Stream, CString) { Stream { thread: Some(worker), commands: tx, - pending_scheduled_event: owned_event, + pending_scheduled_event: Arc::new(owned_event), }, name, ) @@ -95,6 +95,45 @@ const CALLBACK_TIMEOUT: Duration = Duration::from_secs(3); const POLL_INTERVAL: Duration = Duration::from_millis(10); 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::(); + 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 { let mut count = 0; unsafe { Threading::GetProcessHandleCount(Threading::GetCurrentProcess(), &mut count) }