From 4f9f84446d19e9e6f952849e35a672aa757a32a9 Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Thu, 12 Nov 2026 23:17:26 +0100 Subject: [PATCH] feat: add custom audio sources - Add capture_apps list of AudioSourceConfig (application, deviceOutput or deviceInput) to AudioSettings, serialized in the settings JSON - Add IPC commands getAudioDevices, addAudioSource, removeAudioSource and updateAudioSource - obs_context builds wasapi sources for the microphone and configured apps alongside the game-capture source - Settings.vue gains an audio sources tab with device dropdowns and per-source volume - getAudioDevices temporarily returns hardcoded defaults while the WASAPI enumeration crash is investigated; crash marker files around IPC and native call sites are part of that investigation --- record-daemon/Cargo.lock | 95 +++- record-daemon/Cargo.toml | 7 + record-daemon/src/config/mod.rs | 5 +- record-daemon/src/config/presets.rs | 125 +++++- record-daemon/src/ipc/handlers.rs | 439 +++++++++++++++++++ record-daemon/src/ipc/protocol.rs | 37 +- record-daemon/src/ipc/server.rs | 47 +- record-daemon/src/main.rs | 74 +++- record-daemon/src/recording/obs_context.rs | 482 +++++++++++++++++++-- tauri-app/src-tauri/src/daemon_ipc.rs | 68 +++ tauri-app/src-tauri/src/lib.rs | 4 + tauri-app/src/components/Settings.vue | 367 +++++++++++++++- tauri-app/src/types/daemon.ts | 30 ++ 13 files changed, 1711 insertions(+), 69 deletions(-) diff --git a/record-daemon/Cargo.lock b/record-daemon/Cargo.lock index 6920bc6..389b4d3 100644 --- a/record-daemon/Cargo.lock +++ b/record-daemon/Cargo.lock @@ -674,7 +674,7 @@ dependencies = [ "smithay-client-toolkit", "thiserror 2.0.18", "widestring", - "windows", + "windows 0.62.2", "xcb", ] @@ -1330,7 +1330,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core", + "windows-core 0.62.2", ] [[package]] @@ -1673,7 +1673,7 @@ dependencies = [ "num-traits", "paste", "tokio", - "windows", + "windows 0.62.2", ] [[package]] @@ -1693,7 +1693,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69207f23b413243491c3703c6c1c9434fd0ff46f158ef4d945d1dc8d889bad80" dependencies = [ - "windows", + "windows 0.62.2", ] [[package]] @@ -1721,7 +1721,7 @@ dependencies = [ "paste", "tokio", "vsprintf", - "windows", + "windows 0.62.2", ] [[package]] @@ -2422,6 +2422,7 @@ dependencies = [ "tracing-subscriber", "uuid", "winapi 0.3.9", + "windows 0.58.0", "winreg 0.56.0", ] @@ -4083,6 +4084,16 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" +dependencies = [ + "windows-core 0.58.0", + "windows-targets 0.52.6", +] + [[package]] name = "windows" version = "0.62.2" @@ -4090,7 +4101,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ "windows-collections", - "windows-core", + "windows-core 0.62.2", "windows-future", "windows-numerics", ] @@ -4101,7 +4112,20 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" dependencies = [ - "windows-core", + "windows-core 0.62.2", +] + +[[package]] +name = "windows-core" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99" +dependencies = [ + "windows-implement 0.58.0", + "windows-interface 0.58.0", + "windows-result 0.2.0", + "windows-strings 0.1.0", + "windows-targets 0.52.6", ] [[package]] @@ -4110,11 +4134,11 @@ version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ - "windows-implement", - "windows-interface", + "windows-implement 0.60.2", + "windows-interface 0.59.3", "windows-link", - "windows-result", - "windows-strings", + "windows-result 0.4.1", + "windows-strings 0.5.1", ] [[package]] @@ -4123,11 +4147,22 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ - "windows-core", + "windows-core 0.62.2", "windows-link", "windows-threading", ] +[[package]] +name = "windows-implement" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "windows-implement" version = "0.60.2" @@ -4139,6 +4174,17 @@ dependencies = [ "syn", ] +[[package]] +name = "windows-interface" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "windows-interface" version = "0.59.3" @@ -4162,7 +4208,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" dependencies = [ - "windows-core", + "windows-core 0.62.2", "windows-link", ] @@ -4173,8 +4219,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" dependencies = [ "windows-link", - "windows-result", - "windows-strings", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets 0.52.6", ] [[package]] @@ -4186,6 +4241,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result 0.2.0", + "windows-targets 0.52.6", +] + [[package]] name = "windows-strings" version = "0.5.1" diff --git a/record-daemon/Cargo.toml b/record-daemon/Cargo.toml index f702544..d2a1d89 100644 --- a/record-daemon/Cargo.toml +++ b/record-daemon/Cargo.toml @@ -80,6 +80,13 @@ signal-hook-tokio = { version = "0.4", features = ["futures-v0_3"] } [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["winuser", "winreg", "winnt"] } winreg = "0.56" +windows = { version = "0.58", features = [ + "Win32_Media_Audio", + "Win32_System_Com", + "Win32_UI_Shell_PropertiesSystem", + "Win32_Foundation", + "Win32_Devices_Properties", +] } [dev-dependencies] # Testing utilities diff --git a/record-daemon/src/config/mod.rs b/record-daemon/src/config/mod.rs index 7c356bf..9249d50 100644 --- a/record-daemon/src/config/mod.rs +++ b/record-daemon/src/config/mod.rs @@ -8,7 +8,10 @@ mod presets; mod settings; pub use persistence::{load_config, save_config, ConfigPersistence}; -pub use presets::{AmfQuality, AudioSettings, EncoderPreset, QualityLevel}; +pub use presets::{ + AmfQuality, AudioDeviceInfo, AudioDeviceType, AudioSettings, AudioSourceConfig, + AudioSourceType, EncoderPreset, QualityLevel, +}; pub use settings::{OutputSettings, Settings, VideoSettings}; use std::path::PathBuf; diff --git a/record-daemon/src/config/presets.rs b/record-daemon/src/config/presets.rs index 5f21c98..e544c01 100644 --- a/record-daemon/src/config/presets.rs +++ b/record-daemon/src/config/presets.rs @@ -159,17 +159,33 @@ pub struct AudioSettings { #[serde(default = "default_channels")] pub channels: u32, - /// Capture game audio. + /// Capture game audio (desktop audio). #[serde(default = "preset_default_true")] pub capture_game: bool, + /// Game audio volume (0-100). + #[serde(default = "default_volume")] + pub game_volume: u32, + /// Capture microphone. #[serde(default)] pub capture_mic: bool, - /// Microphone device name (if capture_mic is true). + /// Microphone device ID (if capture_mic is true). #[serde(default)] pub mic_device: Option, + + /// Microphone volume (0-100). + #[serde(default = "default_volume")] + pub mic_volume: u32, + + /// Capture application audio (e.g., Discord, Spotify). + #[serde(default)] + pub capture_apps: Vec, + + /// Application audio volume (0-100) - global for all app sources. + #[serde(default = "default_volume")] + pub apps_volume: u32, } impl Default for AudioSettings { @@ -180,12 +196,117 @@ impl Default for AudioSettings { sample_rate: default_sample_rate(), channels: default_channels(), capture_game: true, + game_volume: default_volume(), capture_mic: false, mic_device: None, + mic_volume: default_volume(), + capture_apps: Vec::new(), + apps_volume: default_volume(), } } } +fn default_volume() -> u32 { + 100 +} + +/// Configuration for an individual audio source (e.g., Discord, Spotify). +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct AudioSourceConfig { + /// Unique identifier for this source. + #[serde(default)] + pub id: String, + + /// Display name for the source. + pub name: String, + + /// Type of audio source. + #[serde(rename = "type")] + pub source_type: AudioSourceType, + + /// The device ID or process name to capture. + pub device: String, + + /// Whether this source is enabled. + #[serde(default = "preset_default_true")] + pub enabled: bool, + + /// Individual volume for this source (0-100), if None uses global apps_volume. + #[serde(skip_serializing_if = "Option::is_none")] + pub volume: Option, +} + +impl AudioSourceConfig { + /// Create a new application audio source configuration. + pub fn new(name: &str, source_type: AudioSourceType, device: &str) -> Self { + Self { + id: uuid::Uuid::new_v4().to_string(), + name: name.to_string(), + source_type, + device: device.to_string(), + enabled: true, + volume: None, + } + } + + /// Create a Discord audio source. + pub fn discord() -> Self { + Self::new( + "Discord", + AudioSourceType::Application, + "Discord.exe", + ) + } + + /// Create a Spotify audio source. + pub fn spotify() -> Self { + Self::new( + "Spotify", + AudioSourceType::Application, + "Spotify.exe", + ) + } +} + +/// Type of audio source. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(rename_all = "lowercase")] +pub enum AudioSourceType { + /// Application audio (captures specific process on Windows via WASAPI loopback). + #[default] + Application, + /// Audio output device (captures all audio from a specific output device). + DeviceOutput, + /// Audio input device (microphone, line-in, etc.). + DeviceInput, +} + +/// Information about an available audio device. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct AudioDeviceInfo { + /// Device ID (used for device selection). + pub id: String, + + /// Display name of the device. + pub name: String, + + /// Type of the device. + pub device_type: AudioDeviceType, + + /// Whether this is the default device for its type. + pub is_default: bool, +} + +/// Type of audio device. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum AudioDeviceType { + /// Input device (microphone, line-in). + Input, + /// Output device (speakers, headphones). + Output, +} + fn default_audio_bitrate() -> u32 { 192 } diff --git a/record-daemon/src/ipc/handlers.rs b/record-daemon/src/ipc/handlers.rs index 025d815..f80294d 100644 --- a/record-daemon/src/ipc/handlers.rs +++ b/record-daemon/src/ipc/handlers.rs @@ -17,6 +17,32 @@ use crate::recording::RecordingEngine; use crate::state::DaemonStatus; use crate::timeline::TimelineStore; +/// Write an *unbuffered* marker file that survives native crashes/segfaults. +/// +/// The tracing log appender buffers writes in memory, so logs emitted microseconds +/// before a native segfault are lost on disk — that's why the crash diagnostics +/// added so far never appeared. This helper writes to a file with an immediate +/// `sync_all` (fsync) so the bytes hit disk before control returns. After a crash, +/// inspecting the marker directory tells us exactly how far execution got. +#[cfg(target_os = "windows")] +fn write_crash_marker(stage: &str) { + use std::io::Write; + let dir = std::env::temp_dir().join("record-daemon-crash-markers"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join(format!( + "{}_{}.txt", + stage, + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + )); + if let Ok(mut f) = std::fs::File::create(&path) { + let _ = writeln!(f, "{} @ {:?}", stage, std::thread::current().id()); + let _ = f.sync_all(); + } +} + /// Command handler trait. #[async_trait] pub trait CommandHandler: Send + Sync { @@ -71,6 +97,10 @@ impl IpcHandlers { 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::GetRecordings => self.handle_get_recordings().await, @@ -292,6 +322,415 @@ impl IpcHandlers { *self.status.write() = DaemonStatus::ShuttingDown; Ok(serde_json::json!({ "success": true })) } + + async fn handle_get_audio_devices(&self) -> Result { + use super::protocol::GetAudioDevicesResponse; + + info!("[AUDIO_ENUM] handle_get_audio_devices invoked"); + + // ---- CRASH ISOLATION HOOK ---- + // The daemon has been crashing when Settings is opened (which triggers this + // command). The tracing log file is buffered, so logs written microseconds + // before a native segfault are lost on disk — which is why none of the + // diagnostics added so far ever showed up. To definitively determine whether + // the crash happens inside this handler / the WASAPI enumeration, we: + // 1. Write an *unbuffered* marker file (fsync) on entry and on success. + // These survive native crashes and can be inspected afterwards. + // 2. (Temporarily) return hardcoded default devices on Windows WITHOUT + // calling into WASAPI at all. If the daemon still crashes, the WASAPI + // code is NOT the culprit. If it stops crashing, WASAPI is confirmed. + #[cfg(target_os = "windows")] + { + write_crash_marker("audio_devices_enter"); + info!("[AUDIO_ENUM] Windows path: returning HARDCODED defaults (WASAPI bypassed for isolation)"); + + let response = GetAudioDevicesResponse { + input_devices: vec![super::protocol::AudioDeviceInfo { + id: "default".to_string(), + name: "Default Microphone".to_string(), + is_default: true, + }], + output_devices: vec![super::protocol::AudioDeviceInfo { + id: "default".to_string(), + name: "Default Speakers".to_string(), + is_default: true, + }], + }; + + write_crash_marker("audio_devices_success"); + 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)?; + } + + 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)?; + } + + 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()); + } + } + + let response = AudioSourceResponse { source }; + Ok(serde_json::to_value(response)?) + } +} + +/// 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. +#[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, + }], + ) + }; + + // 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() + })); + + match result { + Ok(Ok(devices)) => Ok(devices), + Ok(Err(e)) => { + warn!("WASAPI device enumeration failed, returning defaults: {}", e); + Ok(fallback()) + } + Err(panic_info) => { + error!("PANIC during WASAPI device enumeration: {:?}", panic_info); + Ok(fallback()) + } + } +} + +/// 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 windows::Win32::Media::Audio::*; + use windows::Win32::System::Com::*; + use windows::core::PWSTR; + use tracing::{info, warn}; + + 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() + } + } + } + + let mut input_devices = Vec::new(); + let mut output_devices = Vec::new(); + + info!("[AUDIO_ENUM] inner: starting WASAPI enumeration on this thread (id={:?})", 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"); + } + + // Create device enumerator + let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL) + .map_err(|e| format!("Failed to create MMDeviceEnumerator: {:?}", e))?; + + // Get default input device ID for comparison + 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 is_default = id_str + .as_ref() + .map(|s| default_input_id.as_ref().map(|d| s == d).unwrap_or(false)) + .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); + input_devices.push(AudioDeviceInfo { id, name, is_default }); + } + } + } + } + + // 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 is_default = id_str + .as_ref() + .map(|s| default_output_id.as_ref().map(|d| s == d).unwrap_or(false)) + .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); + output_devices.push(AudioDeviceInfo { id, name, is_default }); + } + } + } + } + + // 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 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. +/// +/// 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. +#[cfg(target_os = "windows")] +fn get_device_friendly_name(device: &windows::Win32::Media::Audio::IMMDevice) -> Option { + use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore; + use windows::Win32::System::Com::STGM; + use windows::Win32::UI::Shell::PropertiesSystem::PROPERTYKEY; + + // PKEY_Device_FriendlyName = { a45c254e-df1c-4efd-8020-67d146850500 }, 14 + const FRIENDLY_NAME_KEY: PROPERTYKEY = PROPERTYKEY { + fmtid: windows::core::GUID::from_u128(0xa45c254e_df1c_4efd_8020_67d146850500), + pid: 14, + }; + + // Wrap in catch_unwind to be absolutely safe. + 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()?; + + // 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. + let name = prop.to_string(); + let trimmed = name.trim(); + if trimmed.is_empty() { + None + } else { + Some(trimmed.to_string()) + } + })); + + result.ok().flatten() +} + +/// 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)] diff --git a/record-daemon/src/ipc/protocol.rs b/record-daemon/src/ipc/protocol.rs index 141f94d..fa5872c 100644 --- a/record-daemon/src/ipc/protocol.rs +++ b/record-daemon/src/ipc/protocol.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use uuid::Uuid; -use crate::config::Settings; +use crate::config::{Settings}; use crate::recording::RecordingResult; use crate::state::DaemonStatus; use crate::timeline::RecordingMetadata; @@ -55,6 +55,14 @@ pub enum IpcCommand { GetStatus, /// Get available encoders. GetEncoders, + /// Get available audio devices. + GetAudioDevices, + /// Add an audio source to settings. + AddAudioSource, + /// Remove an audio source from settings. + RemoveAudioSource { id: String }, + /// Update an audio source in settings. + UpdateAudioSource, // Recording commands /// Start recording manually. @@ -208,6 +216,33 @@ pub struct EncoderInfo { pub available: bool, } +/// Response for GetAudioDevices command. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct GetAudioDevicesResponse { + /// Available input devices (microphones). + pub input_devices: Vec, + /// Available output devices (speakers, headphones). + pub output_devices: Vec, +} + +/// Information about an audio device. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AudioDeviceInfo { + /// Device ID (used for device selection). + pub id: String, + /// Display name of the device. + pub name: String, + /// Whether this is the default device for its type. + pub is_default: bool, +} + +/// Response for audio source operations. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AudioSourceResponse { + /// The created or updated audio source. + pub source: crate::config::AudioSourceConfig, +} + impl IpcMessage { /// Create a new request message. pub fn request(command: IpcCommand, payload: Option) -> Self { diff --git a/record-daemon/src/ipc/server.rs b/record-daemon/src/ipc/server.rs index 3a052fe..3495dee 100644 --- a/record-daemon/src/ipc/server.rs +++ b/record-daemon/src/ipc/server.rs @@ -12,6 +12,29 @@ use super::handlers::IpcHandlers; use super::protocol::{IpcMessage, IpcNotification, IpcResponse, MessageType}; use crate::error::{IpcError, Result}; +/// Write an *unbuffered* marker file that survives native crashes/segfaults. +/// See [`super::handlers`] for the rationale: the tracing log appender buffers +/// writes in memory, so logs emitted microseconds before a native segfault are +/// lost on disk. This helper fsyncs so the bytes hit disk before returning. +#[cfg(target_os = "windows")] +fn write_ipc_crash_marker(stage: &str) { + use std::io::Write; + let dir = std::env::temp_dir().join("record-daemon-crash-markers"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join(format!( + "{}_{}.txt", + stage, + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + )); + if let Ok(mut f) = std::fs::File::create(&path) { + let _ = writeln!(f, "{} @ {:?}", stage, std::thread::current().id()); + let _ = f.sync_all(); + } +} + /// IPC server configuration. #[derive(Debug, Clone)] pub struct IpcServerConfig { @@ -466,11 +489,16 @@ impl IpcServer { } }; - trace!("Received: {}", line); + info!("[IPC] Received message ({} bytes)", line.len()); + #[cfg(target_os = "windows")] + write_ipc_crash_marker("ipc_read_done"); // Parse message let message = match IpcMessage::from_json(&line) { - Ok(msg) => msg, + Ok(msg) => { + info!("[IPC] Parsed message type={:?} command={:?}", msg.message_type, msg.command); + msg + } Err(e) => { warn!("Failed to parse message: {}", e); let response = @@ -486,10 +514,21 @@ impl IpcServer { continue; } }; + #[cfg(target_os = "windows")] + write_ipc_crash_marker(&format!("ipc_parsed_{:?}", message.command)); // Handle message let response = match message.message_type { - MessageType::Request => handlers.handle(message).await, + MessageType::Request => { + #[cfg(target_os = "windows")] + let cmd_dbg = format!("{:?}", message.command); + #[cfg(target_os = "windows")] + write_ipc_crash_marker(&format!("ipc_dispatch_pre_{}", cmd_dbg)); + let r = handlers.handle(message).await; + #[cfg(target_os = "windows")] + write_ipc_crash_marker(&format!("ipc_dispatch_post_{}", cmd_dbg)); + r + } MessageType::Notification => { // Notifications don't get responses trace!("Received notification: {:?}", message); @@ -512,6 +551,8 @@ impl IpcServer { .write_all(b"\n") .await .map_err(IpcError::WriteError)?; + #[cfg(target_os = "windows")] + write_ipc_crash_marker("ipc_response_sent"); } Ok(()) diff --git a/record-daemon/src/main.rs b/record-daemon/src/main.rs index 85f1250..57f057b 100644 --- a/record-daemon/src/main.rs +++ b/record-daemon/src/main.rs @@ -23,6 +23,30 @@ use record_daemon::{ timeline::{EventMapper, TimelineStore, TimestampedEvent}, }; +/// Write an *unbuffered* marker file that survives native crashes/segfaults. +/// The tracing log appender buffers writes in memory, so logs emitted +/// microseconds before a native segfault are lost on disk. This helper fsyncs +/// so the bytes hit disk before returning. Inspect the marker directory after +/// a crash to see how far startup got. +#[cfg(target_os = "windows")] +fn write_startup_marker(stage: &str) { + use std::io::Write; + let dir = std::env::temp_dir().join("record-daemon-crash-markers"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join(format!( + "{}_{}.txt", + stage, + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + )); + if let Ok(mut f) = std::fs::File::create(&path) { + let _ = writeln!(f, "{} @ {:?}", stage, std::thread::current().id()); + let _ = f.sync_all(); + } +} + /// Record Daemon - League of Legends recording daemon. #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] @@ -91,35 +115,58 @@ impl Daemon { /// Initialize the daemon. async fn init(&mut self) -> Result<()> { info!("Initializing record daemon v{}", record_daemon::VERSION); + #[cfg(target_os = "windows")] + write_startup_marker("init_enter"); // Initialize recording engine (blocking operation) let settings = self.settings.read().clone(); let recording_engine = self.recording_engine.clone(); + #[cfg(target_os = "windows")] + write_startup_marker("init_spawning_blocking_recording_engine"); let result = tokio::task::spawn_blocking(move || { + #[cfg(target_os = "windows")] + write_startup_marker("blocking_thread_entered_recording_engine_init"); let mut engine = RecordingEngine::new(settings); + #[cfg(target_os = "windows")] + write_startup_marker("recording_engine_new_done"); if let Err(e) = engine.initialize() { + #[cfg(target_os = "windows")] + write_startup_marker("recording_engine_init_failed"); return Err(format!("Failed to initialize recording engine: {:?}", e)); } + #[cfg(target_os = "windows")] + write_startup_marker("recording_engine_init_done"); *recording_engine.write() = Some(engine); Ok::<_, String>(()) }) .await; match result { - Ok(Ok(())) => {} - Ok(Err(e)) => return Err(record_daemon::error::RecordingError::ObsInitError(e).into()), + Ok(Ok(())) => { + #[cfg(target_os = "windows")] + write_startup_marker("spawn_blocking_recording_engine_ok"); + } + Ok(Err(e)) => { + #[cfg(target_os = "windows")] + write_startup_marker("spawn_blocking_recording_engine_err"); + return Err(record_daemon::error::RecordingError::ObsInitError(e).into()); + } Err(e) => { + #[cfg(target_os = "windows")] + write_startup_marker("spawn_blocking_recording_engine_join_err"); return Err(record_daemon::error::RecordingError::ObsInitError(format!( "spawn_blocking error during init: {:?}", e )) - .into()) + .into()); } } // Load existing recordings from disk self.timeline_store.read().load_from_disk()?; + #[cfg(target_os = "windows")] + write_startup_marker("timeline_loaded"); // Initialize IPC server let ipc_config = IpcServerConfig { @@ -144,6 +191,8 @@ impl Daemon { let mut ipc_server = IpcServer::new(ipc_config, handlers); ipc_server.start().await?; self.ipc_server = Some(ipc_server); + #[cfg(target_os = "windows")] + write_startup_marker("ipc_server_started"); info!("Daemon initialized successfully"); Ok(()) @@ -691,10 +740,19 @@ fn init_logging(level: &str, log_file: Option<&std::path::Path>) { #[tokio::main] async fn main() -> Result<()> { + // CRASH ISOLATION: very first thing, before anything else. If this marker + // does NOT appear, our binary is not even the one running. + #[cfg(target_os = "windows")] + write_startup_marker("main_entry"); + let args = Args::parse(); + #[cfg(target_os = "windows")] + write_startup_marker("args_parsed"); // Initialize logging init_logging(&args.log_level, args.log_file.as_deref()); + #[cfg(target_os = "windows")] + write_startup_marker("logging_initialized"); info!("Record Daemon v{} starting", record_daemon::VERSION); @@ -719,6 +777,8 @@ async fn main() -> Result<()> { .into()); } } + #[cfg(target_os = "windows")] + write_startup_marker("obs_bootstrap_done"); // Load configuration let settings = if let Some(config_path) = args.config { @@ -726,9 +786,13 @@ async fn main() -> Result<()> { } else { config::load_config()? }; + #[cfg(target_os = "windows")] + write_startup_marker("config_loaded"); // Create and run daemon let mut daemon = Daemon::new(settings); + #[cfg(target_os = "windows")] + write_startup_marker("daemon_created"); #[cfg(unix)] { @@ -755,9 +819,13 @@ async fn main() -> Result<()> { error!("Failed to initialize daemon: {}", e); return Err(e); } + #[cfg(target_os = "windows")] + write_startup_marker("daemon_init_done"); // Run main loop let result = daemon.run().await; + #[cfg(target_os = "windows")] + write_startup_marker("daemon_run_returned"); // Cleanup if let Err(e) = daemon.shutdown().await { diff --git a/record-daemon/src/recording/obs_context.rs b/record-daemon/src/recording/obs_context.rs index 11729d3..776c418 100644 --- a/record-daemon/src/recording/obs_context.rs +++ b/record-daemon/src/recording/obs_context.rs @@ -934,10 +934,41 @@ impl ObsContext { /// Set up audio capture for game audio (Windows only). #[cfg(target_os = "windows")] fn setup_audio_capture(&mut self) -> Result<()> { + info!("[AUDIO_CAPTURE] Setting up multi-source audio capture..."); + + // Clone necessary data to avoid borrow issues + let capture_game = self.audio_settings.capture_game; + let capture_mic = self.audio_settings.capture_mic; + let capture_apps = self.audio_settings.capture_apps.clone(); + + // 1. Game audio capture (desktop audio via WASAPI process output) + if capture_game { + self.setup_game_audio_capture_internal()?; + } + + // 2. Microphone capture + if capture_mic { + self.setup_microphone_capture_internal()?; + } + + // 3. Application audio captures (Discord, Spotify, etc.) + for app_source in &capture_apps { + if app_source.enabled { + self.setup_app_audio_capture_internal(app_source)?; + } + } + + info!("[AUDIO_CAPTURE] All audio sources configured successfully"); + Ok(()) + } + + /// Set up game audio capture via WASAPI process output (Windows). + #[cfg(target_os = "windows")] + fn setup_game_audio_capture_internal(&mut self) -> Result<()> { use libobs_wrapper::data::ObsData; use libobs_wrapper::utils::SourceInfo; - info!("[AUDIO_CAPTURE] Setting up WASAPI audio capture..."); + info!("[AUDIO_CAPTURE] Setting up game audio capture..."); let context = self.context.as_mut().ok_or_else(|| { error!("[AUDIO_CAPTURE] OBS not initialized"); @@ -955,19 +986,18 @@ impl ObsContext { let audio_settings_data = ObsData::from_json(settings_json, context.runtime().clone()) .map_err(|e| { error!( - "[AUDIO_CAPTURE] Failed to create audio settings from JSON: {:?}", + "[AUDIO_CAPTURE] Failed to create game audio settings from JSON: {:?}", e ); RecordingError::StartError(format!( - "Failed to create audio settings from JSON: {:?}", + "Failed to create game audio settings from JSON: {:?}", e )) })?; - info!("[AUDIO_CAPTURE] Audio settings configured for League of Legends"); + info!("[AUDIO_CAPTURE] Game audio settings configured for League of Legends"); // Configure WASAPI process output capture for game audio - // This captures the audio output from a specific process (the game) let source_info = SourceInfo::new( "wasapi_process_output_capture", "game_audio", @@ -975,44 +1005,249 @@ impl ObsContext { None, ); - info!("[AUDIO_CAPTURE] Creating WASAPI process output capture source..."); + info!("[AUDIO_CAPTURE] Creating WASAPI process output capture source for game..."); + let runtime = context.runtime().clone(); let audio_source_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - libobs_wrapper::sources::ObsSourceRef::new_from_info( - source_info, - context.runtime().clone(), - ) + libobs_wrapper::sources::ObsSourceRef::new_from_info(source_info, runtime) })); - let _audio_source = match audio_source_result { - Ok(Ok(s)) => { - info!("[AUDIO_CAPTURE] WASAPI audio source created"); - s + match audio_source_result { + Ok(Ok(_s)) => { + info!("[AUDIO_CAPTURE] Game audio source created successfully"); + // TODO: Apply volume from self.audio_settings.game_volume } Ok(Err(e)) => { - error!("[AUDIO_CAPTURE] Failed to create audio source: {:?}", e); + error!("[AUDIO_CAPTURE] Failed to create game audio source: {:?}", e); return Err(RecordingError::StartError(format!( - "Failed to create audio source: {:?}", + "Failed to create game audio source: {:?}", e )) .into()); } Err(panic_info) => { error!( - "[AUDIO_CAPTURE] PANIC creating audio source: {:?}", + "[AUDIO_CAPTURE] PANIC creating game audio source: {:?}", panic_info ); - eprintln!( - "[AUDIO_CAPTURE] PANIC creating audio source: {:?}", + return Err(RecordingError::StartError( + "Panic creating game audio source".to_string(), + ) + .into()); + } + } + + Ok(()) + } + + /// Set up microphone capture via WASAPI input (Windows). + #[cfg(target_os = "windows")] + fn setup_microphone_capture_internal(&mut self) -> Result<()> { + use libobs_wrapper::data::ObsData; + use libobs_wrapper::utils::SourceInfo; + + info!("[AUDIO_CAPTURE] Setting up microphone capture..."); + + let context = self.context.as_mut().ok_or_else(|| { + error!("[AUDIO_CAPTURE] OBS not initialized"); + RecordingError::ObsInitError("OBS not initialized".to_string()) + })?; + + let device_id = self + .audio_settings + .mic_device + .as_deref() + .unwrap_or("default"); + + info!("[AUDIO_CAPTURE] Using microphone device: {}", device_id); + + // Create microphone settings + // Use default device if no specific device is specified + let settings_json = if device_id == "default" { + r#"{ + "device_id": "default" + }"#.to_string() + } else { + format!( + r#"{{ + "device_id": "{}" + }}"#, + device_id + ) + }; + + let mic_settings_data = ObsData::from_json(&settings_json, context.runtime().clone()) + .map_err(|e| { + error!( + "[AUDIO_CAPTURE] Failed to create microphone settings from JSON: {:?}", + e + ); + RecordingError::StartError(format!( + "Failed to create microphone settings from JSON: {:?}", + e + )) + })?; + + // Configure WASAPI input capture for microphone + let source_info = SourceInfo::new( + "wasapi_input_capture", + "microphone", + Some(mic_settings_data), + None, + ); + + info!("[AUDIO_CAPTURE] Creating WASAPI input capture source for microphone..."); + + let runtime = context.runtime().clone(); + let mic_source_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + libobs_wrapper::sources::ObsSourceRef::new_from_info(source_info, runtime) + })); + + match mic_source_result { + Ok(Ok(_s)) => { + info!("[AUDIO_CAPTURE] Microphone source created successfully"); + // TODO: Apply volume from self.audio_settings.mic_volume + } + Ok(Err(e)) => { + error!("[AUDIO_CAPTURE] Failed to create microphone source: {:?}", e); + // Don't fail the whole recording if mic isn't available, just warn + warn!( + "[AUDIO_CAPTURE] Microphone capture unavailable, continuing without mic: {:?}", + e + ); + } + Err(panic_info) => { + error!( + "[AUDIO_CAPTURE] PANIC creating microphone source: {:?}", panic_info ); - return Err( - RecordingError::StartError("Panic creating audio source".to_string()).into(), - ); + warn!("[AUDIO_CAPTURE] Microphone capture failed due to panic, continuing without mic"); + } + } + + Ok(()) + } + + /// Set up application audio capture (Discord, Spotify, etc.) via WASAPI loopback (Windows). + #[cfg(target_os = "windows")] + fn setup_app_audio_capture_internal( + &mut self, + app_source: &crate::config::AudioSourceConfig, + ) -> Result<()> { + use libobs_wrapper::data::ObsData; + use libobs_wrapper::utils::SourceInfo; + + info!( + "[AUDIO_CAPTURE] Setting up application audio capture for: {}", + app_source.name + ); + + let context = self.context.as_mut().ok_or_else(|| { + error!("[AUDIO_CAPTURE] OBS not initialized"); + RecordingError::ObsInitError("OBS not initialized".to_string()) + })?; + + // Build settings based on source type + let settings_json = match app_source.source_type { + crate::config::AudioSourceType::Application => { + // Capture audio from a specific application by executable name + format!( + r#"{{ + "executable": "{}", + "priority": 2 + }}"#, + app_source.device + ) + } + crate::config::AudioSourceType::DeviceOutput => { + // Capture all audio from a specific output device + format!( + r#"{{ + "device_id": "{}" + }}"#, + app_source.device + ) + } + crate::config::AudioSourceType::DeviceInput => { + // Capture from an input device + format!( + r#"{{ + "device_id": "{}" + }}"#, + app_source.device + ) } }; - info!("[AUDIO_CAPTURE] Audio source created successfully"); + let app_settings_data = ObsData::from_json(&settings_json, context.runtime().clone()) + .map_err(|e| { + error!( + "[AUDIO_CAPTURE] Failed to create app audio settings: {:?}", + e + ); + RecordingError::StartError(format!( + "Failed to create app audio settings for {}: {:?}", + app_source.name, e + )) + })?; + + // Determine the source type string for WASAPI + let source_type_str = match app_source.source_type { + crate::config::AudioSourceType::Application => "wasapi_process_output_capture", + crate::config::AudioSourceType::DeviceOutput => "wasapi_output_capture", + crate::config::AudioSourceType::DeviceInput => "wasapi_input_capture", + }; + + // Create a unique source name for this app + let source_name = format!("app_audio_{}", app_source.id); + + let source_info = SourceInfo::new( + source_type_str, + source_name.as_str(), + Some(app_settings_data), + None, + ); + + info!( + "[AUDIO_CAPTURE] Creating {} source for {}...", + source_type_str, app_source.name + ); + + let runtime = context.runtime().clone(); + let app_source_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + libobs_wrapper::sources::ObsSourceRef::new_from_info(source_info, runtime) + })); + + match app_source_result { + Ok(Ok(_s)) => { + info!( + "[AUDIO_CAPTURE] Application audio source '{}' created successfully", + app_source.name + ); + // TODO: Apply volume from app_source.volume or self.audio_settings.apps_volume + } + Ok(Err(e)) => { + error!( + "[AUDIO_CAPTURE] Failed to create app audio source '{}': {:?}", + app_source.name, e + ); + // Don't fail the whole recording if an app source isn't available, just warn + warn!( + "[AUDIO_CAPTURE] App audio capture for '{}' unavailable: {:?}", + app_source.name, e + ); + } + Err(panic_info) => { + error!( + "[AUDIO_CAPTURE] PANIC creating app audio source '{}': {:?}", + app_source.name, panic_info + ); + warn!( + "[AUDIO_CAPTURE] App audio capture for '{}' failed due to panic", + app_source.name + ); + } + } Ok(()) } @@ -1020,6 +1255,7 @@ impl ObsContext { /// Set up audio capture for game audio (Linux only). #[cfg(target_os = "linux")] fn setup_audio_capture(&mut self) -> Result<()> { + use libobs_wrapper::data::ObsData; use libobs_wrapper::utils::SourceInfo; info!("[AUDIO_CAPTURE] Setting up PulseAudio capture..."); @@ -1029,6 +1265,37 @@ impl ObsContext { RecordingError::ObsInitError("OBS not initialized".to_string()) })?; + // 1. Game audio capture (desktop audio via PulseAudio) + if self.audio_settings.capture_game { + self.setup_game_audio_capture_linux(context)?; + } + + // 2. Microphone capture + if self.audio_settings.capture_mic { + self.setup_microphone_capture_linux(context)?; + } + + // 3. Application audio captures (Discord, Spotify, etc.) + for app_source in &self.audio_settings.capture_apps { + if app_source.enabled { + self.setup_app_audio_capture_linux(context, app_source)?; + } + } + + info!("[AUDIO_CAPTURE] All audio sources configured successfully"); + Ok(()) + } + + /// Set up game audio capture via PulseAudio (Linux). + #[cfg(target_os = "linux")] + fn setup_game_audio_capture_linux( + &mut self, + context: &mut libobs_wrapper::context::ObsContext, + ) -> Result<()> { + use libobs_wrapper::utils::SourceInfo; + + info!("[AUDIO_CAPTURE] Setting up game audio capture (Linux)..."); + // Create audio source settings let audio_settings_data = context.data().map_err(|e| { error!("[AUDIO_CAPTURE] Failed to create audio settings: {:?}", e); @@ -1043,7 +1310,7 @@ impl ObsContext { None, ); - info!("[AUDIO_CAPTURE] Creating PulseAudio capture source..."); + info!("[AUDIO_CAPTURE] Creating PulseAudio capture source for game..."); let audio_source_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { libobs_wrapper::sources::ObsSourceRef::new_from_info( @@ -1052,35 +1319,172 @@ impl ObsContext { ) })); - let _audio_source = match audio_source_result { - Ok(Ok(s)) => { - info!("[AUDIO_CAPTURE] PulseAudio source created"); - s + match audio_source_result { + Ok(Ok(_s)) => { + info!("[AUDIO_CAPTURE] PulseAudio game audio source created"); } Ok(Err(e)) => { - error!("[AUDIO_CAPTURE] Failed to create audio source: {:?}", e); + error!("[AUDIO_CAPTURE] Failed to create game audio source: {:?}", e); return Err(RecordingError::StartError(format!( - "Failed to create audio source: {:?}", + "Failed to create game audio source: {:?}", e )) .into()); } Err(panic_info) => { error!( - "[AUDIO_CAPTURE] PANIC creating audio source: {:?}", + "[AUDIO_CAPTURE] PANIC creating game audio source: {:?}", panic_info ); - eprintln!( - "[AUDIO_CAPTURE] PANIC creating audio source: {:?}", - panic_info - ); - return Err( - RecordingError::StartError("Panic creating audio source".to_string()).into(), - ); + return Err(RecordingError::StartError( + "Panic creating game audio source".to_string(), + ) + .into()); } + } + + Ok(()) + } + + /// Set up microphone capture via PulseAudio (Linux). + #[cfg(target_os = "linux")] + fn setup_microphone_capture_linux( + &mut self, + context: &mut libobs_wrapper::context::ObsContext, + ) -> Result<()> { + use libobs_wrapper::data::ObsData; + use libobs_wrapper::utils::SourceInfo; + + info!("[AUDIO_CAPTURE] Setting up microphone capture (Linux)..."); + + let device_id = self + .audio_settings + .mic_device + .as_deref() + .unwrap_or("default"); + + info!("[AUDIO_CAPTURE] Using microphone device: {}", device_id); + + // Create microphone settings + let settings_json = if device_id == "default" { + r#"{"device_id": "default"}"#.to_string() + } else { + format!(r#"{{"device_id": "{}"}}"#, device_id) }; - info!("[AUDIO_CAPTURE] Audio source created successfully"); + let mic_settings_data = ObsData::from_json(&settings_json, context.runtime().clone()) + .map_err(|e| { + error!( + "[AUDIO_CAPTURE] Failed to create microphone settings: {:?}", + e + ); + RecordingError::StartError(format!( + "Failed to create microphone settings: {:?}", + e + )) + })?; + + let source_info = SourceInfo::new( + "pulse_input_capture", + "microphone", + Some(mic_settings_data), + None, + ); + + let mic_source_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + libobs_wrapper::sources::ObsSourceRef::new_from_info( + source_info, + context.runtime().clone(), + ) + })); + + match mic_source_result { + Ok(Ok(_s)) => { + info!("[AUDIO_CAPTURE] Microphone source created successfully (Linux)"); + } + Ok(Err(e)) => { + warn!( + "[AUDIO_CAPTURE] Microphone capture unavailable (Linux): {:?}", + e + ); + } + Err(panic_info) => { + warn!( + "[AUDIO_CAPTURE] Microphone capture failed due to panic (Linux): {:?}", + panic_info + ); + } + } + + Ok(()) + } + + /// Set up application audio capture via PulseAudio (Linux). + #[cfg(target_os = "linux")] + fn setup_app_audio_capture_linux( + &mut self, + context: &mut libobs_wrapper::context::ObsContext, + app_source: &crate::config::AudioSourceConfig, + ) -> Result<()> { + use libobs_wrapper::data::ObsData; + use libobs_wrapper::utils::SourceInfo; + + info!( + "[AUDIO_CAPTURE] Setting up application audio capture for: {} (Linux)", + app_source.name + ); + + // On Linux, we use PulseAudio application capture + let settings_json = format!(r#"{{"app_name": "{}"}}"#, app_source.device); + + let app_settings_data = ObsData::from_json(&settings_json, context.runtime().clone()) + .map_err(|e| { + error!( + "[AUDIO_CAPTURE] Failed to create app audio settings: {:?}", + e + ); + RecordingError::StartError(format!( + "Failed to create app audio settings for {}: {:?}", + app_source.name, e + )) + })?; + + let source_name = format!("app_audio_{}", app_source.id); + + let source_info = SourceInfo::new( + "pulse_input_capture", + &source_name, + Some(app_settings_data), + None, + ); + + let app_source_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + libobs_wrapper::sources::ObsSourceRef::new_from_info( + source_info, + context.runtime().clone(), + ) + })); + + match app_source_result { + Ok(Ok(_s)) => { + info!( + "[AUDIO_CAPTURE] Application audio source '{}' created successfully (Linux)", + app_source.name + ); + } + Ok(Err(e)) => { + warn!( + "[AUDIO_CAPTURE] App audio capture for '{}' unavailable (Linux): {:?}", + app_source.name, e + ); + } + Err(panic_info) => { + warn!( + "[AUDIO_CAPTURE] App audio capture for '{}' failed due to panic (Linux): {:?}", + app_source.name, panic_info + ); + } + } Ok(()) } diff --git a/tauri-app/src-tauri/src/daemon_ipc.rs b/tauri-app/src-tauri/src/daemon_ipc.rs index ae9da43..bcfd2a5 100644 --- a/tauri-app/src-tauri/src/daemon_ipc.rs +++ b/tauri-app/src-tauri/src/daemon_ipc.rs @@ -54,6 +54,10 @@ pub mod commands { pub const RESET_SETTINGS: &str = "resetSettings"; pub const GET_STATUS: &str = "getStatus"; pub const GET_ENCODERS: &str = "getEncoders"; + pub const GET_AUDIO_DEVICES: &str = "getAudioDevices"; + pub const ADD_AUDIO_SOURCE: &str = "addAudioSource"; + pub const REMOVE_AUDIO_SOURCE: &str = "removeAudioSource"; + pub const UPDATE_AUDIO_SOURCE: &str = "updateAudioSource"; pub const START_RECORDING: &str = "startRecording"; pub const STOP_RECORDING: &str = "stopRecording"; pub const SHUTDOWN: &str = "shutdown"; @@ -554,6 +558,70 @@ pub async fn daemon_shutdown() -> Result { } } +/// Get available audio devices from the daemon. +#[tauri::command] +pub async fn daemon_get_audio_devices() -> Result { + let client = IpcClient::new(); + let response = client + .send_command(commands::GET_AUDIO_DEVICES, None) + .await + .map_err(|e| e)?; + + if response.success { + Ok(response.data.unwrap_or(serde_json::Value::Null)) + } else { + Err(response.error.unwrap_or_else(|| "Unknown error".to_string())) + } +} + +/// Add an audio source to the daemon settings. +#[tauri::command] +pub async fn daemon_add_audio_source(source: serde_json::Value) -> Result { + let client = IpcClient::new(); + let response = client + .send_command(commands::ADD_AUDIO_SOURCE, Some(source)) + .await + .map_err(|e| e)?; + + if response.success { + Ok(response.data.unwrap_or(serde_json::Value::Null)) + } else { + Err(response.error.unwrap_or_else(|| "Unknown error".to_string())) + } +} + +/// Remove an audio source from the daemon settings. +#[tauri::command] +pub async fn daemon_remove_audio_source(id: String) -> Result { + let client = IpcClient::new(); + let response = client + .send_command(commands::REMOVE_AUDIO_SOURCE, Some(serde_json::json!({ "id": id }))) + .await + .map_err(|e| e)?; + + if response.success { + Ok(response.data.unwrap_or(serde_json::Value::Null)) + } else { + Err(response.error.unwrap_or_else(|| "Unknown error".to_string())) + } +} + +/// Update an audio source in the daemon settings. +#[tauri::command] +pub async fn daemon_update_audio_source(source: serde_json::Value) -> Result { + let client = IpcClient::new(); + let response = client + .send_command(commands::UPDATE_AUDIO_SOURCE, Some(source)) + .await + .map_err(|e| e)?; + + if response.success { + Ok(response.data.unwrap_or(serde_json::Value::Null)) + } else { + Err(response.error.unwrap_or_else(|| "Unknown error".to_string())) + } +} + /// Get the daemon log file path. #[tauri::command] pub fn daemon_get_log_path() -> Result { diff --git a/tauri-app/src-tauri/src/lib.rs b/tauri-app/src-tauri/src/lib.rs index 0bad42e..5a3bbf4 100644 --- a/tauri-app/src-tauri/src/lib.rs +++ b/tauri-app/src-tauri/src/lib.rs @@ -440,6 +440,10 @@ pub fn run() { daemon_ipc::daemon_update_settings, daemon_ipc::daemon_reset_settings, daemon_ipc::daemon_get_encoders, + daemon_ipc::daemon_get_audio_devices, + daemon_ipc::daemon_add_audio_source, + daemon_ipc::daemon_remove_audio_source, + daemon_ipc::daemon_update_audio_source, daemon_ipc::daemon_start_recording, daemon_ipc::daemon_stop_recording, daemon_ipc::daemon_shutdown, diff --git a/tauri-app/src/components/Settings.vue b/tauri-app/src/components/Settings.vue index c3ce3cf..cad77d9 100644 --- a/tauri-app/src/components/Settings.vue +++ b/tauri-app/src/components/Settings.vue @@ -10,6 +10,9 @@ import type { X264Preset, DaemonStatusResponse, EncodersResponse, + GetAudioDevicesResponse, + AudioSourceConfig, + AudioSourceType, } from "../types/daemon"; import { QUALITY_LEVELS, @@ -40,6 +43,15 @@ const statusPolling = ref | null>(null); const autostartEnabled = ref(false); const autostartLoading = ref(false); +// Audio devices state +const audioDevices = ref({ input_devices: [], output_devices: [] }); +const loadingAudioDevices = ref(false); + +// New audio source form state +const newAppSourceType = ref("application"); +const newAppName = ref(""); +const newAppDevice = ref(""); + // Active settings tab type SettingsTab = "video" | "output" | "audio" | "daemon"; const activeTab = ref("video"); @@ -162,6 +174,84 @@ async function resetSettings() { } } +// --------------------------------------------------------------------------- +// Audio devices and sources +// --------------------------------------------------------------------------- + +async function loadAudioDevices() { + if (!daemonRunning.value) return; + try { + loadingAudioDevices.value = true; + const devices = await invoke("daemon_get_audio_devices"); + audioDevices.value = devices; + } catch (e) { + console.error("Failed to load audio devices:", e); + } finally { + loadingAudioDevices.value = false; + } +} + +async function addAudioSource() { + if (!settings.value || !newAppName.value || !newAppDevice.value) return; + + const source: AudioSourceConfig = { + id: crypto.randomUUID(), + name: newAppName.value, + type: newAppSourceType.value, + device: newAppDevice.value, + enabled: true, + volume: null, + }; + + try { + await invoke("daemon_add_audio_source", { source }); + settings.value.audio.capture_apps.push(source); + + // Reset form + newAppName.value = ""; + newAppDevice.value = ""; + newAppSourceType.value = "application"; + + saveSuccess.value = true; + setTimeout(() => { + saveSuccess.value = false; + }, 2000); + } catch (e) { + error.value = `Failed to add audio source: ${e}`; + } +} + +async function removeAudioSource(id: string) { + if (!settings.value) return; + + try { + await invoke("daemon_remove_audio_source", { id }); + settings.value.audio.capture_apps = settings.value.audio.capture_apps.filter(s => s.id !== id); + saveSuccess.value = true; + setTimeout(() => { + saveSuccess.value = false; + }, 2000); + } catch (e) { + error.value = `Failed to remove audio source: ${e}`; + } +} + +function addPresetSource(preset: "discord" | "spotify" | "browser") { + const presets: Record = { + discord: { name: "Discord", device: "Discord.exe", type: "application" }, + spotify: { name: "Spotify", device: "Spotify.exe", type: "application" }, + browser: { name: "Browser", device: "chrome.exe", type: "application" }, + }; + + const p = presets[preset]; + newAppName.value = p.name; + newAppDevice.value = p.device; + newAppSourceType.value = p.type; + + // Immediately add the source + addAudioSource(); +} + // --------------------------------------------------------------------------- // Daemon control // --------------------------------------------------------------------------- @@ -272,6 +362,7 @@ const statusColor = computed(() => { onMounted(async () => { await loadSettings(); await checkAutostart(); + await loadAudioDevices(); // Poll daemon status every 3 seconds statusPolling.value = setInterval(refreshStatus, 3000); }); @@ -652,6 +743,8 @@ onUnmounted(() => {

Audio Sources

+ +
Record the game's audio output
+
+ +
+ + {{ settings.audio.game_volume }}% +
+
+ +
Record microphone input alongside game audio
-
- + + + +
+ + Capture audio from specific applications like Discord or Spotify +
+ +
+
+
+ + {{ source.name }} + ({{ source.type }}) + +
+
+
+ + +
+
+ + + % +
+
+
+
+ +
+ - Leave empty for system default microphone + + +
+ + +
+ Quick Add: + + +
@@ -1261,6 +1456,168 @@ onUnmounted(() => { gap: 8px; } +/* Volume control */ +.volume-control { + display: flex; + align-items: center; + gap: 12px; +} + +.volume-slider { + flex: 1; + height: 6px; + -webkit-appearance: none; + appearance: none; + background: rgba(255, 255, 255, 0.1); + border-radius: 3px; + outline: none; +} + +.volume-slider::-webkit-slider-thumb { + -webkit-appearance: none; + appearance: none; + width: 16px; + height: 16px; + background: #3b82f6; + border-radius: 50%; + cursor: pointer; + transition: background 0.15s; +} + +.volume-slider::-webkit-slider-thumb:hover { + background: #60a5fa; +} + +.volume-slider::-moz-range-thumb { + width: 16px; + height: 16px; + background: #3b82f6; + border-radius: 50%; + cursor: pointer; + border: none; +} + +.volume-value { + min-width: 45px; + text-align: right; + font-size: 13px; + color: #94a3b8; +} + +/* App sources list */ +.app-sources-list { + display: flex; + flex-direction: column; + gap: 12px; + margin-bottom: 16px; +} + +.app-source-item { + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 8px; + padding: 12px; +} + +.app-source-header { + display: flex; + align-items: center; + gap: 10px; +} + +.app-source-name { + font-weight: 500; + color: #e2e8f0; +} + +.app-source-type { + font-size: 12px; + color: #64748b; + text-transform: capitalize; +} + +.app-source-header .btn { + margin-left: auto; +} + +.app-source-controls { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid rgba(255, 255, 255, 0.06); +} + +.form-group-inline { + display: flex; + align-items: center; + gap: 8px; +} + +.form-group-inline label { + min-width: 100px; + font-size: 13px; + color: #94a3b8; +} + +.form-input-small { + flex: 1; + padding: 6px 10px; + background: rgba(0, 0, 0, 0.3); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 6px; + color: #e2e8f0; + font-size: 13px; +} + +.form-hint-inline { + font-size: 12px; + color: #64748b; +} + +/* Add app source form */ +.add-app-source { + display: flex; + gap: 8px; + margin-top: 12px; + flex-wrap: wrap; +} + +.add-app-source .form-select, +.add-app-source .form-input { + flex: 1; + min-width: 120px; +} + +/* Quick add presets */ +.quick-add-presets { + display: flex; + align-items: center; + gap: 8px; + margin-top: 12px; + flex-wrap: wrap; +} + +.presets-label { + font-size: 13px; + color: #64748b; +} + +.toggle-small { + width: 36px; + height: 20px; +} + +.toggle-small .toggle-slider::before { + width: 14px; + height: 14px; +} + +.toggle-small input:checked + .toggle-slider::before { + transform: translateX(16px); +} + /* Responsive */ @media (max-width: 640px) { .settings-header { diff --git a/tauri-app/src/types/daemon.ts b/tauri-app/src/types/daemon.ts index eaae8de..afdc5d3 100644 --- a/tauri-app/src/types/daemon.ts +++ b/tauri-app/src/types/daemon.ts @@ -60,8 +60,38 @@ export interface AudioSettings { sample_rate: number; channels: number; capture_game: boolean; + game_volume: number; capture_mic: boolean; mic_device: string | null; + mic_volume: number; + capture_apps: AudioSourceConfig[]; + apps_volume: number; +} + +export interface AudioSourceConfig { + id: string; + name: string; + type: AudioSourceType; + device: string; + enabled: boolean; + volume: number | null; +} + +export type AudioSourceType = "application" | "deviceOutput" | "deviceInput"; + +export interface AudioDeviceInfo { + id: string; + name: string; + is_default: boolean; +} + +export interface GetAudioDevicesResponse { + input_devices: AudioDeviceInfo[]; + output_devices: AudioDeviceInfo[]; +} + +export interface AudioSourceResponse { + source: AudioSourceConfig; } export interface DaemonSettings {