diff --git a/record-daemon/src/ipc/handlers.rs b/record-daemon/src/ipc/handlers.rs index 1a28c1a..ee1c796 100644 --- a/record-daemon/src/ipc/handlers.rs +++ b/record-daemon/src/ipc/handlers.rs @@ -344,8 +344,9 @@ impl IpcHandlers { /// Enumerate audio devices on Windows using WASAPI. /// -/// This runs in a `catch_unwind` so any panic in the unsafe Windows API calls -/// is contained and cannot crash the daemon process. +/// The enumeration runs on a thread of its own, in a COM apartment that is torn down after +/// every device object is released, and inside `catch_unwind`: a panic (or a bad COM object) +/// keeps the daemon alive and falls back to the default endpoints. #[cfg(target_os = "windows")] fn enumerate_windows_audio_devices() -> Result<( Vec, @@ -370,24 +371,53 @@ fn enumerate_windows_audio_devices() -> Result<( ) }; - // Run the actual enumeration inside catch_unwind so a panic can't crash the daemon. - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - enumerate_windows_audio_devices_inner() - })); + // WASAPI wants a COM apartment, and the tokio workers this handler otherwise runs on are + // shared with libobs. The thread initializes COM, enumerates, drops every device, + // uninitializes COM and exits, so nothing COM-shaped outlives its apartment. + let joined = std::thread::Builder::new() + .name("wasapi-enum".to_string()) + .spawn(|| { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + enumerate_windows_audio_devices_inner() + })) + }) + .map_err(|e| format!("no thread for WASAPI enumeration: {e}")) + .and_then(|handle| { + handle + .join() + .map_err(|_| "WASAPI thread panicked".to_string()) + }); - match result { - Ok(Ok(devices)) => Ok(devices), - Ok(Err(e)) => { - warn!( - "WASAPI device enumeration failed, returning defaults: {}", - e - ); + match joined { + Ok(Ok(Ok(devices))) => Ok(devices), + Ok(Ok(Err(e))) => { + warn!("WASAPI enumeration failed, keeping the default devices: {e}"); Ok(fallback()) } - Err(panic_info) => { - error!("PANIC during WASAPI device enumeration: {:?}", panic_info); + Ok(Err(panic)) => { + error!("PANIC during WASAPI device enumeration: {panic:?}"); Ok(fallback()) } + Err(e) => { + error!("{e}"); + Ok(fallback()) + } + } +} + +/// The COM apartment a thread holds while it enumerates, initialized on construction and +/// released when it drops. Declared before the device objects so it goes away after them: +/// releasing a COM object after `CoUninitialize` is what crashed the daemon before. +#[cfg(target_os = "windows")] +struct Apartment(bool); + +#[cfg(target_os = "windows")] +impl Drop for Apartment { + fn drop(&mut self) { + if self.0 { + // SAFETY: paired with the successful CoInitializeEx in the enumeration below. + unsafe { windows::Win32::System::Com::CoUninitialize() } + } } } @@ -424,78 +454,56 @@ fn enumerate_windows_audio_devices_inner() -> std::result::Result< } } - let mut input_devices = Vec::new(); - let mut output_devices = Vec::new(); - info!( - "[AUDIO_ENUM] inner: starting WASAPI enumeration on this thread (id={:?})", + "[AUDIO_ENUM] starting WASAPI enumeration on {:?}", std::thread::current().id() ); - let com_initialized; - unsafe { - // Initialize COM for this dedicated enumeration thread. - // - // This code runs on a short-lived dedicated OS thread spawned just for - // this enumeration, so it is safe to call both `CoInitializeEx` and - // `CoUninitialize` here: the thread is not shared with libobs or any - // tokio async/blocking-pool work, and it dies as soon as enumeration - // completes. Calling `CoUninitialize` at the end properly tears down the - // COM apartment and avoids leaking resources. - let hr = CoInitializeEx(None, COINIT_MULTITHREADED); - com_initialized = hr.is_ok(); - if !com_initialized { - // RPC_E_CHANGED_MODE would indicate the thread already had COM init in - // a conflicting apartment — this should never happen on a fresh thread, - // but log it loudly so we can diagnose if it ever does. - warn!( - "[AUDIO_ENUM] inner: CoInitializeEx failed: HRESULT=0x{:08X}", - hr.0 - ); - } else { - info!("[AUDIO_ENUM] inner: CoInitializeEx(MTA) succeeded"); - } + // SAFETY: this is the dedicated thread the caller spawned for the enumeration. + let hr = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }; + if hr.is_err() { + // RPC_E_CHANGED_MODE means the thread already had a different apartment; the + // enumeration below still works, we just must not uninitialize on the way out. + warn!("[AUDIO_ENUM] CoInitializeEx failed: HRESULT=0x{:08X}", hr.0); + } + let _apartment = Apartment(hr.is_ok()); - // Create device enumerator + let mut input_devices = Vec::new(); + let mut output_devices = Vec::new(); + + // SAFETY: the calls below are the documented sequence for enumerating endpoints, and + // every returned COM object is owned by a local that drops before `_apartment`. + unsafe { let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL) - .map_err(|e| format!("Failed to create MMDeviceEnumerator: {:?}", e))?; + .map_err(|e| format!("Failed to create MMDeviceEnumerator: {e:?}"))?; - // Get default input device ID for comparison + // The default input and output endpoints, to mark them in the list. let default_input_id: Option = enumerator .GetDefaultAudioEndpoint(eCapture, eCommunications) .ok() .and_then(|dev| dev.GetId().ok()) .map(pwstr_to_string); - - // Get default output device ID for comparison let default_output_id: Option = enumerator .GetDefaultAudioEndpoint(eRender, eCommunications) .ok() .and_then(|dev| dev.GetId().ok()) .map(pwstr_to_string); - // Enumerate capture (input) devices if let Ok(capture_collection) = enumerator.EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE) { if let Ok(count) = capture_collection.GetCount() { for i in 0..count { if let Ok(device) = capture_collection.Item(i) { let id_str: Option = device.GetId().ok().map(pwstr_to_string); - let id = id_str.clone().unwrap_or_else(|| format!("input_{}", i)); - + let id = id_str.clone().unwrap_or_else(|| format!("input_{i}")); let is_default = id_str .as_ref() - .map(|s| default_input_id.as_ref().map(|d| s == d).unwrap_or(false)) + .map(|s| default_input_id.as_ref().is_some_and(|d| s == d)) .unwrap_or(false); - let name = get_device_friendly_name(&device) .unwrap_or_else(|| format!("Input Device {}", i + 1)); - - debug!( - "Found input device: {} (id: {}, default: {})", - name, id, is_default - ); + info!("[AUDIO_ENUM] input {i}: {name} (default: {is_default})"); input_devices.push(AudioDeviceInfo { id, name, @@ -506,26 +514,19 @@ fn enumerate_windows_audio_devices_inner() -> std::result::Result< } } - // Enumerate render (output) devices if let Ok(render_collection) = enumerator.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE) { if let Ok(count) = render_collection.GetCount() { for i in 0..count { if let Ok(device) = render_collection.Item(i) { let id_str: Option = device.GetId().ok().map(pwstr_to_string); - let id = id_str.clone().unwrap_or_else(|| format!("output_{}", i)); - + let id = id_str.clone().unwrap_or_else(|| format!("output_{i}")); let is_default = id_str .as_ref() - .map(|s| default_output_id.as_ref().map(|d| s == d).unwrap_or(false)) + .map(|s| default_output_id.as_ref().is_some_and(|d| s == d)) .unwrap_or(false); - let name = get_device_friendly_name(&device) .unwrap_or_else(|| format!("Output Device {}", i + 1)); - - debug!( - "Found output device: {} (id: {}, default: {})", - name, id, is_default - ); + info!("[AUDIO_ENUM] output {i}: {name} (default: {is_default})"); output_devices.push(AudioDeviceInfo { id, name, @@ -535,16 +536,9 @@ fn enumerate_windows_audio_devices_inner() -> std::result::Result< } } } - - // Tear down COM on this dedicated thread before returning. Safe here - // because nothing else on this thread uses COM afterwards and the - // thread is about to exit. - if com_initialized { - CoUninitialize(); - } } - // If no devices found, add defaults + // If no devices came back, hand out the endpoints everyone has. if input_devices.is_empty() { input_devices.push(AudioDeviceInfo { id: "default".to_string(), @@ -552,7 +546,6 @@ fn enumerate_windows_audio_devices_inner() -> std::result::Result< is_default: true, }); } - if output_devices.is_empty() { output_devices.push(AudioDeviceInfo { id: "default".to_string(), @@ -564,51 +557,60 @@ fn enumerate_windows_audio_devices_inner() -> std::result::Result< Ok((input_devices, output_devices)) } -/// Get the friendly name of an audio device. +/// Get the friendly name of an audio device (`PKEY_Device_FriendlyName`). /// -/// Opens the device property store and reads `PKEY_Device_FriendlyName`. -/// This function never panics — it returns `None` on any failure. -/// -/// We deliberately use the safe `to_string()` impl provided by the `windows` crate -/// for `PROPVARIANT` instead of manually poking at the union's raw bytes. Manual -/// offset-based reads assume a specific memory layout that does not match the -/// crate's wrapper on every platform, and that caused native segfaults that -/// `catch_unwind` cannot trap. +/// Failures cost a device its name, not the enumeration, so they are logged and skipped. #[cfg(target_os = "windows")] fn get_device_friendly_name(device: &windows::Win32::Media::Audio::IMMDevice) -> Option { + use tracing::warn; use windows::Win32::System::Com::STGM; use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore; use windows::Win32::UI::Shell::PropertiesSystem::PROPERTYKEY; - // PKEY_Device_FriendlyName = { a45c254e-df1c-4efd-8020-67d146850500 }, 14 + // PKEY_Device_FriendlyName = {a45c254e-df1c-4efd-8020-67d146a850e0}, 14 const FRIENDLY_NAME_KEY: PROPERTYKEY = PROPERTYKEY { - fmtid: windows::core::GUID::from_u128(0xa45c254e_df1c_4efd_8020_67d146850500), + fmtid: windows::core::GUID::from_u128(0xa45c254e_df1c_4efd_8020_67d146a850e0), pid: 14, }; - // Wrap in catch_unwind to be absolutely safe. + // A failure here costs a device its name, not the enumeration, so every step is logged + // and skipped instead of propagated. let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { // Open the property store read-only. - let store: IPropertyStore = device.OpenPropertyStore(STGM(0)).ok()?; - // Read the friendly-name property. - let prop = store - .GetValue(&FRIENDLY_NAME_KEY as *const PROPERTYKEY) - .ok()?; + let store: IPropertyStore = match device.OpenPropertyStore(STGM(0)) { + Ok(store) => store, + Err(e) => { + warn!("[AUDIO_ENUM] OpenPropertyStore failed: {e:?}"); + return None; + } + }; + let prop = match store.GetValue(&FRIENDLY_NAME_KEY as *const PROPERTYKEY) { + Ok(prop) => prop, + Err(e) => { + warn!("[AUDIO_ENUM] GetValue(FriendlyName) failed: {e:?}"); + return None; + } + }; - // The `windows` crate's `PROPVARIANT` implements `Display` via `to_string()`, - // which safely inspects the variant type and converts the value. For - // `VT_LPWSTR` this returns the contained wide string. We avoid any manual - // union/pointer access here — that was the source of the native crash. + // `PROPVARIANT`'s `Display` converts whatever variant the store hands back (the + // friendly name is `VT_LPWSTR`) to a string without touching the union by hand. let name = prop.to_string(); let trimmed = name.trim(); if trimmed.is_empty() { + warn!("[AUDIO_ENUM] device has an empty friendly name"); None } else { Some(trimmed.to_string()) } })); - result.ok().flatten() + match result { + Ok(name) => name, + Err(_) => { + warn!("[AUDIO_ENUM] reading the friendly name panicked"); + None + } + } } /// Enumerate audio devices on Linux using PulseAudio. diff --git a/record-daemon/src/main.rs b/record-daemon/src/main.rs index 5885792..28c4cf6 100644 --- a/record-daemon/src/main.rs +++ b/record-daemon/src/main.rs @@ -44,7 +44,7 @@ struct Args { socket: Option, /// Path to log file. If not specified, logs to stdout/stderr. - #[arg(short, long, value_name = "PATH")] + #[arg(long, value_name = "PATH")] log_file: Option, }