//! IPC command handlers. use std::sync::Arc; use parking_lot::RwLock; use tracing::{debug, info}; use super::protocol::{ EncoderInfo, GetEncodersResponse, GetSettingsResponse, GetStatusResponse, IpcCommand, IpcMessage, IpcResponse, }; use crate::config::Settings; use crate::error::Result; use crate::recording::encoder::{detect_hardware_encoders, EncoderCapability}; use crate::recording::{RecordingEngine, RecordingResult}; use crate::state::DaemonStatus; use crate::timeline::TimelineStore; /// Collection of IPC command handlers. pub struct IpcHandlers { /// Settings reference. settings: Arc>, /// Recording engine reference. recording: Arc>>, /// Timeline store reference. timeline: Arc>, /// Daemon status. status: Arc>, /// Client connection status. client_connected: Arc>, } impl IpcHandlers { /// Create a new handlers collection. pub fn new( settings: Arc>, recording: Arc>>, timeline: Arc>, status: Arc>, client_connected: Arc>, ) -> Self { Self { settings, recording, timeline, status, client_connected, } } /// Handle an incoming message. pub async fn handle(&self, message: IpcMessage) -> IpcResponse { let command = match message.command { Some(cmd) => cmd, None => return IpcResponse::error(message.id, "No command specified"), }; debug!("Handling command: {:?}", command); let result = match command { IpcCommand::GetSettings => self.handle_get_settings().await, IpcCommand::UpdateSettings => self.handle_update_settings(message.payload).await, IpcCommand::ResetSettings => self.handle_reset_settings().await, IpcCommand::GetStatus => self.handle_get_status().await, IpcCommand::GetEncoders => self.handle_get_encoders().await, IpcCommand::GetAudioDevices => self.handle_get_audio_devices().await, IpcCommand::AddAudioSource => self.handle_add_audio_source(message.payload).await, IpcCommand::RemoveAudioSource { id } => self.handle_remove_audio_source(id).await, IpcCommand::UpdateAudioSource => self.handle_update_audio_source(message.payload).await, IpcCommand::StartRecording => self.handle_start_recording().await, IpcCommand::StopRecording => self.handle_stop_recording().await, IpcCommand::Shutdown => self.handle_shutdown().await, }; match result { Ok(data) => IpcResponse::success(message.id, data), Err(e) => { info!("Command failed: {}", e); IpcResponse::error(message.id, e.to_string()) } } } async fn handle_get_settings(&self) -> Result { let settings = self.settings.read().clone(); let response = GetSettingsResponse { settings }; Ok(serde_json::to_value(response)?) } async fn handle_update_settings( &self, payload: Option, ) -> Result { let payload = payload.ok_or_else(|| { crate::error::IpcError::InvalidCommand("Missing settings payload".to_string()) })?; let new_settings: Settings = serde_json::from_value(payload)?; // Validate settings if new_settings.video.frame_rate == 0 || new_settings.video.frame_rate > 240 { return Err( crate::error::ConfigError::InvalidConfig("Invalid frame rate".to_string()).into(), ); } // Update settings *self.settings.write() = new_settings.clone(); // Persist settings crate::config::save_config(&new_settings)?; self.push_settings_to_engine().await?; info!("Settings updated"); Ok(serde_json::json!({ "success": true })) } /// Hand the current settings to the recording engine. /// /// The engine keeps its own copy and rebuilds its audio sources from it, so a change made /// here has to travel there as well. The rebuild touches OBS, which must not happen on an /// async worker. async fn push_settings_to_engine(&self) -> Result<()> { let settings = self.settings.read().clone(); let engine = self.recording.clone(); tokio::task::spawn_blocking(move || { if let Some(engine) = engine.write().as_mut() { engine.update_settings(settings)?; } Ok::<_, crate::error::DaemonError>(()) }) .await .map_err(|e| { crate::error::IpcError::InvalidCommand(format!("settings task failed: {e}")) })??; Ok(()) } async fn handle_reset_settings(&self) -> Result { let default_settings = Settings::default(); *self.settings.write() = default_settings.clone(); crate::config::save_config(&default_settings)?; self.push_settings_to_engine().await?; info!("Settings reset to defaults"); Ok(serde_json::to_value(default_settings)?) } async fn handle_get_status(&self) -> Result { let status = *self.status.read(); let recording = self.recording.read(); let is_recording = recording .as_ref() .map(|r| r.is_recording()) .unwrap_or(false); let client_connected = *self.client_connected.read(); let current_game_id = recording.as_ref().and_then(|r| r.current_game_id()); let response = GetStatusResponse { status, is_recording, current_game_id, client_connected, }; Ok(serde_json::to_value(response)?) } async fn handle_get_encoders(&self) -> Result { let capabilities = detect_hardware_encoders(); let current = self .settings .read() .video .encoder_preset .encoder_name() .to_string(); let available: Vec = capabilities .iter() .map(|cap| match cap { EncoderCapability::Nvenc => EncoderInfo { id: "jim_nvenc".to_string(), name: "NVIDIA NVENC".to_string(), is_hardware: true, available: true, }, EncoderCapability::Amf => EncoderInfo { id: "amd_amf_h264".to_string(), name: "AMD AMF".to_string(), is_hardware: true, available: true, }, EncoderCapability::QuickSync => EncoderInfo { id: "qsv".to_string(), name: "Intel QuickSync".to_string(), is_hardware: true, available: true, }, EncoderCapability::Software => EncoderInfo { id: "x264".to_string(), name: "x264 (Software)".to_string(), is_hardware: false, available: true, }, }) .collect(); let response = GetEncodersResponse { available, current }; Ok(serde_json::to_value(response)?) } async fn handle_start_recording(&self) -> Result { // Starting an output touches OBS and hides the screen it renders; on an async worker it // would stall the runtime (and libobs-wrapper's own runtime panics when it is blocked). let recording = self.recording.clone(); tokio::task::spawn_blocking(move || -> Result<()> { let mut recording_guard = recording.write(); let engine = recording_guard.as_mut().ok_or_else(|| { crate::error::RecordingError::ObsInitError( "Recording engine not initialized".to_string(), ) })?; if engine.is_recording() { return Err(crate::error::RecordingError::AlreadyRecording.into()); } engine.start_recording(None, None) }) .await .map_err(|e| { crate::error::IpcError::InvalidCommand(format!("start recording task failed: {e}")) })??; Ok(serde_json::json!({ "success": true })) } async fn handle_stop_recording(&self) -> Result { // Stopping waits for the muxer to close the file, which is exactly the blocking call // that must stay off the async runtime. let recording = self.recording.clone(); let result = tokio::task::spawn_blocking(move || -> Result { let mut recording_guard = recording.write(); let engine = recording_guard.as_mut().ok_or_else(|| { crate::error::RecordingError::ObsInitError( "Recording engine not initialized".to_string(), ) })?; engine.stop_recording() }) .await .map_err(|e| { crate::error::IpcError::InvalidCommand(format!("stop recording task failed: {e}")) })??; self.timeline.write().add_recording(result.clone())?; Ok(serde_json::to_value(result)?) } async fn handle_shutdown(&self) -> Result { info!("Shutdown requested via IPC"); // Signal shutdown through status *self.status.write() = DaemonStatus::ShuttingDown; Ok(serde_json::json!({ "success": true })) } async fn handle_get_audio_devices(&self) -> Result { use super::protocol::GetAudioDevicesResponse; #[cfg(target_os = "windows")] { let (input_devices, output_devices) = enumerate_windows_audio_devices()?; let response = GetAudioDevicesResponse { input_devices, output_devices, }; Ok(serde_json::to_value(response)?) } #[cfg(target_os = "linux")] { // On Linux, enumerate PulseAudio devices let devices = enumerate_linux_audio_devices()?; let response = GetAudioDevicesResponse { input_devices: devices.0, output_devices: devices.1, }; Ok(serde_json::to_value(response)?) } #[cfg(not(any(target_os = "windows", target_os = "linux")))] { // Fallback for other platforms let response = GetAudioDevicesResponse { input_devices: vec![], output_devices: vec![], }; Ok(serde_json::to_value(response)?) } } async fn handle_add_audio_source( &self, payload: Option, ) -> Result { use super::protocol::AudioSourceResponse; let payload = payload.ok_or_else(|| { crate::error::IpcError::InvalidCommand("Missing audio source payload".to_string()) })?; let mut source: crate::config::AudioSourceConfig = serde_json::from_value(payload)?; // Generate a unique ID if not provided if source.id.is_empty() { source.id = uuid::Uuid::new_v4().to_string(); } info!("Adding audio source: {} ({})", source.name, source.id); // Add to settings { let mut settings = self.settings.write(); settings.audio.capture_apps.push(source.clone()); crate::config::save_config(&settings)?; } self.push_settings_to_engine().await?; let response = AudioSourceResponse { source }; Ok(serde_json::to_value(response)?) } async fn handle_remove_audio_source(&self, id: String) -> Result { info!("Removing audio source: {}", id); { let mut settings = self.settings.write(); settings.audio.capture_apps.retain(|s| s.id != id); crate::config::save_config(&settings)?; } self.push_settings_to_engine().await?; Ok(serde_json::json!({ "success": true })) } async fn handle_update_audio_source( &self, payload: Option, ) -> Result { use super::protocol::AudioSourceResponse; let payload = payload.ok_or_else(|| { crate::error::IpcError::InvalidCommand("Missing audio source payload".to_string()) })?; let source: crate::config::AudioSourceConfig = serde_json::from_value(payload)?; info!("Updating audio source: {} ({})", source.name, source.id); { let mut settings = self.settings.write(); if let Some(existing) = settings .audio .capture_apps .iter_mut() .find(|s| s.id == source.id) { *existing = source.clone(); crate::config::save_config(&settings)?; } else { return Err(crate::error::IpcError::InvalidCommand(format!( "Audio source not found: {}", source.id )) .into()); } } self.push_settings_to_engine().await?; let response = AudioSourceResponse { source }; Ok(serde_json::to_value(response)?) } } /// Enumerate audio devices on Windows using WASAPI. /// /// 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, Vec, )> { use super::protocol::AudioDeviceInfo; use tracing::{error, warn}; // Default fallback devices let fallback = || { ( vec![AudioDeviceInfo { id: "default".to_string(), name: "Default Microphone".to_string(), is_default: true, }], vec![AudioDeviceInfo { id: "default".to_string(), name: "Default Speakers".to_string(), is_default: true, }], ) }; // 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 joined { Ok(Ok(Ok(devices))) => Ok(devices), Ok(Ok(Err(e))) => { warn!("WASAPI enumeration failed, keeping the default devices: {e}"); Ok(fallback()) } 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() } } } } /// Inner implementation of Windows audio device enumeration using WASAPI. #[cfg(target_os = "windows")] fn enumerate_windows_audio_devices_inner() -> std::result::Result< ( Vec, Vec, ), String, > { use super::protocol::AudioDeviceInfo; use tracing::{info, warn}; use windows::core::PWSTR; use windows::Win32::Media::Audio::*; use windows::Win32::System::Com::*; fn pwstr_to_string(p: PWSTR) -> String { if p.is_null() { return String::new(); } unsafe { let mut len = 0usize; while *p.0.add(len) != 0 { len += 1; } if len > 0 { let wide = std::slice::from_raw_parts(p.0, len); String::from_utf16_lossy(wide) } else { String::new() } } } info!( "[AUDIO_ENUM] starting WASAPI enumeration on {:?}", std::thread::current().id() ); // 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()); 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:?}"))?; // 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); let default_output_id: Option = enumerator .GetDefaultAudioEndpoint(eRender, eCommunications) .ok() .and_then(|dev| dev.GetId().ok()) .map(pwstr_to_string); 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 is_default = id_str .as_ref() .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)); info!("[AUDIO_ENUM] input {i}: {name} (default: {is_default})"); input_devices.push(AudioDeviceInfo { id, name, is_default, }); } } } } 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 is_default = id_str .as_ref() .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)); info!("[AUDIO_ENUM] output {i}: {name} (default: {is_default})"); output_devices.push(AudioDeviceInfo { id, name, is_default, }); } } } } } // If no devices came back, hand out the endpoints everyone has. if input_devices.is_empty() { input_devices.push(AudioDeviceInfo { id: "default".to_string(), name: "Default Microphone".to_string(), is_default: true, }); } if output_devices.is_empty() { output_devices.push(AudioDeviceInfo { id: "default".to_string(), name: "Default Speakers".to_string(), is_default: true, }); } Ok((input_devices, output_devices)) } /// Get the friendly name of an audio device (`PKEY_Device_FriendlyName`). /// /// 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-67d146a850e0}, 14 const FRIENDLY_NAME_KEY: PROPERTYKEY = PROPERTYKEY { fmtid: windows::core::GUID::from_u128(0xa45c254e_df1c_4efd_8020_67d146a850e0), pid: 14, }; // 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 = 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; } }; // `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()) } })); match result { Ok(name) => name, Err(_) => { warn!("[AUDIO_ENUM] reading the friendly name panicked"); None } } } /// Enumerate audio devices on Linux using PulseAudio. #[cfg(target_os = "linux")] fn enumerate_linux_audio_devices() -> Result<( Vec, Vec, )> { use super::protocol::AudioDeviceInfo; use tracing::warn; let mut input_devices = Vec::new(); let mut output_devices = Vec::new(); // Provide default devices input_devices.push(AudioDeviceInfo { id: "default".to_string(), name: "Default Microphone".to_string(), is_default: true, }); output_devices.push(AudioDeviceInfo { id: "default".to_string(), name: "Default Speakers".to_string(), is_default: true, }); // TODO: Enumerate actual PulseAudio devices using libpulse-binding warn!("Full PulseAudio device enumeration not yet implemented, returning default devices only"); Ok((input_devices, output_devices)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_handlers_creation() { let settings = Arc::new(RwLock::new(Settings::default())); let recording = Arc::new(RwLock::new(None)); let timeline = Arc::new(RwLock::new(TimelineStore::new())); let status = Arc::new(RwLock::new(DaemonStatus::Idle)); let client_connected = Arc::new(RwLock::new(false)); let _handlers = IpcHandlers::new(settings, recording, timeline, status, client_connected); } }