Add audio device selection

This commit is contained in:
Alvin-Zilverstand committed 2026-09-10 08:38:02 +02:00
1 parent 32a8aa4753
commit 2b465a3555
8 files changed
+192 -16

No files matched your search

+42 -2
View File
@@ -1,3 +1,4 @@
use clipforge::audio::{list_ffmpeg_dshow_audio_inputs, AudioDeviceKind};
use clipforge::capture::{
ffmpeg_is_available, ffmpeg_supports_filter, ffmpeg_supports_input_device,
find_ffmpeg_executable, CaptureBackend, CaptureConfig, CaptureMethod, CaptureSource,
@@ -58,6 +59,7 @@ struct DesktopStatus {
detected_game: Option<String>,
replay_buffer_seconds: u64,
mic_enabled: bool,
mic_device: Option<String>,
auto_record_enabled: bool,
upload_enabled: bool,
session_recording: bool,
@@ -93,6 +95,12 @@ struct GsiConfigDto {
path: String,
}
#[derive(Debug, Serialize)]
struct AudioDeviceDto {
name: String,
kind: String,
}
#[tauri::command]
fn get_status(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
let recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
@@ -162,6 +170,35 @@ fn set_mic_enabled(enabled: bool, runtime: State<'_, AppRuntime>) -> Result<Desk
Ok(status_from_recorder(&recorder, capture.as_ref()))
}
#[tauri::command]
fn list_audio_devices() -> Result<Vec<AudioDeviceDto>, String> {
let ffmpeg = find_ffmpeg_executable()
.ok_or_else(|| "FFmpeg was not found on PATH or in the bundled sidecar.".to_string())?;
Ok(list_ffmpeg_dshow_audio_inputs(&ffmpeg)
.into_iter()
.map(|device| AudioDeviceDto {
name: device.name,
kind: match device.kind {
AudioDeviceKind::Input => "input".to_string(),
AudioDeviceKind::SystemLoopback => "system_loopback".to_string(),
},
})
.collect())
}
#[tauri::command]
fn set_mic_device(
device: Option<String>,
runtime: State<'_, AppRuntime>,
) -> Result<DesktopStatus, String> {
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
recorder.settings.privacy.mic_device = device.filter(|value| !value.trim().is_empty());
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save settings: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref()))
}
#[tauri::command]
fn set_auto_record_enabled(
enabled: bool,
@@ -417,8 +454,8 @@ fn start_capture_inner(runtime: &AppRuntime) -> Result<DesktopStatus, String> {
encoder: EncoderPreference::HardwareH264,
system_audio_enabled,
mic_enabled: recorder.settings.privacy.mic_enabled,
system_audio_device: None,
mic_device: None,
system_audio_device: recorder.settings.privacy.system_audio_device.clone(),
mic_device: recorder.settings.privacy.mic_device.clone(),
};
let mut backend = FfmpegReplayCaptureBackend::new(ffmpeg, &segment_pattern, segment_duration);
backend.start(config).map_err(|error| error.to_string())?;
@@ -722,6 +759,8 @@ fn main() {
list_clips,
set_replay_buffer,
set_mic_enabled,
list_audio_devices,
set_mic_device,
set_auto_record_enabled,
write_gsi_configs,
poll_auto_clip_events,
@@ -842,6 +881,7 @@ fn status_from_recorder(recorder: &RecorderService, capture: Option<&ActiveCaptu
detected_game: recorder.state.detected_game_id.clone(),
replay_buffer_seconds: recorder.settings.replay_buffer.as_secs(),
mic_enabled: recorder.settings.privacy.mic_enabled,
mic_device: recorder.settings.privacy.mic_device.clone(),
auto_record_enabled: !recorder.settings.privacy.desktop_capture_requires_confirmation,
upload_enabled: false,
session_recording: matches!(recorder.state.status, RecordingStatus::RecordingSession),
+76
View File
@@ -0,0 +1,76 @@
use std::path::Path;
use std::process::Command;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AudioDeviceKind {
Input,
SystemLoopback,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AudioDevice {
pub name: String,
pub kind: AudioDeviceKind,
}
pub fn list_ffmpeg_dshow_audio_inputs(ffmpeg: &Path) -> Vec<AudioDevice> {
let Ok(output) = Command::new(ffmpeg)
.args([
"-hide_banner",
"-list_devices",
"true",
"-f",
"dshow",
"-i",
"dummy",
])
.output()
else {
return Vec::new();
};
let combined = format!(
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
parse_dshow_audio_devices(&combined)
}
pub fn parse_dshow_audio_devices(output: &str) -> Vec<AudioDevice> {
output
.lines()
.filter_map(|line| {
if !line.contains("\" (audio)") {
return None;
}
let start = line.find('"')?;
let rest = &line[start + 1..];
let end = rest.find('"')?;
Some(AudioDevice {
name: rest[..end].to_string(),
kind: AudioDeviceKind::Input,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_dshow_audio_devices() {
let output = r#"
[in#0 @ 000001] "HP 5MP Camera" (video)
[in#0 @ 000001] "Microfoon (Realtek(R) Audio)" (audio)
[in#0 @ 000001] Alternative name "@device_cm_{...}"
[in#0 @ 000001] "Headset (Crusher ANC 2)" (audio)
"#;
let devices = parse_dshow_audio_devices(output);
assert_eq!(devices.len(), 2);
assert_eq!(devices[0].name, "Microfoon (Realtek(R) Audio)");
assert_eq!(devices[1].name, "Headset (Crusher ANC 2)");
}
}
+1
View File
@@ -1,3 +1,4 @@
pub mod audio;
pub mod capture;
pub mod database;
pub mod game_detection;
+1 -6
View File
@@ -1,7 +1,7 @@
use clipforge::game_detection::{default_profiles, detect_game, RunningProcess};
use clipforge::recorder::{BufferSegment, RecorderAction, RecorderService};
use clipforge::settings::AppSettings;
use clipforge::storage::{write_placeholder_mp4, LibraryPaths};
use clipforge::storage::LibraryPaths;
use std::env;
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
@@ -48,11 +48,6 @@ fn main() {
let clip_action =
service.save_manual_clip(Duration::from_secs(60), now + Duration::from_secs(60));
if let Some(RecorderAction::CreatedClip { clip_id, .. }) = clip_action {
if let Some(clip) = service.library.all().iter().find(|clip| clip.id == clip_id) {
if let Err(error) = write_placeholder_mp4(&clip.path, &clip.id) {
eprintln!("Could not write placeholder clip: {error}");
}
}
println!("Created manual clip: {clip_id}");
}
} else {
+6
View File
@@ -26,6 +26,10 @@ pub struct HotkeySettings {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PrivacySettings {
pub mic_enabled: bool,
#[serde(default)]
pub mic_device: Option<String>,
#[serde(default)]
pub system_audio_device: Option<String>,
pub desktop_capture_requires_confirmation: bool,
pub excluded_window_titles: Vec<String>,
pub upload_requires_confirmation: bool,
@@ -80,6 +84,8 @@ impl AppSettings {
},
privacy: PrivacySettings {
mic_enabled: false,
mic_device: None,
system_audio_device: None,
desktop_capture_requires_confirmation: true,
excluded_window_titles: Vec::new(),
upload_requires_confirmation: true,
-7
View File
@@ -172,13 +172,6 @@ fn collect_files(root: &Path) -> io::Result<Vec<FileFact>> {
Ok(files)
}
pub fn write_placeholder_mp4(path: &Path, label: &str) -> io::Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, format!("ClipForge placeholder video: {label}\n"))
}
#[cfg(test)]
mod tests {
use super::*;
+64
View File
@@ -40,6 +40,7 @@ type DesktopStatus = {
detected_game: string | null;
replay_buffer_seconds: number;
mic_enabled: boolean;
mic_device: string | null;
auto_record_enabled: boolean;
upload_enabled: boolean;
session_recording: boolean;
@@ -73,6 +74,11 @@ type GsiConfigDto = {
path: string;
};
type AudioDeviceDto = {
name: string;
kind: "input" | "system_loopback";
};
type AppState = {
activeView: "Library" | "Recording" | "Auto Clip" | "Uploads" | "Settings";
recordingState: RecordingState;
@@ -86,6 +92,8 @@ type AppState = {
systemAudioAvailable: boolean;
desktopDuplicationAvailable: boolean;
micEnabled: boolean;
micDevice: string;
audioDevices: AudioDeviceDto[];
autoRecordEnabled: boolean;
autoUpload: boolean;
uploadProvider: "catbox" | "litterbox" | "custom_http" | "lustful";
@@ -125,6 +133,8 @@ const state: AppState = {
systemAudioAvailable: false,
desktopDuplicationAvailable: false,
micEnabled: false,
micDevice: "",
audioDevices: [],
autoRecordEnabled: false,
autoUpload: false,
uploadProvider: "catbox",
@@ -390,6 +400,18 @@ function renderRecordingView() {
<h2>${state.systemAudioAvailable ? "System audio ready" : "System audio unavailable"}</h2>
<p class="muted">${state.systemAudioAvailable ? "FFmpeg reports WASAPI input support." : "This FFmpeg build does not expose WASAPI; video recording still works."}</p>
<label class="toggle"><input type="checkbox" ${state.micEnabled ? "checked" : ""} data-action="toggle-mic" /> Mic capture</label>
<label>Mic device
<select data-action="mic-device">
<option value="">Default microphone</option>
${state.audioDevices
.filter((device) => device.kind === "input")
.map(
(device) =>
`<option value="${escapeHtml(device.name)}" ${state.micDevice === device.name ? "selected" : ""}>${escapeHtml(device.name)}</option>`,
)
.join("")}
</select>
</label>
</article>
</section>
`;
@@ -534,6 +556,11 @@ function bindEvents() {
void saveMicSetting(state.micEnabled);
});
appRoot.querySelector<HTMLSelectElement>("[data-action='mic-device']")?.addEventListener("change", (event) => {
state.micDevice = (event.target as HTMLSelectElement).value;
void saveMicDevice(state.micDevice);
});
appRoot.querySelector<HTMLInputElement>("[data-action='toggle-auto-upload']")?.addEventListener("change", (event) => {
state.autoUpload = (event.target as HTMLInputElement).checked;
render();
@@ -634,6 +661,7 @@ function applyDesktopStatus(status: DesktopStatus) {
state.detectedGame = status.detected_game ?? "Waiting for game";
state.replayBufferSeconds = status.replay_buffer_seconds;
state.micEnabled = status.mic_enabled;
state.micDevice = status.mic_device ?? "";
state.autoRecordEnabled = status.auto_record_enabled;
state.autoUpload = status.upload_enabled;
state.sessionRecording = status.session_recording;
@@ -778,6 +806,20 @@ async function saveMicSetting(enabled: boolean) {
}
}
async function saveMicDevice(device: string) {
if (!tauriInvoke) {
return;
}
try {
const status = await tauriInvoke<DesktopStatus>("set_mic_device", { device: device || null });
applyDesktopStatus(status);
render();
} catch (error) {
console.warn("Could not save mic device", error);
}
}
async function saveAutoRecordSetting(enabled: boolean) {
if (!tauriInvoke) {
return;
@@ -806,6 +848,19 @@ async function refreshStatus() {
}
}
async function refreshAudioDevices() {
if (!tauriInvoke) {
return;
}
try {
state.audioDevices = await tauriInvoke<AudioDeviceDto[]>("list_audio_devices");
render();
} catch (error) {
console.warn("Could not load audio devices", error);
}
}
async function pollAutoClips() {
if (!tauriInvoke || !state.captureActive) {
return;
@@ -840,6 +895,14 @@ function parseTimestamp(value: string) {
return parts[0] * 3600 + parts[1] * 60 + parts[2];
}
function escapeHtml(value: string) {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
async function loadDesktopBridge() {
const hasTauri = "__TAURI_INTERNALS__" in window;
if (!hasTauri) {
@@ -858,6 +921,7 @@ async function loadDesktopBridge() {
state.clips = clips.map(clipFromDto);
state.selectedClipId = state.clips[0]?.id ?? "";
render();
await refreshAudioDevices();
window.setInterval(() => {
void refreshStatus();
}, 3_000);
+2 -1
View File
@@ -336,7 +336,8 @@ label {
font-size: 13px;
}
input {
input,
select {
width: 100%;
padding: 9px 10px;
border: 1px solid #313847;