diff --git a/record-daemon/Cargo.toml b/record-daemon/Cargo.toml index 9e4d437..8cb74f1 100644 --- a/record-daemon/Cargo.toml +++ b/record-daemon/Cargo.toml @@ -88,6 +88,8 @@ windows = { version = "0.58", features = [ "Win32_UI_Shell_PropertiesSystem", "Win32_Foundation", "Win32_Devices_Properties", + "Win32_System_Diagnostics_ToolHelp", + "Win32_UI_WindowsAndMessaging", ] } [dev-dependencies] diff --git a/record-daemon/src/ipc/handlers.rs b/record-daemon/src/ipc/handlers.rs index ee1c796..f56b0bc 100644 --- a/record-daemon/src/ipc/handlers.rs +++ b/record-daemon/src/ipc/handlers.rs @@ -12,7 +12,7 @@ use super::protocol::{ use crate::config::Settings; use crate::error::Result; use crate::recording::encoder::{detect_hardware_encoders, EncoderCapability}; -use crate::recording::RecordingEngine; +use crate::recording::{RecordingEngine, RecordingResult}; use crate::state::DaemonStatus; use crate::timeline::TimelineStore; @@ -109,16 +109,40 @@ impl IpcHandlers { // 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)?) } @@ -187,37 +211,49 @@ impl IpcHandlers { } async fn handle_start_recording(&self) -> Result { - let mut recording_guard = self.recording.write(); - - if let Some(ref mut engine) = *recording_guard { + // 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}")) + })??; - engine.start_recording(None, None)?; - - Ok(serde_json::json!({ "success": true })) - } else { - Err(crate::error::RecordingError::ObsInitError( - "Recording engine not initialized".to_string(), - ) - .into()) - } + Ok(serde_json::json!({ "success": true })) } async fn handle_stop_recording(&self) -> Result { - let mut recording_guard = self.recording.write(); + // 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}")) + })??; - if let Some(ref mut engine) = *recording_guard { - let result = engine.stop_recording()?; - - // Save to timeline - self.timeline.write().add_recording(result.clone())?; - - Ok(serde_json::to_value(result)?) - } else { - Err(crate::error::RecordingError::NotRecording.into()) - } + self.timeline.write().add_recording(result.clone())?; + Ok(serde_json::to_value(result)?) } async fn handle_shutdown(&self) -> Result { @@ -288,6 +324,8 @@ impl IpcHandlers { crate::config::save_config(&settings)?; } + self.push_settings_to_engine().await?; + let response = AudioSourceResponse { source }; Ok(serde_json::to_value(response)?) } @@ -301,6 +339,8 @@ impl IpcHandlers { crate::config::save_config(&settings)?; } + self.push_settings_to_engine().await?; + Ok(serde_json::json!({ "success": true })) } @@ -337,6 +377,8 @@ impl IpcHandlers { } } + self.push_settings_to_engine().await?; + let response = AudioSourceResponse { source }; Ok(serde_json::to_value(response)?) } diff --git a/record-daemon/src/recording/mod.rs b/record-daemon/src/recording/mod.rs index 7f11e40..e282bfe 100644 --- a/record-daemon/src/recording/mod.rs +++ b/record-daemon/src/recording/mod.rs @@ -3,6 +3,7 @@ pub mod encoder; mod obs_context; mod output; +mod process_audio; pub use encoder::EncoderCapability; pub use obs_context::{ObsContext, ObsContextBuilder}; @@ -43,26 +44,34 @@ impl RecordingEngine { } } - /// Initialize the recording engine. + /// Start OBS and build the recording scene. + /// + /// This runs at daemon startup rather than on the first game: the audio captures need to + /// attach while their applications still have a window, and the scene is then reused by + /// every recording. pub fn initialize(&mut self) -> Result<()> { info!("Initializing recording engine"); let settings = self.settings.read().clone(); - let context = ObsContextBuilder::new() + let mut context = ObsContextBuilder::new() .with_video_settings(settings.video.clone()) .with_audio_settings(settings.audio.clone()) .with_output_dir(&settings.output.path) .build()?; + context.start()?; self.context = Some(context); info!("Recording engine initialized"); Ok(()) } - /// Update settings. - pub fn update_settings(&self, new_settings: Settings) -> Result<()> { - *self.settings.write() = new_settings; + /// Take new settings from the app and apply them to the running OBS context. + pub fn update_settings(&mut self, new_settings: Settings) -> Result<()> { + *(self.settings.write()) = new_settings.clone(); + if let Some(context) = self.context.as_mut() { + context.apply_settings(new_settings.video, new_settings.audio)?; + } Ok(()) } diff --git a/record-daemon/src/recording/obs_context.rs b/record-daemon/src/recording/obs_context.rs index dd327b6..f06c82d 100644 --- a/record-daemon/src/recording/obs_context.rs +++ b/record-daemon/src/recording/obs_context.rs @@ -26,6 +26,7 @@ use serde_json::json; use tracing::{debug, error, info, warn}; use super::encoder::{best_available_encoder, EncoderCapability}; +use super::process_audio::{self, ProcessAudio}; use crate::config::{AudioSettings, AudioSourceType, VideoSettings}; use crate::error::{RecordingError, Result}; @@ -33,7 +34,7 @@ use crate::error::{RecordingError, Result}; /// /// libobs can segfault or panic inside plugin code; containing that here /// keeps the daemon alive and surfaces the failure through IPC instead. -fn catch_native(what: &str, f: impl FnOnce() -> Result) -> Result { +pub(crate) fn catch_native(what: &str, f: impl FnOnce() -> Result) -> Result { match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) { Ok(result) => result, Err(_) => { @@ -45,25 +46,13 @@ fn catch_native(what: &str, f: impl FnOnce() -> Result) -> Result { /// Apply a 0-100 volume setting to a source. /// /// obs_source_set_volume takes a linear multiplier, so 100% is 1.0. -fn apply_volume(source: &ObsSourceRef, percent: u32) { +pub(crate) fn apply_volume(source: &ObsSourceRef, percent: u32) { let volume = percent.min(100) as f32 / 100.0; unsafe { libobs::obs_source_set_volume(source.as_ptr().get_ptr(), volume); } } -/// The `window` value an application audio capture source reads. -/// -/// win-wasapi parses it as `title:class:exe` and looks for a window whose fields match, and it -/// reads this key alone. Passing `executable`, `title` and `class` on their own left the source -/// with no target and the recordings silent. `:` and `#` are escaped the way libobs decodes them -/// (`libobs/util/windows/window-helpers.c`), so a title with a colon still yields three fields. -#[cfg(target_os = "windows")] -fn window_string(title: &str, class: &str, executable: &str) -> String { - let escape = |field: &str| field.replace('#', "#22").replace(':', "#3A"); - format!("{}:{}:{}", escape(title), escape(class), escape(executable)) -} - /// libobs writes its own warnings to stdout, and a daemon started in the background has no one /// reading that. A failed game hook or a dropped audio device is exactly what explains a silent /// recording, so OBS's log goes into the daemon log with everything else. @@ -129,8 +118,13 @@ impl ObsContextBuilder { video_settings, audio_settings, context: None, + scene: None, + devices: Vec::new(), + process_audio: None, + video: None, output: None, recording: false, + pending_audio: None, encoder_capability: None, }) } @@ -147,8 +141,19 @@ pub struct ObsContext { video_settings: VideoSettings, audio_settings: AudioSettings, context: Option, + /// The scene that goes on channel 0, built once and kept for every recording. Keeping it + /// means the audio captures inside it stay attached between games. + scene: Option, + /// Microphone and device captures, tracked so a settings change can replace just these. + devices: Vec, + /// Process captures. They are scene items as well, but the watcher owns them. + process_audio: Option, + /// Video source of the recording that is running, added to the scene on start. + video: Option, output: Option, recording: bool, + /// Settings that arrived while a recording was running, applied once it stops. + pending_audio: Option<(VideoSettings, AudioSettings)>, encoder_capability: Option, } @@ -163,8 +168,12 @@ impl ObsContext { self.recording } - /// Initialize OBS. Called lazily from `start_recording`. - fn initialize(&mut self) -> Result<()> { + /// Start OBS and build the scene every recording reuses. + /// + /// The daemon calls this once at startup. Starting early is what lets an application's + /// audio capture attach while the application still has a window, and the scene stays put + /// afterwards so the captures inside it are not rebuilt for every game. + pub fn start(&mut self) -> Result<()> { if self.context.is_some() { return Ok(()); } @@ -192,14 +201,29 @@ impl ObsContext { let info = StartupInfo::default() .set_video_info(video_info) .set_logger(Box::new(ObsLog)); - let context = catch_native("creating the OBS context", || { + let mut context = catch_native("creating the OBS context", || { LibObsContext::new(info).map_err(|e| { RecordingError::ObsInitError(format!("failed to create OBS context: {:?}", e)) .into() }) })?; + let mut scene = context + .scene("main", None) + .map_err(|e| RecordingError::StartError(format!("failed to open scene: {:?}", e)))?; + self.devices = add_device_sources(&context, &mut scene, &self.audio_settings)?; + scene + .set_to_channel(0) + .map_err(|e| RecordingError::StartError(format!("failed to set scene: {:?}", e)))?; + + self.process_audio = Some(ProcessAudio::start( + process_audio::wants(&self.audio_settings), + context.runtime().clone(), + scene.clone(), + )); + self.scene = Some(scene); self.context = Some(context); + info!( "OBS context initialized ({}x{} @ {}fps)", width, height, fps @@ -207,21 +231,95 @@ impl ObsContext { Ok(()) } - /// Start recording to the specified output path. + /// Take new settings. + /// + /// Video changes reset the video pipeline, audio changes rebuild the scene's device sources + /// and the list of processes to capture. A recording in progress keeps the settings it + /// started with and the new ones are applied when it stops. + pub fn apply_settings(&mut self, video: VideoSettings, audio: AudioSettings) -> Result<()> { + if self.recording { + self.pending_audio = Some((video, audio)); + return Ok(()); + } + self.apply_now(video, audio) + } + + fn apply_now(&mut self, video: VideoSettings, audio: AudioSettings) -> Result<()> { + if self.context.is_none() { + self.video_settings = video; + self.audio_settings = audio; + return self.start(); + } + + if video.frame_rate != self.video_settings.frame_rate + || video.quality != self.video_settings.quality + { + let encoder = self + .encoder_capability + .unwrap_or_else(best_available_encoder); + let (width, height) = video.quality.resolution(); + let video_info = ObsVideoInfoBuilder::new() + .fps_num(video.frame_rate) + .fps_den(1) + .base_width(width) + .base_height(height) + .output_width(width) + .output_height(height) + .build(); + if let Some(context) = self.context.as_mut() { + context.reset_video(video_info).map_err(|e| { + RecordingError::StartError(format!("failed to reset video: {:?}", e)) + })?; + } + info!( + "video reset to {}x{} @ {}fps ({:?})", + width, height, video.frame_rate, encoder + ); + } + + if audio != self.audio_settings { + let context = self + .context + .as_ref() + .ok_or_else(|| RecordingError::ObsInitError("OBS not initialized".to_string()))?; + // Remove only the device captures we added; the process captures are scene items + // too and the watcher expects them to stay where they are. + if let Some(scene) = self.scene.as_mut() { + for source in self.devices.drain(..) { + let _ = scene.remove_every_item_of_source(source); + } + self.devices = add_device_sources(context, scene, &audio)?; + } + if let Some(captures) = self.process_audio.as_ref() { + captures.set_wants(process_audio::wants(&audio)); + } + } + + self.video_settings = video; + self.audio_settings = audio; + Ok(()) + } + + /// Start recording to the given path. pub fn start_recording(&mut self, output_path: &Path) -> Result<()> { if self.recording { return Err(RecordingError::AlreadyRecording.into()); } - if self.context.is_none() { - self.initialize()?; + if let Some((video, audio)) = self.pending_audio.take() { + self.apply_now(video, audio)?; } + self.start()?; + let context = self .context .as_ref() .ok_or_else(|| RecordingError::ObsInitError("OBS not initialized".to_string()))?; - // Build the output around the best available encoder. + // A fresh game capture per recording: the previous one is bound to a window that the + // last game closed, and the scene is reused. + add_video_source(context, self.scene.as_mut(), &mut self.video)?; + let encoder = self .encoder_capability .unwrap_or_else(best_available_encoder); @@ -247,14 +345,6 @@ impl ObsContext { .build() .map_err(|e| RecordingError::StartError(format!("failed to build output: {:?}", e)))?; - // Build the scene: video capture plus audio sources. - let audio = self.audio_settings.clone(); - let context = self - .context - .as_mut() - .ok_or_else(|| RecordingError::ObsInitError("OBS not initialized".to_string()))?; - setup_scene(context, &audio)?; - catch_native("starting the output", || { output.start().map_err(|e| { RecordingError::StartError(format!("failed to start output: {:?}", e)).into() @@ -279,15 +369,34 @@ impl ObsContext { })?; } + // The capture is only good for the game that just ended; the scene and the audio + // captures stay. + remove_video_source(self.scene.as_mut(), self.video.take())?; + self.recording = false; + if let Some((video, audio)) = self.pending_audio.take() { + if let Err(e) = self.apply_now(video, audio) { + warn!( + "could not apply the settings saved during the recording: {:?}", + e + ); + } + } info!("recording stopped"); Ok(()) } + /// Shut down OBS. The libobs context cleans up on drop. pub fn shutdown(&mut self) -> Result<()> { if self.recording { self.stop_recording()?; } + // Stop the scan before libobs goes away: it holds sources that must be released first. + if let Some(mut captures) = self.process_audio.take() { + captures.stop(); + } + self.video = None; + self.scene = None; self.output = None; self.context = None; Ok(()) @@ -300,102 +409,14 @@ impl Drop for ObsContext { } } -/// Build the recording scene: a video capture source plus every -/// configured audio source, all added to the scene so libobs actually -/// mixes them into the output. The scene goes on channel 0. -fn setup_scene(context: &mut LibObsContext, audio: &AudioSettings) -> Result<()> { - let mut scene = context - .scene("main", None) - .map_err(|e| RecordingError::StartError(format!("failed to create scene: {:?}", e)))?; - - add_video_source(context, &mut scene)?; - - if audio.enabled { - add_audio_sources(context, &mut scene, audio)?; - } - - scene - .set_to_channel(0) - .map_err(|e| RecordingError::StartError(format!("failed to set scene: {:?}", e)))?; - Ok(()) -} - -/// Add the video capture source: game capture with monitor fallback on -/// Windows, full-screen capture on Linux. -#[cfg(target_os = "windows")] -fn add_video_source( +/// Create an audio source and apply its volume. The caller adds it to the scene. +fn audio_source( context: &LibObsContext, - scene: &mut libobs_wrapper::scenes::ObsSceneRef, -) -> Result<()> { - use libobs_simple::sources::windows::{GameCaptureSourceBuilder, ObsGameCaptureMode}; - - let game = catch_native("creating game capture", || { - GameCaptureSourceBuilder::new("game_capture", context.runtime().clone()) - .map_err(|e| RecordingError::StartError(format!("game capture builder: {:?}", e)))? - .set_capture_mode(ObsGameCaptureMode::Any) - .build() - .map_err(|e| RecordingError::StartError(format!("game capture source: {:?}", e)).into()) - }); - - match game { - Ok(source) => scene.add_source(source).map(|_| ()).map_err(|e| { - RecordingError::StartError(format!("failed to add game capture: {:?}", e)).into() - }), - Err(game_err) => { - warn!( - "game capture unavailable ({}), falling back to monitor capture", - game_err - ); - let source = catch_native("creating monitor capture", || { - use libobs_simple::sources::windows::MonitorCaptureSourceBuilder; - - MonitorCaptureSourceBuilder::new("monitor_capture", context.runtime().clone()) - .map_err(|e| RecordingError::StartError(format!("monitor builder: {:?}", e)))? - .build() - .map_err(|e| { - RecordingError::StartError(format!("monitor capture source: {:?}", e)) - .into() - }) - })?; - scene.add_source(source).map(|_| ()).map_err(|e| { - RecordingError::StartError(format!("failed to add monitor capture: {:?}", e)).into() - }) - } - } -} - -/// Add the video capture source on Linux (X11 or PipeWire). -#[cfg(target_os = "linux")] -fn add_video_source( - context: &LibObsContext, - scene: &mut libobs_wrapper::scenes::ObsSceneRef, -) -> Result<()> { - use libobs_simple::sources::linux::LinuxGeneralScreenCaptureBuilder; - - let source = catch_native("creating screen capture", || { - LinuxGeneralScreenCaptureBuilder::new("screen_capture", context.runtime().clone()) - .map_err(|e| RecordingError::StartError(format!("screen capture builder: {:?}", e)))? - .build() - .map_err(|e| RecordingError::StartError(format!("screen capture source: {:?}", e))) - })?; - scene - .map(|_| ()) - .add_source(source) - .map_err(|e| RecordingError::StartError(format!("failed to add screen capture: {:?}", e))) -} - -/// Create an audio source, apply its volume and add it to the scene. -/// -/// Returns an error description if the source could not be created; the -/// caller decides whether that aborts the recording. -fn add_audio_source( - context: &LibObsContext, - scene: &mut libobs_wrapper::scenes::ObsSceneRef, plugin_id: &str, name: &str, settings: serde_json::Value, volume_percent: u32, -) -> std::result::Result<(), String> { +) -> std::result::Result { let data = ObsData::from_json(&settings.to_string(), context.runtime().clone()) .map_err(|e| format!("settings for {}: {:?}", name, e))?; let info = SourceInfo::new(plugin_id, name, Some(data), None); @@ -409,92 +430,149 @@ fn add_audio_source( .map_err(|e| e.to_string())?; apply_volume(&source, volume_percent); - - scene - .add_source(source) - .map(|_| ()) - .map_err(|e| format!("adding {} to scene: {:?}", name, e)) + Ok(source) } -/// Add every configured audio source. A missing app source (Discord not -/// running, device unplugged) only logs a warning; game and mic failures -/// abort the start so the user notices. -fn add_audio_sources( +/// Audio that comes from a device: the microphone and any configured second device. +/// +/// These live in the scene for the whole session. Process captures are in the scene as well, +/// but the watcher owns them, so a settings change has to leave those items alone. +fn add_device_sources( context: &LibObsContext, scene: &mut libobs_wrapper::scenes::ObsSceneRef, audio: &AudioSettings, -) -> Result<()> { +) -> Result> { #[cfg(target_os = "windows")] - let (game_plugin, mic_plugin, out_plugin) = ( - "wasapi_process_output_capture", - "wasapi_input_capture", - "wasapi_output_capture", - ); + let (mic_plugin, out_plugin) = ("wasapi_input_capture", "wasapi_output_capture"); #[cfg(target_os = "linux")] - let (game_plugin, mic_plugin, out_plugin) = ( - "pulse_output_capture", - "pulse_input_capture", - "pulse_output_capture", - ); + let (mic_plugin, out_plugin) = ("pulse_input_capture", "pulse_output_capture"); - // Game audio: capture the League of Legends process directly. A - // dedicated source (instead of game-capture's built-in audio hook) - // keeps the game volume setting working. - if audio.capture_game { - add_audio_source( - context, - scene, - game_plugin, - "game_audio", - json!({ - "window": window_string( - "League of Legends (TM) Client", - "RiotWindowClass", - "League of Legends.exe" - ), - "priority": 2 - }), - audio.game_volume, - ) - .map_err(|e| RecordingError::StartError(format!("game audio: {}", e)))?; - } + let mut added = Vec::new(); - // Microphone. if audio.capture_mic { - add_audio_source( + let source = audio_source( context, - scene, mic_plugin, "mic", json!({ "device_id": audio.mic_device.as_deref().unwrap_or("default") }), audio.mic_volume, ) .map_err(|e| RecordingError::StartError(format!("microphone: {}", e)))?; + scene + .add_source(source.clone()) + .map_err(|e| RecordingError::StartError(format!("adding the microphone: {:?}", e)))?; + added.push(source); } - // Additional sources (Discord, second device, ...). for app in audio.capture_apps.iter().filter(|a| a.enabled) { let (plugin, settings) = match app.source_type { - AudioSourceType::Application => ( - game_plugin, - json!({ "window": window_string("", "", &app.device), "priority": 2 }), - ), + AudioSourceType::Application => continue, AudioSourceType::DeviceOutput => (out_plugin, json!({ "device_id": app.device })), AudioSourceType::DeviceInput => (mic_plugin, json!({ "device_id": app.device })), }; let volume = app.volume.unwrap_or(audio.apps_volume); - - if let Err(e) = add_audio_source( + match audio_source( context, - scene, plugin, &format!("app_{}", app.id), settings, volume, ) { - warn!("audio source '{}' unavailable: {}", app.name, e); + Ok(source) => match scene.add_source(source.clone()) { + Ok(_) => added.push(source), + Err(e) => warn!("could not add {} to the scene: {:?}", app.name, e), + }, + Err(e) => warn!("audio source '{}' unavailable: {}", app.name, e), } } + Ok(added) +} +/// Put a video capture source in the scene for the recording that is starting. +#[cfg(target_os = "windows")] +fn add_video_source( + context: &LibObsContext, + scene: Option<&mut libobs_wrapper::scenes::ObsSceneRef>, + slot: &mut Option, +) -> Result<()> { + use libobs_simple::sources::windows::{GameCaptureSourceBuilder, ObsGameCaptureMode}; + + let scene = scene + .ok_or_else(|| RecordingError::StartError("the recording scene is missing".to_string()))?; + + let game = catch_native("creating game capture", || { + GameCaptureSourceBuilder::new("game_capture", context.runtime().clone()) + .map_err(|e| RecordingError::StartError(format!("game capture builder: {:?}", e)))? + .set_capture_mode(ObsGameCaptureMode::Any) + .build() + .map_err(|e| RecordingError::StartError(format!("game capture source: {:?}", e)).into()) + }); + + // Both builders hand back their own source type; the scene item only needs the shared ref, + // which is also what removing the source later works on. + let source = match game { + Ok(source) => source.into_inner_source(), + Err(game_err) => { + warn!( + "game capture unavailable ({}), falling back to monitor capture", + game_err + ); + use libobs_simple::sources::windows::MonitorCaptureSourceBuilder; + + catch_native("creating monitor capture", || { + MonitorCaptureSourceBuilder::new("monitor_capture", context.runtime().clone()) + .map_err(|e| RecordingError::StartError(format!("monitor builder: {:?}", e)))? + .build() + .map(|source| source.into_inner_source()) + .map_err(|e| { + RecordingError::StartError(format!("monitor capture source: {:?}", e)) + .into() + }) + })? + } + }; + + scene + .add_source(source.clone()) + .map_err(|e| RecordingError::StartError(format!("failed to add video capture: {:?}", e)))?; + *slot = Some(source); + Ok(()) +} + +/// Video capture on Linux (X11 or PipeWire). +#[cfg(target_os = "linux")] +fn add_video_source( + context: &LibObsContext, + scene: Option<&mut libobs_wrapper::scenes::ObsSceneRef>, + slot: &mut Option, +) -> Result<()> { + use libobs_simple::sources::linux::LinuxGeneralScreenCaptureBuilder; + + let scene = scene + .ok_or_else(|| RecordingError::StartError("the recording scene is missing".to_string()))?; + let source = catch_native("creating screen capture", || { + LinuxGeneralScreenCaptureBuilder::new("screen_capture", context.runtime().clone()) + .map_err(|e| RecordingError::StartError(format!("screen capture builder: {:?}", e)))? + .build() + .map_err(|e| RecordingError::StartError(format!("screen capture source: {:?}", e))) + })?; + scene + .add_source(source.clone()) + .map_err(|e| RecordingError::StartError(format!("failed to add video capture: {:?}", e)))?; + *slot = Some(source); + Ok(()) +} + +/// Take the video source back out of the scene and drop it. +fn remove_video_source( + scene: Option<&mut libobs_wrapper::scenes::ObsSceneRef>, + source: Option, +) -> Result<()> { + let (Some(scene), Some(source)) = (scene, source) else { + return Ok(()); + }; + scene.remove_every_item_of_source(source).map_err(|e| { + RecordingError::StopError(format!("failed to remove video capture: {:?}", e)) + })?; Ok(()) } diff --git a/record-daemon/src/recording/process_audio.rs b/record-daemon/src/recording/process_audio.rs new file mode 100644 index 0000000..2f2be58 --- /dev/null +++ b/record-daemon/src/recording/process_audio.rs @@ -0,0 +1,460 @@ +//! Audio captured from a whole process, kept alive between recordings. +//! +//! win-wasapi's process capture starts from a window: `ms_find_window` rejects any window +//! where `IsWindowVisible` is false, takes the process id from the one it accepts, and opens a +//! process loopback. After that the only check is `IsWindow(hwnd)`, which a hidden window still +//! passes, so a capture that has started survives the app being minimized to the tray. +//! +//! OBS looks like it records a tray-minimized Discord because its source was loaded while +//! Discord was visible. The sources here work the same way and do one better: they are created +//! when the daemon starts, in the scene that outlives every recording, and a scan every couple +//! of seconds adds one as soon as its process shows a window. A source that never gets a window +//! (the app only ever runs in the tray) stays uncaptured, which is also what OBS does. +//! +//! Sources have to sit in the scene: libobs mixes the sources of a view's channels into the +//! output (`mix_audio` over `root_nodes` in `obs-audio.c`), and a source outside every view is +//! captured but never heard. + +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::sync::{Arc, Mutex}; +use std::thread::JoinHandle; +use std::time::Duration; + +use libobs_wrapper::data::ObsData; +use libobs_wrapper::runtime::ObsRuntime; +use libobs_wrapper::scenes::{ObsSceneRef, SceneItemExtSceneTrait}; +use libobs_wrapper::sources::ObsSourceRef; +use libobs_wrapper::utils::SourceInfo; +use serde_json::json; +use tracing::{debug, info, warn}; + +use super::obs_context::{apply_volume, catch_native}; +use crate::config::{AudioSettings, AudioSourceType}; +use crate::error::RecordingError; + +/// How often the window scan runs while the daemon is up. +const SCAN: Duration = Duration::from_secs(2); + +/// The League client that plays the game's sound. +const GAME_EXE: &str = "League of Legends.exe"; + +/// One process whose audio belongs in the recording. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Want { + /// Stable name for the source; also the recording console label. + pub key: String, + /// Executable name as it appears in the process table. + pub exe: String, + /// 0-100, the same scale the settings screen uses. + pub volume: u32, +} + +/// The processes the current audio settings ask for. +pub fn wants(audio: &AudioSettings) -> Vec { + let mut wants = Vec::new(); + if audio.capture_game { + wants.push(Want { + key: "game_audio".to_string(), + exe: GAME_EXE.to_string(), + volume: audio.game_volume, + }); + } + for app in audio.capture_apps.iter().filter(|a| a.enabled) { + if app.source_type != AudioSourceType::Application { + continue; + } + wants.push(Want { + key: format!("app_{}", app.id), + exe: app.device.clone(), + volume: app.volume.unwrap_or(audio.apps_volume), + }); + } + wants +} + +/// The `window` value a process capture source reads. +/// +/// win-wasapi parses it as `title:class:exe` and reads this key alone, so an empty title and +/// class with the executable set asks for any window of that process. `:` and `#` are escaped +/// the way libobs decodes them (`libobs/util/windows/window-helpers.c`), so a title holding a +/// colon still yields three fields. +pub fn window_string(title: &str, class: &str, executable: &str) -> String { + let escape = |field: &str| field.replace('#', "#22").replace(':', "#3A"); + format!("{}:{}:{}", escape(title), escape(class), escape(executable)) +} + +/// A capture that stays attached for as long as its process keeps a window. +struct Live { + key: String, + source: ObsSourceRef, + /// The window the source was created for; a different one means a new process. + window: isize, + volume: u32, +} + +/// Keeps one capture per wanted process, refreshed when a process shows a new window. +/// +/// The captures sit in the recording scene, which is why they have to be created from here +/// rather than by the recording code: the scene lives as long as the daemon does, and a source +/// in a scene on channel 0 is captured and mixed even when no output is running. +pub struct ProcessAudio { + wants: Arc>>, + stop: Sender<()>, + thread: Option>, +} + +impl ProcessAudio { + /// Start the scan. Call after the scene exists and stop it before shutting libobs down. + pub fn start(wants: Vec, runtime: ObsRuntime, scene: ObsSceneRef) -> Self { + let shared = Arc::new(Mutex::new(wants)); + let (stop, stopped) = mpsc::channel(); + let thread = std::thread::Builder::new() + .name("process-audio".to_string()) + .spawn({ + let shared = shared.clone(); + move || watch(shared, stopped, runtime, scene) + }) + .ok(); + if thread.is_none() { + warn!("could not start the process audio scan; app audio needs a new window per recording"); + } + Self { + wants: shared, + stop, + thread, + } + } + + /// Replace the wanted processes, for example after the settings changed. + pub fn set_wants(&self, wants: Vec) { + if let Ok(mut current) = self.wants.lock() { + *current = wants; + } + } + + /// Stop the scan and release every capture. Sources are dropped before this returns. + pub fn stop(&mut self) { + let _ = self.stop.send(()); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +impl Drop for ProcessAudio { + fn drop(&mut self) { + self.stop(); + } +} + +fn watch( + wants: Arc>>, + stop: Receiver<()>, + runtime: ObsRuntime, + scene: ObsSceneRef, +) { + let mut live: Vec = Vec::new(); + loop { + match stop.recv_timeout(SCAN) { + Ok(()) | Err(RecvTimeoutError::Disconnected) => break, + Err(RecvTimeoutError::Timeout) => refresh(&wants, &mut live, &runtime, &scene), + } + } + for capture in live { + detach(&scene, capture); + } + debug!("process audio scan stopped"); +} + +/// One pass: attach what has a window now, drop what is no longer wanted, keep the rest. +fn refresh( + wants: &Arc>>, + live: &mut Vec, + runtime: &ObsRuntime, + scene: &ObsSceneRef, +) { + let wants = match wants.lock() { + Ok(wants) => wants.clone(), + Err(_) => return, + }; + + let mut kept = Vec::with_capacity(live.len()); + for capture in live.drain(..) { + if wants.iter().any(|want| want.key == capture.key) { + kept.push(capture); + } else { + detach(scene, capture); + } + } + *live = kept; + + for want in &wants { + let window = visible_window(&want.exe); + match live.iter().position(|capture| capture.key == want.key) { + Some(index) => { + // A new window means the process restarted; the old capture has nothing to + // follow, so it goes and a fresh source takes its place. + if let Some(window) = window { + if window != live[index].window { + info!("{} opened a new window; catching its audio again", want.exe); + let old = live.remove(index); + detach(scene, old); + if let Some(capture) = create(want, window, runtime, scene) { + live.insert(index, capture); + } + } + } + if let Some(capture) = live.get_mut(index) { + if capture.volume != want.volume { + apply_volume(&capture.source, want.volume); + capture.volume = want.volume; + } + } + } + None => { + if let Some(window) = window { + if let Some(capture) = create(want, window, runtime, scene) { + info!("{} audio attached", want.exe); + live.push(capture); + } + } + } + } + } +} + +/// Add a source to the scene and keep the handles needed to replace it later. +fn create(want: &Want, window: isize, runtime: &ObsRuntime, scene: &ObsSceneRef) -> Option { + let plugin = process_plugin()?; + let settings = json!({ + "window": window_string("", "", &want.exe), + "priority": 2, + }); + let data = ObsData::from_json(&settings.to_string(), runtime.clone()).ok()?; + // A name per window keeps libobs from renaming the source when it replaces an old one. + let name = format!("{}-{}", want.key, window); + let info = SourceInfo::new(plugin, name.as_str(), Some(data), None); + let source = catch_native(&format!("creating {} audio", want.exe), || { + ObsSourceRef::new_from_info(info, runtime.clone()) + .map_err(|e| RecordingError::StartError(format!("{} audio: {:?}", want.exe, e)).into()) + }) + .ok()?; + + apply_volume(&source, want.volume); + let mut scene = scene.clone(); + if let Err(e) = scene.add_source(source.clone()) { + warn!("could not add {} audio to the scene: {:?}", want.exe, e); + return None; + } + Some(Live { + key: want.key.clone(), + source, + window, + volume: want.volume, + }) +} + +/// Take a capture back out of the scene; the source goes with it. +fn detach(scene: &ObsSceneRef, capture: Live) { + let mut scene = scene.clone(); + if let Err(e) = scene.remove_every_item_of_source(capture.source) { + warn!( + "could not remove the {} audio capture: {:?}", + capture.key, e + ); + } +} + +/// A visible top-level window owned by `exe`, if the process has one. +/// +/// The filters are win-wasapi's: visible, not a tool window, not a child, and with a client +/// area that has a size. That is the set of windows `ms_find_window` would accept. +#[cfg(target_os = "windows")] +fn visible_window(exe: &str) -> Option { + use windows::Win32::Foundation::{BOOL, HWND, LPARAM, RECT, TRUE}; + use windows::Win32::UI::WindowsAndMessaging::{ + EnumWindows, GetClientRect, GetWindowLongW, GetWindowThreadProcessId, IsWindowVisible, + GWL_EXSTYLE, GWL_STYLE, WS_CHILD, WS_EX_TOOLWINDOW, + }; + + struct Scan<'a> { + pids: &'a [u32], + found: Option, + } + + unsafe extern "system" fn each(hwnd: HWND, param: LPARAM) -> BOOL { + // SAFETY: the scan outlives the enumeration, which stops at the first match. + let scan = unsafe { &mut *(param.0 as *mut Scan) }; + unsafe { + if !IsWindowVisible(hwnd).as_bool() { + return TRUE; + } + let ex_style = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32; + let style = GetWindowLongW(hwnd, GWL_STYLE) as u32; + if ex_style & WS_EX_TOOLWINDOW.0 != 0 || style & WS_CHILD.0 != 0 { + return TRUE; + } + let mut pid = 0; + GetWindowThreadProcessId(hwnd, Some(&mut pid)); + if !scan.pids.contains(&pid) { + return TRUE; + } + let mut rect = RECT::default(); + if GetClientRect(hwnd, &mut rect).is_err() || rect.right == 0 || rect.bottom == 0 { + return TRUE; + } + scan.found = Some(hwnd.0 as isize); + } + BOOL(0) + } + + let pids = pids_of(exe); + if pids.is_empty() { + return None; + } + let mut scan = Scan { + pids: &pids, + found: None, + }; + unsafe { + let _ = EnumWindows(Some(each), LPARAM(&mut scan as *mut Scan as isize)); + } + scan.found +} + +#[cfg(not(target_os = "windows"))] +fn visible_window(_exe: &str) -> Option { + None +} + +/// Live process ids for `exe`, compared the way the settings screen compares names. +#[cfg(target_os = "windows")] +fn pids_of(exe: &str) -> Vec { + use windows::Win32::Foundation::CloseHandle; + use windows::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, + TH32CS_SNAPPROCESS, + }; + + let wanted = normalize(exe); + let mut pids = Vec::new(); + unsafe { + let Ok(snapshot) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else { + return pids; + }; + let mut entry = PROCESSENTRY32W { + dwSize: std::mem::size_of::() as u32, + ..Default::default() + }; + if Process32FirstW(snapshot, &mut entry).is_ok() { + loop { + let name: String = entry + .szExeFile + .iter() + .take_while(|c| **c != 0) + .map(|c| *c as u8 as char) + .collect(); + if normalize(&name) == wanted { + pids.push(entry.th32ProcessID); + } + if Process32NextW(snapshot, &mut entry).is_err() { + break; + } + } + } + let _ = CloseHandle(snapshot); + } + pids +} + +/// `Discord.exe` and `discord` name the same process. +fn normalize(name: &str) -> String { + let name = name.trim().to_ascii_lowercase(); + name.strip_suffix(".exe").unwrap_or(&name).to_string() +} + +/// The win-wasapi process capture source, when the platform has one. +#[cfg(target_os = "windows")] +fn process_plugin() -> Option<&'static str> { + Some("wasapi_process_output_capture") +} + +#[cfg(not(target_os = "windows"))] +fn process_plugin() -> Option<&'static str> { + // The pulse sources capture a device, not a process, so there is nothing to follow. + None +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::{AudioSourceConfig, Settings}; + + #[test] + fn a_window_string_escapes_the_separators() { + // libobs decodes both escapes, so a title holding a colon still splits into three. + assert_eq!( + window_string("a:b", "c#d", "game.exe"), + "a#3Ab:c#22d:game.exe" + ); + assert_eq!(window_string("", "", "Discord.exe"), "::Discord.exe"); + } + + #[test] + fn the_settings_name_the_processes_to_capture() { + let mut settings = Settings::default(); + settings.audio.capture_game = true; + settings.audio.game_volume = 70; + settings.audio.capture_apps = vec![ + AudioSourceConfig { + id: "discord".into(), + name: "Discord".into(), + source_type: AudioSourceType::Application, + device: "Discord.exe".into(), + volume: Some(45), + enabled: true, + }, + AudioSourceConfig { + id: "muted-app".into(), + name: "Muted".into(), + source_type: AudioSourceType::Application, + device: "Muted.exe".into(), + volume: None, + enabled: false, + }, + AudioSourceConfig { + id: "second-mic".into(), + name: "Second mic".into(), + source_type: AudioSourceType::DeviceInput, + device: "mic".into(), + volume: None, + enabled: true, + }, + ]; + + let wants = wants(&settings.audio); + assert_eq!(wants.len(), 2); + assert_eq!( + wants[0], + Want { + key: "game_audio".into(), + exe: GAME_EXE.into(), + volume: 70 + } + ); + assert_eq!( + wants[1], + Want { + key: "app_discord".into(), + exe: "Discord.exe".into(), + volume: 45 + } + ); + } + + #[test] + fn process_names_fold_case_and_extension() { + assert_eq!(normalize("Discord.exe"), "discord"); + assert_eq!(normalize(" DISCORD "), "discord"); + } +}