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.
This commit is contained in:
vhaudiquet committed 2026-11-19 18:37:20 +01:00
1 parent 4f2ee4256a
commit eabc3780c9
13 files changed
+545 -46

No files matched your search

+6
View File
@@ -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,
+58 -8
View File
@@ -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<EncoderCapability>,
/// What each audio track of the running recording carries, in file order.
tracks: Vec<String>,
}
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<String> {
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),
}
}
+3
View File
@@ -31,6 +31,9 @@ pub struct RecordingResult {
pub end_time: DateTime<Utc>,
/// 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<String>,
}
impl RecordingResult {
+150 -3
View File
@@ -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<Item = (usize, &crate::config::AudioSourceConfig)> {
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<String> {
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<Want> {
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<Want> {
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),
}
);
}
+4
View File
@@ -48,6 +48,9 @@ pub struct Timeline {
/// Video file name (just the filename, not the full path).
#[serde(default)]
pub video_file: Option<String>,
/// What each audio track of the video carries, in the order the file holds them.
#[serde(default)]
pub audio_tracks: Vec<String>,
}
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(),
}
}
+12
View File
@@ -71,6 +71,9 @@ pub struct RecordingMetadata {
pub file_path: Option<PathBuf>,
/// Video file name (just the filename, not the full path).
pub video_file: Option<String>,
/// What each audio track of the video carries, in file order.
#[serde(default)]
pub audio_tracks: Vec<String>,
/// File size in bytes.
pub file_size: Option<u64>,
/// 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();