Add native WASAPI audio capture
This commit is contained in:
1 parent
a89e61ed95
commit
bb07173857
11 files changed
+898
-81
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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::*;
|
||||
|
||||
Reference in new issue
Block a user