Files
leaguerecorder/record-daemon/src/recording/mod.rs
T
vhaudiquet 365e4ad732 record-daemon: keep app audio attached across recordings
OBS starts with the daemon and builds one scene, and every recording reuses it.
The process captures that used to be created per recording stay in that scene, so
a game or Discord window that disappears mid-session keeps feeding the mix.

The captures come from a watcher that scans for a window every two seconds: a
process with no window cannot be opened, so each source waits for its app to show
one, and a new window means the process restarted and needs a fresh source.

Settings now travel to the engine, and an audio change swaps only the device
captures. Applying them used to clear the scene, which took the process captures
with it.
2026-11-16 23:26:31 +01:00

220 lines
6.4 KiB
Rust

//! Recording module for video capture using libobs.
pub mod encoder;
mod obs_context;
mod output;
mod process_audio;
pub use encoder::EncoderCapability;
pub use obs_context::{ObsContext, ObsContextBuilder};
pub use output::{RecordingOutput, RecordingResult};
use std::sync::Arc;
use chrono::{DateTime, Utc};
use parking_lot::RwLock;
use tracing::{info, warn};
use crate::config::Settings;
use crate::error::{RecordingError, Result};
/// Recording engine that manages the recording pipeline.
pub struct RecordingEngine {
/// OBS context.
context: Option<ObsContext>,
/// Current settings.
settings: Arc<RwLock<Settings>>,
/// Current recording output.
current_output: Option<RecordingOutput>,
/// Recording start time.
start_time: Option<DateTime<Utc>>,
/// Whether recording is active.
is_recording: bool,
}
impl RecordingEngine {
/// Create a new recording engine.
pub fn new(settings: Settings) -> Self {
Self {
context: None,
settings: Arc::new(RwLock::new(settings)),
current_output: None,
start_time: None,
is_recording: false,
}
}
/// Start OBS and build the recording scene.
///
/// This runs at daemon startup rather than on the first game: the audio captures need to
/// attach while their applications still have a window, and the scene is then reused by
/// every recording.
pub fn initialize(&mut self) -> Result<()> {
info!("Initializing recording engine");
let settings = self.settings.read().clone();
let mut context = ObsContextBuilder::new()
.with_video_settings(settings.video.clone())
.with_audio_settings(settings.audio.clone())
.with_output_dir(&settings.output.path)
.build()?;
context.start()?;
self.context = Some(context);
info!("Recording engine initialized");
Ok(())
}
/// Take new settings from the app and apply them to the running OBS context.
pub fn update_settings(&mut self, new_settings: Settings) -> Result<()> {
*(self.settings.write()) = new_settings.clone();
if let Some(context) = self.context.as_mut() {
context.apply_settings(new_settings.video, new_settings.audio)?;
}
Ok(())
}
/// Get current settings.
pub fn settings(&self) -> Settings {
self.settings.read().clone()
}
/// Check if currently recording.
pub fn is_recording(&self) -> bool {
self.is_recording
}
/// Get the current game ID if recording.
pub fn current_game_id(&self) -> Option<u64> {
self.current_output.as_ref().and_then(|o| o.game_id)
}
/// Start recording.
pub fn start_recording(&mut self, game_id: Option<u64>, champion: Option<&str>) -> Result<()> {
if self.is_recording {
return Err(RecordingError::AlreadyRecording.into());
}
let settings = self.settings.read().clone();
let filename = self.generate_filename(game_id, champion);
let output_path = settings.output.path.join(&filename);
let context = self
.context
.as_mut()
.ok_or_else(|| RecordingError::ObsInitError("OBS not initialized".to_string()))?;
context.start_recording(&output_path)?;
self.current_output = Some(RecordingOutput {
path: output_path,
game_id,
champion: champion.map(String::from),
});
self.start_time = Some(Utc::now());
self.is_recording = true;
info!("Recording started");
Ok(())
}
/// Stop recording.
pub fn stop_recording(&mut self) -> Result<RecordingResult> {
if !self.is_recording {
return Err(RecordingError::NotRecording.into());
}
let context = self.context.as_mut().ok_or(RecordingError::ObsInitError(
"OBS not initialized".to_string(),
))?;
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();
self.is_recording = false;
info!("Recording stopped: {:?}", output.path);
Ok(RecordingResult {
path: output.path,
game_id: output.game_id,
champion: output.champion,
start_time,
end_time,
duration: end_time - start_time,
})
}
/// Generate a filename for the recording.
fn generate_filename(&self, game_id: Option<u64>, champion: Option<&str>) -> String {
let settings = self.settings.read();
let now = Utc::now();
let date = now.format("%Y-%m-%d").to_string();
let time = now.format("%H-%M-%S").to_string();
let game_id_str = game_id.map(|id| id.to_string()).unwrap_or_default();
let champion_str = champion.unwrap_or("unknown");
let filename = settings
.output
.naming_pattern
.replace("{date}", &date)
.replace("{time}", &time)
.replace("{game_id}", &game_id_str)
.replace("{champion}", champion_str);
format!("{}.{}", filename, settings.output.container)
}
/// Shutdown the recording engine.
pub fn shutdown(&mut self) -> Result<()> {
if self.is_recording {
self.stop_recording()?;
}
if let Some(mut context) = self.context.take() {
context.shutdown()?;
}
info!("Recording engine shut down");
Ok(())
}
}
impl Drop for RecordingEngine {
fn drop(&mut self) {
if let Err(e) = self.shutdown() {
warn!("Error shutting down recording engine: {}", e);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_recording_engine_creation() {
let settings = Settings::default();
let engine = RecordingEngine::new(settings);
assert!(!engine.is_recording());
}
#[test]
fn test_filename_generation() {
let settings = Settings::default();
let engine = RecordingEngine::new(settings);
let filename = engine.generate_filename(Some(12345), Some("Ahri"));
assert!(filename.ends_with(".mp4"));
assert!(filename.contains("Ahri"));
}
}