From eabc3780c9248a6ba1657bfdb2b7df991d9a66ca Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Thu, 19 Nov 2026 18:37:20 +0100 Subject: [PATCH] record: keep a track per audio source and let the review mute them The recorder put every source on one mixer track, so the file had one audio stream and the review screen could not tell the game's sound from the microphone or from Discord. The daemon now gives each source a track: 1 for the game, 2 for the microphone, then one per application in the settings, up to OBS's six. Every track above the first gets an audio encoder and the output is told which tracks to write, which is what libobs's muxer reads to lay the streams out in track order. The timeline's new `audio_tracks` names what each stream holds, with empty names for the tracks no source fed. The app opens one player per stream, copied out of the clip into the audio cache, and the transport carries a toggle per channel. A channel that is off is neither heard nor kept: clip and highlight exports mix only the tracks left on. Recordings made before this change have one stream and play as they did. --- app/README.md | 10 +- app/src/app.rs | 12 +- app/src/daemon.rs | 7 + app/src/export.rs | 96 ++++++++- app/src/history.rs | 5 + app/src/screens/review.rs | 205 ++++++++++++++++--- record-daemon/README.md | 12 ++ record-daemon/src/recording/mod.rs | 6 + record-daemon/src/recording/obs_context.rs | 66 +++++- record-daemon/src/recording/output.rs | 3 + record-daemon/src/recording/process_audio.rs | 153 +++++++++++++- record-daemon/src/timeline/mod.rs | 4 + record-daemon/src/timeline/store.rs | 12 ++ 13 files changed, 545 insertions(+), 46 deletions(-) diff --git a/app/README.md b/app/README.md index 970d443..d2b1552 100644 --- a/app/README.md +++ b/app/README.md @@ -89,12 +89,16 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti 6. Game review: done. The clip fills the window at 16:9, with play/pause, +/-10 s, and a scrubber that marks every event; highlights (play, export) and the timeline sit in a side panel, one press away. ffmpeg exports each highlight. -7. OS integration: tray icon with open/hide/record/quit, launch at login through the Run key, +7. Audio channels: the recorder writes one audio stream per source, and the review screen opens + one player per stream (`export::extract_tracks` copies each into the audio cache). Toggles + under the transport mute a channel for listening, and clip and highlight exports mix only + the channels left on. Recordings made before the split play as one mixed track. +8. OS integration: tray icon with open/hide/record/quit, launch at login through the Run key, single instance, and toasts on recording start and stop. -8. Installer: `packager.toml` targets NSIS and copies the daemon and its OBS files beside the +9. Installer: `packager.toml` targets NSIS and copies the daemon and its OBS files beside the exe. `cargo install cargo-packager --locked && cargo packager --release`. The installer has not been run on a clean VM yet. -9. Parity: `tauri-app` is still in the tree. Delete it once the items above are verified on a +10. Parity: `tauri-app` is still in the tree. Delete it once the items above are verified on a machine with a live League Client. ### Known gaps diff --git a/app/src/app.rs b/app/src/app.rs index 916de00..0f902fc 100644 --- a/app/src/app.rs +++ b/app/src/app.rs @@ -1028,11 +1028,21 @@ pub fn demo_review(app: &mut App) { } screens::review::show(app, sample.remove(0)); app.review.error = Some("Sample recording: no clip on disk.".to_string()); - // Snapshot hook: draw a real clip when one is handed in. + // Snapshot hook: draw a real clip when one is handed in, with as many audio tracks as + // `LR_DEMO_TRACKS` names. if let Ok(path) = std::env::var("LR_DEMO_VIDEO") { let player = rune::Player::file(&path); player.set_looping(false); app.review.player = Some(player); app.review.error = None; + if let Ok(tracks) = std::env::var("LR_DEMO_TRACKS") { + if let Some(game) = app.review.game.as_mut() { + game.audio_tracks = tracks + .split(',') + .map(|name| name.trim().to_string()) + .collect(); + } + app.review.open_sound(&path); + } } } diff --git a/app/src/daemon.rs b/app/src/daemon.rs index 88a7a14..6a5daec 100644 --- a/app/src/daemon.rs +++ b/app/src/daemon.rs @@ -11,6 +11,13 @@ use crate::ipc::Client; /// Set this to point the app and the daemon at a scratch directory, as scripts do. pub const HOME_ENV: &str = "RECORD_DAEMON_HOME"; +/// Where the review screen keeps one audio file per track of a clip. +pub fn audio_cache_dir() -> PathBuf { + data_dir() + .map(|p| p.join("audio-cache")) + .unwrap_or_else(|| PathBuf::from("./audio-cache")) +} + /// The daemon's data directory, shared with the daemon itself. pub fn data_dir() -> Option { if let Some(home) = std::env::var_os(HOME_ENV).filter(|value| !value.is_empty()) { diff --git a/app/src/export.rs b/app/src/export.rs index e2496f7..1b5056e 100644 --- a/app/src/export.rs +++ b/app/src/export.rs @@ -25,7 +25,8 @@ pub fn ensure_ffmpeg() -> Result<(), String> { } /// Export `start..end` of `video`. Stream copy is fast and keyframe-aligned; `precise` re-encodes -/// with x264 for exact cuts. +/// with x264 for exact cuts. `audio` names the audio streams the clip keeps, empty for all of +/// them as they are. pub fn export_clip( video: &str, start: f64, @@ -33,6 +34,7 @@ pub fn export_clip( output_name: &str, precise: bool, quality: &str, + audio: &[usize], ) -> Result { ensure_ffmpeg()?; if !PathBuf::from(video).exists() { @@ -53,7 +55,38 @@ pub fn export_clip( .arg(video) .arg("-t") .arg(format!("{duration:.3}")); - if precise { + + // Which tracks the clip keeps. One track is mapped whole; several are mixed into a single + // stereo track, because a clip is meant to be played, not to carry a track picker. + let kept: Vec = audio + .iter() + .map(|stream| format!("[0:a:{stream}]")) + .collect(); + if kept.len() > 1 { + command + .arg("-filter_complex") + .arg(format!( + "{}amix=inputs={}:normalize=0[out]", + kept.concat(), + kept.len() + )) + .arg("-map") + .arg("0:v") + .arg("-map") + .arg("[out]") + .arg("-c:a") + .arg("aac") + .arg("-b:a") + .arg("160k"); + } else if let Some(stream) = audio.first() { + command + .arg("-map") + .arg("0:v") + .arg("-map") + .arg(format!("0:a:{stream}")); + } + + if precise || kept.len() > 1 { let crf = match quality { "low" => "28", "high" => "18", @@ -77,7 +110,6 @@ pub fn export_clip( .arg("-avoid_negative_ts") .arg("make_zero"); } - let iter = command .arg(output.to_string_lossy().to_string()) .spawn() @@ -105,6 +137,64 @@ pub fn export_clip( Ok(output.display().to_string()) } +/// Copy each audio track of `video` into a file of its own, so a player can be opened per +/// track. Files are kept between sessions; a track older than the clip is cut again. +pub fn extract_tracks(video: &str, stem: &str, count: usize) -> Result, String> { + ensure_ffmpeg()?; + let dir = crate::daemon::audio_cache_dir().join(sanitize(stem)); + std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; + let clip_time = std::fs::metadata(video) + .and_then(|m| m.modified()) + .map_err(|e| format!("cannot read {video}: {e}"))?; + + let mut paths = Vec::new(); + for track in 0..count { + let path = dir.join(format!("track-{track}.m4a")); + let fresh = std::fs::metadata(&path) + .and_then(|m| m.modified()) + .map(|time| time >= clip_time) + .unwrap_or(false); + if !fresh { + let mut command = FfmpegCommand::new(); + command + .arg("-y") + .arg("-i") + .arg(video) + .arg("-map") + .arg(format!("0:a:{track}")) + .arg("-vn") + .arg("-c:a") + .arg("aac") + .arg("-b:a") + .arg("160k") + .arg(path.to_string_lossy().to_string()); + let mut errors = Vec::new(); + for event in command + .spawn() + .map_err(|e| format!("cannot start ffmpeg: {e}"))? + .iter() + .map_err(|e| format!("cannot read ffmpeg output: {e}"))? + { + match event { + FfmpegEvent::Error(e) => errors.push(e), + FfmpegEvent::Log(LogLevel::Error, msg) => errors.push(msg), + _ => {} + } + } + let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0); + if size == 0 { + return Err(if errors.is_empty() { + format!("audio track {track} came out empty") + } else { + errors.join("; ") + }); + } + } + paths.push(path); + } + Ok(paths) +} + fn sanitize(name: &str) -> String { name.chars() .map(|c| { diff --git a/app/src/history.rs b/app/src/history.rs index 1cbc68b..8acd30c 100644 --- a/app/src/history.rs +++ b/app/src/history.rs @@ -38,6 +38,10 @@ pub struct Timeline { pub raw_end_game_stats: Option, #[serde(default)] pub video_file: Option, + /// What each audio track of the video carries, in file order. Empty for recordings made + /// before the recorder wrote one track per source. + #[serde(default)] + pub audio_tracks: Vec, } #[derive(Debug, Clone, Deserialize)] @@ -581,6 +585,7 @@ pub fn sample() -> Vec { } })), video_file: None, + audio_tracks: Vec::new(), } }; vec![ diff --git a/app/src/screens/review.rs b/app/src/screens/review.rs index f13a25c..72d414d 100644 --- a/app/src/screens/review.rs +++ b/app/src/screens/review.rs @@ -18,11 +18,8 @@ pub struct Review { /// Set while that file is on its way to the screen. pub loading: bool, pub player: Option, - /// The clip's soundtrack, played by its own player. Rune's video player asks Media Foundation - /// for pictures and sound from one reader, and that reader stamps the sound from its own - /// clock instead of the clip's, so the sound never lines up with the clock and plays silent. - /// An audio-only player reads the same file and needs no video, so its sound starts at zero. - pub sound: Option, + /// The clip's audio tracks, one player each, so the channels are heard apart. + pub sounds: Vec, /// The picture time the soundtrack was last put back to, to spot a window that stopped drawing. steady_at: f64, pub time: f64, @@ -38,10 +35,12 @@ pub struct Review { pub volume: f32, pub muted: bool, pub error: Option, + /// Why the channels could not be opened, when the clip has more than one. + pub channel_error: Option, } impl Review { - /// The video player only draws; the soundtrack player carries the gain and the mute. + /// The video player only draws; the audio players carry the gain and the mute. fn mute_video(player: &Player) { player.set_muted(true); } @@ -52,21 +51,86 @@ impl Review { if self.volume > 0.0 { self.muted = false; } - if let Some(sound) = &self.sound { - sound.set_volume(self.volume); - sound.set_muted(self.muted); + for channel in &self.sounds { + channel.sound.set_volume(self.volume); + channel.sound.set_muted(!channel.heard(self.muted)); } } pub fn toggle_muted(&mut self) { self.muted = !self.muted; - if let Some(sound) = &self.sound { - sound.set_muted(self.muted); + for channel in &self.sounds { + channel.sound.set_muted(!channel.heard(self.muted)); } } - /// Start the soundtrack's player, at the place the viewer is watching. - fn open_sound(&mut self, path: &str) { + /// Turn one track on or off, and make the change audible now rather than at the next seek. + pub fn toggle_channel(&mut self, index: usize) { + let Some(channel) = self.sounds.get_mut(index) else { + return; + }; + channel.on = !channel.on; + channel.sound.set_muted(!channel.heard(self.muted)); + } + + /// The audio streams a clip or highlight keeps: the tracks the viewer left on. + pub fn kept_tracks(&self) -> Vec { + self.sounds + .iter() + .filter(|channel| channel.on) + .map(|channel| channel.stream) + .collect() + } + + /// Start the soundtrack's players, at the place the viewer is watching. + pub fn open_sound(&mut self, path: &str) { + self.sounds.clear(); + self.channel_error = None; + let labels = self + .game + .as_ref() + .map(|game| game.audio_tracks.clone()) + .unwrap_or_default(); + if labels.len() < 2 { + // One track, or a recording made before the recorder split them: the file's own + // sound is the whole mix, and an audio player reads it as it is. + let label = labels + .first() + .cloned() + .unwrap_or_else(|| "All audio".to_string()); + let channel = self.channel(0, label, path); + self.sounds.push(channel); + return; + } + let stem = self + .game + .as_ref() + .and_then(|game| game.video_file.clone()) + .or_else(|| { + std::path::Path::new(path) + .file_name() + .map(|name| name.to_string_lossy().to_string()) + }) + .unwrap_or_default(); + let stem = stem.rsplit_once('.').map(|(name, _)| name).unwrap_or(&stem); + let files = match crate::export::extract_tracks(path, stem, labels.len()) { + Ok(files) => files, + Err(e) => { + self.channel_error = Some(e); + return; + } + }; + for (stream, file) in files.iter().enumerate() { + // A track no source fed is silent in the file; it gets no toggle. + let Some(label) = labels.get(stream).filter(|label| !label.trim().is_empty()) else { + continue; + }; + let channel = self.channel(stream, label.clone(), &file.to_string_lossy()); + self.sounds.push(channel); + } + } + + fn channel(&self, stream: usize, label: String, path: &str) -> Channel { let sound = Player::audio(path.to_string()); sound.set_looping(false); sound.set_volume(self.volume); @@ -79,7 +143,12 @@ impl Review { if playing { sound.play(); } - self.sound = Some(sound); + Channel { + label, + stream, + sound, + on: true, + } } fn playback(&mut self) { @@ -91,15 +160,14 @@ impl Review { player.play(); } } - if let Some(sound) = &self.sound { + for channel in &self.sounds { if playing { - sound.pause(); + channel.sound.pause(); } else { - sound.play(); + channel.sound.play(); } } } - /// The Clip button: start a selection at the viewer's place, or drop the one on screen. pub fn toggle_clip(&mut self) { self.clip = match self.clip { @@ -136,11 +204,33 @@ impl Review { player.seek(at); self.time = at; } - if let Some(sound) = &self.sound { - sound.seek(at); + for channel in &self.sounds { + channel.sound.seek(at); } } } +/// One audio track of the clip, copied to a file of its own and played on its own, so the +/// channels are heard apart and can be kept apart. +/// Rune's video player asks Media Foundation for pictures and sound from one reader, and that +/// reader stamps the sound from its own clock instead of the clip's, so the sound never lines +/// up with the clock and plays silent. Audio-only players read one track each and need no +/// video, so their sound starts at zero. +pub struct Channel { + /// What the track carries, as the recorder named it. + pub label: String, + /// The stream this track is, in the file. + pub stream: usize, + pub sound: Player, + /// Off means the viewer does not hear it, and a clip or highlight does not keep it. + pub on: bool, +} + +impl Channel { + /// Whether this track goes into the current mix, given the master mute. + fn heard(&self, muted: bool) -> bool { + self.on && !muted + } +} /// A clip being chosen on the scrubber: where it starts and where it ends. #[derive(Clone, Copy)] @@ -166,7 +256,7 @@ impl Default for Review { game: None, loading: false, player: None, - sound: None, + sounds: Vec::new(), steady_at: 0.0, time: 0.0, duration: 0.0, @@ -181,6 +271,7 @@ impl Default for Review { // headroom, and the transport bar can change it. volume: 0.8, muted: false, + channel_error: None, } } } @@ -229,7 +320,7 @@ pub fn show(app: &mut App, game: Timeline) { player.set_waker(waker.clone()); } app.review.player = Some(player); - app.review.sound = None; + app.review.sounds.clear(); app.review.steady_at = 0.0; Review::mute_video(app.review.player.as_ref().expect("just set")); } @@ -240,7 +331,7 @@ fn follow_sound(app: &mut App) { let Some(player) = &app.review.player else { return; }; - if app.review.sound.is_some() || player.has_sound() != Some(true) { + if !app.review.sounds.is_empty() || player.has_sound() != Some(true) { return; } let Some(path) = app @@ -259,7 +350,7 @@ pub fn leave(app: &mut App) { app.review_rx = None; app.review.loading = false; app.review.player = None; - app.review.sound = None; + app.review.sounds.clear(); app.review.game = None; app.review.highlights.clear(); app.review.time = 0.0; @@ -272,7 +363,10 @@ pub fn leave(app: &mut App) { /// Sound from a second player drifts from the pictures by a few milliseconds a minute. Past a /// quarter second it is worth a seek, and short of that a seek would be audible. fn keep_in_step(app: &mut App) { - let (Some(player), Some(sound)) = (&app.review.player, &app.review.sound) else { + let (Some(player), Some(sound)) = ( + &app.review.player, + app.review.sounds.first().map(|channel| &channel.sound), + ) else { return; }; if !player.is_playing() { @@ -626,12 +720,64 @@ fn transport(app: &App, p: Paint) -> El { .w_full() .gap(space::S2) .child(bar); + if let Some(line) = channels(app, p) { + column = column.child(line); + } if let Some(clip) = app.review.clip { column = column.child(clip_row(app, p, clip)); } column } +/// One toggle per audio track, shown once the clip carries more than one. A track that is off +/// is neither heard nor kept in an export. +fn channels(app: &App, p: Paint) -> Option { + if app.review.sounds.len() < 2 { + return None; + } + let mut line = row().key("channels").center_y().gap(space::S2).child( + text("Audio") + .key("channels-label") + .font(body(11.5)) + .color(p.muted()), + ); + for (index, channel) in app.review.sounds.iter().enumerate() { + let label = channel.label.clone(); + let on = channel.on; + line = line.child( + el().key(format!("channel-{index}")) + .role("switch") + .label(label.clone()) + .checked(on) + .focusable(true) + .h(24.0) + .px(10.0) + .center() + .radius(radius::MD) + .fill(if on { p.accent } else { p.t.control_off }) + .hover(p.t.hover) + .press(p.t.press) + .on_press(move |app: &mut App| app.review.toggle_channel(index)) + .child( + text(label) + .key("label") + .font(type_::LABEL) + .color(if on { p.accent_ink } else { p.muted() }) + .a11y_hidden(), + ), + ); + } + if let Some(error) = &app.review.channel_error { + line = line.child( + text(error.clone()) + .key("channels-error") + .font(body(11.5)) + .color(p.warning), + ); + } + Some(line) +} + /// The row under the transport while a clip is being chosen: the two ends, its length, and the /// two things to do with it. fn clip_row(app: &App, p: Paint, clip: Clip) -> El { @@ -673,9 +819,10 @@ fn clip_row(app: &App, p: Paint, clip: Clip) -> El { Some(clip) => (clip.start, clip.end), None => return, }; + let audio = app.review.kept_tracks(); std::thread::spawn(move || { let result = - crate::export::export_clip(&video, start, end, &name, true, "high"); + crate::export::export_clip(&video, start, end, &name, true, "high", &audio); let _ = tx.send(result); }); app.review.export = Some(rx); @@ -907,9 +1054,11 @@ fn highlights(app: &App, p: Paint, game: &Timeline) -> El { let (tx, rx) = channel(); let Some(video) = video.clone() else { return }; let name = name.clone(); + let audio = app.review.kept_tracks(); std::thread::spawn(move || { - let result = - crate::export::export_clip(&video, start, end, &name, true, "high"); + let result = crate::export::export_clip( + &video, start, end, &name, true, "high", &audio, + ); let _ = tx.send(result); }); app.review.export = Some(rx); diff --git a/record-daemon/README.md b/record-daemon/README.md index 4598601..d877f57 100644 --- a/record-daemon/README.md +++ b/record-daemon/README.md @@ -50,6 +50,18 @@ record-daemon/ │ └── error.rs # Error types ``` + +### Audio tracks + +Each source records to a mixer track of its own, and the file keeps them as separate streams: +track 1 is the game's sound, track 2 the microphone, then one track per application in the +settings, up to OBS's six. The stream order is the track order. A recording made when a track +had no source carries a silent stream for it, and the timeline's `audio_tracks` names what each +stream holds, empty for those gaps. + +The app plays one audio player per track, so the review screen can mute any of them, and a +clip or highlight export mixes only the tracks left on. + ## Platform Support | Feature | Linux | Windows | diff --git a/record-daemon/src/recording/mod.rs b/record-daemon/src/recording/mod.rs index e282bfe..ee9b6e9 100644 --- a/record-daemon/src/recording/mod.rs +++ b/record-daemon/src/recording/mod.rs @@ -142,7 +142,13 @@ impl RecordingEngine { self.is_recording = false; info!("Recording stopped: {:?}", output.path); + let audio_tracks = self + .context + .as_ref() + .map(ObsContext::audio_tracks) + .unwrap_or_default(); Ok(RecordingResult { + audio_tracks, path: output.path, game_id: output.game_id, champion: output.champion, diff --git a/record-daemon/src/recording/obs_context.rs b/record-daemon/src/recording/obs_context.rs index f06c82d..2c58fcc 100644 --- a/record-daemon/src/recording/obs_context.rs +++ b/record-daemon/src/recording/obs_context.rs @@ -17,11 +17,12 @@ use libobs_simple::wrapper::utils::{ObsPath, ObsString}; use libobs_wrapper::context::ObsContext as LibObsContext; use libobs_wrapper::data::object::ObsObjectTrait; use libobs_wrapper::data::ObsData; -use libobs_wrapper::data::ObsObjectBuilder; +use libobs_wrapper::data::{ObsDataSetters, ObsObjectBuilder}; +use libobs_wrapper::encoders::ObsAudioEncoderType; use libobs_wrapper::enums::ObsLogLevel; use libobs_wrapper::logger::ObsLogger; use libobs_wrapper::sources::{ObsSourceBuilder, ObsSourceRef}; -use libobs_wrapper::utils::{SourceInfo, StartupInfo}; +use libobs_wrapper::utils::{AudioEncoderInfo, SourceInfo, StartupInfo}; use serde_json::json; use tracing::{debug, error, info, warn}; @@ -126,6 +127,7 @@ impl ObsContextBuilder { recording: false, pending_audio: None, encoder_capability: None, + tracks: Vec::new(), }) } } @@ -155,6 +157,8 @@ pub struct ObsContext { /// Settings that arrived while a recording was running, applied once it stops. pending_audio: Option<(VideoSettings, AudioSettings)>, encoder_capability: Option, + /// What each audio track of the running recording carries, in file order. + tracks: Vec, } impl ObsContext { @@ -163,6 +167,11 @@ impl ObsContext { self.context.is_some() } + /// What each audio track of the last recording carries, in file order. + pub fn audio_tracks(&self) -> Vec { + self.tracks.clone() + } + /// Check if currently recording. pub fn is_recording(&self) -> bool { self.recording @@ -341,9 +350,45 @@ impl ObsContext { EncoderCapability::Software => builder, }; - let output = builder + let mut output = builder .build() .map_err(|e| RecordingError::StartError(format!("failed to build output: {:?}", e)))?; + let tracks = process_audio::tracks(&self.audio_settings); + let mut mixers: usize = 0; + for (track, _) in &tracks { + mixers |= 1usize << track; + } + // One encoder per track the sources feed, and an output told which tracks to write: that + // is what puts each channel in the file separately. The builder encodes track 1; the + // muxer takes one encoder per track number up to the highest written, so the numbers + // below it get an encoder even when no source feeds them. + let highest = tracks.iter().map(|(track, _)| *track).max().unwrap_or(0); + for track in 1..=highest { + let mut audio_data = context.data().map_err(|e| { + RecordingError::StartError(format!("audio encoder settings: {:?}", e)) + })?; + audio_data + .set_string("rate_control", "CBR") + .map_err(|e| RecordingError::StartError(format!("audio rate control: {:?}", e)))?; + audio_data + .set_int("bitrate", self.audio_settings.bitrate as i64) + .map_err(|e| RecordingError::StartError(format!("audio bitrate: {:?}", e)))?; + let info = AudioEncoderInfo::new( + ObsAudioEncoderType::FFMPEG_AAC, + format!("output_audio_encoder_{track}"), + Some(audio_data), + None, + ); + output + .create_and_set_audio_encoder(info, track as usize) + .map_err(|e| { + RecordingError::StartError(format!("audio encoder for track {track}: {:?}", e)) + })?; + } + unsafe { + libobs::obs_output_set_mixers(output.as_ptr().get_ptr(), mixers); + } + debug!("recording tracks: {:?}", tracks); catch_native("starting the output", || { output.start().map_err(|e| { @@ -351,6 +396,7 @@ impl ObsContext { }) })?; + self.tracks = process_audio::labels(&self.audio_settings); self.output = Some(output); self.recording = true; info!("recording started: {}", output_path.display()); @@ -458,13 +504,14 @@ fn add_device_sources( audio.mic_volume, ) .map_err(|e| RecordingError::StartError(format!("microphone: {}", e)))?; + process_audio::set_track(&source, process_audio::MIC_TRACK); scene .add_source(source.clone()) .map_err(|e| RecordingError::StartError(format!("adding the microphone: {:?}", e)))?; added.push(source); } - for app in audio.capture_apps.iter().filter(|a| a.enabled) { + for (index, app) in process_audio::enabled_apps(audio) { let (plugin, settings) = match app.source_type { AudioSourceType::Application => continue, AudioSourceType::DeviceOutput => (out_plugin, json!({ "device_id": app.device })), @@ -478,10 +525,13 @@ fn add_device_sources( settings, volume, ) { - Ok(source) => match scene.add_source(source.clone()) { - Ok(_) => added.push(source), - Err(e) => warn!("could not add {} to the scene: {:?}", app.name, e), - }, + Ok(source) => { + process_audio::set_track(&source, process_audio::app_track(index)); + match scene.add_source(source.clone()) { + Ok(_) => added.push(source), + Err(e) => warn!("could not add {} to the scene: {:?}", app.name, e), + } + } Err(e) => warn!("audio source '{}' unavailable: {}", app.name, e), } } diff --git a/record-daemon/src/recording/output.rs b/record-daemon/src/recording/output.rs index e00168c..3354589 100644 --- a/record-daemon/src/recording/output.rs +++ b/record-daemon/src/recording/output.rs @@ -31,6 +31,9 @@ pub struct RecordingResult { pub end_time: DateTime, /// Recording duration. pub duration: Duration, + /// What each audio track in the file carries, in the order the file holds them. + #[serde(default)] + pub audio_tracks: Vec, } impl RecordingResult { diff --git a/record-daemon/src/recording/process_audio.rs b/record-daemon/src/recording/process_audio.rs index 2f2be58..6dec6ed 100644 --- a/record-daemon/src/recording/process_audio.rs +++ b/record-daemon/src/recording/process_audio.rs @@ -20,6 +20,7 @@ use std::sync::{Arc, Mutex}; use std::thread::JoinHandle; use std::time::Duration; +use libobs_wrapper::data::object::ObsObjectTrait; use libobs_wrapper::data::ObsData; use libobs_wrapper::runtime::ObsRuntime; use libobs_wrapper::scenes::{ObsSceneRef, SceneItemExtSceneTrait}; @@ -32,6 +33,80 @@ use super::obs_context::{apply_volume, catch_native}; use crate::config::{AudioSettings, AudioSourceType}; use crate::error::RecordingError; +/// The OBS mixer track the game's sound feeds. +pub const GAME_TRACK: u32 = 0; +/// The track the microphone feeds. +pub const MIC_TRACK: u32 = 1; +/// OBS mixes six tracks at most, numbered 0 to 5. +pub const MAX_TRACKS: u32 = 6; + +/// The track the application at `index` (its place among the enabled ones) feeds. Past the +/// fourth application they share the last track: heard, but not separable. +pub fn app_track(index: usize) -> u32 { + (2 + index as u32).min(MAX_TRACKS - 1) +} + +/// The applications the settings ask for, each with its place among them, which picks its +/// mixer track. +pub fn enabled_apps( + audio: &AudioSettings, +) -> impl Iterator { + audio.capture_apps.iter().filter(|a| a.enabled).enumerate() +} + +/// The tracks this recording writes and what each one carries, in track order. +/// +/// One track per source is what keeps the channels apart: the review screen plays the tracks a +/// viewer keeps and mutes the rest, and an export mixes only those into the clip. +pub fn tracks(audio: &AudioSettings) -> Vec<(u32, String)> { + let mut tracks: Vec<(u32, String)> = Vec::new(); + if audio.capture_game { + tracks.push((GAME_TRACK, "Game".to_string())); + } + if audio.capture_mic { + tracks.push((MIC_TRACK, "Microphone".to_string())); + } + for (index, app) in enabled_apps(audio) { + let track = app_track(index); + match tracks.iter_mut().find(|(t, _)| *t == track) { + Some((_, label)) => { + label.push_str(" and "); + label.push_str(&app.name); + } + None => tracks.push((track, app.name.clone())), + } + } + tracks +} + +/// One name per audio track of the recording, in track order, gaps included. +/// +/// The muxer writes a stream for every track up to the highest one a source feeds, so a +/// recording with only an application at track 3 still has streams 1 and 2, silent. The empty +/// names stand for those. +pub fn labels(audio: &AudioSettings) -> Vec { + let tracks = tracks(audio); + let Some(highest) = tracks.iter().map(|(track, _)| *track).max() else { + return Vec::new(); + }; + (0..=highest) + .map(|track| { + tracks + .iter() + .find(|(t, _)| *t == track) + .map(|(_, label)| label.clone()) + .unwrap_or_default() + }) + .collect() +} +/// Put a source on one mixer track, so only that track carries its sound. +pub(crate) fn set_track(source: &ObsSourceRef, track: u32) { + let mask = 1u32 << track.min(MAX_TRACKS - 1); + unsafe { + libobs::obs_source_set_audio_mixers(source.as_ptr().get_ptr(), mask); + } +} + /// How often the window scan runs while the daemon is up. const SCAN: Duration = Duration::from_secs(2); @@ -47,6 +122,8 @@ pub struct Want { pub exe: String, /// 0-100, the same scale the settings screen uses. pub volume: u32, + /// The mixer track this capture feeds, which keeps it separate in the file. + pub track: u32, } /// The processes the current audio settings ask for. @@ -57,9 +134,10 @@ pub fn wants(audio: &AudioSettings) -> Vec { key: "game_audio".to_string(), exe: GAME_EXE.to_string(), volume: audio.game_volume, + track: GAME_TRACK, }); } - for app in audio.capture_apps.iter().filter(|a| a.enabled) { + for (index, app) in enabled_apps(audio) { if app.source_type != AudioSourceType::Application { continue; } @@ -67,6 +145,7 @@ pub fn wants(audio: &AudioSettings) -> Vec { key: format!("app_{}", app.id), exe: app.device.clone(), volume: app.volume.unwrap_or(audio.apps_volume), + track: app_track(index), }); } wants @@ -241,6 +320,7 @@ fn create(want: &Want, window: isize, runtime: &ObsRuntime, scene: &ObsSceneRef) .ok()?; apply_volume(&source, want.volume); + set_track(&source, want.track); let mut scene = scene.clone(); if let Err(e) = scene.add_source(source.clone()) { warn!("could not add {} audio to the scene: {:?}", want.exe, e); @@ -390,6 +470,71 @@ mod tests { use super::*; use crate::config::{AudioSourceConfig, Settings}; + #[test] + fn every_source_gets_a_track_of_its_own() { + let mut settings = Settings::default(); + settings.audio.capture_game = true; + settings.audio.capture_mic = true; + settings.audio.capture_apps = vec![ + AudioSourceConfig { + id: "discord".into(), + name: "Discord".into(), + source_type: AudioSourceType::Application, + device: "Discord.exe".into(), + enabled: true, + volume: None, + }, + AudioSourceConfig { + id: "browser".into(), + name: "Browser".into(), + source_type: AudioSourceType::DeviceOutput, + device: "default".into(), + enabled: true, + volume: None, + }, + ]; + + assert_eq!( + tracks(&settings.audio), + vec![ + (GAME_TRACK, "Game".to_string()), + (MIC_TRACK, "Microphone".to_string()), + (2, "Discord".to_string()), + (3, "Browser".to_string()), + ] + ); + assert_eq!(labels(&settings.audio).len(), 4); + } + + #[test] + fn a_track_no_source_feeds_keeps_its_place_and_no_name() { + let mut settings = Settings::default(); + settings.audio.capture_game = false; + settings.audio.capture_mic = false; + settings.audio.capture_apps = vec![ + AudioSourceConfig { + id: "first".into(), + name: "First".into(), + source_type: AudioSourceType::Application, + device: "First.exe".into(), + enabled: false, + volume: None, + }, + AudioSourceConfig { + id: "second".into(), + name: "Second".into(), + source_type: AudioSourceType::Application, + device: "Second.exe".into(), + enabled: true, + volume: None, + }, + ]; + + // The disabled one is not counted, so the enabled one lands on the first app track. + assert_eq!(tracks(&settings.audio), vec![(2, "Second".to_string())]); + assert_eq!(labels(&settings.audio), vec!["", "", "Second"]); + } + #[test] fn a_window_string_escapes_the_separators() { // libobs decodes both escapes, so a title holding a colon still splits into three. @@ -439,7 +584,8 @@ mod tests { Want { key: "game_audio".into(), exe: GAME_EXE.into(), - volume: 70 + volume: 70, + track: GAME_TRACK } ); assert_eq!( @@ -447,7 +593,8 @@ mod tests { Want { key: "app_discord".into(), exe: "Discord.exe".into(), - volume: 45 + volume: 45, + track: app_track(0), } ); } diff --git a/record-daemon/src/timeline/mod.rs b/record-daemon/src/timeline/mod.rs index 74d6f86..61f20c0 100644 --- a/record-daemon/src/timeline/mod.rs +++ b/record-daemon/src/timeline/mod.rs @@ -48,6 +48,9 @@ pub struct Timeline { /// Video file name (just the filename, not the full path). #[serde(default)] pub video_file: Option, + /// What each audio track of the video carries, in the order the file holds them. + #[serde(default)] + pub audio_tracks: Vec, } impl Timeline { @@ -74,6 +77,7 @@ impl Timeline { raw_live_client_data: None, raw_end_game_stats: None, video_file: None, + audio_tracks: Vec::new(), } } diff --git a/record-daemon/src/timeline/store.rs b/record-daemon/src/timeline/store.rs index ca1d31c..7a49b55 100644 --- a/record-daemon/src/timeline/store.rs +++ b/record-daemon/src/timeline/store.rs @@ -71,6 +71,9 @@ pub struct RecordingMetadata { pub file_path: Option, /// Video file name (just the filename, not the full path). pub video_file: Option, + /// What each audio track of the video carries, in file order. + #[serde(default)] + pub audio_tracks: Vec, /// File size in bytes. pub file_size: Option, /// Number of events. @@ -112,6 +115,7 @@ impl RecordingMetadata { .file_name() .and_then(|n| n.to_str()) .map(String::from), + audio_tracks: result.audio_tracks.clone(), file_size: result.file_size(), event_count: 0, finalized: false, @@ -170,6 +174,7 @@ impl TimelineStore { duration: Duration::zero(), file_path: None, video_file: None, + audio_tracks: Vec::new(), file_size: None, event_count: 0, finalized: false, @@ -200,6 +205,7 @@ impl TimelineStore { .file_name() .and_then(|n| n.to_str()) .map(String::from); + metadata.audio_tracks = result.audio_tracks.clone(); metadata.file_size = result.file_size(); metadata.finalized = true; @@ -231,6 +237,7 @@ impl TimelineStore { .file_name() .and_then(|n| n.to_str()) .map(String::from), + audio_tracks: result.audio_tracks.clone(), file_size: result.file_size(), event_count: 0, finalized: true, @@ -335,6 +342,7 @@ impl TimelineStore { raw_live_client_data: metadata.raw_live_client_data.clone(), raw_end_game_stats: metadata.raw_end_game_stats.clone(), video_file: metadata.video_file.clone(), + audio_tracks: metadata.audio_tracks.clone(), }) } @@ -379,6 +387,7 @@ impl TimelineStore { raw_live_client_data: metadata.raw_live_client_data, raw_end_game_stats: metadata.raw_end_game_stats, video_file: metadata.video_file, + audio_tracks: metadata.audio_tracks, }; let file_path = self.storage_dir.join(format!("{}.json", id)); @@ -415,6 +424,7 @@ impl TimelineStore { let raw_live_client_data = timeline.raw_live_client_data; let raw_end_game_stats = timeline.raw_end_game_stats; let video_file = timeline.video_file; + let audio_tracks = timeline.audio_tracks; let events = timeline.events; let metadata = RecordingMetadata { @@ -431,6 +441,7 @@ impl TimelineStore { duration, file_path: None, video_file, + audio_tracks, file_size: None, event_count, finalized: true, @@ -475,6 +486,7 @@ mod tests { start_time: Utc::now(), end_time: Utc::now() + Duration::seconds(60), duration: Duration::seconds(60), + audio_tracks: Vec::new(), }; let id = store.add_recording(result).unwrap();