From 400dc76c55f818450cda6c7418a5145df15d2b00 Mon Sep 17 00:00:00 2001 From: Danny Ward Date: Sat, 24 Oct 2026 16:27:11 -0400 Subject: [PATCH 1/6] fix(wasapi): initialize notification threads as MTA --- src/host/com.rs | 64 +++++++++++++++++++++++++-------------- src/host/wasapi/device.rs | 20 ++++++++---- src/host/wasapi/stream.rs | 43 +++++++++++++++++++++++--- 3 files changed, 95 insertions(+), 32 deletions(-) diff --git a/src/host/com.rs b/src/host/com.rs index 2e9781760..70c391713 100644 --- a/src/host/com.rs +++ b/src/host/com.rs @@ -4,31 +4,18 @@ use std::{io::Error as IoError, marker::PhantomData}; use windows::Win32::{ Foundation::RPC_E_CHANGED_MODE, - System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx, CoTaskMemFree, CoUninitialize}, + System::Com::{ + COINIT, COINIT_APARTMENTTHREADED, COINIT_MULTITHREADED, CoInitializeEx, CoTaskMemFree, + CoUninitialize, + }, }; thread_local!(static COM_INITIALIZED: ComInitialized = { - unsafe { - // Try to initialize COM with STA by default to avoid compatibility issues with the ASIO - // backend (where CoInitialize() is called by the ASIO SDK) or winit (where drag and drop - // requires STA). - // This call can fail with RPC_E_CHANGED_MODE if another library initialized COM with MTA. - // That's OK though since COM ensures thread-safety/compatibility through marshalling when - // necessary. - let result = CoInitializeEx(None, COINIT_APARTMENTTHREADED); - if result.is_ok() || result == RPC_E_CHANGED_MODE { - ComInitialized { - result, - _ptr: PhantomData, - } - } else { - // COM initialization failed in another way, something is really wrong. - panic!( - "Failed to initialize COM: {}", - IoError::from_raw_os_error(result.0) - ); - } - } + ComInitialized::new(COINIT_APARTMENTTHREADED) +}); + +thread_local!(static COM_INITIALIZED_MTA: ComInitialized = { + ComInitialized::new(COINIT_MULTITHREADED) }); /// RAII object that guards the fact that COM is initialized. @@ -50,6 +37,28 @@ impl Drop for ComInitialized { } } +impl ComInitialized { + fn new(concurrency_model: COINIT) -> Self { + unsafe { + // This can fail with RPC_E_CHANGED_MODE if another library initialized COM with a + // different model. That's OK: COM is already initialized on this thread. + let result = CoInitializeEx(None, concurrency_model); + if result.is_ok() || result == RPC_E_CHANGED_MODE { + ComInitialized { + result, + _ptr: PhantomData, + } + } else { + // COM initialization failed in another way, something is really wrong. + panic!( + "Failed to initialize COM: {}", + IoError::from_raw_os_error(result.0) + ); + } + } + } +} + /// RAII wrapper for COM-allocated wide strings freed with `CoTaskMemFree`. pub(super) struct ComString(pub windows::core::PWSTR); @@ -61,5 +70,16 @@ impl Drop for ComString { /// Ensures that COM is initialized in this thread. pub fn com_initialized() { + // Try to initialize COM as an STA by default to avoid compatibility issues with the ASIO + // backend or UI frameworks such as winit. A thread already initialized as MTA keeps that + // model when CoInitializeEx returns RPC_E_CHANGED_MODE. COM_INITIALIZED.with(|_| {}); } + +/// Ensures COM is initialized with the multithreaded apartment on this thread. +/// +/// Use this for system-managed worker threads so they do not become STAs, which are incompatible +/// with Windows thread pools. +pub fn com_initialized_mta() { + COM_INITIALIZED_MTA.with(|_| {}); +} diff --git a/src/host/wasapi/device.rs b/src/host/wasapi/device.rs index 85290fe85..f5fa3c6ef 100644 --- a/src/host/wasapi/device.rs +++ b/src/host/wasapi/device.rs @@ -555,6 +555,7 @@ impl Device { DeviceHandle::DefaultInput => Audio::eCapture, DeviceHandle::Specific(_) => return Ok(None), }; + com::com_initialized(); let enumerator = get_enumerator() .context("Failed to get device enumerator")? .0 @@ -1165,9 +1166,17 @@ static ENUMERATOR: OnceLock> = OnceLock /// Shared by [`Device::immdevice`] and the stream-side `get_current_default` helper to /// avoid duplicating the `GetDefaultAudioEndpoint` call. pub(super) fn current_default_endpoint(flow: Audio::EDataFlow) -> Option { - // Ensure COM is initialised on this thread — callers include notification callbacks on - // threads that may not have called CoInitialize themselves. com::com_initialized(); + current_default_endpoint_inner(flow) +} + +/// Returns the current default endpoint when called from a worker initialized as MTA. +pub(super) fn current_default_endpoint_on_mta(flow: Audio::EDataFlow) -> Option { + com::com_initialized_mta(); + current_default_endpoint_inner(flow) +} + +fn current_default_endpoint_inner(flow: Audio::EDataFlow) -> Option { // SAFETY: `get_enumerator()` is a thread-safe singleton initialised at first use. unsafe { get_enumerator() @@ -1181,12 +1190,10 @@ pub(super) fn current_default_endpoint(flow: Audio::EDataFlow) -> Option Result<&'static Enumerator, windows::core::Error> { ENUMERATOR .get_or_init(|| { - // COM initialization is thread local, but we only need to have COM initialized in the - // thread we create the objects in - com::com_initialized(); - // SAFETY: `MMDeviceEnumerator` is a well-known in-process COM class; the returned // interface pointer is only read through the safe `IMMDeviceEnumerator` wrapper. + // Callers initialize COM with the apartment appropriate for their thread before + // reaching this function. unsafe { Com::CoCreateInstance::<_, Audio::IMMDeviceEnumerator>( &Audio::MMDeviceEnumerator, @@ -1276,6 +1283,7 @@ pub struct Devices { impl Devices { pub fn new() -> Result { + com::com_initialized(); unsafe { // can fail because of wrong parameters (should never happen) or out of memory let collection = get_enumerator() diff --git a/src/host/wasapi/stream.rs b/src/host/wasapi/stream.rs index 80169fd71..b4c357c5b 100644 --- a/src/host/wasapi/stream.rs +++ b/src/host/wasapi/stream.rs @@ -32,7 +32,7 @@ use crate::{ /// When a replacement *does* exist this returns `Some` and we skip signalling, letting /// `OnDefaultDeviceChanged` fire as the sole notifier and avoiding a double wakeup. fn get_current_default(flow: Audio::EDataFlow) -> Option { - super::device::current_default_endpoint(flow) + super::device::current_default_endpoint_on_mta(flow) } /// Fires a Windows auto-reset event when the system default audio device changes. @@ -84,9 +84,9 @@ impl DefaultDeviceMonitor { impl Drop for DefaultDeviceMonitor { fn drop(&mut self) { - // Ensure COM is initialised on this thread before making COM calls. Drop can run on - // any thread (e.g. the audio run thread), which may not have called CoInitialize. - crate::host::com::com_initialized(); + // Drop can run on any thread. Use MTA so dropping a stream on a long-lived worker does not + // turn that thread into an STA. + crate::host::com::com_initialized_mta(); unsafe { // Synchronous: waits for any in-progress IMMNotificationClient callback to finish // before returning. Notification callbacks must not invoke the user error callback: @@ -1115,3 +1115,38 @@ fn output_timestamp( device: playback, }) } + +#[cfg(test)] +mod tests { + use super::{Audio, get_current_default}; + use windows::Win32::{ + Foundation::CO_E_NOTINITIALIZED, + System::Com::{APTTYPE, APTTYPE_STA, APTTYPEQUALIFIER, CoGetApartmentType}, + }; + + #[test] + fn default_endpoint_query_does_not_turn_worker_thread_into_sta() { + std::thread::spawn(|| { + let mut apartment_type = APTTYPE(-1); + let mut apartment_qualifier = APTTYPEQUALIFIER(0); + let before = + unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) }; + assert_eq!( + before.unwrap_err().code(), + CO_E_NOTINITIALIZED, + "test worker should start without COM initialized" + ); + + let _ = get_current_default(Audio::eRender); + + unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) } + .expect("default endpoint query should initialize COM"); + assert_ne!( + apartment_type, APTTYPE_STA, + "default endpoint query must not initialize a worker as an STA" + ); + }) + .join() + .expect("worker thread should complete"); + } +} From 8e9b48f6c42c0f7323fd1a26c9509de48c6b2b9f Mon Sep 17 00:00:00 2001 From: Danny Ward Date: Sat, 24 Oct 2026 23:50:23 -0400 Subject: [PATCH 2/6] fix(wasapi): keep endpoint monitor apartment-local --- src/host/wasapi/device.rs | 65 ++--- src/host/wasapi/stream.rs | 553 ++++++++++++++++++++++++++++---------- 2 files changed, 446 insertions(+), 172 deletions(-) diff --git a/src/host/wasapi/device.rs b/src/host/wasapi/device.rs index f5fa3c6ef..9a35bda14 100644 --- a/src/host/wasapi/device.rs +++ b/src/host/wasapi/device.rs @@ -129,9 +129,9 @@ impl DeviceTrait for Device { D: FnMut(&Data, &CallbackInfo) + Send + 'static, E: FnMut(Error) + Send + 'static, { + let monitor = self.default_device_monitor()?; let stream_inner = self.build_input_stream_raw_inner(config, sample_format, timeout)?; let error_callback: ErrorCallbackArc = Arc::new(Mutex::new(error_callback)); - let monitor = self.default_device_monitor()?; let stream = Stream::new_input(stream_inner, data_callback, error_callback, monitor)?; stream.signal_ready(); Ok(stream) @@ -152,9 +152,9 @@ impl DeviceTrait for Device { // Keep `playback` monotonic: an underrun can saturate `buffered` to zero, pulling // `playback` backward. let data_callback = crate::host::monotonic_output_callback(data_callback); + let monitor = self.default_device_monitor()?; let stream_inner = self.build_output_stream_raw_inner(config, sample_format, timeout)?; let error_callback: ErrorCallbackArc = Arc::new(Mutex::new(error_callback)); - let monitor = self.default_device_monitor()?; let stream = Stream::new_output(stream_inner, data_callback, error_callback, monitor)?; stream.signal_ready(); Ok(stream) @@ -555,12 +555,7 @@ impl Device { DeviceHandle::DefaultInput => Audio::eCapture, DeviceHandle::Specific(_) => return Ok(None), }; - com::com_initialized(); - let enumerator = get_enumerator() - .context("Failed to get device enumerator")? - .0 - .clone(); - DefaultDeviceMonitor::new(enumerator, flow).map(Some) + DefaultDeviceMonitor::new(flow).map(Some) } /// Ensures that `future_audio_client` contains a `Some` and returns a locked mutex to it. @@ -1162,26 +1157,37 @@ impl Endpoint { static ENUMERATOR: OnceLock> = OnceLock::new(); /// Returns the current default audio endpoint for `flow`, or `None` if none exists. -/// -/// Shared by [`Device::immdevice`] and the stream-side `get_current_default` helper to -/// avoid duplicating the `GetDefaultAudioEndpoint` call. pub(super) fn current_default_endpoint(flow: Audio::EDataFlow) -> Option { - com::com_initialized(); - current_default_endpoint_inner(flow) + // These queries can be made from Windows-managed thread-pool callbacks. Initialize a free + // thread as MTA so a persistent pool thread is not changed into an STA. CoInitializeEx + // returns RPC_E_CHANGED_MODE for an existing STA, which remains unchanged for UI callers. + com::com_initialized_mta(); + let enumerator = create_enumerator().ok()?; + current_default_endpoint_with(&enumerator, flow) } -/// Returns the current default endpoint when called from a worker initialized as MTA. -pub(super) fn current_default_endpoint_on_mta(flow: Audio::EDataFlow) -> Option { - com::com_initialized_mta(); - current_default_endpoint_inner(flow) +/// Creates an enumerator for use on the calling thread. +/// +/// The caller must keep the interface on the same COM apartment for its entire lifetime. +pub(super) fn create_enumerator() -> Result { + // SAFETY: `MMDeviceEnumerator` is a well-known in-process COM class. + unsafe { + Com::CoCreateInstance::<_, Audio::IMMDeviceEnumerator>( + &Audio::MMDeviceEnumerator, + None, + Com::CLSCTX_ALL, + ) + } } -fn current_default_endpoint_inner(flow: Audio::EDataFlow) -> Option { - // SAFETY: `get_enumerator()` is a thread-safe singleton initialised at first use. +/// Returns the current default endpoint using an enumerator owned by the caller's apartment. +pub(super) fn current_default_endpoint_with( + enumerator: &Audio::IMMDeviceEnumerator, + flow: Audio::EDataFlow, +) -> Option { + // SAFETY: the enumerator is valid and owned by the caller's COM apartment. unsafe { - get_enumerator() - .ok()? - .0 + enumerator .GetDefaultAudioEndpoint(flow, Audio::eConsole) .ok() } @@ -1189,20 +1195,7 @@ fn current_default_endpoint_inner(flow: Audio::EDataFlow) -> Option Result<&'static Enumerator, windows::core::Error> { ENUMERATOR - .get_or_init(|| { - // SAFETY: `MMDeviceEnumerator` is a well-known in-process COM class; the returned - // interface pointer is only read through the safe `IMMDeviceEnumerator` wrapper. - // Callers initialize COM with the apartment appropriate for their thread before - // reaching this function. - unsafe { - Com::CoCreateInstance::<_, Audio::IMMDeviceEnumerator>( - &Audio::MMDeviceEnumerator, - None, - Com::CLSCTX_ALL, - ) - } - .map(Enumerator) - }) + .get_or_init(|| create_enumerator().map(Enumerator)) .as_ref() .map_err(Clone::clone) } diff --git a/src/host/wasapi/stream.rs b/src/host/wasapi/stream.rs index b4c357c5b..97c1e94fe 100644 --- a/src/host/wasapi/stream.rs +++ b/src/host/wasapi/stream.rs @@ -4,7 +4,7 @@ use std::{ ptr, slice, sync::{ Arc, - atomic::{AtomicBool, AtomicU64, Ordering}, + atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}, mpsc::{Receiver, Sender, channel}, }, thread::{self, JoinHandle}, @@ -24,94 +24,241 @@ use crate::{ traits::StreamTrait, }; -/// Returns the current default audio endpoint for `flow`, or `None` if none exists. +const DEVICE_ERROR_NONE: u8 = 0; +const DEVICE_ERROR_NOT_AVAILABLE: u8 = 1; +const DEVICE_ERROR_CHANGED: u8 = 2; + +/// A kernel event whose lifetime is shared by the monitor and the audio run loop. /// -/// Used by `OnDeviceStateChanged` and `OnDeviceRemoved` to cover the edge case where the -/// default device becomes unavailable with no replacement: in that situation Windows does -/// not fire `OnDefaultDeviceChanged`, so these callbacks must signal the run loop instead. -/// When a replacement *does* exist this returns `Some` and we skip signalling, letting -/// `OnDefaultDeviceChanged` fire as the sole notifier and avoiding a double wakeup. -fn get_current_default(flow: Audio::EDataFlow) -> Option { - super::device::current_default_endpoint_on_mta(flow) +/// The audio loop can outlive `DefaultDeviceMonitor` when a stream is dropped from one of its +/// callbacks. Store the opaque handle as an integer so the shared owner is `Send + Sync`; event +/// handles can be signalled and waited on from any thread. +struct MonitorEvent(usize); + +impl MonitorEvent { + fn new(handle: Foundation::HANDLE) -> Self { + Self(handle.0 as usize) + } + + fn handle(&self) -> Foundation::HANDLE { + Foundation::HANDLE(self.0 as *mut std::ffi::c_void) + } +} + +impl Drop for MonitorEvent { + fn drop(&mut self) { + unsafe { + let _ = Foundation::CloseHandle(self.handle()); + } + } } /// Fires a Windows auto-reset event when the system default audio device changes. pub(crate) struct DefaultDeviceMonitor { - enumerator: Audio::IMMDeviceEnumerator, - client: Audio::IMMNotificationClient, - event: Foundation::HANDLE, - pub(crate) flow: Audio::EDataFlow, - pub(crate) pending_device_changed: Arc, + stop_event: Foundation::HANDLE, + worker: Option>, + event: Arc, + pending_device_error: Arc, } -// SAFETY: `IMMDeviceEnumerator` and `IMMNotificationClient` are COM objects used only for -// register/unregister (in new/drop) and `SetEvent` (from the Windows notification thread). -// All of these are thread-safe operations on Windows. -unsafe impl Send for DefaultDeviceMonitor {} -unsafe impl Sync for DefaultDeviceMonitor {} - impl DefaultDeviceMonitor { - pub fn new( - enumerator: Audio::IMMDeviceEnumerator, - flow: Audio::EDataFlow, - ) -> Result { - let event = - unsafe { Threading::CreateEventW(None, false, false, None).map_err(Error::from)? }; + pub fn new(flow: Audio::EDataFlow) -> Result { + let event = Arc::new(MonitorEvent::new(unsafe { + Threading::CreateEventW(None, false, false, None).map_err(Error::from)? + })); + let notification_event = match unsafe { Threading::CreateEventW(None, false, false, None) } + { + Ok(event) => event, + Err(error) => { + drop(event); + return Err(Error::from(error)); + } + }; + let notification_event = Arc::new(MonitorEvent::new(notification_event)); + let stop_event = match unsafe { Threading::CreateEventW(None, false, false, None) } { + Ok(event) => event, + Err(error) => { + drop(event); + drop(notification_event); + return Err(Error::from(error)); + } + }; + let pending_default_changed = Arc::new(AtomicBool::new(false)); + let pending_device_error = Arc::new(AtomicU8::new(DEVICE_ERROR_NONE)); + let worker_pending_default_changed = pending_default_changed.clone(); + let worker_pending_device_error = pending_device_error.clone(); + // `HANDLE` is an opaque, thread-safe kernel handle, but the windows crate models it as a + // raw pointer and therefore does not implement `Send`. Move its bit pattern as `usize`. + let event_handle = event.handle().0 as usize; + let stop_event_handle = stop_event.0 as usize; + let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel::>(1); + + let worker = match thread::Builder::new() + .name("cpal_wasapi_device_monitor".to_owned()) + .spawn(move || { + let event = Foundation::HANDLE(event_handle as *mut std::ffi::c_void); + let stop_event = Foundation::HANDLE(stop_event_handle as *mut std::ffi::c_void); + // Keep every IMMDeviceEnumerator call, including unregister, on the apartment + // that created the enumerator. Notification callbacks only signal an event. + crate::host::com::com_initialized_mta(); + let enumerator = match super::device::create_enumerator() { + Ok(enumerator) => enumerator, + Err(error) => { + let _ = ready_tx.send(Err(error.to_string())); + close_default_device_monitor_handles(stop_event); + return; + } + }; + let client: Audio::IMMNotificationClient = DefaultDeviceNotificationImpl { + flow, + notification_event: Arc::clone(¬ification_event), + pending_default_changed: worker_pending_default_changed, + } + .into(); + + if let Err(error) = + unsafe { enumerator.RegisterEndpointNotificationCallback(&client) } + { + let _ = ready_tx.send(Err(error.to_string())); + close_default_device_monitor_handles(stop_event); + return; + } - let pending_device_changed = Arc::new(AtomicBool::new(false)); - let client: Audio::IMMNotificationClient = DefaultDeviceNotificationImpl { - flow, - event, - pending_device_changed: pending_device_changed.clone(), - } - .into(); + if ready_tx.send(Ok(())).is_err() { + let unregistered = + unsafe { enumerator.UnregisterEndpointNotificationCallback(&client) } + .is_ok(); + close_default_device_monitor_handles_after_unregister( + Arc::clone(¬ification_event), + stop_event, + unregistered, + ); + return; + } - unsafe { - enumerator - .RegisterEndpointNotificationCallback(&client) - .map_err(Error::from)?; + let handles = [stop_event, notification_event.handle()]; + loop { + let result = unsafe { + Threading::WaitForMultipleObjectsEx( + &handles, + false, + Threading::INFINITE, + false, + ) + }; + if result == Foundation::WAIT_FAILED { + break; + } + + match (result.0 - Foundation::WAIT_OBJECT_0.0) as usize { + 0 => break, + 1 => { + let default_changed = + pending_default_changed.swap(false, Ordering::AcqRel); + let default_available = + super::device::current_default_endpoint_with(&enumerator, flow) + .is_some(); + if default_changed || !default_available { + let error = if default_available { + DEVICE_ERROR_CHANGED + } else { + DEVICE_ERROR_NOT_AVAILABLE + }; + worker_pending_device_error.store(error, Ordering::Release); + unsafe { + let _ = Threading::SetEvent(event); + } + } + } + _ => break, + } + } + + let unregistered = + unsafe { enumerator.UnregisterEndpointNotificationCallback(&client) }.is_ok(); + close_default_device_monitor_handles_after_unregister( + Arc::clone(¬ification_event), + stop_event, + unregistered, + ); + }) { + Ok(worker) => worker, + Err(error) => { + close_default_device_monitor_handles(stop_event); + return Err(Error::with_message( + ErrorKind::ResourceExhausted, + format!("Failed to create device notification thread: {error}"), + )); + } + }; + + match ready_rx.recv() { + Ok(Ok(())) => {} + Ok(Err(error)) => { + let _ = worker.join(); + return Err(Error::with_message( + ErrorKind::BackendError, + format!("Failed to register device notification callback: {error}"), + )); + } + Err(_) => { + let _ = worker.join(); + return Err(Error::with_message( + ErrorKind::BackendError, + "Device notification thread exited before registration completed", + )); + } } Ok(Self { - enumerator, - client, + stop_event, + worker: Some(worker), event, - flow, - pending_device_changed, + pending_device_error, }) } } +fn close_default_device_monitor_handles(stop_event: Foundation::HANDLE) { + unsafe { + let _ = Foundation::CloseHandle(stop_event); + } +} + +fn close_default_device_monitor_handles_after_unregister( + notification_event: Arc, + stop_event: Foundation::HANDLE, + unregistered: bool, +) { + if unregistered { + close_default_device_monitor_handles(stop_event); + } else { + // A failed unregister can leave callbacks in flight. Keep the callback event alive in + // case Windows still invokes the registered client after this worker exits. + std::mem::forget(notification_event); + unsafe { + let _ = Foundation::CloseHandle(stop_event); + } + } +} + impl Drop for DefaultDeviceMonitor { fn drop(&mut self) { - // Drop can run on any thread. Use MTA so dropping a stream on a long-lived worker does not - // turn that thread into an STA. - crate::host::com::com_initialized_mta(); unsafe { - // Synchronous: waits for any in-progress IMMNotificationClient callback to finish - // before returning. Notification callbacks must not invoke the user error callback: - // if the user dropped the Stream in response, this call would deadlock waiting for - // the in-progress callback. Instead, callbacks set `pending_device_changed` and - // the audio thread delivers the error on its next iteration. - // - // Only close the event handle on success; if unregister fails the callback may - // still hold a reference and could later call SetEvent on a closed/reused handle. - if self - .enumerator - .UnregisterEndpointNotificationCallback(&self.client) - .is_ok() - { - let _ = Foundation::CloseHandle(self.event); - } + let _ = Threading::SetEvent(self.stop_event); + } + if let Some(worker) = self.worker.take() { + let _ = worker.join(); } + // `event` remains open until the audio run loop drops its shared reference. } } #[windows::core::implement(Audio::IMMNotificationClient)] struct DefaultDeviceNotificationImpl { flow: Audio::EDataFlow, - event: Foundation::HANDLE, - pending_device_changed: Arc, + notification_event: Arc, + pending_default_changed: Arc, } impl Audio::IMMNotificationClient_Impl for DefaultDeviceNotificationImpl_Impl { @@ -122,12 +269,9 @@ impl Audio::IMMNotificationClient_Impl for DefaultDeviceNotificationImpl_Impl { _pwstrdefaultdeviceid: &windows::core::PCWSTR, ) -> windows::core::Result<()> { if flow == self.flow && role == Audio::eConsole { - // SAFETY: event handle is valid for the lifetime of DefaultDeviceMonitor, which - // outlives all uses of this HANDLE copy. + self.pending_default_changed.store(true, Ordering::Release); unsafe { - if Threading::SetEvent(self.event).is_err() { - self.pending_device_changed.store(true, Ordering::Relaxed); - } + let _ = Threading::SetEvent(self.notification_event.handle()); } } Ok(()) @@ -143,17 +287,14 @@ impl Audio::IMMNotificationClient_Impl for DefaultDeviceNotificationImpl_Impl { // `DEVICE_STATE_NOTPRESENT`: hardware absent; endpoint may persist as a ghost record. // `DEVICE_STATE_DISABLED`: device was manually disabled by the user. // - // Only signal when there is no replacement default; if one exists `OnDefaultDeviceChanged` - // will fire instead, avoiding a double wakeup. let is_unavailable = dwnewstate == Audio::DEVICE_STATE_DISABLED || dwnewstate == Audio::DEVICE_STATE_NOTPRESENT || dwnewstate == Audio::DEVICE_STATE_UNPLUGGED; - if is_unavailable && get_current_default(self.flow).is_none() { - // SAFETY: event handle is valid for the lifetime of DefaultDeviceMonitor. + if is_unavailable { + // The monitor thread checks for a replacement default without making COM calls from + // this Windows-managed callback thread. unsafe { - if Threading::SetEvent(self.event).is_err() { - self.pending_device_changed.store(true, Ordering::Relaxed); - } + let _ = Threading::SetEvent(self.notification_event.handle()); } } Ok(()) @@ -164,15 +305,10 @@ impl Audio::IMMNotificationClient_Impl for DefaultDeviceNotificationImpl_Impl { } fn OnDeviceRemoved(&self, _pwstrdeviceid: &windows::core::PCWSTR) -> windows::core::Result<()> { - // Only signal when there is no replacement default; if one exists `OnDefaultDeviceChanged` - // will fire instead, avoiding a double wakeup. - if get_current_default(self.flow).is_none() { - // SAFETY: event handle is valid for the lifetime of DefaultDeviceMonitor. - unsafe { - if Threading::SetEvent(self.event).is_err() { - self.pending_device_changed.store(true, Ordering::Relaxed); - } - } + // The monitor thread checks for a replacement default without making COM calls from this + // Windows-managed callback thread. + unsafe { + let _ = Threading::SetEvent(self.notification_event.handle()); } Ok(()) } @@ -208,8 +344,8 @@ pub struct Stream { // QueryPerformanceFrequency result, cached at construction (constant for the system lifetime). qpc_frequency: u64, - // Present for default-device streams. Dropped after the run thread joins, ensuring the - // HANDLE is not waited on when it is closed. + // Present for default-device streams. The monitor and run loop share the event owner, so a + // self-drop from a callback cannot close a handle the run loop is about to wait on. _default_device_monitor: Option, // Latch that ensures no callbacks fire before the caller receives the `Stream` handle. @@ -222,19 +358,14 @@ pub struct Stream { fill_usec: Arc, } -// SAFETY: All fields of Stream are Send: -// - Option>, Sender, u32, u64, Latch, -// Arc, Arc: all trivially Send -// - Foundation::HANDLE: Windows event HANDLEs are safe to send between threads -// (see https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createeventa) -// - Option: has its own unsafe impl Send +// SAFETY: Stream's event HANDLE is a kernel event that can be signalled from any thread. The +// default-device monitor uses a joined worker, atomic state, and an Arc-owned event handle; the +// run loop retains the event owner until it stops waiting on the handle. unsafe impl Send for Stream {} -// SAFETY: All fields of Stream are Sync: -// - Option>, Sender, u32, u64, Latch, -// Arc, Arc: all trivially Sync -// - Foundation::HANDLE: SetEvent/WaitForSingleObject are thread-safe -// - Option: has its own unsafe impl Sync +// SAFETY: Shared access to Stream is limited to the thread-safe command sender, atomics, and +// kernel-event signalling. The raw event handle is closed only after the run loop exits or drops +// its shared owner, and the monitor worker is joined during exclusive Stream destruction. unsafe impl Sync for Stream {} struct RunContext { @@ -247,11 +378,11 @@ struct RunContext { commands: Receiver, - // Set by a device-change notification callback when SetEvent fails. - pending_device_changed: Option>, + // Set by the monitor thread before it signals a default-device change. + pending_device_error: Option>, - // Set when this stream tracks the default device, rather than a pinned one. - default_device_flow: Option, + // Keeps the monitor event alive until this run loop stops waiting on it. + _default_device_monitor_event: Option>, // Owned here so the worker thread closes it on exit in a self-join case. pending_scheduled_event: Foundation::HANDLE, @@ -348,20 +479,22 @@ impl Stream { } let mut handles = vec![pending_scheduled_event, stream_inner.event]; - if let Some(ref monitor) = default_device_monitor { - handles.push(monitor.event); + let default_device_monitor_event = default_device_monitor + .as_ref() + .map(|monitor| Arc::clone(&monitor.event)); + if let Some(ref event) = default_device_monitor_event { + handles.push(event.handle()); } - let pending_device_changed = default_device_monitor + let pending_device_error = default_device_monitor .as_ref() - .map(|m| m.pending_device_changed.clone()); - let default_device_flow = default_device_monitor.as_ref().map(|m| m.flow); + .map(|m| m.pending_device_error.clone()); let run_context = RunContext { handles, stream: stream_inner, commands: rx, - pending_device_changed, - default_device_flow, + pending_device_error, + _default_device_monitor_event: default_device_monitor_event, pending_scheduled_event, }; @@ -424,20 +557,22 @@ impl Stream { } let mut handles = vec![pending_scheduled_event, stream_inner.event]; - if let Some(ref monitor) = default_device_monitor { - handles.push(monitor.event); + let default_device_monitor_event = default_device_monitor + .as_ref() + .map(|monitor| Arc::clone(&monitor.event)); + if let Some(ref event) = default_device_monitor_event { + handles.push(event.handle()); } - let pending_device_changed = default_device_monitor + let pending_device_error = default_device_monitor .as_ref() - .map(|m| m.pending_device_changed.clone()); - let default_device_flow = default_device_monitor.as_ref().map(|m| m.flow); + .map(|m| m.pending_device_error.clone()); let run_context = RunContext { handles, stream: stream_inner, commands: rx, - pending_device_changed, - default_device_flow, + pending_device_error, + _default_device_monitor_event: default_device_monitor_event, pending_scheduled_event, }; @@ -829,13 +964,22 @@ fn boost_current_thread_priority( } } -fn default_device_change_error(flow: Option) -> Error { - match flow.and_then(get_current_default) { - None => ErrorKind::DeviceNotAvailable.into(), - Some(_) => ErrorKind::DeviceChanged.into(), +fn default_device_change_error(reason: u8) -> Option { + match reason { + DEVICE_ERROR_NOT_AVAILABLE => Some(ErrorKind::DeviceNotAvailable.into()), + DEVICE_ERROR_CHANGED => Some(ErrorKind::DeviceChanged.into()), + _ => None, } } +fn take_default_device_change_error(run_context: &RunContext) -> Option { + let reason = run_context + .pending_device_error + .as_ref()? + .swap(DEVICE_ERROR_NONE, Ordering::AcqRel); + default_device_change_error(reason) +} + fn process_commands_and_await_signal( run_context: &mut RunContext, error_callback: &ErrorCallbackArc, @@ -856,13 +1000,8 @@ fn process_commands_and_await_signal( return ControlFlow::Continue(true); } - if let Some(ref flag) = run_context.pending_device_changed { - if flag.swap(false, Ordering::Relaxed) { - emit_error( - error_callback, - default_device_change_error(run_context.default_device_flow), - ); - } + if let Some(error) = take_default_device_change_error(run_context) { + emit_error(error_callback, error); } // Wait for any of the handles to be signalled. @@ -879,10 +1018,9 @@ fn process_commands_and_await_signal( // Continue(true) = audio event fired, proceed to process audio this iteration. // Continue(false) = command or device-change event, loop around and wait again. if handle_idx >= 2 { - emit_error( - error_callback, - default_device_change_error(run_context.default_device_flow), - ); + if let Some(error) = take_default_device_change_error(run_context) { + emit_error(error_callback, error); + } return ControlFlow::Continue(false); } ControlFlow::Continue(handle_idx != 0) @@ -1118,14 +1256,104 @@ fn output_timestamp( #[cfg(test)] mod tests { - use super::{Audio, get_current_default}; + use super::{Audio, DefaultDeviceMonitor, DefaultDeviceNotificationImpl, MonitorEvent}; + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; use windows::Win32::{ - Foundation::CO_E_NOTINITIALIZED, - System::Com::{APTTYPE, APTTYPE_STA, APTTYPEQUALIFIER, CoGetApartmentType}, + Foundation::{CO_E_NOTINITIALIZED, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT}, + System::{ + Com::{ + APTTYPE, APTTYPE_MAINSTA, APTTYPE_MTA, APTTYPE_STA, APTTYPEQUALIFIER, + CoGetApartmentType, + }, + Threading, + }, }; + use windows::core::PCWSTR; + + #[test] + fn notification_callbacks_do_not_initialize_com() { + let notification_event = Arc::new(MonitorEvent::new(unsafe { + Threading::CreateEventW(None, false, false, None) + .expect("notification event should be created") + })); + + std::thread::spawn(move || { + let notification_event_handle = notification_event.handle(); + let mut apartment_type = APTTYPE(-1); + let mut apartment_qualifier = APTTYPEQUALIFIER(0); + let before = + unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) }; + assert_eq!( + before.unwrap_err().code(), + CO_E_NOTINITIALIZED, + "test worker should start without COM initialized" + ); + + let pending_default_changed = Arc::new(AtomicBool::new(false)); + let notification: Audio::IMMNotificationClient = DefaultDeviceNotificationImpl { + flow: Audio::eRender, + notification_event: Arc::clone(¬ification_event), + pending_default_changed: pending_default_changed.clone(), + } + .into(); + drop(notification_event); + let device_id = PCWSTR::null(); + + unsafe { + notification + .OnDefaultDeviceChanged(Audio::eRender, Audio::eConsole, device_id) + .expect("default-device callback should succeed"); + } + assert!(pending_default_changed.load(Ordering::Acquire)); + assert_eq!( + unsafe { Threading::WaitForSingleObject(notification_event_handle, 0) }, + WAIT_OBJECT_0 + ); + + unsafe { + notification + .OnDeviceStateChanged(device_id, Audio::DEVICE_STATE_UNPLUGGED) + .expect("device-state callback should succeed"); + } + assert_eq!( + unsafe { Threading::WaitForSingleObject(notification_event_handle, 0) }, + WAIT_OBJECT_0 + ); + + unsafe { + notification + .OnDeviceRemoved(device_id) + .expect("device-removed callback should succeed"); + } + assert_eq!( + unsafe { Threading::WaitForSingleObject(notification_event_handle, 0) }, + WAIT_OBJECT_0 + ); + + let after = + unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) }; + assert_eq!( + after.unwrap_err().code(), + CO_E_NOTINITIALIZED, + "notification callbacks must not initialize their caller's COM apartment" + ); + + drop(notification); + assert_eq!( + unsafe { Threading::WaitForSingleObject(notification_event_handle, 0) }, + WAIT_FAILED, + "the callback event should close when its final owner is dropped" + ); + }) + .join() + .expect("worker thread should complete"); + } #[test] - fn default_endpoint_query_does_not_turn_worker_thread_into_sta() { + fn default_endpoint_queries_initialize_uninitialized_threads_as_mta() { std::thread::spawn(|| { let mut apartment_type = APTTYPE(-1); let mut apartment_qualifier = APTTYPEQUALIFIER(0); @@ -1137,16 +1365,69 @@ mod tests { "test worker should start without COM initialized" ); - let _ = get_current_default(Audio::eRender); + let _ = super::super::device::current_default_endpoint(Audio::eRender); unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) } .expect("default endpoint query should initialize COM"); - assert_ne!( - apartment_type, APTTYPE_STA, - "default endpoint query must not initialize a worker as an STA" + assert_eq!( + apartment_type, APTTYPE_MTA, + "default endpoint queries must not initialize pool workers as STAs" + ); + }) + .join() + .expect("worker thread should complete"); + } + + #[test] + fn default_endpoint_query_preserves_an_existing_sta() { + std::thread::spawn(|| { + crate::host::com::com_initialized(); + let mut apartment_type = APTTYPE(-1); + let mut apartment_qualifier = APTTYPEQUALIFIER(0); + unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) } + .expect("test thread should be initialized as an STA"); + assert!( + apartment_type == APTTYPE_STA || apartment_type == APTTYPE_MAINSTA, + "test thread should be initialized as an STA" + ); + + let _ = super::super::device::current_default_endpoint(Audio::eRender); + + unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) } + .expect("default endpoint query should leave COM initialized"); + assert!( + apartment_type == APTTYPE_STA || apartment_type == APTTYPE_MAINSTA, + "default endpoint queries must preserve a caller's existing STA" ); }) .join() .expect("worker thread should complete"); } + + #[test] + fn monitor_event_stays_open_until_the_run_loop_releases_it() { + let handle = unsafe { + Threading::CreateEventW(None, false, false, None) + .expect("monitor event should be created") + }; + let event = Arc::new(MonitorEvent::new(handle)); + let run_loop_event = Arc::clone(&event); + let raw_handle = event.handle(); + + drop(event); + assert_eq!( + unsafe { Threading::WaitForSingleObject(raw_handle, 0) }, + WAIT_TIMEOUT, + "dropping the monitor must not close an event still owned by the run loop" + ); + + drop(run_loop_event); + } + + #[test] + fn default_device_monitor_registers_on_its_mta_worker() { + let monitor = DefaultDeviceMonitor::new(Audio::eRender) + .expect("device monitor should register on its MTA worker"); + drop(monitor); + } } From f279e1458f8f4e97197621dceda5c9375689fce6 Mon Sep 17 00:00:00 2001 From: Danny Ward Date: Sat, 24 Oct 2026 23:56:32 -0400 Subject: [PATCH 3/6] test(wasapi): make callback apartment test runner-safe --- src/host/wasapi/stream.rs | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/host/wasapi/stream.rs b/src/host/wasapi/stream.rs index 97c1e94fe..46e94b13c 100644 --- a/src/host/wasapi/stream.rs +++ b/src/host/wasapi/stream.rs @@ -1282,16 +1282,17 @@ mod tests { std::thread::spawn(move || { let notification_event_handle = notification_event.handle(); - let mut apartment_type = APTTYPE(-1); - let mut apartment_qualifier = APTTYPEQUALIFIER(0); - let before = - unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) }; - assert_eq!( - before.unwrap_err().code(), - CO_E_NOTINITIALIZED, - "test worker should start without COM initialized" - ); - + let apartment_state = || { + let mut apartment_type = APTTYPE(-1); + let mut apartment_qualifier = APTTYPEQUALIFIER(0); + match unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) } { + Ok(()) => Some((apartment_type, apartment_qualifier)), + Err(error) if error.code() == CO_E_NOTINITIALIZED => None, + Err(error) => { + panic!("failed to query the test thread's COM apartment: {error}") + } + } + }; let pending_default_changed = Arc::new(AtomicBool::new(false)); let notification: Audio::IMMNotificationClient = DefaultDeviceNotificationImpl { flow: Audio::eRender, @@ -1299,6 +1300,7 @@ mod tests { pending_default_changed: pending_default_changed.clone(), } .into(); + let before = apartment_state(); drop(notification_event); let device_id = PCWSTR::null(); @@ -1333,11 +1335,9 @@ mod tests { WAIT_OBJECT_0 ); - let after = - unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) }; assert_eq!( - after.unwrap_err().code(), - CO_E_NOTINITIALIZED, + apartment_state(), + before, "notification callbacks must not initialize their caller's COM apartment" ); From 07930c16647e001632f12bec78f8ebe11acb0930 Mon Sep 17 00:00:00 2001 From: Danny Ward Date: Sun, 25 Oct 2026 00:10:00 -0400 Subject: [PATCH 4/6] fix(wasapi): preserve caller apartment on device lookup --- src/host/wasapi/device.rs | 32 +++++++++++++++++++++-------- src/host/wasapi/stream.rs | 42 ++++++++++++++++++++++++++++++--------- 2 files changed, 57 insertions(+), 17 deletions(-) diff --git a/src/host/wasapi/device.rs b/src/host/wasapi/device.rs index 9a35bda14..948caa588 100644 --- a/src/host/wasapi/device.rs +++ b/src/host/wasapi/device.rs @@ -9,6 +9,7 @@ use std::{ Arc, Mutex, MutexGuard, OnceLock, atomic::{AtomicBool, AtomicU64}, }, + thread, time::Duration, }; @@ -1158,14 +1159,29 @@ static ENUMERATOR: OnceLock> = OnceLock /// Returns the current default audio endpoint for `flow`, or `None` if none exists. pub(super) fn current_default_endpoint(flow: Audio::EDataFlow) -> Option { - // These queries can be made from Windows-managed thread-pool callbacks. Initialize a free - // thread as MTA so a persistent pool thread is not changed into an STA. CoInitializeEx - // returns RPC_E_CHANGED_MODE for an existing STA, which remains unchanged for UI callers. - com::com_initialized_mta(); + // Resolve endpoints on the caller's apartment. Public default-device lookups check + // availability on a short-lived MTA worker so they do not initialize Windows-owned callback + // threads or change an uninitialized UI thread's default STA policy. + com::com_initialized(); let enumerator = create_enumerator().ok()?; current_default_endpoint_with(&enumerator, flow) } +fn default_endpoint_available(flow: Audio::EDataFlow) -> bool { + thread::Builder::new() + .name("cpal_wasapi_default_endpoint_query".to_owned()) + .spawn(move || { + com::com_initialized_mta(); + let Ok(enumerator) = create_enumerator() else { + return false; + }; + current_default_endpoint_with(&enumerator, flow).is_some() + }) + .ok() + .and_then(|worker| worker.join().ok()) + .unwrap_or(false) +} + /// Creates an enumerator for use on the calling thread. /// /// The caller must keep the interface on the same COM apartment for its entire lifetime. @@ -1324,13 +1340,13 @@ impl Iterator for Devices { } pub fn default_input_device() -> Option { - // Detect if a default input device exists before creating a `Device` for it. - current_default_endpoint(Audio::eCapture).map(|_| Device::default_input()) + // Check availability on an owned MTA worker, leaving the caller's apartment unchanged. + default_endpoint_available(Audio::eCapture).then(Device::default_input) } pub fn default_output_device() -> Option { - // Detect if a default output device exists before creating a `Device` for it. - current_default_endpoint(Audio::eRender).map(|_| Device::default_output()) + // Check availability on an owned MTA worker, leaving the caller's apartment unchanged. + default_endpoint_available(Audio::eRender).then(Device::default_output) } impl From for DeviceDirection { diff --git a/src/host/wasapi/stream.rs b/src/host/wasapi/stream.rs index 46e94b13c..f7d300bae 100644 --- a/src/host/wasapi/stream.rs +++ b/src/host/wasapi/stream.rs @@ -1264,10 +1264,7 @@ mod tests { use windows::Win32::{ Foundation::{CO_E_NOTINITIALIZED, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT}, System::{ - Com::{ - APTTYPE, APTTYPE_MAINSTA, APTTYPE_MTA, APTTYPE_STA, APTTYPEQUALIFIER, - CoGetApartmentType, - }, + Com::{APTTYPE, APTTYPE_MAINSTA, APTTYPE_STA, APTTYPEQUALIFIER, CoGetApartmentType}, Threading, }, }; @@ -1353,7 +1350,34 @@ mod tests { } #[test] - fn default_endpoint_queries_initialize_uninitialized_threads_as_mta() { + fn default_device_lookup_leaves_an_uninitialized_caller_uninitialized() { + std::thread::spawn(|| { + let mut apartment_type = APTTYPE(-1); + let mut apartment_qualifier = APTTYPEQUALIFIER(0); + let before = + unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) }; + assert_eq!( + before.unwrap_err().code(), + CO_E_NOTINITIALIZED, + "test worker should start without COM initialized" + ); + + let _ = super::super::device::default_output_device(); + + let after = + unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) }; + assert_eq!( + after.unwrap_err().code(), + CO_E_NOTINITIALIZED, + "default-device availability checks must not initialize the caller's COM apartment" + ); + }) + .join() + .expect("worker thread should complete"); + } + + #[test] + fn default_endpoint_resolution_initializes_uninitialized_callers_as_sta() { std::thread::spawn(|| { let mut apartment_type = APTTYPE(-1); let mut apartment_qualifier = APTTYPEQUALIFIER(0); @@ -1368,10 +1392,10 @@ mod tests { let _ = super::super::device::current_default_endpoint(Audio::eRender); unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) } - .expect("default endpoint query should initialize COM"); - assert_eq!( - apartment_type, APTTYPE_MTA, - "default endpoint queries must not initialize pool workers as STAs" + .expect("default endpoint resolution should initialize COM"); + assert!( + apartment_type == APTTYPE_STA || apartment_type == APTTYPE_MAINSTA, + "default endpoint resolution should preserve cpal's default STA policy" ); }) .join() From 55c4031f45db9eb5188e112c92b2c1ca850b3b56 Mon Sep 17 00:00:00 2001 From: Danny Ward Date: Sun, 25 Oct 2026 00:15:45 -0400 Subject: [PATCH 5/6] test(wasapi): account for implicit MTA threads --- src/host/wasapi/device.rs | 8 ++++---- src/host/wasapi/stream.rs | 37 +++++++++++++++++++++---------------- 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/src/host/wasapi/device.rs b/src/host/wasapi/device.rs index 948caa588..b79130e63 100644 --- a/src/host/wasapi/device.rs +++ b/src/host/wasapi/device.rs @@ -1160,8 +1160,8 @@ static ENUMERATOR: OnceLock> = OnceLock /// Returns the current default audio endpoint for `flow`, or `None` if none exists. pub(super) fn current_default_endpoint(flow: Audio::EDataFlow) -> Option { // Resolve endpoints on the caller's apartment. Public default-device lookups check - // availability on a short-lived MTA worker so they do not initialize Windows-owned callback - // threads or change an uninitialized UI thread's default STA policy. + // availability on a short-lived MTA worker so they do not explicitly initialize the caller + // or change an uninitialized UI thread's default STA policy. com::com_initialized(); let enumerator = create_enumerator().ok()?; current_default_endpoint_with(&enumerator, flow) @@ -1340,12 +1340,12 @@ impl Iterator for Devices { } pub fn default_input_device() -> Option { - // Check availability on an owned MTA worker, leaving the caller's apartment unchanged. + // Check availability on an owned MTA worker without explicitly initializing the caller. default_endpoint_available(Audio::eCapture).then(Device::default_input) } pub fn default_output_device() -> Option { - // Check availability on an owned MTA worker, leaving the caller's apartment unchanged. + // Check availability on an owned MTA worker without explicitly initializing the caller. default_endpoint_available(Audio::eRender).then(Device::default_output) } diff --git a/src/host/wasapi/stream.rs b/src/host/wasapi/stream.rs index f7d300bae..5a3531dad 100644 --- a/src/host/wasapi/stream.rs +++ b/src/host/wasapi/stream.rs @@ -1264,7 +1264,10 @@ mod tests { use windows::Win32::{ Foundation::{CO_E_NOTINITIALIZED, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT}, System::{ - Com::{APTTYPE, APTTYPE_MAINSTA, APTTYPE_STA, APTTYPEQUALIFIER, CoGetApartmentType}, + Com::{ + APTTYPE, APTTYPE_MAINSTA, APTTYPE_MTA, APTTYPE_STA, APTTYPEQUALIFIER, + APTTYPEQUALIFIER_IMPLICIT_MTA, CoGetApartmentType, + }, Threading, }, }; @@ -1350,27 +1353,29 @@ mod tests { } #[test] - fn default_device_lookup_leaves_an_uninitialized_caller_uninitialized() { + fn default_device_lookup_does_not_explicitly_initialize_caller() { std::thread::spawn(|| { let mut apartment_type = APTTYPE(-1); let mut apartment_qualifier = APTTYPEQUALIFIER(0); - let before = - unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) }; - assert_eq!( - before.unwrap_err().code(), - CO_E_NOTINITIALIZED, - "test worker should start without COM initialized" - ); let _ = super::super::device::default_output_device(); - let after = - unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) }; - assert_eq!( - after.unwrap_err().code(), - CO_E_NOTINITIALIZED, - "default-device availability checks must not initialize the caller's COM apartment" - ); + match unsafe { CoGetApartmentType(&mut apartment_type, &mut apartment_qualifier) } { + Err(error) if error.code() == CO_E_NOTINITIALIZED => {} + Ok(()) => { + assert_eq!( + apartment_type, + APTTYPE_MTA, + "an uninitialized caller may observe the process MTA implicitly" + ); + assert_eq!( + apartment_qualifier, + APTTYPEQUALIFIER_IMPLICIT_MTA, + "default-device availability checks must not explicitly initialize the caller" + ); + } + Err(error) => panic!("failed to query the caller's COM apartment: {error}"), + } }) .join() .expect("worker thread should complete"); From c80685927b203210b7b92659f1ad4095d571fc34 Mon Sep 17 00:00:00 2001 From: dannyward630 Date: Sun, 25 Oct 2026 19:52:31 -0400 Subject: [PATCH 6/6] fix(wasapi): reuse enumerators and own events --- src/host/com.rs | 4 +- src/host/wasapi/device.rs | 86 +++++++++++++------- src/host/wasapi/stream.rs | 163 +++++++++++++++----------------------- 3 files changed, 122 insertions(+), 131 deletions(-) diff --git a/src/host/com.rs b/src/host/com.rs index 70c391713..67ca91f64 100644 --- a/src/host/com.rs +++ b/src/host/com.rs @@ -22,7 +22,7 @@ thread_local!(static COM_INITIALIZED_MTA: ComInitialized = { /// // We store a raw pointer because it's the only way at the moment to remove `Send`/`Sync` from the // object. -struct ComInitialized { +pub(super) struct ComInitialized { result: windows::core::HRESULT, _ptr: PhantomData<*mut ()>, } @@ -38,7 +38,7 @@ impl Drop for ComInitialized { } impl ComInitialized { - fn new(concurrency_model: COINIT) -> Self { + pub(super) fn new(concurrency_model: COINIT) -> Self { unsafe { // This can fail with RPC_E_CHANGED_MODE if another library initialized COM with a // different model. That's OK: COM is already initialized on this thread. diff --git a/src/host/wasapi/device.rs b/src/host/wasapi/device.rs index b79130e63..4dd49dcfc 100644 --- a/src/host/wasapi/device.rs +++ b/src/host/wasapi/device.rs @@ -8,6 +8,7 @@ use std::{ sync::{ Arc, Mutex, MutexGuard, OnceLock, atomic::{AtomicBool, AtomicU64}, + mpsc::{self, Sender, SyncSender}, }, thread, time::Duration, @@ -1155,31 +1156,46 @@ impl Endpoint { } } -static ENUMERATOR: OnceLock> = OnceLock::new(); +thread_local! { + static ENUMERATOR: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +type DefaultEndpointQuery = (Audio::EDataFlow, SyncSender); +static DEFAULT_ENDPOINT_QUERY: OnceLock>> = OnceLock::new(); /// Returns the current default audio endpoint for `flow`, or `None` if none exists. pub(super) fn current_default_endpoint(flow: Audio::EDataFlow) -> Option { - // Resolve endpoints on the caller's apartment. Public default-device lookups check - // availability on a short-lived MTA worker so they do not explicitly initialize the caller - // or change an uninitialized UI thread's default STA policy. com::com_initialized(); - let enumerator = create_enumerator().ok()?; + let enumerator = get_enumerator().ok()?; current_default_endpoint_with(&enumerator, flow) } fn default_endpoint_available(flow: Audio::EDataFlow) -> bool { - thread::Builder::new() - .name("cpal_wasapi_default_endpoint_query".to_owned()) - .spawn(move || { - com::com_initialized_mta(); - let Ok(enumerator) = create_enumerator() else { - return false; - }; - current_default_endpoint_with(&enumerator, flow).is_some() + let Some(sender) = DEFAULT_ENDPOINT_QUERY + .get_or_init(|| { + let (query_tx, query_rx) = mpsc::channel::(); + thread::Builder::new() + .name("cpal_wasapi_default_endpoint_query".to_owned()) + .spawn(move || { + com::com_initialized_mta(); + let Ok(enumerator) = create_enumerator() else { + return; + }; + while let Ok((flow, result_tx)) = query_rx.recv() { + let available = current_default_endpoint_with(&enumerator, flow).is_some(); + let _ = result_tx.send(available); + } + }) + .ok() + .map(|_| query_tx) }) - .ok() - .and_then(|worker| worker.join().ok()) - .unwrap_or(false) + .as_ref() + else { + return false; + }; + + let (result_tx, result_rx) = mpsc::sync_channel(1); + sender.send((flow, result_tx)).is_ok() && result_rx.recv().unwrap_or(false) } /// Creates an enumerator for use on the calling thread. @@ -1209,11 +1225,24 @@ pub(super) fn current_default_endpoint_with( } } -fn get_enumerator() -> Result<&'static Enumerator, windows::core::Error> { - ENUMERATOR - .get_or_init(|| create_enumerator().map(Enumerator)) - .as_ref() - .map_err(Clone::clone) +fn get_enumerator() -> Result { + ENUMERATOR.with(|cache| { + let mut cache = cache.borrow_mut(); + if cache.is_none() { + let com_initialized = + com::ComInitialized::new(windows::Win32::System::Com::COINIT_APARTMENTTHREADED); + let interface = create_enumerator()?; + *cache = Some(Enumerator { + interface, + _com_initialized: com_initialized, + }); + } + Ok(cache + .as_ref() + .expect("enumerator was initialized above") + .interface + .clone()) + }) } // Helper function to query a DWORD property from a WASAPI device property store @@ -1277,11 +1306,11 @@ unsafe fn get_property_string( result } -/// Send/Sync wrapper around `IMMDeviceEnumerator`. -struct Enumerator(Audio::IMMDeviceEnumerator); - -unsafe impl Send for Enumerator {} -unsafe impl Sync for Enumerator {} +/// Per-thread cache that keeps its COM apartment initialized until after the interface is released. +struct Enumerator { + interface: Audio::IMMDeviceEnumerator, + _com_initialized: com::ComInitialized, +} /// WASAPI implementation for `Devices`. pub struct Devices { @@ -1295,9 +1324,8 @@ impl Devices { com::com_initialized(); unsafe { // can fail because of wrong parameters (should never happen) or out of memory - let collection = get_enumerator() - .context("Failed to get device enumerator")? - .0 + let enumerator = get_enumerator().context("Failed to get device enumerator")?; + let collection = enumerator .EnumAudioEndpoints(Audio::eAll, Audio::DEVICE_STATE_ACTIVE) .context("Failed to enumerate audio endpoints")?; diff --git a/src/host/wasapi/stream.rs b/src/host/wasapi/stream.rs index 5a3531dad..01d97a1b7 100644 --- a/src/host/wasapi/stream.rs +++ b/src/host/wasapi/stream.rs @@ -24,28 +24,37 @@ use crate::{ traits::StreamTrait, }; -const DEVICE_ERROR_NONE: u8 = 0; -const DEVICE_ERROR_NOT_AVAILABLE: u8 = 1; -const DEVICE_ERROR_CHANGED: u8 = 2; +#[repr(u8)] +#[derive(Clone, Copy)] +enum DeviceChangeError { + None = 0, + NotAvailable = 1, + Changed = 2, +} /// A kernel event whose lifetime is shared by the monitor and the audio run loop. /// /// The audio loop can outlive `DefaultDeviceMonitor` when a stream is dropped from one of its -/// callbacks. Store the opaque handle as an integer so the shared owner is `Send + Sync`; event -/// handles can be signalled and waited on from any thread. -struct MonitorEvent(usize); - -impl MonitorEvent { - fn new(handle: Foundation::HANDLE) -> Self { - Self(handle.0 as usize) +/// callbacks. Arc-based ownership keeps the handle valid until every waiter and signaler is done. +struct OwnedEvent(Foundation::HANDLE); + +// SAFETY: Windows event handles can be waited on and signalled from any thread. The Arc keeps +// the handle open until all users have released their ownership. +unsafe impl Send for OwnedEvent {} +unsafe impl Sync for OwnedEvent {} + +impl OwnedEvent { + fn new() -> windows::core::Result { + let handle = unsafe { Threading::CreateEventW(None, false, false, None)? }; + Ok(Self(handle)) } fn handle(&self) -> Foundation::HANDLE { - Foundation::HANDLE(self.0 as *mut std::ffi::c_void) + self.0 } } -impl Drop for MonitorEvent { +impl Drop for OwnedEvent { fn drop(&mut self) { unsafe { let _ = Foundation::CloseHandle(self.handle()); @@ -55,49 +64,29 @@ impl Drop for MonitorEvent { /// Fires a Windows auto-reset event when the system default audio device changes. pub(crate) struct DefaultDeviceMonitor { - stop_event: Foundation::HANDLE, + stop_event: Arc, worker: Option>, - event: Arc, + event: Arc, pending_device_error: Arc, } impl DefaultDeviceMonitor { pub fn new(flow: Audio::EDataFlow) -> Result { - let event = Arc::new(MonitorEvent::new(unsafe { - Threading::CreateEventW(None, false, false, None).map_err(Error::from)? - })); - let notification_event = match unsafe { Threading::CreateEventW(None, false, false, None) } - { - Ok(event) => event, - Err(error) => { - drop(event); - return Err(Error::from(error)); - } - }; - let notification_event = Arc::new(MonitorEvent::new(notification_event)); - let stop_event = match unsafe { Threading::CreateEventW(None, false, false, None) } { - Ok(event) => event, - Err(error) => { - drop(event); - drop(notification_event); - return Err(Error::from(error)); - } - }; + let event = Arc::new(OwnedEvent::new().map_err(Error::from)?); + let notification_event = Arc::new(OwnedEvent::new().map_err(Error::from)?); + let stop_event = Arc::new(OwnedEvent::new().map_err(Error::from)?); let pending_default_changed = Arc::new(AtomicBool::new(false)); - let pending_device_error = Arc::new(AtomicU8::new(DEVICE_ERROR_NONE)); + let pending_device_error = Arc::new(AtomicU8::new(DeviceChangeError::None as u8)); let worker_pending_default_changed = pending_default_changed.clone(); let worker_pending_device_error = pending_device_error.clone(); - // `HANDLE` is an opaque, thread-safe kernel handle, but the windows crate models it as a - // raw pointer and therefore does not implement `Send`. Move its bit pattern as `usize`. - let event_handle = event.handle().0 as usize; - let stop_event_handle = stop_event.0 as usize; + let worker_event = Arc::clone(&event); + let worker_notification_event = Arc::clone(¬ification_event); + let worker_stop_event = Arc::clone(&stop_event); let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel::>(1); let worker = match thread::Builder::new() .name("cpal_wasapi_device_monitor".to_owned()) .spawn(move || { - let event = Foundation::HANDLE(event_handle as *mut std::ffi::c_void); - let stop_event = Foundation::HANDLE(stop_event_handle as *mut std::ffi::c_void); // Keep every IMMDeviceEnumerator call, including unregister, on the apartment // that created the enumerator. Notification callbacks only signal an event. crate::host::com::com_initialized_mta(); @@ -105,13 +94,14 @@ impl DefaultDeviceMonitor { Ok(enumerator) => enumerator, Err(error) => { let _ = ready_tx.send(Err(error.to_string())); - close_default_device_monitor_handles(stop_event); return; } }; + // The worker and COM callback share one handle owner; the Arc keeps the event + // open until both have finished using it. let client: Audio::IMMNotificationClient = DefaultDeviceNotificationImpl { flow, - notification_event: Arc::clone(¬ification_event), + notification_event: Arc::clone(&worker_notification_event), pending_default_changed: worker_pending_default_changed, } .into(); @@ -120,7 +110,6 @@ impl DefaultDeviceMonitor { unsafe { enumerator.RegisterEndpointNotificationCallback(&client) } { let _ = ready_tx.send(Err(error.to_string())); - close_default_device_monitor_handles(stop_event); return; } @@ -128,15 +117,14 @@ impl DefaultDeviceMonitor { let unregistered = unsafe { enumerator.UnregisterEndpointNotificationCallback(&client) } .is_ok(); - close_default_device_monitor_handles_after_unregister( - Arc::clone(¬ification_event), - stop_event, - unregistered, - ); + retain_event_if_unregister_failed(worker_notification_event, unregistered); return; } - let handles = [stop_event, notification_event.handle()]; + let handles = [ + worker_stop_event.handle(), + worker_notification_event.handle(), + ]; loop { let result = unsafe { Threading::WaitForMultipleObjectsEx( @@ -160,13 +148,13 @@ impl DefaultDeviceMonitor { .is_some(); if default_changed || !default_available { let error = if default_available { - DEVICE_ERROR_CHANGED + DeviceChangeError::Changed } else { - DEVICE_ERROR_NOT_AVAILABLE + DeviceChangeError::NotAvailable }; - worker_pending_device_error.store(error, Ordering::Release); - unsafe { - let _ = Threading::SetEvent(event); + worker_pending_device_error.store(error as u8, Ordering::Release); + if unsafe { Threading::SetEvent(worker_event.handle()) }.is_err() { + break; } } } @@ -176,15 +164,10 @@ impl DefaultDeviceMonitor { let unregistered = unsafe { enumerator.UnregisterEndpointNotificationCallback(&client) }.is_ok(); - close_default_device_monitor_handles_after_unregister( - Arc::clone(¬ification_event), - stop_event, - unregistered, - ); + retain_event_if_unregister_failed(worker_notification_event, unregistered); }) { Ok(worker) => worker, Err(error) => { - close_default_device_monitor_handles(stop_event); return Err(Error::with_message( ErrorKind::ResourceExhausted, format!("Failed to create device notification thread: {error}"), @@ -219,33 +202,17 @@ impl DefaultDeviceMonitor { } } -fn close_default_device_monitor_handles(stop_event: Foundation::HANDLE) { - unsafe { - let _ = Foundation::CloseHandle(stop_event); - } -} - -fn close_default_device_monitor_handles_after_unregister( - notification_event: Arc, - stop_event: Foundation::HANDLE, - unregistered: bool, -) { - if unregistered { - close_default_device_monitor_handles(stop_event); - } else { - // A failed unregister can leave callbacks in flight. Keep the callback event alive in - // case Windows still invokes the registered client after this worker exits. - std::mem::forget(notification_event); - unsafe { - let _ = Foundation::CloseHandle(stop_event); - } +fn retain_event_if_unregister_failed(event: Arc, unregistered: bool) { + if !unregistered { + // A failed unregister can leave callbacks in flight, so preserve their event handle. + std::mem::forget(event); } } impl Drop for DefaultDeviceMonitor { fn drop(&mut self) { unsafe { - let _ = Threading::SetEvent(self.stop_event); + let _ = Threading::SetEvent(self.stop_event.handle()); } if let Some(worker) = self.worker.take() { let _ = worker.join(); @@ -257,7 +224,7 @@ impl Drop for DefaultDeviceMonitor { #[windows::core::implement(Audio::IMMNotificationClient)] struct DefaultDeviceNotificationImpl { flow: Audio::EDataFlow, - notification_event: Arc, + notification_event: Arc, pending_default_changed: Arc, } @@ -271,7 +238,7 @@ impl Audio::IMMNotificationClient_Impl for DefaultDeviceNotificationImpl_Impl { if flow == self.flow && role == Audio::eConsole { self.pending_default_changed.store(true, Ordering::Release); unsafe { - let _ = Threading::SetEvent(self.notification_event.handle()); + Threading::SetEvent(self.notification_event.handle())?; } } Ok(()) @@ -294,7 +261,7 @@ impl Audio::IMMNotificationClient_Impl for DefaultDeviceNotificationImpl_Impl { // The monitor thread checks for a replacement default without making COM calls from // this Windows-managed callback thread. unsafe { - let _ = Threading::SetEvent(self.notification_event.handle()); + Threading::SetEvent(self.notification_event.handle())?; } } Ok(()) @@ -308,7 +275,7 @@ impl Audio::IMMNotificationClient_Impl for DefaultDeviceNotificationImpl_Impl { // The monitor thread checks for a replacement default without making COM calls from this // Windows-managed callback thread. unsafe { - let _ = Threading::SetEvent(self.notification_event.handle()); + Threading::SetEvent(self.notification_event.handle())?; } Ok(()) } @@ -382,7 +349,7 @@ struct RunContext { pending_device_error: Option>, // Keeps the monitor event alive until this run loop stops waiting on it. - _default_device_monitor_event: Option>, + _default_device_monitor_event: Option>, // Owned here so the worker thread closes it on exit in a self-join case. pending_scheduled_event: Foundation::HANDLE, @@ -966,8 +933,10 @@ fn boost_current_thread_priority( fn default_device_change_error(reason: u8) -> Option { match reason { - DEVICE_ERROR_NOT_AVAILABLE => Some(ErrorKind::DeviceNotAvailable.into()), - DEVICE_ERROR_CHANGED => Some(ErrorKind::DeviceChanged.into()), + value if value == DeviceChangeError::NotAvailable as u8 => { + Some(ErrorKind::DeviceNotAvailable.into()) + } + value if value == DeviceChangeError::Changed as u8 => Some(ErrorKind::DeviceChanged.into()), _ => None, } } @@ -976,7 +945,7 @@ fn take_default_device_change_error(run_context: &RunContext) -> Option { let reason = run_context .pending_device_error .as_ref()? - .swap(DEVICE_ERROR_NONE, Ordering::AcqRel); + .swap(DeviceChangeError::None as u8, Ordering::AcqRel); default_device_change_error(reason) } @@ -1256,7 +1225,7 @@ fn output_timestamp( #[cfg(test)] mod tests { - use super::{Audio, DefaultDeviceMonitor, DefaultDeviceNotificationImpl, MonitorEvent}; + use super::{Audio, DefaultDeviceMonitor, DefaultDeviceNotificationImpl, OwnedEvent}; use std::sync::{ Arc, atomic::{AtomicBool, Ordering}, @@ -1275,10 +1244,8 @@ mod tests { #[test] fn notification_callbacks_do_not_initialize_com() { - let notification_event = Arc::new(MonitorEvent::new(unsafe { - Threading::CreateEventW(None, false, false, None) - .expect("notification event should be created") - })); + let notification_event = + Arc::new(OwnedEvent::new().expect("notification event should be created")); std::thread::spawn(move || { let notification_event_handle = notification_event.handle(); @@ -1435,11 +1402,7 @@ mod tests { #[test] fn monitor_event_stays_open_until_the_run_loop_releases_it() { - let handle = unsafe { - Threading::CreateEventW(None, false, false, None) - .expect("monitor event should be created") - }; - let event = Arc::new(MonitorEvent::new(handle)); + let event = Arc::new(OwnedEvent::new().expect("monitor event should be created")); let run_loop_event = Arc::clone(&event); let raw_handle = event.handle();