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
This commit is contained in:
vhaudiquet committed 2026-11-13 00:06:16 +01:00
1 parent 4f9f84446d
commit 2e98159083
15 files changed
+457 -2662

No files matched your search

+1
View File
@@ -2398,6 +2398,7 @@ dependencies = [
"directories",
"display-info",
"futures",
"libobs",
"libobs-bootstrapper",
"libobs-simple",
"libobs-wrapper",
+1
View File
@@ -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" }
+2 -10
View File
@@ -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")
}
}
-7
View File
@@ -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 {
+60 -151
View File
@@ -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<serde_json::Value>) -> Result<serde_json::Value>;
}
/// 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<serde_json::Value> {
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<serde_json::Value> {
let recording = self.timeline.read().get_recording(id)?;
Ok(serde_json::to_value(recording)?)
}
async fn handle_delete_recording(&self, id: uuid::Uuid) -> Result<serde_json::Value> {
self.timeline.write().delete_recording(id)?;
Ok(serde_json::json!({ "success": true }))
}
async fn handle_get_timeline(&self, recording_id: uuid::Uuid) -> Result<serde_json::Value> {
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<serde_json::Value> {
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<serde_json::Value> {
info!("Shutdown requested via IPC");
// Signal shutdown through status
@@ -326,38 +230,13 @@ impl IpcHandlers {
async fn handle_get_audio_devices(&self) -> Result<serde_json::Value> {
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<super::protocol::AudioDeviceInfo>, Vec<super::protocol::AudioDeviceInfo>)> {
fn enumerate_windows_audio_devices() -> Result<(
Vec<super::protocol::AudioDeviceInfo>,
Vec<super::protocol::AudioDeviceInfo>,
)> {
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<super::protocol::AudioDeviceInfo>, Vec<super::protocol::AudioDeviceInfo>),
fn enumerate_windows_audio_devices_inner() -> std::result::Result<
(
Vec<super::protocol::AudioDeviceInfo>,
Vec<super::protocol::AudioDeviceInfo>,
),
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<String> = 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<String> {
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<super::protocol::AudioDeviceInfo>, Vec<super::protocol::AudioDeviceInfo>)> {
fn enumerate_linux_audio_devices() -> Result<(
Vec<super::protocol::AudioDeviceInfo>,
Vec<super::protocol::AudioDeviceInfo>,
)> {
use super::protocol::AudioDeviceInfo;
use tracing::warn;
+1 -1
View File
@@ -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};
+1 -32
View File
@@ -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<RecordingMetadata>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetEncodersResponse {
pub available: Vec<EncoderInfo>,
+5 -40
View File
@@ -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(())
+44 -142
View File
@@ -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);
-238
View File
@@ -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<String>,
/// Process name to capture.
pub process_name: Option<String>,
/// Capture mode.
pub mode: CaptureMode,
/// Whether to capture cursor.
pub capture_cursor: bool,
/// Window class (Windows only).
pub window_class: Option<String>,
}
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<String> {
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<String>,
/// 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"));
}
}
+43 -410
View File
@@ -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<u32>,
/// 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<libobs_simple::output::simple::HardwareCodec> {
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<EncoderCapability> {
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<GpuVendor> {
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::<String, _>("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::<String, _>("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
));
}
}
+15 -63
View File
@@ -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<ObsContext>,
@@ -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<u64>, 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<chrono::Duration> {
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.
File diff suppressed because it is too large. Load diff
+3 -194
View File
@@ -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<Utc>,
/// Recording duration.
// #[serde(with = "chrono::serde::seconds")]
pub duration: Duration,
/// Recording statistics (if available).
#[serde(skip_serializing_if = "Option::is_none")]
pub stats: Option<RecordingStats>,
}
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<u64> {
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());
}
}
-1
View File
@@ -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();