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

+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);
}
}