From 2e98159083145f35686743a58163b808228b58ab Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Fri, 13 Nov 2026 00:06:16 +0100 Subject: [PATCH] fix: apply audio volumes, enumerate real devices, remove dead code - Audio sources were created but never added to the scene, so mic, game and app audio never reached the output; all sources are now added with their configured volume via obs_source_set_volume - getAudioDevices enumerates real WASAPI devices again instead of returning hardcoded defaults (the crash-isolation bypass) - Recording module split: encoder selection and output building move to their own files; obs_context shrinks from 1556 to 464 lines - Remove unused IPC (recordings/timeline/export commands), the CommandHandler trait, crash marker files, and the stats plumbing that was never wired to the frontend - Deduplicate the LCU reconnect logic into connect_and_listen --- record-daemon/Cargo.lock | 1 + record-daemon/Cargo.toml | 1 + record-daemon/src/config/presets.rs | 12 +- record-daemon/src/config/settings.rs | 7 - record-daemon/src/ipc/handlers.rs | 211 +-- record-daemon/src/ipc/mod.rs | 2 +- record-daemon/src/ipc/protocol.rs | 33 +- record-daemon/src/ipc/server.rs | 45 +- record-daemon/src/main.rs | 186 +-- record-daemon/src/recording/capture.rs | 238 --- record-daemon/src/recording/encoder.rs | 453 +----- record-daemon/src/recording/mod.rs | 78 +- record-daemon/src/recording/obs_context.rs | 1654 ++++---------------- record-daemon/src/recording/output.rs | 197 +-- record-daemon/src/timeline/store.rs | 1 - 15 files changed, 457 insertions(+), 2662 deletions(-) delete mode 100644 record-daemon/src/recording/capture.rs diff --git a/record-daemon/Cargo.lock b/record-daemon/Cargo.lock index 389b4d3..ad0c5e0 100644 --- a/record-daemon/Cargo.lock +++ b/record-daemon/Cargo.lock @@ -2398,6 +2398,7 @@ dependencies = [ "directories", "display-info", "futures", + "libobs", "libobs-bootstrapper", "libobs-simple", "libobs-wrapper", diff --git a/record-daemon/Cargo.toml b/record-daemon/Cargo.toml index d2a1d89..cd8c062 100644 --- a/record-daemon/Cargo.toml +++ b/record-daemon/Cargo.toml @@ -64,6 +64,7 @@ base64 = "0.22" regex = "1" # OBS recording library +libobs = { version = "5.0.1" } libobs-simple = { version = "8.0.1" } libobs-bootstrapper = { version = "0.4.0", features = ["install_dummy_dll"] } libobs-wrapper = { version = "9.0.4" } diff --git a/record-daemon/src/config/presets.rs b/record-daemon/src/config/presets.rs index e544c01..2950f7e 100644 --- a/record-daemon/src/config/presets.rs +++ b/record-daemon/src/config/presets.rs @@ -251,20 +251,12 @@ impl AudioSourceConfig { /// Create a Discord audio source. pub fn discord() -> Self { - Self::new( - "Discord", - AudioSourceType::Application, - "Discord.exe", - ) + Self::new("Discord", AudioSourceType::Application, "Discord.exe") } /// Create a Spotify audio source. pub fn spotify() -> Self { - Self::new( - "Spotify", - AudioSourceType::Application, - "Spotify.exe", - ) + Self::new("Spotify", AudioSourceType::Application, "Spotify.exe") } } diff --git a/record-daemon/src/config/settings.rs b/record-daemon/src/config/settings.rs index 50e44c4..acc8f8b 100644 --- a/record-daemon/src/config/settings.rs +++ b/record-daemon/src/config/settings.rs @@ -90,13 +90,6 @@ pub struct OutputSettings { pub split_time_minutes: u32, } -impl OutputSettings { - /// Get the output format enum for this container. - pub fn output_format(&self) -> crate::recording::OutputFormat { - crate::recording::OutputFormat::from(self.container.as_str()) - } -} - impl Default for OutputSettings { fn default() -> Self { Self { diff --git a/record-daemon/src/ipc/handlers.rs b/record-daemon/src/ipc/handlers.rs index f80294d..1a28c1a 100644 --- a/record-daemon/src/ipc/handlers.rs +++ b/record-daemon/src/ipc/handlers.rs @@ -2,13 +2,12 @@ use std::sync::Arc; -use async_trait::async_trait; use parking_lot::RwLock; use tracing::{debug, info}; use super::protocol::{ - EncoderInfo, GetEncodersResponse, GetRecordingsResponse, GetSettingsResponse, - GetStatusResponse, IpcCommand, IpcMessage, IpcResponse, + EncoderInfo, GetEncodersResponse, GetSettingsResponse, GetStatusResponse, IpcCommand, + IpcMessage, IpcResponse, }; use crate::config::Settings; use crate::error::Result; @@ -17,39 +16,6 @@ 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 { - /// Handle the command and return a response. - async fn handle(&self, payload: Option) -> Result; -} - /// Collection of IPC command handlers. pub struct IpcHandlers { /// Settings reference. @@ -103,19 +69,8 @@ impl IpcHandlers { 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, - IpcCommand::GetRecording { id } => self.handle_get_recording(id).await, - IpcCommand::DeleteRecording { id } => self.handle_delete_recording(id).await, - IpcCommand::GetTimeline { recording_id } => { - self.handle_get_timeline(recording_id).await - } - IpcCommand::ExportTimeline { - recording_id, - format, - } => self.handle_export_timeline(recording_id, format).await, IpcCommand::Shutdown => self.handle_shutdown().await, }; - match result { Ok(data) => IpcResponse::success(message.id, data), Err(e) => { @@ -265,57 +220,6 @@ impl IpcHandlers { } } - async fn handle_get_recordings(&self) -> Result { - let recordings = self.timeline.read().get_all_recordings()?; - let response = GetRecordingsResponse { recordings }; - Ok(serde_json::to_value(response)?) - } - - async fn handle_get_recording(&self, id: uuid::Uuid) -> Result { - let recording = self.timeline.read().get_recording(id)?; - Ok(serde_json::to_value(recording)?) - } - - async fn handle_delete_recording(&self, id: uuid::Uuid) -> Result { - self.timeline.write().delete_recording(id)?; - Ok(serde_json::json!({ "success": true })) - } - - async fn handle_get_timeline(&self, recording_id: uuid::Uuid) -> Result { - let timeline = self.timeline.read().get_timeline(recording_id)?; - Ok(serde_json::to_value(timeline)?) - } - - async fn handle_export_timeline( - &self, - recording_id: uuid::Uuid, - format: super::protocol::ExportFormat, - ) -> Result { - let timeline = self.timeline.read().get_timeline(recording_id)?; - - let exported = match format { - super::protocol::ExportFormat::Json => serde_json::to_string_pretty(&timeline)?, - super::protocol::ExportFormat::Csv => { - // Convert to CSV format - let mut csv = String::from("timestamp,event_type,description\n"); - for event in &timeline.events { - csv.push_str(&format!( - "{},{},{}\n", - event.timestamp.to_rfc3339(), - event.event_type, - event.description, - )); - } - csv - } - }; - - Ok(serde_json::json!({ - "data": exported, - "format": format, - })) - } - async fn handle_shutdown(&self) -> Result { info!("Shutdown requested via IPC"); // Signal shutdown through status @@ -326,38 +230,13 @@ impl IpcHandlers { 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 (input_devices, output_devices) = enumerate_windows_audio_devices()?; 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, - }], + input_devices, + output_devices, }; - - write_crash_marker("audio_devices_success"); Ok(serde_json::to_value(response)?) } @@ -418,10 +297,7 @@ impl IpcHandlers { { let mut settings = self.settings.write(); - settings - .audio - .capture_apps - .retain(|s| s.id != id); + settings.audio.capture_apps.retain(|s| s.id != id); crate::config::save_config(&settings)?; } @@ -471,8 +347,10 @@ impl IpcHandlers { /// 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)> { +fn enumerate_windows_audio_devices() -> Result<( + Vec, + Vec, +)> { use super::protocol::AudioDeviceInfo; use tracing::{error, warn}; @@ -500,7 +378,10 @@ fn enumerate_windows_audio_devices( match result { Ok(Ok(devices)) => Ok(devices), Ok(Err(e)) => { - warn!("WASAPI device enumeration failed, returning defaults: {}", e); + warn!( + "WASAPI device enumeration failed, returning defaults: {}", + e + ); Ok(fallback()) } Err(panic_info) => { @@ -512,16 +393,18 @@ fn enumerate_windows_audio_devices( /// Inner implementation of Windows audio device enumeration using WASAPI. #[cfg(target_os = "windows")] -fn enumerate_windows_audio_devices_inner( -) -> std::result::Result< - (Vec, Vec), +fn enumerate_windows_audio_devices_inner() -> std::result::Result< + ( + Vec, + Vec, + ), String, > { use super::protocol::AudioDeviceInfo; + use tracing::{info, warn}; + use windows::core::PWSTR; use windows::Win32::Media::Audio::*; use windows::Win32::System::Com::*; - use windows::core::PWSTR; - use tracing::{info, warn}; fn pwstr_to_string(p: PWSTR) -> String { if p.is_null() { @@ -544,7 +427,10 @@ fn enumerate_windows_audio_devices_inner( 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()); + info!( + "[AUDIO_ENUM] inner: starting WASAPI enumeration on this thread (id={:?})", + std::thread::current().id() + ); let com_initialized; unsafe { @@ -562,14 +448,18 @@ fn enumerate_windows_audio_devices_inner( // 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); + 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))?; + 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 @@ -586,7 +476,8 @@ fn enumerate_windows_audio_devices_inner( .map(pwstr_to_string); // Enumerate capture (input) devices - if let Ok(capture_collection) = enumerator.EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE) { + 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) { @@ -601,8 +492,15 @@ fn enumerate_windows_audio_devices_inner( 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 }); + debug!( + "Found input device: {} (id: {}, default: {})", + name, id, is_default + ); + input_devices.push(AudioDeviceInfo { + id, + name, + is_default, + }); } } } @@ -624,8 +522,15 @@ fn enumerate_windows_audio_devices_inner( 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 }); + debug!( + "Found output device: {} (id: {}, default: {})", + name, id, is_default + ); + output_devices.push(AudioDeviceInfo { + id, + name, + is_default, + }); } } } @@ -671,8 +576,8 @@ fn enumerate_windows_audio_devices_inner( /// `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::IPropertyStore; use windows::Win32::UI::Shell::PropertiesSystem::PROPERTYKEY; // PKEY_Device_FriendlyName = { a45c254e-df1c-4efd-8020-67d146850500 }, 14 @@ -686,7 +591,9 @@ fn get_device_friendly_name(device: &windows::Win32::Media::Audio::IMMDevice) -> // Open the property store read-only. let store: IPropertyStore = device.OpenPropertyStore(STGM(0)).ok()?; // Read the friendly-name property. - let prop = store.GetValue(&FRIENDLY_NAME_KEY as *const PROPERTYKEY).ok()?; + let 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 @@ -706,8 +613,10 @@ fn get_device_friendly_name(device: &windows::Win32::Media::Audio::IMMDevice) -> /// Enumerate audio devices on Linux using PulseAudio. #[cfg(target_os = "linux")] -fn enumerate_linux_audio_devices( -) -> Result<(Vec, Vec)> { +fn enumerate_linux_audio_devices() -> Result<( + Vec, + Vec, +)> { use super::protocol::AudioDeviceInfo; use tracing::warn; diff --git a/record-daemon/src/ipc/mod.rs b/record-daemon/src/ipc/mod.rs index d5228f4..454a3c8 100644 --- a/record-daemon/src/ipc/mod.rs +++ b/record-daemon/src/ipc/mod.rs @@ -7,7 +7,7 @@ mod handlers; mod protocol; mod server; -pub use handlers::{CommandHandler, IpcHandlers}; +pub use handlers::IpcHandlers; pub use protocol::{IpcCommand, IpcMessage, IpcNotification, IpcResponse}; pub use server::{IpcServer, IpcServerConfig}; diff --git a/record-daemon/src/ipc/protocol.rs b/record-daemon/src/ipc/protocol.rs index fa5872c..b410656 100644 --- a/record-daemon/src/ipc/protocol.rs +++ b/record-daemon/src/ipc/protocol.rs @@ -5,10 +5,9 @@ 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; /// IPC message wrapper. #[derive(Debug, Clone, Serialize, Deserialize)] @@ -70,37 +69,12 @@ pub enum IpcCommand { /// Stop recording. StopRecording, /// Get list of recordings. - GetRecordings, - /// Get specific recording details. - GetRecording { id: Uuid }, - /// Delete a recording. - DeleteRecording { id: Uuid }, - - // Timeline commands - /// Get timeline for a recording. - GetTimeline { recording_id: Uuid }, - /// Export timeline to file. - ExportTimeline { - recording_id: Uuid, - format: ExportFormat, - }, // Daemon control /// Shutdown the daemon. Shutdown, } -/// Export format for timeline. -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "lowercase")] -pub enum ExportFormat { - /// JSON format. - Json, - /// CSV format. - Csv, -} - -/// IPC response. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct IpcResponse { /// Original request ID. @@ -192,11 +166,6 @@ pub struct GetStatusResponse { pub client_connected: bool, } -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct GetRecordingsResponse { - pub recordings: Vec, -} - #[derive(Debug, Clone, Serialize, Deserialize)] pub struct GetEncodersResponse { pub available: Vec, diff --git a/record-daemon/src/ipc/server.rs b/record-daemon/src/ipc/server.rs index 3495dee..a590076 100644 --- a/record-daemon/src/ipc/server.rs +++ b/record-daemon/src/ipc/server.rs @@ -12,29 +12,6 @@ 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 { @@ -490,13 +467,14 @@ impl IpcServer { }; 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) => { - info!("[IPC] Parsed message type={:?} command={:?}", msg.message_type, msg.command); + info!( + "[IPC] Parsed message type={:?} command={:?}", + msg.message_type, msg.command + ); msg } Err(e) => { @@ -514,21 +492,10 @@ 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 => { - #[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::Request => handlers.handle(message).await, MessageType::Notification => { // Notifications don't get responses trace!("Received notification: {:?}", message); @@ -551,8 +518,6 @@ 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 57f057b..5885792 100644 --- a/record-daemon/src/main.rs +++ b/record-daemon/src/main.rs @@ -15,7 +15,7 @@ use record_daemon::{ error::Result, ipc::{self, IpcHandlers, IpcServer, IpcServerConfig}, lqp::{ - describe_event, LockfileWatcher, LqpClient, EVENT_TYPE_CHAMPION_PICK, + describe_event, LockfileCredentials, LockfileWatcher, LqpClient, EVENT_TYPE_CHAMPION_PICK, EVENT_TYPE_GAME_START, EVENT_TYPE_PHASE_CHANGE, }, recording::RecordingEngine, @@ -23,30 +23,6 @@ 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)] @@ -115,46 +91,27 @@ 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(())) => { - #[cfg(target_os = "windows")] - write_startup_marker("spawn_blocking_recording_engine_ok"); - } + Ok(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 @@ -165,8 +122,6 @@ impl Daemon { // 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 { @@ -191,8 +146,6 @@ 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(()) @@ -259,26 +212,8 @@ impl Daemon { info!("League Client detected"); if let Some(creds) = watcher.credentials() { - match self.lqp_client.connect(creds.clone()).await { - Ok(()) => { - // Only transition to Monitoring after successful connection - self.state_machine - .transition(StateTransition::ClientStarted); - - if let Err(e) = self.lqp_client.start_event_listener().await { - warn!("Failed to start event listener: {}", e); - // Still stay in Monitoring, will retry on next check - } else { - // Start polling for live client events (kills, deaths, objectives) - self.lqp_client.start_live_client_event_poller().await; - } - } - Err(e) => { - warn!("Failed to connect to League Client: {}", e); - // Don't transition to Monitoring - will retry on next check - // The lockfile watcher will return None on next check since - // credentials are already set, so we need to handle reconnection - } + if let Err(e) = self.connect_and_listen(creds.clone()).await { + warn!("Failed to connect to League Client: {}", e); } } } @@ -290,29 +225,12 @@ impl Daemon { self.lqp_client.disconnect().await; } None => { - // No change in lockfile status - // Check if we need to reconnect (lockfile exists but WebSocket not connected) + // No change in lockfile status: reconnect if the websocket dropped if watcher.credentials().is_some() && !self.lqp_client.is_ws_connected().await { - info!("Lockfile exists but WebSocket not connected, attempting reconnect..."); + info!("League Client websocket not connected, attempting reconnect"); if let Some(creds) = watcher.credentials() { - match self.lqp_client.connect(creds.clone()).await { - Ok(()) => { - // Transition to Monitoring if not already - if !self.state_machine.is_monitoring() { - self.state_machine - .transition(StateTransition::ClientStarted); - } - - if let Err(e) = self.lqp_client.start_event_listener().await { - warn!("Failed to start event listener on reconnect: {}", e); - } else { - self.lqp_client.start_live_client_event_poller().await; - } - } - Err(e) => { - info!("Reconnect attempt failed: {}", e); - // Will retry on next check - } + if let Err(e) = self.connect_and_listen(creds.clone()).await { + warn!("Reconnect attempt failed: {}", e); } } } @@ -323,16 +241,33 @@ impl Daemon { Ok(()) } + /// Connect to the LCU websocket and start listening for events. + /// + /// Shared by the initial connection and reconnects; the Monitoring + /// transition is skipped when the state machine is already there. + async fn connect_and_listen(&self, creds: LockfileCredentials) -> Result<()> { + self.lqp_client.connect(creds).await?; + + if !self.state_machine.is_monitoring() { + self.state_machine + .transition(StateTransition::ClientStarted); + } + + if let Err(e) = self.lqp_client.start_event_listener().await { + warn!("Failed to start event listener: {}", e); + return Ok(()); // stay in Monitoring; retry on next check + } + self.lqp_client.start_live_client_event_poller().await; + Ok(()) + } + /// Handle a game event. async fn handle_game_event(&self, parsed: record_daemon::lqp::ParsedEvent) -> Result<()> { let event_type = &parsed.event_type; let raw_data = &parsed.raw_data; let description = describe_event(event_type, raw_data); - info!( - "[EVENT_HANDLER] Game event received: type={}, desc={}", - event_type, description - ); + debug!("game event: type={}, desc={}", event_type, description); // Handle pre-game data collection match event_type.as_str() { @@ -342,7 +277,7 @@ impl Daemon { .or_else(|| raw_data.get("phase").and_then(|v| v.as_str())) .unwrap_or(""); if phase == "ChampSelect" { - info!("[EVENT_HANDLER] Champion select started"); + info!("Champion select started"); } } EVENT_TYPE_CHAMPION_PICK => { @@ -357,12 +292,12 @@ impl Daemon { .or_else(|| raw_data.get("champion_name")) .and_then(|v| v.as_str()) .unwrap_or("unknown"); - info!("[EVENT_HANDLER] Local player picked champion: {}", champion); + info!("Local player picked champion: {}", champion); } } EVENT_TYPE_GAME_START => { let game_id = raw_data.get("gameId").and_then(|v| v.as_u64()).unwrap_or(0); - info!("[EVENT_HANDLER] Game started with game_id: {}", game_id); + info!("Game started with game_id: {}", game_id); } _ => {} } @@ -405,7 +340,7 @@ impl Daemon { // Process state transitions if let Some(transition) = self.state_machine.process_event(event_type, raw_data) { - info!("[EVENT_HANDLER] State transition: {:?}", transition); + info!("State transition: {:?}", transition); // Only process the transition if it's valid if let Some(_new_state) = self.state_machine.transition(transition.clone()) { @@ -415,23 +350,18 @@ impl Daemon { // Extract game_id from raw_data let game_id = raw_data.get("gameId").and_then(|v| v.as_u64()).unwrap_or(0); - info!( - "[EVENT_HANDLER] GameStarted transition - game_id: {}", - game_id - ); + info!("GameStarted transition - game_id: {}", game_id); // If already recording, stop the current recording first if self.state_machine.is_recording() { - info!( - "[EVENT_HANDLER] Stopping previous recording before starting new one" - ); + info!("Stopping previous recording before starting new one"); if let Err(e) = self.stop_recording().await { - warn!("[EVENT_HANDLER] Failed to stop previous recording: {}", e); + warn!("Failed to stop previous recording: {}", e); } } - info!("[EVENT_HANDLER] Calling start_recording..."); + info!("Calling start_recording..."); // Fetch raw API data in parallel let ( @@ -463,28 +393,28 @@ impl Daemon { .start_recording_with_metadata(game_id, metadata_update) .await { - error!("[EVENT_HANDLER] Failed to start recording: {}", e); + error!("Failed to start recording: {}", e); // Don't propagate error - keep daemon running } else { - info!("[EVENT_HANDLER] start_recording completed successfully"); + info!("start_recording completed successfully"); } } StateTransition::GameEnded => { - info!("[EVENT_HANDLER] GameEnded transition"); + info!("GameEnded transition"); // Fetch raw end-of-game stats from API let raw_end_game_stats = self.lqp_client.fetch_raw_end_game_stats().await.ok(); info!( - "[EVENT_HANDLER] Game end stats from API: {:?}", + "Game end stats from API: {:?}", raw_end_game_stats.is_some() ); if let Err(e) = self.stop_recording_with_metadata(raw_end_game_stats).await { - error!("[EVENT_HANDLER] Failed to stop recording: {}", e); + error!("Failed to stop recording: {}", e); // Don't propagate error - keep daemon running } @@ -492,14 +422,11 @@ impl Daemon { _ => {} } } else { - warn!( - "[EVENT_HANDLER] State transition rejected: {:?}", - transition - ); + warn!("State transition rejected: {:?}", transition); } } - info!("[EVENT_HANDLER] Event handling complete"); + info!("Event handling complete"); Ok(()) } @@ -740,19 +667,9 @@ 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); @@ -777,23 +694,14 @@ 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 { config::ConfigPersistence::new(config_path).load()? } 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)] { // Handle shutdown signals @@ -819,14 +727,8 @@ 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 { error!("Error during shutdown: {}", e); diff --git a/record-daemon/src/recording/capture.rs b/record-daemon/src/recording/capture.rs deleted file mode 100644 index b28681e..0000000 --- a/record-daemon/src/recording/capture.rs +++ /dev/null @@ -1,238 +0,0 @@ -//! Game capture source configuration using libobs-simple. -//! -//! This module provides capture sources for recording game footage, -//! including game capture, window capture, and monitor capture. - -use serde::{Deserialize, Serialize}; - -/// Game capture source for recording game footage. -/// -/// Uses OBS game capture for efficient GPU-based capture. -#[derive(Debug, Clone)] -pub struct GameCapture { - /// Source name. - pub name: String, - /// Window title to capture (if specific window). - pub window: Option, - /// Process name to capture. - pub process_name: Option, - /// Capture mode. - pub mode: CaptureMode, - /// Whether to capture cursor. - pub capture_cursor: bool, - /// Window class (Windows only). - pub window_class: Option, -} - -impl Default for GameCapture { - fn default() -> Self { - Self { - name: "Game Capture".to_string(), - window: None, - process_name: Some("League of Legends.exe".to_string()), - mode: CaptureMode::Process, - capture_cursor: false, - window_class: Some("RiotWindowClass".to_string()), - } - } -} - -impl GameCapture { - /// Create a new game capture source. - pub fn new(name: &str) -> Self { - Self { - name: name.to_string(), - ..Default::default() - } - } - - /// Create a game capture configured for League of Legends. - pub fn for_league_of_legends() -> Self { - Self { - name: "League of Legends Capture".to_string(), - window: Some("League of Legends (TM) Client".to_string()), - process_name: Some("League of Legends.exe".to_string()), - mode: CaptureMode::Window, - capture_cursor: false, - window_class: Some("RiotWindowClass".to_string()), - } - } - - /// Set the window to capture. - pub fn with_window(mut self, window: &str) -> Self { - self.window = Some(window.to_string()); - self.mode = CaptureMode::Window; - self - } - - /// Set the process name to capture. - pub fn with_process(mut self, process: &str) -> Self { - self.process_name = Some(process.to_string()); - self.mode = CaptureMode::Process; - self - } - - /// Set the window class (Windows only). - pub fn with_window_class(mut self, class: &str) -> Self { - self.window_class = Some(class.to_string()); - self - } - - /// Set whether to capture the cursor. - pub fn with_cursor(mut self, capture: bool) -> Self { - self.capture_cursor = capture; - self - } - - /// Get the window string for OBS in the format "Title:Class:Executable". - pub fn window_string(&self) -> Option { - match (&self.window, &self.window_class, &self.process_name) { - (Some(window), Some(class), Some(process)) => { - Some(format!("{}:{}:{}", window, class, process)) - } - (Some(window), None, Some(process)) => Some(format!("{}::{}", window, process)), - (Some(window), Some(class), None) => Some(format!("{}:{}:", window, class)), - _ => None, - } - } -} - -/// Capture mode. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -#[derive(Default)] -pub enum CaptureMode { - /// Capture any fullscreen application. - Any, - /// Capture a specific window. - Window, - /// Capture a specific process. - #[default] - Process, -} - -/// Window capture source (alternative to game capture). -/// -/// Uses OBS window capture which works with more applications -/// but may have slightly higher overhead than game capture. -#[derive(Debug, Clone)] -pub struct WindowCapture { - /// Source name. - pub name: String, - /// Window title. - pub window_title: String, - /// Window class (X11/Windows). - pub window_class: Option, - /// Whether to capture cursor. - pub capture_cursor: bool, -} - -impl WindowCapture { - /// Create a new window capture source. - pub fn new(name: &str, window_title: &str) -> Self { - Self { - name: name.to_string(), - window_title: window_title.to_string(), - window_class: None, - capture_cursor: false, - } - } - - /// Set the window class (for X11/Windows). - pub fn with_class(mut self, class: &str) -> Self { - self.window_class = Some(class.to_string()); - self - } - - /// Set whether to capture the cursor. - pub fn with_cursor(mut self, capture: bool) -> Self { - self.capture_cursor = capture; - self - } -} - -/// Monitor capture source (fallback). -/// -/// Captures an entire monitor. Useful as a fallback when -/// game capture or window capture don't work. -#[derive(Debug, Clone)] -pub struct MonitorCapture { - /// Source name. - pub name: String, - /// Monitor index (0-based). - pub monitor: u32, - /// Whether to capture cursor. - pub capture_cursor: bool, -} - -impl MonitorCapture { - /// Create a new monitor capture source. - pub fn new(name: &str, monitor: u32) -> Self { - Self { - name: name.to_string(), - monitor, - capture_cursor: false, - } - } - - /// Set whether to capture the cursor. - pub fn with_cursor(mut self, capture: bool) -> Self { - self.capture_cursor = capture; - self - } -} - -/// Capture source type. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SourceType { - /// Game capture source. - GameCapture, - /// Window capture source. - WindowCapture, - /// Monitor capture source. - MonitorCapture, -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_game_capture_creation() { - let capture = GameCapture::new("Test Capture"); - assert_eq!(capture.name, "Test Capture"); - assert_eq!(capture.mode, CaptureMode::Process); - } - - #[test] - fn test_game_capture_with_process() { - let capture = GameCapture::new("Test").with_process("League of Legends.exe"); - - assert_eq!( - capture.process_name, - Some("League of Legends.exe".to_string()) - ); - assert_eq!(capture.mode, CaptureMode::Process); - } - - #[test] - fn test_league_capture_config() { - let capture = GameCapture::for_league_of_legends(); - assert_eq!(capture.name, "League of Legends Capture"); - assert_eq!( - capture.process_name, - Some("League of Legends.exe".to_string()) - ); - assert_eq!(capture.window_class, Some("RiotWindowClass".to_string())); - } - - #[test] - fn test_window_string() { - let capture = GameCapture::for_league_of_legends(); - let window_str = capture.window_string(); - assert!(window_str.is_some()); - let s = window_str.unwrap(); - assert!(s.contains("League of Legends")); - assert!(s.contains("RiotWindowClass")); - } -} diff --git a/record-daemon/src/recording/encoder.rs b/record-daemon/src/recording/encoder.rs index 030b2d0..fb1da54 100644 --- a/record-daemon/src/recording/encoder.rs +++ b/record-daemon/src/recording/encoder.rs @@ -1,244 +1,9 @@ -//! Video and audio encoder configuration. +//! Hardware encoder detection. //! -//! This module provides encoder configuration types that integrate with -//! libobs-simple for hardware and software encoding. +//! Queries GPU vendor info to decide which OBS hardware encoder +//! (NVENC, AMF, QuickSync) can be used, falling back to x264. -use serde::{Deserialize, Serialize}; - -use crate::config::{AmfQuality, EncoderPreset, QualityLevel}; - -/// Video encoder configuration. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EncoderConfig { - /// Encoder ID (e.g., "jim_nvenc", "x264"). - pub encoder_id: String, - /// Target bitrate in kbps. - pub bitrate: u32, - /// Keyframe interval in seconds. - pub keyframe_interval: u32, - /// Encoder-specific settings. - pub settings: EncoderSettings, -} - -impl Default for EncoderConfig { - fn default() -> Self { - Self { - encoder_id: "jim_nvenc".to_string(), - bitrate: 6000, - keyframe_interval: 2, - settings: EncoderSettings::Nvenc { - cq_level: 20, - two_pass: true, - preset: "p4".to_string(), - rate_control: NvencRateControl::Vbr, - }, - } - } -} - -/// Encoder-specific settings. -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(tag = "type", rename_all = "lowercase")] -pub enum EncoderSettings { - /// NVIDIA NVENC settings. - Nvenc { - /// Constant Quality level (0-51, lower = better). - cq_level: u32, - /// Use two-pass encoding. - two_pass: bool, - /// Preset (p1-p7, lower = faster). - preset: String, - /// Rate control mode. - rate_control: NvencRateControl, - }, - /// AMD AMF settings. - Amf { - /// Quality preset. - quality: AmfQuality, - /// Rate control method. - rate_control: AmfRateControl, - }, - /// x264 settings. - X264 { - /// Preset name. - preset: String, - /// Constant Rate Factor (if using CRF). - crf: Option, - /// Use threads. - threads: u32, - }, -} - -/// NVENC rate control modes. -#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)] -#[serde(rename_all = "lowercase")] -pub enum NvencRateControl { - /// Constant bitrate. - Cbr, - /// Variable bitrate. - #[default] - Vbr, - /// Constant quality. - Cqp, -} - -/// AMF rate control modes. -#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)] -#[serde(rename_all = "lowercase")] -pub enum AmfRateControl { - /// Constant bitrate. - Cbr, - /// Variable bitrate. - #[default] - Vbr, - /// Constant QP. - Cqp, -} - -impl EncoderConfig { - /// Create encoder config from preset. - pub fn from_preset(preset: &EncoderPreset) -> Self { - match preset { - EncoderPreset::Nvenc { - bitrate, - cq_level, - two_pass, - } => Self { - encoder_id: "jim_nvenc".to_string(), - bitrate: *bitrate, - keyframe_interval: 2, - settings: EncoderSettings::Nvenc { - cq_level: *cq_level, - two_pass: *two_pass, - preset: "p4".to_string(), // Balanced preset - rate_control: NvencRateControl::Vbr, - }, - }, - EncoderPreset::Amf { bitrate, quality } => Self { - encoder_id: "amd_amf_h264".to_string(), - bitrate: *bitrate, - keyframe_interval: 2, - settings: EncoderSettings::Amf { - quality: *quality, - rate_control: AmfRateControl::Vbr, - }, - }, - EncoderPreset::X264 { - preset, - bitrate, - crf, - } => Self { - encoder_id: "x264".to_string(), - bitrate: *bitrate, - keyframe_interval: 2, - settings: EncoderSettings::X264 { - preset: preset.clone(), - crf: *crf, - threads: 0, // Auto - }, - }, - } - } - - /// Get the encoder name for display. - pub fn encoder_name(&self) -> &str { - &self.encoder_id - } - - /// Check if this is a hardware encoder. - pub fn is_hardware(&self) -> bool { - matches!( - self.settings, - EncoderSettings::Nvenc { .. } | EncoderSettings::Amf { .. } - ) - } - - /// Check if this is an NVIDIA encoder. - pub fn is_nvenc(&self) -> bool { - matches!(self.settings, EncoderSettings::Nvenc { .. }) - } - - /// Check if this is an AMD encoder. - pub fn is_amf(&self) -> bool { - matches!(self.settings, EncoderSettings::Amf { .. }) - } - - /// Check if this is a software encoder. - pub fn is_software(&self) -> bool { - matches!(self.settings, EncoderSettings::X264 { .. }) - } - - /// Get the hardware codec type for libobs-simple. - pub fn hardware_codec(&self) -> Option { - use libobs_simple::output::simple::HardwareCodec; - - match &self.settings { - EncoderSettings::Nvenc { .. } => Some(HardwareCodec::H264), - EncoderSettings::Amf { .. } => Some(HardwareCodec::H264), - EncoderSettings::X264 { .. } => None, - } - } - - /// Get the hardware preset for libobs-simple. - pub fn hardware_preset(&self) -> libobs_simple::output::simple::HardwarePreset { - use libobs_simple::output::simple::HardwarePreset; - - match &self.settings { - EncoderSettings::Nvenc { preset, .. } => match preset.as_str() { - "p1" => HardwarePreset::Speed, - "p2" => HardwarePreset::Speed, - "p3" => HardwarePreset::Balanced, - "p4" => HardwarePreset::Balanced, - "p5" => HardwarePreset::Quality, - "p6" => HardwarePreset::Quality, - "p7" => HardwarePreset::Quality, - _ => HardwarePreset::Balanced, - }, - EncoderSettings::Amf { quality, .. } => match quality { - AmfQuality::Speed => HardwarePreset::Speed, - AmfQuality::Balanced => HardwarePreset::Balanced, - AmfQuality::Quality => HardwarePreset::Quality, - }, - EncoderSettings::X264 { .. } => HardwarePreset::Balanced, - } - } -} - -/// Audio encoder configuration. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct AudioEncoderConfig { - /// Encoder ID (usually "ffmpeg_aac"). - pub encoder_id: String, - /// Bitrate in kbps. - pub bitrate: u32, - /// Sample rate in Hz. - pub sample_rate: u32, - /// Number of channels. - pub channels: u32, -} - -impl Default for AudioEncoderConfig { - fn default() -> Self { - Self { - encoder_id: "ffmpeg_aac".to_string(), - bitrate: 192, - sample_rate: 48000, - channels: 2, - } - } -} - -impl AudioEncoderConfig { - /// Create a new audio encoder config with the specified bitrate. - pub fn with_bitrate(bitrate: u32) -> Self { - Self { - bitrate, - ..Default::default() - } - } -} - -/// Encoder capability. +/// A video encoder the daemon can drive through OBS. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum EncoderCapability { /// NVIDIA NVENC. @@ -247,98 +12,39 @@ pub enum EncoderCapability { Amf, /// Intel QuickSync. QuickSync, - /// Software (x264). + /// x264 on the CPU. Always available. Software, } -impl EncoderCapability { - /// Get the recommended encoder preset for this capability. - pub fn recommended_preset(&self, quality: QualityLevel) -> EncoderPreset { - let bitrate = quality.recommended_bitrate(); - - match self { - EncoderCapability::Nvenc => EncoderPreset::Nvenc { - bitrate, - cq_level: 20, - two_pass: true, - }, - EncoderCapability::Amf => EncoderPreset::Amf { - bitrate, - quality: AmfQuality::Balanced, - }, - EncoderCapability::QuickSync => EncoderPreset::X264 { - preset: "veryfast".to_string(), - bitrate, - crf: None, - }, - EncoderCapability::Software => EncoderPreset::X264 { - preset: "superfast".to_string(), - bitrate: (bitrate as f32 * 0.8) as u32, - crf: Some(23), - }, - } - } - - /// Get a human-readable name for this encoder capability. - pub fn name(&self) -> &'static str { - match self { - EncoderCapability::Nvenc => "NVIDIA NVENC", - EncoderCapability::Amf => "AMD AMF", - EncoderCapability::QuickSync => "Intel QuickSync", - EncoderCapability::Software => "Software (x264)", - } - } -} - -/// Detect available hardware encoders. -/// -/// This function checks the system for available GPU encoders. +/// All encoders available on this machine. pub fn detect_hardware_encoders() -> Vec { - use tracing::info; - - info!("[ENCODER_DETECT] Starting hardware encoder detection..."); - - // Software encoding is always available= - let capabilities = vec![EncoderCapability::Software]; - - #[cfg(target_os = "linux")] - { - let _capabilities = [EncoderCapability::Software]; - } + let mut capabilities = vec![EncoderCapability::Software]; #[cfg(target_os = "windows")] { - let mut capabilities = vec![EncoderCapability::Software]; - let gpu_vendors = detect_gpu_vendors(); - - if gpu_vendors.contains(&GpuVendor::Nvidia) { - info!("[ENCODER_DETECT] NVENC available"); + let vendors = detect_gpu_vendors(); + if vendors.contains(&GpuVendor::Nvidia) { capabilities.push(EncoderCapability::Nvenc); - } else { - info!("[ENCODER_DETECT] NVENC not available"); } - - if gpu_vendors.contains(&GpuVendor::Amd) { - info!("[ENCODER_DETECT] AMF available"); + if vendors.contains(&GpuVendor::Amd) { capabilities.push(EncoderCapability::Amf); - } else { - info!("[ENCODER_DETECT] AMF not available"); } - - if gpu_vendors.contains(&GpuVendor::Intel) { - info!("[ENCODER_DETECT] QuickSync available"); + if vendors.contains(&GpuVendor::Intel) { capabilities.push(EncoderCapability::QuickSync); - } else { - info!("[ENCODER_DETECT] QuickSync not available"); } } - info!("[ENCODER_DETECT] Detected encoders: {:?}", capabilities); - capabilities } -/// GPU vendor type for encoder detection. +/// The single best encoder for recording, hardware over software. +pub fn best_available_encoder() -> EncoderCapability { + detect_hardware_encoders() + .into_iter() + .find(|cap| *cap != EncoderCapability::Software) + .unwrap_or(EncoderCapability::Software) +} + #[cfg(target_os = "windows")] #[derive(Debug, Clone, Copy, PartialEq)] enum GpuVendor { @@ -347,133 +53,60 @@ enum GpuVendor { Intel, } -/// Detect GPU vendors by querying Windows registry. -/// This is more reliable than checking for specific DLL paths. +/// Detect GPU vendors from the Windows display adapter registry keys. #[cfg(target_os = "windows")] fn detect_gpu_vendors() -> Vec { use tracing::info; use winreg::enums::HKEY_LOCAL_MACHINE; use winreg::RegKey; - let mut vendors = Vec::new(); - - // Display adapter class GUID in Windows registry const DISPLAY_ADAPTER_CLASS: &str = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"; - info!("[ENCODER_DETECT] Querying Windows registry for GPU vendors..."); + let mut vendors = Vec::new(); - // Open the display adapter class key - let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); - - let class_key = match hklm.open_subkey(DISPLAY_ADAPTER_CLASS) { + let class_key = match RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(DISPLAY_ADAPTER_CLASS) { Ok(key) => key, Err(e) => { - info!( - "[ENCODER_DETECT] Failed to open display adapter registry key: {}", - e - ); + info!("Cannot read display adapter registry key: {}", e); return vendors; } }; - // Enumerate subkeys (each subkey is a display adapter) for subkey_name in class_key.enum_keys().filter_map(|k| k.ok()) { - if let Ok(adapter_key) = class_key.open_subkey(&subkey_name) { - // Read ProviderName - if let Ok(provider) = adapter_key.get_value::("ProviderName") { - info!("[ENCODER_DETECT] Found GPU provider: {}", provider); + let adapter = match class_key.open_subkey(&subkey_name) { + Ok(a) => a, + Err(_) => continue, + }; + let provider = match adapter.get_value::("ProviderName") { + Ok(p) => p.to_lowercase(), + Err(_) => continue, + }; - let provider_lower = provider.to_lowercase(); - if provider_lower.contains("nvidia") && !vendors.contains(&GpuVendor::Nvidia) { - vendors.push(GpuVendor::Nvidia); - } else if (provider_lower.contains("amd") - || provider_lower.contains("advanced micro devices") - || provider_lower.contains("radeon")) - && !vendors.contains(&GpuVendor::Amd) - { - vendors.push(GpuVendor::Amd); - } else if provider_lower.contains("intel") && !vendors.contains(&GpuVendor::Intel) { - vendors.push(GpuVendor::Intel); - } - } + if provider.contains("nvidia") && !vendors.contains(&GpuVendor::Nvidia) { + vendors.push(GpuVendor::Nvidia); + } else if (provider.contains("amd") + || provider.contains("advanced micro devices") + || provider.contains("radeon")) + && !vendors.contains(&GpuVendor::Amd) + { + vendors.push(GpuVendor::Amd); + } else if provider.contains("intel") && !vendors.contains(&GpuVendor::Intel) { + vendors.push(GpuVendor::Intel); } } - info!("[ENCODER_DETECT] Detected GPU vendors: {:?}", vendors); + info!("GPU vendors: {:?}", vendors); vendors } -/// Get the best available encoder capability. -pub fn best_available_encoder() -> EncoderCapability { - let capabilities = detect_hardware_encoders(); - - // Prefer hardware encoders - for cap in &capabilities { - if matches!( - cap, - EncoderCapability::Nvenc | EncoderCapability::Amf | EncoderCapability::QuickSync - ) { - return *cap; - } - } - - // Fall back to software - EncoderCapability::Software -} - #[cfg(test)] mod tests { use super::*; #[test] - fn test_encoder_config_from_nvenc_preset() { - let preset = EncoderPreset::Nvenc { - bitrate: 8000, - cq_level: 20, - two_pass: true, - }; - - let config = EncoderConfig::from_preset(&preset); - - assert_eq!(config.encoder_id, "jim_nvenc"); - assert_eq!(config.bitrate, 8000); - assert!(config.is_hardware()); - assert!(config.is_nvenc()); - } - - #[test] - fn test_encoder_config_from_x264_preset() { - let preset = EncoderPreset::X264 { - preset: "fast".to_string(), - bitrate: 6000, - crf: Some(23), - }; - - let config = EncoderConfig::from_preset(&preset); - - assert_eq!(config.encoder_id, "x264"); - assert!(!config.is_hardware()); - assert!(config.is_software()); - } - - #[test] - fn test_detect_hardware_encoders() { + fn detects_at_least_software() { let capabilities = detect_hardware_encoders(); - assert!(!capabilities.is_empty()); assert!(capabilities.contains(&EncoderCapability::Software)); } - - #[test] - fn test_best_available_encoder() { - let best = best_available_encoder(); - // Should always return something - assert!(matches!( - best, - EncoderCapability::Nvenc - | EncoderCapability::Amf - | EncoderCapability::QuickSync - | EncoderCapability::Software - )); - } } diff --git a/record-daemon/src/recording/mod.rs b/record-daemon/src/recording/mod.rs index 2f86397..7f11e40 100644 --- a/record-daemon/src/recording/mod.rs +++ b/record-daemon/src/recording/mod.rs @@ -1,28 +1,23 @@ //! Recording module for video capture using libobs. -//! -//! This module provides the recording engine that captures game footage -//! and encodes it using hardware or software encoders. -mod capture; pub mod encoder; mod obs_context; mod output; -pub use capture::{CaptureMode, GameCapture, MonitorCapture, SourceType, WindowCapture}; -pub use encoder::{AudioEncoderConfig, EncoderCapability, EncoderConfig, EncoderSettings}; +pub use encoder::EncoderCapability; pub use obs_context::{ObsContext, ObsContextBuilder}; -pub use output::{OutputConfig, OutputFormat, RecordingOutput, RecordingResult, RecordingStats}; +pub use output::{RecordingOutput, RecordingResult}; use std::sync::Arc; use chrono::{DateTime, Utc}; use parking_lot::RwLock; -use tracing::{error, info, warn}; +use tracing::{info, warn}; use crate::config::Settings; use crate::error::{RecordingError, Result}; -/// Recording engine that manages the entire recording pipeline. +/// Recording engine that manages the recording pipeline. pub struct RecordingEngine { /// OBS context. context: Option, @@ -49,14 +44,11 @@ impl RecordingEngine { } /// Initialize the recording engine. - /// - /// This sets up OBS and prepares for recording. pub fn initialize(&mut self) -> Result<()> { info!("Initializing recording engine"); let settings = self.settings.read().clone(); - // Build OBS context let context = ObsContextBuilder::new() .with_video_settings(settings.video.clone()) .with_audio_settings(settings.audio.clone()) @@ -64,15 +56,13 @@ impl RecordingEngine { .build()?; self.context = Some(context); - info!("Recording engine initialized successfully"); - + info!("Recording engine initialized"); Ok(()) } /// Update settings. pub fn update_settings(&self, new_settings: Settings) -> Result<()> { - let mut settings = self.settings.write(); - *settings = new_settings; + *self.settings.write() = new_settings; Ok(()) } @@ -92,39 +82,20 @@ impl RecordingEngine { } /// Start recording. - /// - /// # Arguments - /// * `game_id` - Optional game ID for the recording. - /// * `champion` - Optional champion name for the filename. pub fn start_recording(&mut self, game_id: Option, champion: Option<&str>) -> Result<()> { - info!( - "RecordingEngine::start_recording called - game_id: {:?}, champion: {:?}", - game_id, champion - ); - if self.is_recording { - warn!("Already recording, returning error"); return Err(RecordingError::AlreadyRecording.into()); } - info!("Reading settings..."); let settings = self.settings.read().clone(); - - // Generate output filename let filename = self.generate_filename(game_id, champion); let output_path = settings.output.path.join(&filename); - info!("Starting recording to: {:?}", output_path); - - // Start the recording - let context = self.context.as_mut().ok_or_else(|| { - error!("OBS not initialized when start_recording was called"); - RecordingError::ObsInitError("OBS not initialized".to_string()) - })?; - - info!("Calling OBS context start_recording..."); + let context = self + .context + .as_mut() + .ok_or_else(|| RecordingError::ObsInitError("OBS not initialized".to_string()))?; context.start_recording(&output_path)?; - info!("OBS context start_recording returned successfully"); self.current_output = Some(RecordingOutput { path: output_path, @@ -134,7 +105,7 @@ impl RecordingEngine { self.start_time = Some(Utc::now()); self.is_recording = true; - info!("Recording started successfully"); + info!("Recording started"); Ok(()) } @@ -147,48 +118,29 @@ impl RecordingEngine { let context = self.context.as_mut().ok_or(RecordingError::ObsInitError( "OBS not initialized".to_string(), ))?; - - info!("Stopping recording"); - - // Stop the recording context.stop_recording()?; let output = self .current_output .take() .ok_or(RecordingError::StopError("No active output".to_string()))?; - let start_time = self .start_time .take() .ok_or(RecordingError::StopError("No start time".to_string()))?; let end_time = Utc::now(); - let duration = end_time - start_time; - self.is_recording = false; - let result = RecordingResult { + info!("Recording stopped: {:?}", output.path); + Ok(RecordingResult { path: output.path, game_id: output.game_id, champion: output.champion, start_time, end_time, - duration, - stats: None, // Stats would be populated from OBS context if available - }; - - info!("Recording stopped: {:?}", result.path); - Ok(result) - } - - /// Get the current recording timestamp (time since recording started). - pub fn current_timestamp(&self) -> Option { - if !self.is_recording { - return None; - } - - self.start_time.map(|start| Utc::now() - start) + duration: end_time - start_time, + }) } /// Generate a filename for the recording. diff --git a/record-daemon/src/recording/obs_context.rs b/record-daemon/src/recording/obs_context.rs index 776c418..c84fb96 100644 --- a/record-daemon/src/recording/obs_context.rs +++ b/record-daemon/src/recording/obs_context.rs @@ -1,6 +1,9 @@ -//! OBS context initialization and management. +//! OBS context lifecycle and recording sessions. //! -//! This module handles the lifecycle of the OBS library context using libobs-simple. +//! The context is created lazily on the first recording and kept alive +//! until shutdown. Every recording start builds a fresh output and a +//! fresh scene with one video source (game capture, monitor fallback) +//! plus the configured audio sources. use std::path::Path; @@ -9,17 +12,44 @@ use libobs_simple::output::simple::{ }; use libobs_simple::wrapper::data::output::ObsOutputTrait; use libobs_simple::wrapper::data::video::ObsVideoInfoBuilder; -use libobs_simple::wrapper::data::ObsObjectBuilder; use libobs_simple::wrapper::scenes::SceneItemExtSceneTrait; use libobs_simple::wrapper::utils::{ObsPath, ObsString}; use libobs_wrapper::context::ObsContext as LibObsContext; -use libobs_wrapper::utils::StartupInfo; -use tracing::{error, info, warn}; +use libobs_wrapper::data::object::ObsObjectTrait; +use libobs_wrapper::data::ObsData; +use libobs_wrapper::data::ObsObjectBuilder; +use libobs_wrapper::sources::{ObsSourceBuilder, ObsSourceRef}; +use libobs_wrapper::utils::{SourceInfo, StartupInfo}; +use serde_json::json; +use tracing::{info, warn}; use super::encoder::{best_available_encoder, EncoderCapability}; -use crate::config::{AudioSettings, VideoSettings}; +use crate::config::{AudioSettings, AudioSourceType, VideoSettings}; use crate::error::{RecordingError, Result}; +/// Run a call into native OBS code, converting a panic into an error. +/// +/// 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 { + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) { + Ok(result) => result, + Err(_) => { + Err(RecordingError::StartError(format!("panic in native code during {}", what)).into()) + } + } +} + +/// 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) { + let volume = percent.min(100) as f32 / 100.0; + unsafe { + libobs::obs_source_set_volume(source.as_ptr().get_ptr(), volume); + } +} + /// Builder for OBS context. pub struct ObsContextBuilder { video_settings: Option, @@ -28,7 +58,6 @@ pub struct ObsContextBuilder { } impl ObsContextBuilder { - /// Create a new OBS context builder. pub fn new() -> Self { Self { video_settings: None, @@ -37,25 +66,21 @@ impl ObsContextBuilder { } } - /// Set video settings. pub fn with_video_settings(mut self, settings: VideoSettings) -> Self { self.video_settings = Some(settings); self } - /// Set audio settings. pub fn with_audio_settings(mut self, settings: AudioSettings) -> Self { self.audio_settings = Some(settings); self } - /// Set output directory. pub fn with_output_dir(mut self, dir: &Path) -> Self { self.output_dir = Some(dir.to_path_buf()); self } - /// Build the OBS context. pub fn build(self) -> Result { let video_settings = self.video_settings.unwrap_or_default(); let audio_settings = self.audio_settings.unwrap_or_default(); @@ -63,24 +88,19 @@ impl ObsContextBuilder { .output_dir .unwrap_or_else(|| std::path::PathBuf::from("./recordings")); - // Ensure output directory exists if !output_dir.exists() { std::fs::create_dir_all(&output_dir) .map_err(|e| RecordingError::OutputDirError(e.to_string()))?; } - let context = ObsContext { + Ok(ObsContext { video_settings, audio_settings, - output_dir, context: None, output: None, recording: false, - current_output: None, encoder_capability: None, - }; - - Ok(context) + }) } } @@ -91,25 +111,12 @@ impl Default for ObsContextBuilder { } /// OBS context wrapper. -/// -/// This manages the OBS library lifecycle and provides access to -/// recording functionality. pub struct ObsContext { - /// Video configuration. video_settings: VideoSettings, - /// Audio configuration. audio_settings: AudioSettings, - /// Output directory for recordings. - output_dir: std::path::PathBuf, - /// The underlying libobs context. context: Option, - /// The current output. output: Option, - /// Whether currently recording. recording: bool, - /// Current output path (if recording). - current_output: Option, - /// Detected encoder capability. encoder_capability: Option, } @@ -124,47 +131,19 @@ impl ObsContext { self.recording } - /// Get the video settings. - pub fn video_settings(&self) -> &VideoSettings { - &self.video_settings - } - - /// Get the output directory for recordings. - pub fn output_dir(&self) -> &std::path::Path { - &self.output_dir - } - - /// Initialize OBS. + /// Initialize OBS. Called lazily from `start_recording`. fn initialize(&mut self) -> Result<()> { if self.context.is_some() { - info!("OBS context already initialized"); return Ok(()); } - info!("[OBS_INIT] Starting OBS context initialization..."); - - // Pre-flight checks for OBS - self.preflight_checks()?; - - // Detect best available encoder - info!("[OBS_INIT] Detecting best available encoder..."); - let encoder = best_available_encoder(); - info!("[OBS_INIT] Detected encoder: {}", encoder.name()); - self.encoder_capability = Some(encoder); + info!("OBS encoder: {:?}", encoder); let (width, height) = self.video_settings.quality.resolution(); let fps = self.video_settings.frame_rate; - info!( - "[OBS_INIT] OBS video config: {}x{} @ {}fps", - width, height, fps - ); - - // Create startup info with video configuration - info!("[OBS_INIT] Creating OBS video info builder..."); - let video_info = ObsVideoInfoBuilder::new() .fps_num(fps) .fps_den(1) @@ -173,1384 +152,313 @@ impl ObsContext { .output_width(width) .output_height(height) .build(); - info!("[OBS_INIT] OBS video info built successfully"); - info!("[OBS_INIT] Building OBS context with LibObsContext::builder()..."); - - let compat = LibObsContext::check_version_compatibility(); - if !compat { - error!("OBS version compatibility is wrong. This will not go well..."); + if !LibObsContext::check_version_compatibility() { + warn!("libobs version mismatch with wrapper, continuing anyway"); } - //FIXME: this is crashing here. - // LibObsContext::new makes the whole application crash, even with default options let info = StartupInfo::default().set_video_info(video_info); - let context_result = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| LibObsContext::new(info))); - - let context = match context_result { - Ok(Ok(ctx)) => { - info!("[OBS_INIT] OBS context created successfully"); - - ctx - } - Ok(Err(e)) => { - error!("[OBS_INIT] Failed to create OBS context: {:?}", e); - - return Err(RecordingError::ObsInitError(format!( - "Failed to create OBS context: {:?}", - e - )) - .into()); - } - Err(panic_info) => { - error!( - "[OBS_INIT] PANIC during OBS context creation: {:?}", - panic_info - ); - - eprintln!( - "[OBS_INIT] PANIC during OBS context creation: {:?}", - panic_info - ); - return Err(RecordingError::ObsInitError( - "Panic during OBS context creation".to_string(), - ) - .into()); - } - }; - - if self.audio_settings.enabled { - info!( - "[OBS_INIT] OBS audio config: {} channels @ {}Hz", - self.audio_settings.channels, self.audio_settings.sample_rate - ); - } + let context = catch_native("creating the OBS context", || { + LibObsContext::new(info).map_err(|e| { + RecordingError::ObsInitError(format!("failed to create OBS context: {:?}", e)) + .into() + }) + })?; self.context = Some(context); - info!("[OBS_INIT] OBS context initialized successfully"); - + info!( + "OBS context initialized ({}x{} @ {}fps)", + width, height, fps + ); Ok(()) } - /// Pre-flight checks for OBS initialization. - fn preflight_checks(&self) -> Result<()> { - info!("[PREFLIGHT] Running OBS pre-flight checks..."); - - // Check for OBS installation directory - // libobs-bootstrapper typically extracts OBS to a specific location - let obs_paths = self.get_obs_search_paths(); - - info!("[PREFLIGHT] OBS search paths: {:?}", obs_paths); - - let mut obs_found = false; - for path in &obs_paths { - if path.exists() { - info!("[PREFLIGHT] Found OBS at: {:?}", path); - - // Check for plugins directory - let plugins_path = path.join("obs-plugins"); - if plugins_path.exists() { - info!("[PREFLIGHT] Found OBS plugins at: {:?}", plugins_path); - - // Check for 64-bit plugins - let plugins_64 = plugins_path.join("64bit"); - if plugins_64.exists() { - info!("[PREFLIGHT] Found 64-bit plugins at: {:?}", plugins_64); - - // List available plugins - if let Ok(entries) = std::fs::read_dir(&plugins_64) { - let plugins: Vec = entries - .filter_map(|e| e.ok()) - .filter_map(|e| e.file_name().to_str().map(|s| s.to_string())) - .collect(); - info!("[PREFLIGHT] Available plugins: {:?}", plugins); - } - } - } - - obs_found = true; - break; - } - } - - if !obs_found { - warn!( - "[PREFLIGHT] OBS installation not found in standard paths - this may cause issues" - ); - } - - // Check for display (required for capture) - #[cfg(target_os = "windows")] - { - info!("[PREFLIGHT] Checking for display availability..."); - - // On Windows, check if we have a display - use std::ptr; - unsafe { - let dc = winapi::um::winuser::GetDC(ptr::null_mut()); - if dc.is_null() { - warn!("[PREFLIGHT] No display context available - capture may fail"); - } else { - info!("[PREFLIGHT] Display context available"); - winapi::um::winuser::ReleaseDC(ptr::null_mut(), dc); - } - } - } - - info!("[PREFLIGHT] Pre-flight checks completed"); - - Ok(()) - } - - /// Get OBS search paths based on platform. - fn get_obs_search_paths(&self) -> Vec { - let mut paths = Vec::new(); - - // Current directory - paths.push(std::env::current_dir().unwrap_or_default().join("obs")); - - // libobs-bootstrapper default locations - #[cfg(target_os = "windows")] - { - // Check AppData - if let Some(app_data) = std::env::var_os("LOCALAPPDATA") { - paths.push(std::path::PathBuf::from(app_data).join("obs-studio")); - } - if let Some(app_data) = std::env::var_os("APPDATA") { - paths.push(std::path::PathBuf::from(app_data).join("obs-studio")); - } - // Program Files - paths.push(std::path::PathBuf::from("C:\\Program Files\\obs-studio")); - paths.push(std::path::PathBuf::from( - "C:\\Program Files (x86)\\obs-studio", - )); - } - - #[cfg(target_os = "linux")] - { - paths.push(std::path::PathBuf::from("/usr/share/obs")); - paths.push(std::path::PathBuf::from("/usr/local/share/obs")); - if let Some(home) = std::env::var_os("HOME") { - paths.push(std::path::PathBuf::from(home).join(".local/share/obs")); - } - } - - paths - } - /// Start recording to the specified output path. pub fn start_recording(&mut self, output_path: &Path) -> Result<()> { - info!( - "[START_REC] start_recording called with path: {:?}", - output_path - ); - if self.recording { - warn!("[START_REC] Already recording, returning error"); return Err(RecordingError::AlreadyRecording.into()); } if self.context.is_none() { - info!("[START_REC] OBS context not initialized, initializing now..."); - self.initialize()?; - info!("[START_REC] OBS initialization complete"); } + let context = self + .context + .as_ref() + .ok_or_else(|| RecordingError::ObsInitError("OBS not initialized".to_string()))?; - let context = self.context.as_ref().ok_or_else(|| { - error!("[START_REC] OBS not initialized after initialize()"); - - RecordingError::ObsInitError("OBS not initialized".to_string()) - })?; - - info!("[START_REC] Starting OBS recording to: {:?}", output_path); - - // Get bitrate from encoder preset - let bitrate = self.video_settings.encoder_preset.effective_bitrate(); - info!("[START_REC] Using bitrate: {} kbps", bitrate); - - // Create output path - let path_str = output_path.to_string_lossy(); - let obs_path = ObsPath::new(&path_str); - - // Get detected encoder capability + // Build the output around the best available encoder. let encoder = self .encoder_capability .unwrap_or_else(best_available_encoder); - info!("[START_REC] Using encoder: {}", encoder.name()); + let bitrate = self.video_settings.encoder_preset.effective_bitrate(); + let obs_path = ObsPath::new(&output_path.to_string_lossy()); - // Build the output based on encoder capability - info!("[START_REC] Creating SimpleOutputBuilder..."); - - let output_result = match encoder { + let mut builder = + SimpleOutputBuilder::new(context.clone(), ObsString::from("output"), obs_path) + .video_bitrate(bitrate) + .audio_bitrate(self.audio_settings.bitrate) + .format(OutputFormat::Mpeg4); + builder = match encoder { EncoderCapability::Nvenc => { - info!("Building NVENC output..."); - SimpleOutputBuilder::new(context.clone(), ObsString::from("output"), obs_path) - .video_bitrate(bitrate) - .audio_bitrate(self.audio_settings.bitrate) - .hardware_encoder(HardwareCodec::H264, HardwarePreset::Speed) - .format(OutputFormat::Mpeg4) - .build() + builder.hardware_encoder(HardwareCodec::H264, HardwarePreset::Speed) } - EncoderCapability::Amf => { - info!("Building AMF output..."); - SimpleOutputBuilder::new(context.clone(), ObsString::from("output"), obs_path) - .video_bitrate(bitrate) - .audio_bitrate(self.audio_settings.bitrate) - .hardware_encoder(HardwareCodec::H264, HardwarePreset::Balanced) - .format(OutputFormat::Mpeg4) - .build() - } - EncoderCapability::QuickSync => { - info!("Building QuickSync output..."); - SimpleOutputBuilder::new(context.clone(), ObsString::from("output"), obs_path) - .video_bitrate(bitrate) - .audio_bitrate(self.audio_settings.bitrate) - .hardware_encoder(HardwareCodec::H264, HardwarePreset::Balanced) - .format(OutputFormat::Mpeg4) - .build() - } - EncoderCapability::Software => { - info!("Building software (x264) output..."); - SimpleOutputBuilder::new(context.clone(), ObsString::from("output"), obs_path) - .video_bitrate(bitrate) - .audio_bitrate(self.audio_settings.bitrate) - .format(OutputFormat::Mpeg4) - .build() + EncoderCapability::Amf | EncoderCapability::QuickSync => { + builder.hardware_encoder(HardwareCodec::H264, HardwarePreset::Balanced) } + EncoderCapability::Software => builder, }; - info!("[START_REC] Output build complete, checking for errors..."); + let output = builder + .build() + .map_err(|e| RecordingError::StartError(format!("failed to build output: {:?}", e)))?; - let output = output_result.map_err(|e| { - error!("[START_REC] Failed to create 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)?; - RecordingError::StartError(format!("Failed to create output: {:?}", e)) + catch_native("starting the output", || { + output.start().map_err(|e| { + RecordingError::StartError(format!("failed to start output: {:?}", e)).into() + }) })?; - info!("[START_REC] Output created successfully, setting up game capture..."); - - // Set up game capture source - self.setup_game_capture()?; - - // Set up audio capture source - if self.audio_settings.enabled && self.audio_settings.capture_game { - info!("[START_REC] Setting up audio capture..."); - self.setup_audio_capture()?; - info!("[START_REC] Audio capture set up successfully"); - } - - info!("[START_REC] Game capture set up, starting output..."); - - // Start the output - wrap in catch_unwind as this may crash in native code - let start_result = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| output.start())); - - match start_result { - Ok(Ok(())) => { - info!("[START_REC] Output started successfully"); - } - Ok(Err(e)) => { - error!("[START_REC] Failed to start output: {:?}", e); - - return Err( - RecordingError::StartError(format!("Failed to start output: {:?}", e)).into(), - ); - } - Err(panic_info) => { - error!("[START_REC] PANIC starting output: {:?}", panic_info); - - eprintln!("[START_REC] PANIC starting output: {:?}", panic_info); - return Err(RecordingError::StartError("Panic starting output".to_string()).into()); - } - } - self.output = Some(output); - self.current_output = Some(output_path.to_path_buf()); self.recording = true; - - info!("[START_REC] OBS recording started successfully"); - + info!("recording started: {}", output_path.display()); Ok(()) } - /// Set up capture source with fallback from game capture to monitor capture. - #[cfg(target_os = "windows")] - fn setup_game_capture(&mut self) -> Result<()> { - info!("[CAPTURE] Setting up capture source..."); - - // Try game capture first, fall back to monitor capture - match self.try_game_capture() { - Ok(()) => { - info!("[CAPTURE] Game capture set up successfully"); - - Ok(()) - } - Err(e) => { - warn!( - "[CAPTURE] Game capture failed: {}, falling back to monitor capture", - e - ); - - self.setup_monitor_capture() - } - } - } - - /// Set up capture source on Linux using screen capture. - #[cfg(target_os = "linux")] - fn setup_game_capture(&mut self) -> Result<()> { - info!("[CAPTURE] Setting up screen capture for Linux..."); - - self.setup_linux_screen_capture() - } - - /// Try to set up game capture source (Windows only). - #[cfg(target_os = "windows")] - fn try_game_capture(&mut self) -> Result<()> { - use libobs_simple::sources::windows::{GameCaptureSourceBuilder, ObsGameCaptureMode}; - use libobs_simple::sources::ObsSourceBuilder; - - info!("[GAME_CAPTURE] Attempting game capture setup..."); - - let context = self.context.as_mut().ok_or_else(|| { - error!("[GAME_CAPTURE] OBS not initialized in setup_game_capture"); - - RecordingError::ObsInitError("OBS not initialized".to_string()) - })?; - - // Create a scene - info!("[GAME_CAPTURE] Creating scene 'main'..."); - - let mut scene = context.scene("main", None).map_err(|e| { - error!("[GAME_CAPTURE] Failed to create scene: {:?}", e); - - RecordingError::StartError(format!("Failed to create scene: {:?}", e)) - })?; - info!("[GAME_CAPTURE] Scene created successfully"); - - // Build game capture source - info!("[GAME_CAPTURE] Getting OBS runtime..."); - - let runtime = context.runtime(); - - info!("[GAME_CAPTURE] Creating game capture source builder..."); - - // Wrap game capture builder in catch_unwind as it may crash in native code - let builder_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - GameCaptureSourceBuilder::new("game_capture", runtime.clone()) - })); - - let builder = match builder_result { - Ok(Ok(b)) => { - info!("[GAME_CAPTURE] Game capture builder created"); - - b - } - Ok(Err(e)) => { - error!( - "[GAME_CAPTURE] Failed to create game capture builder: {:?}", - e - ); - - return Err(RecordingError::StartError(format!( - "Failed to create game capture builder: {:?}", - e - )) - .into()); - } - Err(panic_info) => { - error!( - "[GAME_CAPTURE] PANIC creating game capture builder: {:?}", - panic_info - ); - - eprintln!( - "[GAME_CAPTURE] PANIC creating game capture builder: {:?}", - panic_info - ); - return Err(RecordingError::StartError( - "Panic creating game capture builder".to_string(), - ) - .into()); - } - }; - - info!("[GAME_CAPTURE] Configuring game capture for League of Legends..."); - - // Use "Any" mode to capture any fullscreen application - // This is the most reliable mode for games like League of Legends - info!("[GAME_CAPTURE] Using 'Any' mode to capture fullscreen games..."); - - // Wrap source build in catch_unwind - // Enable capture_audio so the game capture source automatically creates - // an "Application Audio Capture" (WASAPI) source for the captured game. - let source_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - builder - .set_capture_mode(ObsGameCaptureMode::Any) - .set_capture_audio(true) - .expect("[GAME_CAPTURE] Audio capture not available on this system") - .build() - })); - - let source = match source_result { - Ok(Ok(s)) => { - info!("[GAME_CAPTURE] Game capture source created"); - - s - } - Ok(Err(e)) => { - error!( - "[GAME_CAPTURE] Failed to create game capture source: {:?}", - e - ); - - return Err(RecordingError::StartError(format!( - "Failed to create game capture source: {:?}", - e - )) - .into()); - } - Err(panic_info) => { - error!( - "[GAME_CAPTURE] PANIC creating game capture source: {:?}", - panic_info - ); - - eprintln!( - "[GAME_CAPTURE] PANIC creating game capture source: {:?}", - panic_info - ); - return Err(RecordingError::StartError( - "Panic creating game capture source".to_string(), - ) - .into()); - } - }; - - // Add source to scene using add_source - info!("[GAME_CAPTURE] Adding source to scene..."); - - scene.add_source(source).map_err(|e| { - error!("[GAME_CAPTURE] Failed to add source to scene: {:?}", e); - - RecordingError::StartError(format!("Failed to add source to scene: {:?}", e)) - })?; - info!("[GAME_CAPTURE] Source added to scene"); - - // Set the scene as active - info!("[GAME_CAPTURE] Setting scene as active on channel 0..."); - - scene.set_to_channel(0).map_err(|e| { - error!("[GAME_CAPTURE] Failed to set scene: {:?}", e); - RecordingError::StartError(format!("Failed to set scene: {:?}", e)) - })?; - - info!("[GAME_CAPTURE] Game capture source configured successfully"); - - Ok(()) - } - - /// Set up monitor capture as fallback (Windows only). - #[cfg(target_os = "windows")] - fn setup_monitor_capture(&mut self) -> Result<()> { - use libobs_simple::sources::windows::MonitorCaptureSourceBuilder; - use libobs_simple::sources::ObsSourceBuilder; - - info!("[MONITOR_CAPTURE] Setting up monitor capture as fallback..."); - - let context = self.context.as_mut().ok_or_else(|| { - error!("[MONITOR_CAPTURE] OBS not initialized"); - - RecordingError::ObsInitError("OBS not initialized".to_string()) - })?; - - // Create a scene - info!("[MONITOR_CAPTURE] Creating scene 'main'..."); - - let mut scene = context.scene("main", None).map_err(|e| { - error!("[MONITOR_CAPTURE] Failed to create scene: {:?}", e); - - RecordingError::StartError(format!("Failed to create scene: {:?}", e)) - })?; - info!("[MONITOR_CAPTURE] Scene created successfully"); - - // Get monitor info - info!("[MONITOR_CAPTURE] Detecting monitors..."); - - let monitors = display_info::DisplayInfo::all().map_err(|e| { - error!("[MONITOR_CAPTURE] Failed to get display info: {:?}", e); - - RecordingError::StartError(format!("Failed to get display info: {:?}", e)) - })?; - - if monitors.is_empty() { - error!("[MONITOR_CAPTURE] No monitors detected"); - - return Err(RecordingError::StartError("No monitors detected".to_string()).into()); - } - - // Use the primary monitor (first in the list) - let primary_monitor = &monitors[0]; - info!( - "[MONITOR_CAPTURE] Using monitor: {}x{} at ({}, {})", - primary_monitor.width, primary_monitor.height, primary_monitor.x, primary_monitor.y - ); - - // Build monitor capture source - info!("[MONITOR_CAPTURE] Creating monitor capture source builder..."); - - let builder_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - MonitorCaptureSourceBuilder::new("monitor_capture", context.runtime().clone()) - })); - - let builder = match builder_result { - Ok(Ok(b)) => { - info!("[MONITOR_CAPTURE] Monitor capture builder created"); - - b - } - Ok(Err(e)) => { - error!( - "[MONITOR_CAPTURE] Failed to create monitor capture builder: {:?}", - e - ); - - return Err(RecordingError::StartError(format!( - "Failed to create monitor capture builder: {:?}", - e - )) - .into()); - } - Err(panic_info) => { - error!( - "[MONITOR_CAPTURE] PANIC creating monitor capture builder: {:?}", - panic_info - ); - - eprintln!( - "[MONITOR_CAPTURE] PANIC creating monitor capture builder: {:?}", - panic_info - ); - return Err(RecordingError::StartError( - "Panic creating monitor capture builder".to_string(), - ) - .into()); - } - }; - - // Build the source - let source_result = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| builder.build())); - - let source = match source_result { - Ok(Ok(s)) => { - info!("[MONITOR_CAPTURE] Monitor capture source created"); - - s - } - Ok(Err(e)) => { - error!( - "[MONITOR_CAPTURE] Failed to create monitor capture source: {:?}", - e - ); - - return Err(RecordingError::StartError(format!( - "Failed to create monitor capture source: {:?}", - e - )) - .into()); - } - Err(panic_info) => { - error!( - "[MONITOR_CAPTURE] PANIC creating monitor capture source: {:?}", - panic_info - ); - - eprintln!( - "[MONITOR_CAPTURE] PANIC creating monitor capture source: {:?}", - panic_info - ); - return Err(RecordingError::StartError( - "Panic creating monitor capture source".to_string(), - ) - .into()); - } - }; - - // Add source to scene - info!("[MONITOR_CAPTURE] Adding source to scene..."); - - scene.add_source(source).map_err(|e| { - error!("[MONITOR_CAPTURE] Failed to add source to scene: {:?}", e); - - RecordingError::StartError(format!("Failed to add source to scene: {:?}", e)) - })?; - info!("[MONITOR_CAPTURE] Source added to scene"); - - // Set the scene as active - info!("[MONITOR_CAPTURE] Setting scene as active on channel 0..."); - - scene.set_to_channel(0).map_err(|e| { - error!("[MONITOR_CAPTURE] Failed to set scene: {:?}", e); - RecordingError::StartError(format!("Failed to set scene: {:?}", e)) - })?; - - info!("[MONITOR_CAPTURE] Monitor capture source configured successfully"); - - Ok(()) - } - - /// Set up screen capture on Linux using X11 or PipeWire. - #[cfg(target_os = "linux")] - fn setup_linux_screen_capture(&mut self) -> Result<()> { - use libobs_simple::sources::linux::LinuxGeneralScreenCaptureBuilder; - use libobs_simple::sources::ObsSourceBuilder; - - info!("[LINUX_CAPTURE] Setting up Linux screen capture..."); - - let context = self.context.as_mut().ok_or_else(|| { - error!("[LINUX_CAPTURE] OBS not initialized"); - - RecordingError::ObsInitError("OBS not initialized".to_string()) - })?; - - // Create a scene - info!("[LINUX_CAPTURE] Creating scene 'main'..."); - - let mut scene = context.scene("main", None).map_err(|e| { - error!("[LINUX_CAPTURE] Failed to create scene: {:?}", e); - - RecordingError::StartError(format!("Failed to create scene: {:?}", e)) - })?; - info!("[LINUX_CAPTURE] Scene created successfully"); - - // Build screen capture source using LinuxGeneralScreenCaptureBuilder - // This automatically uses X11 or PipeWire depending on the platform - info!("[LINUX_CAPTURE] Creating screen capture source builder..."); - - let builder_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - LinuxGeneralScreenCaptureBuilder::new("screen_capture", context.runtime().clone()) - })); - - let builder = match builder_result { - Ok(Ok(b)) => { - info!("[LINUX_CAPTURE] Screen capture builder created"); - - b - } - Ok(Err(e)) => { - error!( - "[LINUX_CAPTURE] Failed to create screen capture builder: {:?}", - e - ); - - return Err(RecordingError::StartError(format!( - "Failed to create screen capture builder: {:?}", - e - )) - .into()); - } - Err(panic_info) => { - error!( - "[LINUX_CAPTURE] PANIC creating screen capture builder: {:?}", - panic_info - ); - - eprintln!( - "[LINUX_CAPTURE] PANIC creating screen capture builder: {:?}", - panic_info - ); - return Err(RecordingError::StartError( - "Panic creating screen capture builder".to_string(), - ) - .into()); - } - }; - - // Build the source - let source_result = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| builder.build())); - - let source = match source_result { - Ok(Ok(s)) => { - info!("[LINUX_CAPTURE] Screen capture source created"); - - s - } - Ok(Err(e)) => { - error!( - "[LINUX_CAPTURE] Failed to create screen capture source: {:?}", - e - ); - - return Err(RecordingError::StartError(format!( - "Failed to create screen capture source: {:?}", - e - )) - .into()); - } - Err(panic_info) => { - error!( - "[LINUX_CAPTURE] PANIC creating screen capture source: {:?}", - panic_info - ); - - eprintln!( - "[LINUX_CAPTURE] PANIC creating screen capture source: {:?}", - panic_info - ); - return Err(RecordingError::StartError( - "Panic creating screen capture source".to_string(), - ) - .into()); - } - }; - - // Add source to scene - info!("[LINUX_CAPTURE] Adding source to scene..."); - - scene.add_source(source).map_err(|e| { - error!("[LINUX_CAPTURE] Failed to add source to scene: {:?}", e); - - RecordingError::StartError(format!("Failed to add source to scene: {:?}", e)) - })?; - info!("[LINUX_CAPTURE] Source added to scene"); - - // Set the scene as active - info!("[LINUX_CAPTURE] Setting scene as active on channel 0..."); - - scene.set_to_channel(0).map_err(|e| { - error!("[LINUX_CAPTURE] Failed to set scene: {:?}", e); - RecordingError::StartError(format!("Failed to set scene: {:?}", e)) - })?; - - info!("[LINUX_CAPTURE] Screen capture source configured successfully"); - - Ok(()) - } - - /// 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 game audio capture..."); - - let context = self.context.as_mut().ok_or_else(|| { - error!("[AUDIO_CAPTURE] OBS not initialized"); - RecordingError::ObsInitError("OBS not initialized".to_string()) - })?; - - // Create audio source settings using JSON for reliable string handling - let settings_json = r#"{ - "executable": "League of Legends.exe", - "title": "League of Legends (TM) Client", - "class": "RiotWindowClass", - "priority": 2 - }"#; - - let audio_settings_data = ObsData::from_json(settings_json, context.runtime().clone()) - .map_err(|e| { - error!( - "[AUDIO_CAPTURE] Failed to create game audio settings from JSON: {:?}", - e - ); - RecordingError::StartError(format!( - "Failed to create game audio settings from JSON: {:?}", - e - )) - })?; - - info!("[AUDIO_CAPTURE] Game audio settings configured for League of Legends"); - - // Configure WASAPI process output capture for game audio - let source_info = SourceInfo::new( - "wasapi_process_output_capture", - "game_audio", - Some(audio_settings_data), - None, - ); - - 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, runtime) - })); - - 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 game audio source: {:?}", e); - return Err(RecordingError::StartError(format!( - "Failed to create game audio source: {:?}", - e - )) - .into()); - } - Err(panic_info) => { - error!( - "[AUDIO_CAPTURE] PANIC creating game audio source: {:?}", - panic_info - ); - 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 - ); - 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 - ) - } - }; - - 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(()) - } - - /// 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..."); - - let context = self.context.as_mut().ok_or_else(|| { - error!("[AUDIO_CAPTURE] OBS not initialized"); - 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); - RecordingError::StartError(format!("Failed to create audio settings: {:?}", e)) - })?; - - // Configure PulseAudio capture for game audio on Linux - let source_info = SourceInfo::new( - "pulse_input_capture", - "game_audio", - Some(audio_settings_data), - None, - ); - - 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( - source_info, - context.runtime().clone(), - ) - })); - - match audio_source_result { - Ok(Ok(_s)) => { - info!("[AUDIO_CAPTURE] PulseAudio game audio source created"); - } - Ok(Err(e)) => { - error!("[AUDIO_CAPTURE] Failed to create game audio source: {:?}", e); - return Err(RecordingError::StartError(format!( - "Failed to create game audio source: {:?}", - e - )) - .into()); - } - Err(panic_info) => { - error!( - "[AUDIO_CAPTURE] PANIC creating game audio source: {:?}", - panic_info - ); - 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) - }; - - 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(()) - } - - /// Stop recording. + /// Stop the active recording. pub fn stop_recording(&mut self) -> Result<()> { if !self.recording { return Err(RecordingError::NotRecording.into()); } - info!("Stopping OBS recording"); - if let Some(mut output) = self.output.take() { output.stop().map_err(|e| { - RecordingError::StopError(format!("Failed to stop output: {:?}", e)) + RecordingError::StopError(format!("failed to stop output: {:?}", e)) })?; } self.recording = false; - self.current_output = None; - - info!("OBS recording stopped successfully"); + info!("recording stopped"); Ok(()) } - - /// Shutdown OBS. + /// Shut down OBS. The libobs context cleans up on drop. pub fn shutdown(&mut self) -> Result<()> { if self.recording { self.stop_recording()?; } - - if self.output.is_some() { - self.output = None; - } - - if self.context.is_some() { - info!("Shutting down OBS context"); - // The LibObsContext handles cleanup on drop - self.context = None; - } - + self.output = None; + self.context = None; Ok(()) } } impl Drop for ObsContext { fn drop(&mut self) { - if let Err(e) = self.shutdown() { - warn!("Error shutting down OBS context: {}", e); + let _ = self.shutdown(); + } +} + +/// 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( + 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() + }) } } } -#[cfg(test)] -mod tests { - use super::*; +/// 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; - #[test] - fn test_obs_context_builder() { - let context = ObsContextBuilder::new() - .with_video_settings(VideoSettings::default()) - .with_audio_settings(AudioSettings::default()) + 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() - .unwrap(); + .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))) +} - assert!(!context.is_initialized()); - assert!(!context.is_recording()); +/// 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> { + 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); + let runtime = context.runtime().clone(); + + let source = catch_native(&format!("creating audio source {}", name), || { + ObsSourceRef::new_from_info(info, runtime).map_err(|e| { + RecordingError::StartError(format!("audio source {}: {:?}", name, e)).into() + }) + }) + .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)) +} + +/// 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( + context: &LibObsContext, + scene: &mut libobs_wrapper::scenes::ObsSceneRef, + audio: &AudioSettings, +) -> Result<()> { + #[cfg(target_os = "windows")] + let (game_plugin, mic_plugin, out_plugin) = ( + "wasapi_process_output_capture", + "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", + ); + + // 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!({ + "executable": "League of Legends.exe", + "title": "League of Legends (TM) Client", + "class": "RiotWindowClass", + "priority": 2 + }), + audio.game_volume, + ) + .map_err(|e| RecordingError::StartError(format!("game audio: {}", e)))?; } + + // Microphone. + if audio.capture_mic { + add_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)))?; + } + + // 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!({ "executable": app.device, "priority": 2 }), + ), + 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( + context, + scene, + plugin, + &format!("app_{}", app.id), + settings, + volume, + ) { + warn!("audio source '{}' unavailable: {}", app.name, e); + } + } + + Ok(()) } diff --git a/record-daemon/src/recording/output.rs b/record-daemon/src/recording/output.rs index 02fc4da..e00168c 100644 --- a/record-daemon/src/recording/output.rs +++ b/record-daemon/src/recording/output.rs @@ -1,38 +1,11 @@ -//! Recording output configuration and results. +//! Recording output files and results. use std::path::PathBuf; use chrono::{DateTime, Duration, Utc}; use serde::{Deserialize, Serialize}; -/// Output configuration for recordings. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct OutputConfig { - /// Output container format. - pub container: String, - /// Output file path pattern. - pub path_pattern: String, - /// Maximum file size before splitting (MB). 0 = no limit. - pub max_size_mb: u32, - /// Maximum duration before splitting (seconds). 0 = no limit. - pub max_duration_secs: u32, - /// Whether to use fragmented MP4 for better crash recovery. - pub fragmented: bool, -} - -impl Default for OutputConfig { - fn default() -> Self { - Self { - container: "mp4".to_string(), - path_pattern: "{date}_{time}".to_string(), - max_size_mb: 0, - max_duration_secs: 0, - fragmented: false, - } - } -} - -/// Recording output handle. +/// An active recording output. #[derive(Debug, Clone)] pub struct RecordingOutput { /// Output file path. @@ -57,176 +30,12 @@ pub struct RecordingResult { /// Recording end time. pub end_time: DateTime, /// Recording duration. - // #[serde(with = "chrono::serde::seconds")] pub duration: Duration, - /// Recording statistics (if available). - #[serde(skip_serializing_if = "Option::is_none")] - pub stats: Option, } impl RecordingResult { - /// Get the file size in bytes. + /// Get the file size in bytes, if the file still exists. pub fn file_size(&self) -> Option { std::fs::metadata(&self.path).ok().map(|m| m.len()) } - - /// Get the file size in a human-readable format. - pub fn file_size_human(&self) -> String { - let bytes = self.file_size().unwrap_or(0); - let mb = bytes as f64 / (1024.0 * 1024.0); - format!("{:.2} MB", mb) - } - - /// Get the duration in a human-readable format. - pub fn duration_human(&self) -> String { - let total_secs = self.duration.num_seconds(); - let hours = total_secs / 3600; - let mins = (total_secs % 3600) / 60; - let secs = total_secs % 60; - - if hours > 0 { - format!("{}h {}m {}s", hours, mins, secs) - } else if mins > 0 { - format!("{}m {}s", mins, secs) - } else { - format!("{}s", secs) - } - } - - /// Check if the recording file exists. - pub fn exists(&self) -> bool { - self.path.exists() - } - - /// Delete the recording file. - pub fn delete(&self) -> std::io::Result<()> { - std::fs::remove_file(&self.path) - } -} - -/// Output format type. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum OutputFormat { - /// MP4 container. - Mp4, - /// MKV container. - Mkv, - /// MOV container. - Mov, - /// FLV container. - Flv, -} - -impl OutputFormat { - /// Get the file extension. - pub fn extension(&self) -> &'static str { - match self { - OutputFormat::Mp4 => "mp4", - OutputFormat::Mkv => "mkv", - OutputFormat::Mov => "mov", - OutputFormat::Flv => "flv", - } - } - - /// Get the OBS output ID. - pub fn obs_output_id(&self) -> &'static str { - match self { - OutputFormat::Mp4 => "ffmpeg_muxer", - OutputFormat::Mkv => "ffmpeg_muxer", - OutputFormat::Mov => "ffmpeg_muxer", - OutputFormat::Flv => "ffmpeg_muxer", - } - } - - /// Get the FFmpeg format name. - pub fn ffmpeg_format(&self) -> &'static str { - match self { - OutputFormat::Mp4 => "mp4", - OutputFormat::Mkv => "matroska", - OutputFormat::Mov => "mov", - OutputFormat::Flv => "flv", - } - } -} - -impl From<&str> for OutputFormat { - fn from(s: &str) -> Self { - match s.to_lowercase().as_str() { - "mp4" => OutputFormat::Mp4, - "mkv" => OutputFormat::Mkv, - "mov" => OutputFormat::Mov, - "flv" => OutputFormat::Flv, - _ => OutputFormat::Mp4, - } - } -} - -/// Recording statistics. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct RecordingStats { - /// Total frames recorded. - pub frames_recorded: u64, - /// Frames dropped due to encoding lag. - pub frames_dropped: u64, - /// Average frame time in milliseconds. - pub avg_frame_time_ms: f64, - /// Current bitrate in kbps. - pub current_bitrate: u32, - /// Recording duration in seconds. - pub duration_secs: f64, -} - -impl RecordingStats { - /// Calculate the drop rate percentage. - pub fn drop_rate(&self) -> f64 { - if self.frames_recorded == 0 { - return 0.0; - } - (self.frames_dropped as f64 / self.frames_recorded as f64) * 100.0 - } - - /// Check if the recording is healthy (low drop rate). - pub fn is_healthy(&self) -> bool { - self.drop_rate() < 5.0 // Less than 5% dropped frames - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_output_format_from_str() { - assert_eq!(OutputFormat::from("mp4"), OutputFormat::Mp4); - assert_eq!(OutputFormat::from("MKV"), OutputFormat::Mkv); - assert_eq!(OutputFormat::from("unknown"), OutputFormat::Mp4); - } - - #[test] - fn test_recording_result_duration_human() { - let result = RecordingResult { - path: PathBuf::from("/tmp/test.mp4"), - game_id: Some(12345), - champion: Some("Ahri".to_string()), - start_time: Utc::now(), - end_time: Utc::now() + Duration::seconds(125), - duration: Duration::seconds(125), - stats: None, - }; - - assert_eq!(result.duration_human(), "2m 5s"); - } - - #[test] - fn test_recording_stats_drop_rate() { - let stats = RecordingStats { - frames_recorded: 1000, - frames_dropped: 40, - ..Default::default() - }; - - assert_eq!(stats.drop_rate(), 4.0); - assert!(stats.is_healthy()); - } } diff --git a/record-daemon/src/timeline/store.rs b/record-daemon/src/timeline/store.rs index 7a456f4..ca1d31c 100644 --- a/record-daemon/src/timeline/store.rs +++ b/record-daemon/src/timeline/store.rs @@ -475,7 +475,6 @@ mod tests { start_time: Utc::now(), end_time: Utc::now() + Duration::seconds(60), duration: Duration::seconds(60), - stats: None, }; let id = store.add_recording(result).unwrap();