Add native WASAPI audio capture

This commit is contained in:
Alvin-Zilverstand committed 2026-09-10 13:55:32 +02:00
1 parent a89e61ed95
commit bb07173857
11 files changed
+898 -81

No files matched your search

Generated
+38
View File
@@ -20,6 +20,12 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
@@ -86,6 +92,7 @@ dependencies = [
"serde",
"serde_json",
"sysinfo",
"wasapi",
"windows-capture",
]
@@ -578,6 +585,24 @@ dependencies = [
"winapi",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -1244,6 +1269,19 @@ dependencies = [
"try-lock",
]
[[package]]
name = "wasapi"
version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee144c215d8d31e94c1a599fbaf540ca82a7017e4f1786816b179f334fac751d"
dependencies = [
"log",
"num-integer",
"thiserror",
"windows 0.62.2",
"windows-core 0.62.2",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
+1
View File
@@ -19,6 +19,7 @@ rusqlite = { version = "0.32", features = ["bundled"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sysinfo = "0.31"
wasapi = "0.24.0"
windows-capture = "2.0.1"
[profile.dev]
+2 -2
View File
@@ -6,14 +6,14 @@ ClipForge is a Windows-first, local-first game clipping app inspired by tools li
- Rolling replay capture writes short MP4 segments and manual clips extract from those segments.
- Full-session recording concatenates the session segments into a saved MP4.
- Video-only capture prefers native Windows Graphics Capture with H.264, then falls back to FFmpeg Desktop Duplication (`ddagrab`) or `gdigrab`.
- Capture prefers native Windows Graphics Capture with H.264 for detected game windows or the desktop, then falls back to FFmpeg Desktop Duplication (`ddagrab`) or `gdigrab`.
- FFmpeg Media Foundation H.264 is used when available.
- FFmpeg is bundled as a Tauri sidecar for installer builds, so users do not need a separate FFmpeg install.
- SQLite stores the clip library; `settings.json` stores versioned local settings.
- Global hotkeys are registered while the app runs: `F8`, `Shift+F8`, and `Alt+F7`.
- League Live Client events and Valve GSI-style events feed the auto-clip pipeline.
- Catbox, Litterbox, and custom multipart HTTP upload adapters are implemented; the UI can choose providers.
- Native Rust WASAPI mixing is still future work; audio-enabled recording currently uses the FFmpeg path.
- Native WASAPI system-audio and mic capture are wired into the native Windows Graphics Capture path; FFmpeg remains the fallback capture path.
## Commands
+11 -10
View File
@@ -10,7 +10,8 @@
- Runtime FFmpeg detection checks the bundled sidecar first and then system PATH.
- Tauri commands exist for status, live game detection, clip listing, manual clip creation, auto-clip polling, Start Capture, Stop Capture, clip delete, reveal in Explorer, trim, upload, and settings updates.
- Start Capture launches a rolling segmented replay recorder with a low-spec default profile: 720p30 at 6 Mbps using H.264 when available.
- Video-only recording now prefers native Windows Graphics Capture with Windows Media Foundation H.264; an ignored local smoke test produced real MP4 segments from the desktop.
- Recording now prefers native Windows Graphics Capture with Windows Media Foundation H.264; it targets detected game windows when possible and falls back to the primary monitor.
- Native Windows Graphics Capture can now embed native WASAPI system loopback audio and default mic capture; ignored local smoke tests cover standalone loopback, standalone mic, WGC plus loopback, and WGC plus mic.
- Audio-enabled capture falls back to FFmpeg's Windows Desktop Duplication `ddagrab` filter when available and then `gdigrab`; a local smoke test produced a real MP4 segment with `ddagrab`.
- Stop Capture asks FFmpeg to finalize gracefully, falls back after a short timeout, concatenates recorded segments, and adds the completed full-session MP4 to the local library.
- Manual clips now extract from the rolling segment buffer instead of writing placeholder MP4 files.
@@ -26,6 +27,7 @@
- Event debouncing supports duplicate detection and merge-window behavior.
- League Live Client Data events are polled from the local Riot endpoint while recording and normalize into shared `GameEvent` records.
- A localhost Valve GSI receiver on `127.0.0.1:49321` accepts CS2/Dota-style event posts and queues normalized event clips.
- A backend worker loop now refreshes game detection and drains auto-clip integrations while the desktop app is running, independent of the currently selected UI view.
- Local clip library can add, filter, remove, update upload state, write a tab-separated manifest, and persist clip metadata in SQLite.
- Versioned local settings are saved to `settings.json`; replay buffer length and mic toggle are wired from the UI to Rust.
- Storage layer creates the planned folders, sanitizes clip paths, keeps placeholder helpers for tests/demo paths, and cleans oldest temporary files under a size limit.
@@ -35,18 +37,17 @@
## Not Fully Working Yet
- Native Windows Graphics Capture is wired for video-only rolling replay capture; game/window targeting and native audio mixing still need more work.
- WASAPI/system-audio capture is enabled only when the selected FFmpeg build exposes a WASAPI input device; native Rust WASAPI capture/mixing is still pending, so video capture remains enabled while system-audio capture is marked unavailable on FFmpeg builds without WASAPI.
- Native Windows Graphics Capture is wired for rolling replay capture with native audio; resolution downscaling still needs more work.
- Native WASAPI audio is mixed into a single AAC track for MVP clips; separate audio tracks and per-process audio capture are still future work.
- Capture has not yet been manually QA-tested on real NVIDIA/AMD/Intel gaming systems.
- Upload provider configuration UI is not complete; Catbox is live from the default Upload action, but Litterbox/custom HTTP need UI selection and configuration.
- Valve GSI receiver is a lightweight MVP receiver; config templates can be generated from the Auto Clip screen, but richer event mapping per game is still needed.
- Auto start/stop is conservative: live process detection updates the current game/session state, but capture still starts from explicit user action/hotkey.
- Auto start/stop is conservative but live: when auto-record is enabled, supported detected games can start recording and stop when the game disappears.
## Next Engineering Steps
1. Extend native Windows Graphics Capture from primary-monitor video capture to proper game/window targeting and resolution scaling.
2. Add native Rust WASAPI capture/mixing.
3. Add upload provider configuration UI for Litterbox/custom HTTP.
4. Generate CS2/Dota GSI config files and expand event mapping.
5. Add installer/onboarding screens for privacy, capture source, storage, and hotkeys.
6. Run manual QA on Windows gaming hardware and tune CPU/GPU overhead.
1. Extend native Windows Graphics Capture with resolution downscaling and richer capture-source selection.
2. Add separate audio tracks and optional per-process loopback capture.
3. Expand CS2/Dota GSI event mapping beyond the current MVP event parser.
4. Add installer/onboarding screens for privacy, capture source, storage, and hotkeys.
5. Run manual QA on Windows gaming hardware and tune CPU/GPU overhead.
+23
View File
@@ -365,6 +365,7 @@ dependencies = [
"serde",
"serde_json",
"sysinfo",
"wasapi",
"windows-capture",
]
@@ -2098,6 +2099,15 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -4305,6 +4315,19 @@ dependencies = [
"try-lock",
]
[[package]]
name = "wasapi"
version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee144c215d8d31e94c1a599fbaf540ca82a7017e4f1786816b179f334fac751d"
dependencies = [
"log",
"num-integer",
"thiserror 2.0.20",
"windows 0.62.2",
"windows-core 0.62.2",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
+119 -21
View File
@@ -17,6 +17,10 @@ use clipforge::media::{
trim_clip as ffmpeg_trim_clip,
};
use clipforge::models::{Clip, ClipSource, GameEvent, RecordingStatus};
use clipforge::native_audio::{
list_native_audio_devices, native_microphone_available, native_system_loopback_available,
NativeAudioSource,
};
use clipforge::native_wgc::NativeWgcReplayCaptureBackend;
use clipforge::recorder::{RecorderAction, RecorderService};
use clipforge::settings::{load_or_create_settings, save_settings};
@@ -79,6 +83,7 @@ struct DesktopStatus {
recording_state: String,
detected_game: Option<String>,
replay_buffer_seconds: u64,
system_audio_enabled: bool,
mic_enabled: bool,
mic_device: Option<String>,
auto_record_enabled: bool,
@@ -132,8 +137,13 @@ fn get_status(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
#[tauri::command]
fn refresh_detected_game(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
refresh_detected_game_inner(runtime.inner())
}
fn refresh_detected_game_inner(runtime: &AppRuntime) -> Result<DesktopStatus, String> {
let detected = detect_game(&running_processes(), &default_profiles());
let mut should_auto_start = false;
let mut should_auto_stop = false;
{
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
@@ -154,15 +164,23 @@ fn refresh_detected_game(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus
None if capture.is_none() => {
let _ = recorder.stop();
}
None => {}
None => {
should_auto_stop = recorder.state.detected_game_id.as_deref() != Some("desktop");
}
}
if !should_auto_start {
return Ok(status_from_recorder(&recorder, capture.as_ref()));
if !should_auto_stop {
return Ok(status_from_recorder(&recorder, capture.as_ref()));
}
}
}
start_capture_inner(runtime.inner())
if should_auto_stop {
stop_capture_inner(runtime)
} else {
start_capture_inner(runtime)
}
}
#[tauri::command]
@@ -192,20 +210,50 @@ fn set_mic_enabled(enabled: bool, runtime: State<'_, AppRuntime>) -> Result<Desk
Ok(status_from_recorder(&recorder, capture.as_ref()))
}
#[tauri::command]
fn set_system_audio_enabled(
enabled: bool,
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.system_audio_enabled = enabled;
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 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)
let mut devices = list_native_audio_devices()
.into_iter()
.map(|device| AudioDeviceDto {
name: device.name,
kind: match device.kind {
AudioDeviceKind::Input => "input".to_string(),
AudioDeviceKind::SystemLoopback => "system_loopback".to_string(),
kind: match device.source {
NativeAudioSource::Microphone => "input".to_string(),
NativeAudioSource::SystemLoopback => "system_loopback".to_string(),
},
})
.collect())
.collect::<Vec<_>>();
if let Some(ffmpeg) = find_ffmpeg_executable() {
for device in list_ffmpeg_dshow_audio_inputs(&ffmpeg) {
if !devices
.iter()
.any(|existing| existing.name == device.name && existing.kind == "input")
{
devices.push(AudioDeviceDto {
name: device.name,
kind: match device.kind {
AudioDeviceKind::Input => "input".to_string(),
AudioDeviceKind::SystemLoopback => "system_loopback".to_string(),
},
});
}
}
}
Ok(devices)
}
#[tauri::command]
@@ -251,6 +299,10 @@ fn write_gsi_configs(runtime: State<'_, AppRuntime>) -> Result<Vec<GsiConfigDto>
#[tauri::command]
fn poll_auto_clip_events(runtime: State<'_, AppRuntime>) -> Result<Vec<ClipDto>, String> {
poll_auto_clip_events_inner(runtime.inner())
}
fn poll_auto_clip_events_inner(runtime: &AppRuntime) -> Result<Vec<ClipDto>, String> {
let (session_id, game_id, session_started_at) = {
let recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
@@ -282,8 +334,8 @@ fn poll_auto_clip_events(runtime: State<'_, AppRuntime>) -> Result<Vec<ClipDto>,
let integration = LeagueIntegration;
for raw_event in raw_events {
if let Some(event) = integration.normalize_event(&raw_event, &session_id) {
if let Some(clip) = handle_auto_event_inner(event, runtime.inner())? {
if let Some(event) = integration.normalize_event(&raw_event, &session_id) {
if let Some(clip) = handle_auto_event_inner(event, runtime)? {
created.push(clip);
}
}
@@ -305,7 +357,7 @@ fn poll_auto_clip_events(runtime: State<'_, AppRuntime>) -> Result<Vec<ClipDto>,
};
for raw_event in raw_events {
if let Some(event) = integration.normalize_event(&raw_event, &session_id) {
if let Some(clip) = handle_auto_event_inner(event, runtime.inner())? {
if let Some(clip) = handle_auto_event_inner(event, runtime)? {
created.push(clip);
}
}
@@ -443,7 +495,14 @@ fn start_capture_inner(runtime: &AppRuntime) -> Result<DesktopStatus, String> {
.ok_or_else(|| "FFmpeg was not found on PATH or in the bundled sidecar.".to_string())?;
let now = SystemTime::now();
if recorder.state.active_session_id.is_none() {
recorder.start_for_game("desktop", now);
let detected = detect_game(&running_processes(), &default_profiles());
recorder.start_for_game(
detected
.as_ref()
.map(|game| game.game_id.as_str())
.unwrap_or("desktop"),
now,
);
}
recorder.toggle_session_recording();
@@ -460,14 +519,27 @@ fn start_capture_inner(runtime: &AppRuntime) -> Result<DesktopStatus, String> {
let segment_duration = Duration::from_secs(5);
let segment_pattern = buffer_dir.join("segment-%05d.mp4");
let system_audio_enabled = ffmpeg_supports_input_device(&ffmpeg, "wasapi");
let native_system_audio_available = native_system_loopback_available();
let native_mic_available = native_microphone_available();
let ffmpeg_system_audio_available = ffmpeg_supports_input_device(&ffmpeg, "wasapi");
let system_audio_enabled = recorder.settings.privacy.system_audio_enabled
&& (native_system_audio_available || ffmpeg_system_audio_available);
let method = if ffmpeg_supports_filter(&ffmpeg, "ddagrab") {
CaptureMethod::DesktopDuplication
} else {
CaptureMethod::GdiGrab
};
let source = detect_game(&running_processes(), &default_profiles())
.map(|game| CaptureSource::GameWindow {
process_name: game.process.process_name,
window_title: game
.process
.window_title
.unwrap_or(game.display_name),
})
.unwrap_or(CaptureSource::Desktop);
let config = CaptureConfig {
source: CaptureSource::Desktop,
source,
method,
width: recorder.settings.quality.width,
height: recorder.settings.quality.height,
@@ -484,7 +556,9 @@ fn start_capture_inner(runtime: &AppRuntime) -> Result<DesktopStatus, String> {
&segment_pattern,
segment_duration,
config,
system_audio_enabled || recorder.settings.privacy.mic_enabled,
native_system_audio_available,
native_mic_available,
ffmpeg_system_audio_available,
)?;
*capture = Some(ActiveCapture {
buffer_dir,
@@ -735,6 +809,7 @@ fn main() {
})
.setup(|app| {
start_valve_gsi_receiver(app.handle().clone());
start_backend_workers(app.handle().clone());
#[cfg(desktop)]
{
use tauri_plugin_global_shortcut::{
@@ -786,6 +861,7 @@ fn main() {
list_clips,
set_replay_buffer,
set_mic_enabled,
set_system_audio_enabled,
list_audio_devices,
set_mic_device,
set_auto_record_enabled,
@@ -877,9 +953,13 @@ fn start_best_capture_backend(
segment_pattern: &std::path::Path,
segment_duration: Duration,
config: CaptureConfig,
needs_ffmpeg_audio: bool,
native_system_audio_available: bool,
native_mic_available: bool,
ffmpeg_system_audio_available: bool,
) -> Result<ActiveCaptureBackend, String> {
if !needs_ffmpeg_audio {
if (!config.system_audio_enabled || native_system_audio_available)
&& (!config.mic_enabled || native_mic_available)
{
let mut native = NativeWgcReplayCaptureBackend::new(segment_pattern, segment_duration);
if native.start(config.clone()).is_ok() {
return Ok(ActiveCaptureBackend::NativeWgc(native));
@@ -887,8 +967,12 @@ fn start_best_capture_backend(
}
let mut ffmpeg_backend = FfmpegReplayCaptureBackend::new(ffmpeg, segment_pattern, segment_duration);
let mut ffmpeg_config = config;
if ffmpeg_config.system_audio_enabled && !ffmpeg_system_audio_available {
ffmpeg_config.system_audio_enabled = false;
}
ffmpeg_backend
.start(config)
.start(ffmpeg_config)
.map_err(|error| error.to_string())?;
Ok(ActiveCaptureBackend::Ffmpeg(ffmpeg_backend))
}
@@ -923,11 +1007,24 @@ fn start_valve_gsi_receiver(app: tauri::AppHandle) {
});
}
fn start_backend_workers(app: tauri::AppHandle) {
thread::Builder::new()
.name("clipforge-backend-workers".to_string())
.spawn(move || loop {
let runtime = app.state::<AppRuntime>();
let _ = refresh_detected_game_inner(runtime.inner());
let _ = poll_auto_clip_events_inner(runtime.inner());
thread::sleep(Duration::from_secs(2));
})
.expect("could not start ClipForge backend workers");
}
fn status_from_recorder(recorder: &RecorderService, capture: Option<&ActiveCapture>) -> DesktopStatus {
DesktopStatus {
recording_state: recording_status_name(&recorder.state.status).to_string(),
detected_game: recorder.state.detected_game_id.clone(),
replay_buffer_seconds: recorder.settings.replay_buffer.as_secs(),
system_audio_enabled: recorder.settings.privacy.system_audio_enabled,
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,
@@ -940,7 +1037,8 @@ fn status_from_recorder(recorder: &RecorderService, capture: Option<&ActiveCaptu
library_root: recorder.paths.clip_root.display().to_string(),
ffmpeg_available: ffmpeg_is_available(),
ffmpeg_path: find_ffmpeg_executable().map(|path| path.display().to_string()),
system_audio_available: find_ffmpeg_executable()
system_audio_available: native_system_loopback_available()
|| find_ffmpeg_executable()
.map(|path| ffmpeg_supports_input_device(&path, "wasapi"))
.unwrap_or(false),
desktop_duplication_available: find_ffmpeg_executable()
+1
View File
@@ -10,6 +10,7 @@ pub mod jobs;
pub mod library;
pub mod media;
pub mod models;
pub mod native_audio;
pub mod native_wgc;
pub mod recorder;
pub mod settings;
+296
View File
@@ -0,0 +1,296 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NativeAudioSource {
SystemLoopback,
Microphone,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeAudioDevice {
pub name: String,
pub source: NativeAudioSource,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NativePcmFormat {
pub sample_rate: u32,
pub channels: u16,
pub bits_per_sample: u16,
pub block_align: u16,
}
impl NativePcmFormat {
pub fn stereo_i16_48khz() -> Self {
Self {
sample_rate: 48_000,
channels: 2,
bits_per_sample: 16,
block_align: 4,
}
}
}
pub struct NativeAudioCapture {
stop: Arc<AtomicBool>,
rx: Receiver<Vec<u8>>,
worker: Option<JoinHandle<()>>,
format: NativePcmFormat,
}
impl NativeAudioCapture {
#[cfg(target_os = "windows")]
pub fn start_default_system_loopback() -> Result<Self, String> {
Self::start_system_loopback(None)
}
#[cfg(not(target_os = "windows"))]
pub fn start_default_system_loopback() -> Result<Self, String> {
Err("native WASAPI capture is only available on Windows".to_string())
}
#[cfg(target_os = "windows")]
pub fn start_default_microphone() -> Result<Self, String> {
Self::start_microphone(None)
}
#[cfg(not(target_os = "windows"))]
pub fn start_default_microphone() -> Result<Self, String> {
Err("native WASAPI capture is only available on Windows".to_string())
}
#[cfg(target_os = "windows")]
pub fn start_system_loopback(device_name: Option<&str>) -> Result<Self, String> {
Self::start(
NativeAudioSource::SystemLoopback,
device_name.map(str::to_string),
)
}
#[cfg(not(target_os = "windows"))]
pub fn start_system_loopback(_device_name: Option<&str>) -> Result<Self, String> {
Err("native WASAPI capture is only available on Windows".to_string())
}
#[cfg(target_os = "windows")]
pub fn start_microphone(device_name: Option<&str>) -> Result<Self, String> {
Self::start(
NativeAudioSource::Microphone,
device_name.map(str::to_string),
)
}
#[cfg(not(target_os = "windows"))]
pub fn start_microphone(_device_name: Option<&str>) -> Result<Self, String> {
Err("native WASAPI capture is only available on Windows".to_string())
}
pub fn format(&self) -> NativePcmFormat {
self.format
}
pub fn drain_chunks(&self) -> Vec<Vec<u8>> {
let mut chunks = Vec::new();
while let Ok(chunk) = self.rx.try_recv() {
chunks.push(chunk);
}
chunks
}
#[cfg(target_os = "windows")]
fn start(source: NativeAudioSource, device_name: Option<String>) -> Result<Self, String> {
let stop = Arc::new(AtomicBool::new(false));
let (tx, rx) = mpsc::channel();
let worker_stop = stop.clone();
let format = NativePcmFormat::stereo_i16_48khz();
let worker = thread::Builder::new()
.name(match source {
NativeAudioSource::SystemLoopback => "clipforge-wasapi-loopback".to_string(),
NativeAudioSource::Microphone => "clipforge-wasapi-mic".to_string(),
})
.spawn(move || {
if let Err(error) = windows_impl::capture_loop(source, device_name, worker_stop, tx)
{
eprintln!("ClipForge native audio capture stopped: {error}");
}
})
.map_err(|error| error.to_string())?;
Ok(Self {
stop,
rx,
worker: Some(worker),
format,
})
}
}
impl Drop for NativeAudioCapture {
fn drop(&mut self) {
self.stop.store(true, Ordering::SeqCst);
if let Some(worker) = self.worker.take() {
let _ = worker.join();
}
}
}
#[cfg(target_os = "windows")]
pub fn list_native_audio_devices() -> Vec<NativeAudioDevice> {
windows_impl::list_native_audio_devices().unwrap_or_default()
}
#[cfg(not(target_os = "windows"))]
pub fn list_native_audio_devices() -> Vec<NativeAudioDevice> {
Vec::new()
}
pub fn native_system_loopback_available() -> bool {
list_native_audio_devices()
.iter()
.any(|device| device.source == NativeAudioSource::SystemLoopback)
}
pub fn native_microphone_available() -> bool {
list_native_audio_devices()
.iter()
.any(|device| device.source == NativeAudioSource::Microphone)
}
#[cfg(target_os = "windows")]
mod windows_impl {
use super::{NativeAudioDevice, NativeAudioSource, NativePcmFormat};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::Sender;
use std::sync::Arc;
use wasapi::{initialize_mta, DeviceEnumerator, Direction, SampleType, StreamMode, WaveFormat};
type WasapiResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
pub fn list_native_audio_devices() -> WasapiResult<Vec<NativeAudioDevice>> {
initialize_mta().ok()?;
let enumerator = DeviceEnumerator::new()?;
let mut devices = Vec::new();
if let Ok(collection) = enumerator.get_device_collection(&Direction::Render) {
for device in &collection {
let device = device?;
devices.push(NativeAudioDevice {
name: device.get_friendlyname()?,
source: NativeAudioSource::SystemLoopback,
});
}
}
if let Ok(collection) = enumerator.get_device_collection(&Direction::Capture) {
for device in &collection {
let device = device?;
devices.push(NativeAudioDevice {
name: device.get_friendlyname()?,
source: NativeAudioSource::Microphone,
});
}
}
Ok(devices)
}
pub fn capture_loop(
source: NativeAudioSource,
device_name: Option<String>,
stop: Arc<AtomicBool>,
tx: Sender<Vec<u8>>,
) -> WasapiResult<()> {
initialize_mta().ok()?;
let format = NativePcmFormat::stereo_i16_48khz();
let desired_format = WaveFormat::new(
format.bits_per_sample as usize,
format.bits_per_sample as usize,
&SampleType::Int,
format.sample_rate as usize,
format.channels as usize,
None,
);
let block_align = desired_format.get_blockalign() as usize;
let chunksize_frames = 2048usize;
let enumerator = DeviceEnumerator::new()?;
let direction = match source {
NativeAudioSource::SystemLoopback => Direction::Render,
NativeAudioSource::Microphone => Direction::Capture,
};
let device = if let Some(name) = device_name {
enumerator
.get_device_collection(&direction)?
.get_device_with_name(&name)?
} else {
enumerator.get_default_device(&direction)?
};
let mut audio_client = device.get_iaudioclient()?;
let mode = StreamMode::EventsShared {
autoconvert: true,
buffer_duration_hns: 0,
};
audio_client.initialize_client(&desired_format, &Direction::Capture, &mode)?;
let event = audio_client.set_get_eventhandle()?;
let capture_client = audio_client.get_audiocaptureclient()?;
let mut sample_queue = VecDeque::with_capacity(block_align * chunksize_frames * 4);
audio_client.start_stream()?;
while !stop.load(Ordering::SeqCst) {
capture_client.read_from_device_to_deque(&mut sample_queue)?;
while sample_queue.len() >= block_align * chunksize_frames {
let mut chunk = Vec::with_capacity(block_align * chunksize_frames);
for _ in 0..(block_align * chunksize_frames) {
if let Some(byte) = sample_queue.pop_front() {
chunk.push(byte);
}
}
if tx.send(chunk).is_err() {
stop.store(true, Ordering::SeqCst);
break;
}
}
let _ = event.wait_for_event(250);
}
audio_client.stop_stream()?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_pcm_format_matches_encoder_audio_settings() {
let format = NativePcmFormat::stereo_i16_48khz();
assert_eq!(format.sample_rate, 48_000);
assert_eq!(format.channels, 2);
assert_eq!(format.bits_per_sample, 16);
assert_eq!(format.block_align, 4);
}
#[cfg(target_os = "windows")]
#[test]
#[ignore = "opens the default WASAPI system loopback client briefly"]
fn native_system_loopback_smoke_starts() {
let capture = NativeAudioCapture::start_default_system_loopback()
.expect("start default WASAPI loopback");
std::thread::sleep(std::time::Duration::from_millis(500));
assert_eq!(capture.format(), NativePcmFormat::stereo_i16_48khz());
}
#[cfg(target_os = "windows")]
#[test]
#[ignore = "opens the default WASAPI microphone capture client briefly"]
fn native_microphone_smoke_starts() {
let capture =
NativeAudioCapture::start_default_microphone().expect("start default WASAPI mic");
std::thread::sleep(std::time::Duration::from_millis(500));
assert_eq!(capture.format(), NativePcmFormat::stereo_i16_48khz());
}
}
+374 -47
View File
@@ -4,6 +4,7 @@ use std::path::PathBuf;
#[cfg(target_os = "windows")]
mod windows_impl {
use super::*;
use crate::native_audio::NativeAudioCapture;
use std::error::Error;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
@@ -18,8 +19,9 @@ mod windows_impl {
use windows_capture::monitor::Monitor;
use windows_capture::settings::{
ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings,
MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings,
GraphicsCaptureItemType, MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings,
};
use windows_capture::window::Window;
type HandlerError = Box<dyn Error + Send + Sync>;
@@ -30,10 +32,15 @@ mod windows_impl {
height: u32,
fps: u32,
bitrate: u32,
system_audio_enabled: bool,
mic_enabled: bool,
system_audio_device: Option<String>,
mic_device: Option<String>,
}
struct WgcRecorderHandler {
encoder: Option<VideoEncoder>,
audio: Vec<NativeAudioCapture>,
stop: Arc<AtomicBool>,
started_at: Instant,
}
@@ -46,10 +53,15 @@ mod windows_impl {
height: u32,
fps: u32,
bitrate: u32,
system_audio_enabled: bool,
mic_enabled: bool,
system_audio_device: Option<String>,
mic_device: Option<String>,
}
struct WgcSegmentHandler {
encoder: Option<VideoEncoder>,
audio: Vec<NativeAudioCapture>,
stop: Arc<AtomicBool>,
segment_pattern: String,
segment_duration: Duration,
@@ -72,13 +84,21 @@ mod windows_impl {
.bitrate(ctx.flags.bitrate);
let encoder = VideoEncoder::new(
video,
AudioSettingsBuilder::default().disabled(true),
AudioSettingsBuilder::default()
.disabled(!(ctx.flags.system_audio_enabled || ctx.flags.mic_enabled)),
ContainerSettingsBuilder::default(),
&ctx.flags.output_path,
)?;
let audio = start_audio_captures(
ctx.flags.system_audio_enabled,
ctx.flags.mic_enabled,
ctx.flags.system_audio_device.as_deref(),
ctx.flags.mic_device.as_deref(),
)?;
Ok(Self {
encoder: Some(encoder),
audio,
stop: ctx.flags.stop,
started_at: Instant::now(),
})
@@ -90,6 +110,9 @@ mod windows_impl {
capture_control: InternalCaptureControl,
) -> Result<(), Self::Error> {
if let Some(encoder) = self.encoder.as_mut() {
for chunk in mixed_audio_chunks(&self.audio) {
encoder.send_audio_buffer(&chunk, 0)?;
}
encoder.send_frame(frame)?;
}
@@ -122,10 +145,18 @@ mod windows_impl {
ctx.flags.height,
ctx.flags.fps,
ctx.flags.bitrate,
ctx.flags.system_audio_enabled || ctx.flags.mic_enabled,
)?;
let audio = start_audio_captures(
ctx.flags.system_audio_enabled,
ctx.flags.mic_enabled,
ctx.flags.system_audio_device.as_deref(),
ctx.flags.mic_device.as_deref(),
)?;
Ok(Self {
encoder: Some(encoder),
audio,
stop: ctx.flags.stop,
segment_pattern: ctx.flags.segment_pattern,
segment_duration: ctx.flags.segment_duration,
@@ -156,10 +187,14 @@ mod windows_impl {
self.height,
self.fps,
self.bitrate,
!self.audio.is_empty(),
)?);
}
if let Some(encoder) = self.encoder.as_mut() {
for chunk in mixed_audio_chunks(&self.audio) {
encoder.send_audio_buffer(&chunk, 0)?;
}
encoder.send_frame(frame)?;
}
@@ -185,6 +220,7 @@ mod windows_impl {
height: u32,
fps: u32,
bitrate: u32,
include_audio: bool,
) -> Result<VideoEncoder, HandlerError> {
let video = VideoSettingsBuilder::new(width, height)
.sub_type(VideoSettingsSubType::H264)
@@ -192,12 +228,76 @@ mod windows_impl {
.bitrate(bitrate);
Ok(VideoEncoder::new(
video,
AudioSettingsBuilder::default().disabled(true),
AudioSettingsBuilder::default().disabled(!include_audio),
ContainerSettingsBuilder::default(),
output_path,
)?)
}
fn start_audio_captures(
system_audio_enabled: bool,
mic_enabled: bool,
system_audio_device: Option<&str>,
mic_device: Option<&str>,
) -> Result<Vec<NativeAudioCapture>, HandlerError> {
let mut captures = Vec::new();
if system_audio_enabled {
captures.push(NativeAudioCapture::start_system_loopback(
system_audio_device,
)?);
}
if mic_enabled {
captures.push(NativeAudioCapture::start_microphone(mic_device)?);
}
Ok(captures)
}
fn mixed_audio_chunks(audio: &[NativeAudioCapture]) -> Vec<Vec<u8>> {
match audio {
[] => Vec::new(),
[single] => single.drain_chunks(),
captures => {
let drained = captures
.iter()
.map(NativeAudioCapture::drain_chunks)
.collect::<Vec<_>>();
let chunk_count = drained.iter().map(Vec::len).max().unwrap_or(0);
let mut mixed = Vec::new();
for chunk_index in 0..chunk_count {
let target_len = drained
.iter()
.filter_map(|chunks| chunks.get(chunk_index))
.map(Vec::len)
.max()
.unwrap_or(0);
if target_len == 0 {
continue;
}
let mut output = vec![0u8; target_len - (target_len % 2)];
for sample_offset in (0..output.len()).step_by(2) {
let mut sample = 0i32;
for chunks in &drained {
if let Some(chunk) = chunks.get(chunk_index) {
if sample_offset + 1 < chunk.len() {
let value = i16::from_le_bytes([
chunk[sample_offset],
chunk[sample_offset + 1],
]);
sample += value as i32;
}
}
}
let sample = sample.clamp(i16::MIN as i32, i16::MAX as i32) as i16;
output[sample_offset..sample_offset + 2]
.copy_from_slice(&sample.to_le_bytes());
}
mixed.push(output);
}
mixed
}
}
}
fn segment_path(pattern: &str, index: u32) -> String {
if pattern.contains("%05d") {
pattern.replace("%05d", &format!("{index:05}"))
@@ -241,31 +341,36 @@ mod windows_impl {
std::fs::create_dir_all(parent)
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?;
let monitor = Monitor::primary()
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?;
let width = even_dimension(monitor.width().unwrap_or(config.width).min(config.width));
let height =
even_dimension(monitor.height().unwrap_or(config.height).min(config.height));
let stop = Arc::new(AtomicBool::new(false));
let settings = Settings::new(
monitor,
CursorCaptureSettings::Default,
DrawBorderSettings::WithoutBorder,
SecondaryWindowSettings::Default,
MinimumUpdateIntervalSettings::Default,
DirtyRegionSettings::Default,
ColorFormat::Bgra8,
WgcFlags {
output_path: self.output_path.display().to_string(),
stop: stop.clone(),
let control = if let Some(window) = find_window_for_source(&config.source)
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?
{
let (width, height) = window_size(window, config.width, config.height);
let settings = recording_settings(
window,
&self.output_path,
&config,
stop.clone(),
width,
height,
fps: config.fps,
bitrate: config.bitrate_kbps.saturating_mul(1_000),
},
);
let control = WgcRecorderHandler::start_free_threaded(settings)
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?;
);
WgcRecorderHandler::start_free_threaded(settings)
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?
} else {
let monitor = Monitor::primary()
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?;
let (width, height) = monitor_size(monitor, config.width, config.height);
let settings = recording_settings(
monitor,
&self.output_path,
&config,
stop.clone(),
width,
height,
);
WgcRecorderHandler::start_free_threaded(settings)
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?
};
self.stop = Some(stop);
self.control = Some(control);
Ok(())
@@ -326,31 +431,38 @@ mod windows_impl {
std::fs::create_dir_all(parent)
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?;
let monitor = Monitor::primary()
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?;
let width = even_dimension(monitor.width().unwrap_or(config.width));
let height = even_dimension(monitor.height().unwrap_or(config.height));
let stop = Arc::new(AtomicBool::new(false));
let settings = Settings::new(
monitor,
CursorCaptureSettings::Default,
DrawBorderSettings::WithoutBorder,
SecondaryWindowSettings::Default,
MinimumUpdateIntervalSettings::Default,
DirtyRegionSettings::Default,
ColorFormat::Bgra8,
WgcSegmentFlags {
segment_pattern: self.segment_pattern.display().to_string(),
stop: stop.clone(),
segment_duration: self.segment_duration,
let control = if let Some(window) = find_window_for_source(&config.source)
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?
{
let (width, height) = window_size(window, config.width, config.height);
let settings = segment_settings(
window,
&self.segment_pattern,
self.segment_duration,
&config,
stop.clone(),
width,
height,
fps: config.fps,
bitrate: config.bitrate_kbps.saturating_mul(1_000),
},
);
let control = WgcSegmentHandler::start_free_threaded(settings)
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?;
);
WgcSegmentHandler::start_free_threaded(settings)
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?
} else {
let monitor = Monitor::primary()
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?;
let (width, height) = monitor_size(monitor, config.width, config.height);
let settings = segment_settings(
monitor,
&self.segment_pattern,
self.segment_duration,
&config,
stop.clone(),
width,
height,
);
WgcSegmentHandler::start_free_threaded(settings)
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?
};
self.stop = Some(stop);
self.control = Some(control);
Ok(())
@@ -379,6 +491,125 @@ mod windows_impl {
fn even_dimension(value: u32) -> u32 {
value.saturating_sub(value % 2).max(2)
}
fn find_window_for_source(
source: &crate::capture::CaptureSource,
) -> Result<Option<Window>, HandlerError> {
let crate::capture::CaptureSource::GameWindow {
process_name,
window_title,
} = source
else {
return Ok(None);
};
let lowered_title = window_title.to_lowercase();
for window in Window::enumerate()? {
let process_matches = window
.process_name()
.map(|name| name.eq_ignore_ascii_case(process_name))
.unwrap_or(false);
let title_matches = if lowered_title.is_empty() {
false
} else {
window
.title()
.map(|title| title.to_lowercase().contains(&lowered_title))
.unwrap_or(false)
};
if process_matches || title_matches {
return Ok(Some(window));
}
}
Ok(None)
}
fn window_size(window: Window, fallback_width: u32, fallback_height: u32) -> (u32, u32) {
let width = window
.width()
.ok()
.and_then(|value| u32::try_from(value.max(0)).ok())
.unwrap_or(fallback_width);
let height = window
.height()
.ok()
.and_then(|value| u32::try_from(value.max(0)).ok())
.unwrap_or(fallback_height);
(even_dimension(width), even_dimension(height))
}
fn monitor_size(monitor: Monitor, fallback_width: u32, fallback_height: u32) -> (u32, u32) {
(
even_dimension(monitor.width().unwrap_or(fallback_width)),
even_dimension(monitor.height().unwrap_or(fallback_height)),
)
}
fn recording_settings<T: TryInto<GraphicsCaptureItemType> + Send + 'static>(
item: T,
output_path: &std::path::Path,
config: &CaptureConfig,
stop: Arc<AtomicBool>,
width: u32,
height: u32,
) -> Settings<WgcFlags, T> {
Settings::new(
item,
CursorCaptureSettings::Default,
DrawBorderSettings::WithoutBorder,
SecondaryWindowSettings::Default,
MinimumUpdateIntervalSettings::Default,
DirtyRegionSettings::Default,
ColorFormat::Bgra8,
WgcFlags {
output_path: output_path.display().to_string(),
stop,
width,
height,
fps: config.fps,
bitrate: config.bitrate_kbps.saturating_mul(1_000),
system_audio_enabled: config.system_audio_enabled,
mic_enabled: config.mic_enabled,
system_audio_device: config.system_audio_device.clone(),
mic_device: config.mic_device.clone(),
},
)
}
fn segment_settings<T: TryInto<GraphicsCaptureItemType> + Send + 'static>(
item: T,
segment_pattern: &std::path::Path,
segment_duration: Duration,
config: &CaptureConfig,
stop: Arc<AtomicBool>,
width: u32,
height: u32,
) -> Settings<WgcSegmentFlags, T> {
Settings::new(
item,
CursorCaptureSettings::Default,
DrawBorderSettings::WithoutBorder,
SecondaryWindowSettings::Default,
MinimumUpdateIntervalSettings::Default,
DirtyRegionSettings::Default,
ColorFormat::Bgra8,
WgcSegmentFlags {
segment_pattern: segment_pattern.display().to_string(),
stop,
segment_duration,
width,
height,
fps: config.fps,
bitrate: config.bitrate_kbps.saturating_mul(1_000),
system_audio_enabled: config.system_audio_enabled,
mic_enabled: config.mic_enabled,
system_audio_device: config.system_audio_device.clone(),
mic_device: config.mic_device.clone(),
},
)
}
}
#[cfg(target_os = "windows")]
@@ -442,12 +673,16 @@ impl CaptureBackend for NativeWgcReplayCaptureBackend {
mod tests {
use super::*;
use crate::capture::{CaptureMethod, CaptureSource, EncoderPreference};
use std::sync::Mutex;
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
static WGC_SMOKE_LOCK: Mutex<()> = Mutex::new(());
#[test]
#[ignore = "captures the desktop for a short local smoke test"]
fn native_wgc_replay_smoke_writes_segment() {
let _guard = WGC_SMOKE_LOCK.lock().expect("lock WGC smoke");
let root = std::env::temp_dir().join(format!(
"clipforge-wgc-smoke-{}",
SystemTime::now()
@@ -489,4 +724,96 @@ mod tests {
);
let _ = std::fs::remove_dir_all(root);
}
#[test]
#[ignore = "captures the desktop with native WASAPI system loopback briefly"]
fn native_wgc_replay_smoke_writes_segment_with_system_audio() {
let _guard = WGC_SMOKE_LOCK.lock().expect("lock WGC smoke");
let root = std::env::temp_dir().join(format!(
"clipforge-wgc-audio-smoke-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
));
std::fs::create_dir_all(&root).expect("smoke root");
let pattern = root.join("segment-%05d.mp4");
let config = CaptureConfig {
source: CaptureSource::Desktop,
method: CaptureMethod::DesktopDuplication,
width: 1280,
height: 720,
fps: 10,
bitrate_kbps: 1_000,
encoder: EncoderPreference::HardwareH264,
system_audio_enabled: true,
mic_enabled: false,
system_audio_device: None,
mic_device: None,
};
let mut backend = NativeWgcReplayCaptureBackend::new(&pattern, Duration::from_secs(1));
backend.start(config).expect("start native WGC with audio");
thread::sleep(Duration::from_secs(3));
backend.stop().expect("stop native WGC with audio");
let segment_count = std::fs::read_dir(&root)
.expect("read smoke root")
.filter_map(Result::ok)
.filter(|entry| {
entry.path().extension().and_then(|value| value.to_str()) == Some("mp4")
})
.count();
assert!(
segment_count > 0,
"native WGC with audio should write at least one segment"
);
let _ = std::fs::remove_dir_all(root);
}
#[test]
#[ignore = "captures the desktop with native WASAPI microphone briefly"]
fn native_wgc_replay_smoke_writes_segment_with_mic() {
let _guard = WGC_SMOKE_LOCK.lock().expect("lock WGC smoke");
let root = std::env::temp_dir().join(format!(
"clipforge-wgc-mic-smoke-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
));
std::fs::create_dir_all(&root).expect("smoke root");
let pattern = root.join("segment-%05d.mp4");
let config = CaptureConfig {
source: CaptureSource::Desktop,
method: CaptureMethod::DesktopDuplication,
width: 1280,
height: 720,
fps: 10,
bitrate_kbps: 1_000,
encoder: EncoderPreference::HardwareH264,
system_audio_enabled: false,
mic_enabled: true,
system_audio_device: None,
mic_device: None,
};
let mut backend = NativeWgcReplayCaptureBackend::new(&pattern, Duration::from_secs(1));
backend.start(config).expect("start native WGC with mic");
thread::sleep(Duration::from_secs(3));
backend.stop().expect("stop native WGC with mic");
let segment_count = std::fs::read_dir(&root)
.expect("read smoke root")
.filter_map(Result::ok)
.filter(|entry| {
entry.path().extension().and_then(|value| value.to_str()) == Some("mp4")
})
.count();
assert!(
segment_count > 0,
"native WGC with mic should write at least one segment"
);
let _ = std::fs::remove_dir_all(root);
}
}
+7
View File
@@ -25,6 +25,8 @@ pub struct HotkeySettings {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PrivacySettings {
#[serde(default = "default_true")]
pub system_audio_enabled: bool,
pub mic_enabled: bool,
#[serde(default)]
pub mic_device: Option<String>,
@@ -83,6 +85,7 @@ impl AppSettings {
screenshot: "F9".to_string(),
},
privacy: PrivacySettings {
system_audio_enabled: true,
mic_enabled: false,
mic_device: None,
system_audio_device: None,
@@ -134,6 +137,10 @@ pub fn settings_path(root: impl Into<PathBuf>) -> PathBuf {
root.into().join("settings.json")
}
fn default_true() -> bool {
true
}
#[cfg(test)]
mod tests {
use super::*;
+26 -1
View File
@@ -39,6 +39,7 @@ type DesktopStatus = {
recording_state: RecordingState;
detected_game: string | null;
replay_buffer_seconds: number;
system_audio_enabled: boolean;
mic_enabled: boolean;
mic_device: string | null;
auto_record_enabled: boolean;
@@ -85,6 +86,7 @@ type AppState = {
recordingState: RecordingState;
detectedGame: string;
replayBufferSeconds: number;
systemAudioEnabled: boolean;
sessionRecording: boolean;
captureActive: boolean;
captureBackend: string | null;
@@ -127,6 +129,7 @@ const state: AppState = {
recordingState: "Buffering",
detectedGame: "Counter-Strike 2",
replayBufferSeconds: 60,
systemAudioEnabled: true,
sessionRecording: false,
captureActive: false,
captureBackend: null,
@@ -402,7 +405,8 @@ function renderRecordingView() {
<article class="settings-panel">
<p class="eyebrow">Audio</p>
<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>
<p class="muted">${state.systemAudioAvailable ? "Native WASAPI or FFmpeg audio capture is available." : "No system loopback device is available; video recording still works."}</p>
<label class="toggle"><input type="checkbox" ${state.systemAudioEnabled ? "checked" : ""} data-action="toggle-system-audio" /> System audio</label>
<label class="toggle"><input type="checkbox" ${state.micEnabled ? "checked" : ""} data-action="toggle-mic" /> Mic capture</label>
<label>Mic device
<select data-action="mic-device">
@@ -560,6 +564,12 @@ function bindEvents() {
void saveMicSetting(state.micEnabled);
});
appRoot.querySelector<HTMLInputElement>("[data-action='toggle-system-audio']")?.addEventListener("change", (event) => {
state.systemAudioEnabled = (event.target as HTMLInputElement).checked;
render();
void saveSystemAudioSetting(state.systemAudioEnabled);
});
appRoot.querySelector<HTMLSelectElement>("[data-action='mic-device']")?.addEventListener("change", (event) => {
state.micDevice = (event.target as HTMLSelectElement).value;
void saveMicDevice(state.micDevice);
@@ -664,6 +674,7 @@ function applyDesktopStatus(status: DesktopStatus) {
state.recordingState = status.recording_state;
state.detectedGame = status.detected_game ?? "Waiting for game";
state.replayBufferSeconds = status.replay_buffer_seconds;
state.systemAudioEnabled = status.system_audio_enabled;
state.micEnabled = status.mic_enabled;
state.micDevice = status.mic_device ?? "";
state.autoRecordEnabled = status.auto_record_enabled;
@@ -811,6 +822,20 @@ async function saveMicSetting(enabled: boolean) {
}
}
async function saveSystemAudioSetting(enabled: boolean) {
if (!tauriInvoke) {
return;
}
try {
const status = await tauriInvoke<DesktopStatus>("set_system_audio_enabled", { enabled });
applyDesktopStatus(status);
render();
} catch (error) {
console.warn("Could not save system audio setting", error);
}
}
async function saveMicDevice(device: string) {
if (!tauriInvoke) {
return;