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

-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());
}
}